xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / session.ts

3.5 KB
1import {
2  closeSync,
3  fsyncSync,
4  mkdirSync,
5  openSync,
6  writeSync,
7} from "node:fs";
8import { randomBytes } from "node:crypto";
9import { join } from "node:path";
10import { contentText, type Message, type Tool } from "@earendil-works/pi-ai";
11
12interface SessionHeader {
13  type: "session";
14  version: 1;
15  id: string;
16  cwd: string;
17  createdAt: string;
18  title: string;
19}
20
21interface RequestRecord {
22  type: "request";
23  at: string;
24  provider: string;
25  model: string;
26  api: string;
27  thinkingEffort: string;
28  systemPrompt: string;
29  tools: Tool[];
30}
31
32interface MessageRecord {
33  type: "message";
34  at: string;
35  message: Message;
36}
37
38type SessionRecord = SessionHeader | RequestRecord | MessageRecord;
39
40function slugify(text: string): string {
41  const slug = text
42    .toLowerCase()
43    .replace(/[^a-z0-9]+/g, "-")
44    .replace(/^-+|-+$/g, "")
45    .slice(0, 40)
46    .replace(/-+$/, "");
47  return slug || "session";
48}
49
50const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
51
52function shortId(): string {
53  const bytes = randomBytes(6);
54  let out = "";
55  for (let i = 0; i < 6; i++) out += ALPHABET[bytes[i] % 36];
56  return out;
57}
58
59function timestamp(date: Date): string {
60  const p = (n: number) => String(n).padStart(2, "0");
61  return (
62    `${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}` +
63    `-${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}`
64  );
65}
66
67function titleFor(message: Message): string {
68  if (message.role !== "user") return "session";
69  return slugify(contentText(message.content, " "));
70}
71
72export class Session {
73  private readonly sessionsDir: string;
74  private readonly cwd: string;
75  id: string | null = null;
76  private fd: number | null = null;
77  private closed = false;
78
79  constructor(sessionsDir: string, cwd: string) {
80    this.sessionsDir = sessionsDir;
81    this.cwd = cwd;
82  }
83
84  appendMessage(message: Message): void {
85    if (this.closed) return;
86    this.ensure(titleFor(message));
87    this.write({
88      type: "message",
89      at: new Date().toISOString(),
90      message,
91    });
92  }
93
94  appendRequest(input: Omit<RequestRecord, "type" | "at">): void {
95    if (this.closed) return;
96    this.ensure("session");
97    this.write({ type: "request", at: new Date().toISOString(), ...input });
98  }
99
100  close(): void {
101    this.closed = true;
102    if (this.fd !== null) {
103      closeSync(this.fd);
104      this.fd = null;
105    }
106  }
107
108  private ensure(title: string): void {
109    if (this.fd !== null) return;
110    mkdirSync(this.sessionsDir, { recursive: true });
111    const stamp = timestamp(new Date());
112    for (let attempt = 0; attempt < 16; attempt++) {
113      const name = `${stamp}-${title}-${shortId()}`;
114      const dir = join(this.sessionsDir, name);
115      try {
116        mkdirSync(dir);
117      } catch (error) {
118        if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
119        throw error;
120      }
121      this.id = name;
122      const logPath = join(dir, "session.jsonl");
123      this.fd = openSync(logPath, "a");
124      const header: SessionHeader = {
125        type: "session",
126        version: 1,
127        id: name,
128        cwd: this.cwd,
129        createdAt: new Date().toISOString(),
130        title,
131      };
132      this.write(header);
133      return;
134    }
135    throw new Error(`session: could not create a unique directory in ${this.sessionsDir}`);
136  }
137
138  private write(record: SessionRecord): void {
139    if (this.fd === null) throw new Error("session: append before create");
140    writeSync(this.fd, JSON.stringify(record) + "\n");
141    fsyncSync(this.fd);
142  }
143}