fnloom 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +31 -18
  2. package/package.json +2 -7
  3. package/packages/build/package.json +1 -1
  4. package/packages/cli/package.json +1 -1
  5. package/packages/cli/src/commands/available.ts +63 -22
  6. package/packages/cli/src/commands/install.ts +86 -28
  7. package/packages/cli/src/index.ts +3 -2
  8. package/packages/cli/src/local.ts +6 -0
  9. package/packages/cli/src/premade.ts +80 -0
  10. package/packages/core/package.json +1 -1
  11. package/packages/hub/package.json +1 -1
  12. package/packages/hub/src/link/process.ts +6 -1
  13. package/packages/sdk/package.json +1 -1
  14. package/packages/web/package.json +1 -1
  15. package/premade/claude.zip +0 -0
  16. package/premade/database.zip +0 -0
  17. package/premade/web.zip +0 -0
  18. package/scripts/dev-env.ts +4 -4
  19. package/scripts/stack.ts +42 -27
  20. package/scripts/start.ts +26 -16
  21. package/systems/api/package.json +1 -1
  22. package/systems/code/package.json +1 -1
  23. package/systems/embedder/package.json +1 -1
  24. package/systems/fs/package.json +1 -1
  25. package/systems/google-calendar/package.json +1 -1
  26. package/systems/input/package.json +1 -1
  27. package/systems/mcp/package.json +1 -1
  28. package/systems/ollama/package.json +1 -1
  29. package/systems/schedule/package.json +1 -1
  30. package/systems/template/package.json +1 -1
  31. package/systems/widgets/package.json +1 -1
  32. package/systems/claude/client/FleetPage.vue +0 -132
  33. package/systems/claude/client/NewSessionForm.vue +0 -62
  34. package/systems/claude/client/SessionList.vue +0 -64
  35. package/systems/claude/client/SessionPage.vue +0 -199
  36. package/systems/claude/client/TaskList.vue +0 -61
  37. package/systems/claude/client/fakes.ts +0 -186
  38. package/systems/claude/client/host.ts +0 -23
  39. package/systems/claude/client/index.ts +0 -15
  40. package/systems/claude/client/logic.ts +0 -270
  41. package/systems/claude/client/state.ts +0 -344
  42. package/systems/claude/package.json +0 -23
  43. package/systems/claude/server/agent-sdk.ts +0 -379
  44. package/systems/claude/server/driver.ts +0 -153
  45. package/systems/claude/server/env.ts +0 -64
  46. package/systems/claude/server/fake-driver.ts +0 -112
  47. package/systems/claude/server/fleet.ts +0 -376
  48. package/systems/claude/server/impl.ts +0 -568
  49. package/systems/claude/server/index.ts +0 -8
  50. package/systems/claude/server/main.ts +0 -38
  51. package/systems/claude/server/preview.ts +0 -76
  52. package/systems/claude/server/questions.ts +0 -117
  53. package/systems/claude/server/transcript.ts +0 -83
  54. package/systems/claude/shared/index.ts +0 -262
  55. package/systems/claude/shared/session.ts +0 -284
  56. package/systems/claude/shared/shapes.ts +0 -106
  57. package/systems/claude/system.json +0 -18
  58. package/systems/claude/tsconfig.json +0 -6
  59. package/systems/database/package.json +0 -25
  60. package/systems/database/server/author.ts +0 -41
  61. package/systems/database/server/authoring.ts +0 -322
  62. package/systems/database/server/catalog.ts +0 -117
  63. package/systems/database/server/compile.ts +0 -332
  64. package/systems/database/server/dialects.ts +0 -17
  65. package/systems/database/server/drivers/database.ts +0 -71
  66. package/systems/database/server/drivers/index.ts +0 -23
  67. package/systems/database/server/drivers/postgres.ts +0 -157
  68. package/systems/database/server/drivers/sqlite.ts +0 -151
  69. package/systems/database/server/drivers/sqlserver.ts +0 -176
  70. package/systems/database/server/env.ts +0 -35
  71. package/systems/database/server/fixture.ts +0 -169
  72. package/systems/database/server/impl.ts +0 -793
  73. package/systems/database/server/index.ts +0 -7
  74. package/systems/database/server/instance.ts +0 -398
  75. package/systems/database/server/main.ts +0 -47
  76. package/systems/database/server/pick.ts +0 -97
  77. package/systems/database/server/queries.ts +0 -390
  78. package/systems/database/server/results.ts +0 -39
  79. package/systems/database/server/schema.ts +0 -59
  80. package/systems/database/server/table-fns.ts +0 -237
  81. package/systems/database/server/types.ts +0 -253
  82. package/systems/database/shared/index.ts +0 -544
  83. package/systems/database/shared/shapes.ts +0 -413
  84. package/systems/database/system.json +0 -14
  85. package/systems/database/tsconfig.json +0 -6
  86. package/systems/web/client/ReadView.vue +0 -110
  87. package/systems/web/client/SearchView.vue +0 -215
  88. package/systems/web/client/StatusChip.vue +0 -38
  89. package/systems/web/client/fakes.ts +0 -48
  90. package/systems/web/client/index.ts +0 -15
  91. package/systems/web/client/view.ts +0 -131
  92. package/systems/web/package.json +0 -22
  93. package/systems/web/server/chrome.ts +0 -121
  94. package/systems/web/server/crawl.ts +0 -333
  95. package/systems/web/server/env.ts +0 -63
  96. package/systems/web/server/guard.ts +0 -60
  97. package/systems/web/server/http.ts +0 -89
  98. package/systems/web/server/impl.ts +0 -203
  99. package/systems/web/server/index.ts +0 -71
  100. package/systems/web/server/loader.ts +0 -104
  101. package/systems/web/server/main.ts +0 -70
  102. package/systems/web/server/mentions.ts +0 -111
  103. package/systems/web/server/problem.ts +0 -72
  104. package/systems/web/server/renderer.ts +0 -243
  105. package/systems/web/server/robots.ts +0 -75
  106. package/systems/web/server/searches.ts +0 -29
  107. package/systems/web/server/tavily.ts +0 -144
  108. package/systems/web/server/testing.ts +0 -165
  109. package/systems/web/server/uploads.ts +0 -33
  110. package/systems/web/shared/index.ts +0 -343
  111. package/systems/web/shared/urls.ts +0 -60
  112. package/systems/web/system.json +0 -15
  113. package/systems/web/tsconfig.json +0 -6
@@ -1,112 +0,0 @@
1
- /**
2
- * A scripted Claude for tests: no process, no model, no credits. Each opened session records what it was sent and
3
- * told, and a test drives it through its listener as Claude would: `emit` an event, `permit` a tool use or `question`
4
- * a question (each resolves with what the person decided). Claude's store is a list the test fills.
5
- */
6
- import type { ClaudePermissionMode, ClaudeSessionId, ClaudeTranscriptItem } from '../shared/session.ts';
7
- import { sliceOf, type ClaudeDriver, type DriverEvent, type DriverOpen, type DriverPage, type FoundImportable, type LiveSession, type PermitDecision, type PermitRequest, type QuestionReply, type QuestionRequest, type SessionListener, type StoredSession, type TranscriptRequest, type TranscriptSlice } from './driver.ts';
8
-
9
- /** One session the fake opened, and what happened to it. */
10
- export class FakeSession implements LiveSession {
11
- readonly open: DriverOpen;
12
- readonly sent: string[] = [];
13
- readonly modes: ClaudePermissionMode[] = [];
14
- interrupts = 0;
15
- closed = false;
16
- readonly #listener: SessionListener;
17
- readonly #aborts = new Set<AbortController>();
18
-
19
- constructor(open: DriverOpen, listener: SessionListener) {
20
- this.open = open;
21
- this.#listener = listener;
22
- }
23
-
24
- send(text: string): void { this.sent.push(text); }
25
-
26
- interrupt(): Promise<void> {
27
- this.interrupts += 1;
28
- // as Claude does: what the turn waited on is withdrawn
29
- for (const abort of this.#aborts) { abort.abort(); }
30
- return Promise.resolve();
31
- }
32
-
33
- setMode(mode: ClaudePermissionMode): Promise<void> {
34
- this.modes.push(mode);
35
- return Promise.resolve();
36
- }
37
-
38
- close(): void { this.closed = true; }
39
-
40
- /** Report something, as Claude would. */
41
- emit(event: DriverEvent): void { this.#listener.event(event); }
42
-
43
- /** Ask for a tool use, as Claude's `canUseTool` would. */
44
- permit(request: PermitRequest): Promise<PermitDecision> {
45
- return this.#asking((signal) => this.#listener.permit(request, signal));
46
- }
47
-
48
- /** Ask a question, as `AskUserQuestion` or an elicitation would. */
49
- question(request: QuestionRequest): Promise<QuestionReply> {
50
- return this.#asking((signal) => this.#listener.question(request, signal));
51
- }
52
-
53
- async #asking<T>(ask: (signal: AbortSignal) => Promise<T>): Promise<T> {
54
- const abort = new AbortController();
55
- this.#aborts.add(abort);
56
- try {
57
- return await ask(abort.signal);
58
- } finally {
59
- this.#aborts.delete(abort);
60
- }
61
- }
62
- }
63
-
64
- /** The scripted driver. */
65
- export class FakeClaudeDriver implements ClaudeDriver {
66
- readonly opened: FakeSession[] = [];
67
- /** Claude's store, newest first. */
68
- readonly stored: StoredSession[] = [];
69
- /** Transcripts by session (or `session/agent`). */
70
- readonly transcripts = new Map<string, ClaudeTranscriptItem[]>();
71
- /** What `importables` finds in every folder. */
72
- found: FoundImportable[] = [];
73
- /** Skill texts by name. */
74
- readonly skills = new Map<string, string>();
75
-
76
- /** The last session opened with this id. */
77
- live(session: ClaudeSessionId): FakeSession {
78
- const found = this.opened.findLast((s) => s.open.session === session);
79
- if (found === undefined) { throw new Error(`no session ${session} was opened`); }
80
- return found;
81
- }
82
-
83
- open(open: DriverOpen, listener: SessionListener): LiveSession {
84
- const session = new FakeSession(open, listener);
85
- this.opened.push(session);
86
- return session;
87
- }
88
-
89
- sessions(query: { readonly folder?: string | undefined; readonly offset: number; readonly limit: number }): Promise<DriverPage<StoredSession>> {
90
- const all = this.stored.filter((s) => query.folder === undefined || s.folder === query.folder);
91
- return Promise.resolve({ items: all.slice(query.offset, query.offset + query.limit), more: all.length > query.offset + query.limit });
92
- }
93
-
94
- session(session: ClaudeSessionId): Promise<StoredSession | undefined> {
95
- return Promise.resolve(this.stored.find((s) => s.session === session));
96
- }
97
-
98
- /** Each scripted item stands for one stored message. */
99
- transcript(query: TranscriptRequest): Promise<TranscriptSlice> {
100
- const all = this.transcripts.get(query.agent === undefined ? query.session : `${query.session}/${query.agent}`) ?? [];
101
- const { start, end } = sliceOf(all.length, query);
102
- return Promise.resolve({ items: all.slice(start, end), offset: start, end, more: end < all.length });
103
- }
104
-
105
- importables(): Promise<FoundImportable[]> {
106
- return Promise.resolve(this.found);
107
- }
108
-
109
- skillText(name: string): Promise<string | undefined> {
110
- return Promise.resolve(this.skills.get(name));
111
- }
112
- }
@@ -1,376 +0,0 @@
1
- /**
2
- * The live sessions of one claude instance (process state, like the database system's waiting changes): their
3
- * handles, the requests they wait on, and the record each is mirrored as. What a session reports updates its
4
- * `ClaudeSession` value, which is written to its hub record a debounce later. A tool use or a question becomes a
5
- * proposed run (`permit` / `answer`) for the session's person, and the request waits in `#waiting` until that run is
6
- * approved (its fn calls `settle`) or declined (the run event calls `declined`). Nothing here survives a restart: the
7
- * requests are gone and their runs fail plainly; the sessions stay in Claude's store, resumable.
8
- */
9
- import { randomUUID } from 'node:crypto';
10
- import { proposalKeyFor, type ApprovalPreview, type GinTypeDef, type Json, type RecordId, type RunId, type SessionId } from '@harness/core';
11
- import type { ClaudePermissionMode, ClaudeSession, ClaudeSessionId, ClaudeTask } from '../shared/session.ts';
12
- import { g, wireType, type Log } from '@harness/sdk';
13
- import type { ClaudeDriver, DriverEvent, DriverOpen, LiveSession, PermitDecision, PermitRequest, QuestionReply, SessionListener, TaskChange } from './driver.ts';
14
- import { permitPreview, questionPreview } from './preview.ts';
15
-
16
- /** A run the fleet proposes for a session's person. */
17
- export interface Proposal {
18
- readonly fn: 'permit' | 'answer';
19
- readonly args: Json;
20
- readonly key: string;
21
- readonly preview: ApprovalPreview;
22
- readonly for: ClaudeSession['owner'];
23
- readonly chat?: SessionId | undefined;
24
- /** The form the person fills; its value becomes `args[into]`. */
25
- readonly ask?: { readonly type: GinTypeDef; readonly into: string } | undefined;
26
- }
27
-
28
- /** What the fleet needs of the hub, outside any run. */
29
- export interface FleetHub {
30
- /** Write a session's record (it keeps its owner). */
31
- saveSession(id: RecordId, value: ClaudeSession): Promise<void>;
32
- /** Propose a run for a person; resolves with the run. */
33
- propose(proposal: Proposal): Promise<RunId>;
34
- }
35
-
36
- /** The fleet's tunables (from the env slice) and its clock. */
37
- export interface FleetOptions {
38
- readonly instance: string;
39
- readonly debounce: number;
40
- readonly lastTextMax: number;
41
- readonly previewMax: number;
42
- readonly now: () => number;
43
- readonly log: Log;
44
- }
45
-
46
- /** How a turn a run waits on ended. */
47
- export type TurnEnd = { readonly ok: boolean; readonly text: string; readonly costUsd: number } | { readonly ended: true; readonly problem?: string | undefined };
48
-
49
- /** A request a session waits on. */
50
- type Waiting =
51
- | { readonly kind: 'permit'; readonly session: ClaudeSessionId; run?: RunId; key?: string; readonly resolve: (decision: PermitDecision) => void }
52
- | { readonly kind: 'answer'; readonly session: ClaudeSessionId; run?: RunId; key?: string; readonly resolve: (reply: QuestionReply) => void };
53
-
54
- /** One live session. */
55
- interface Entry {
56
- readonly record: RecordId;
57
- value: ClaudeSession;
58
- readonly handle: LiveSession;
59
- readonly turnWaiters: Set<(end: TurnEnd) => void>;
60
- readonly watchers: Set<(line: string) => void>;
61
- idleClose: number;
62
- writeTimer?: NodeJS.Timeout | undefined;
63
- idleTimer?: NodeJS.Timeout | undefined;
64
- }
65
-
66
- /** What `settle` says when the request is gone. */
67
- export const NOT_WAITING = 'This request is no longer waiting: the session ended, Claude withdrew it, or the claude system restarted.';
68
-
69
- export class SessionFleet {
70
- readonly #driver: ClaudeDriver;
71
- readonly #hub: () => FleetHub | undefined;
72
- readonly #options: FleetOptions;
73
- readonly #live = new Map<ClaudeSessionId, Entry>();
74
- readonly #waiting = new Map<string, Waiting>();
75
- readonly #byRun = new Map<RunId, string>();
76
-
77
- constructor(driver: ClaudeDriver, hub: () => FleetHub | undefined, options: FleetOptions) {
78
- this.#driver = driver;
79
- this.#hub = hub;
80
- this.#options = options;
81
- }
82
-
83
- /** How many sessions are live. */
84
- get size(): number { return this.#live.size; }
85
-
86
- /** A live session's current value, or `undefined` when it isn't live. */
87
- value(session: ClaudeSessionId): ClaudeSession | undefined {
88
- return this.#live.get(session)?.value;
89
- }
90
-
91
- /** Whether a session is live here. */
92
- isLive(session: ClaudeSessionId): boolean {
93
- return this.#live.has(session);
94
- }
95
-
96
- /**
97
- * Make a session live: start (or resume) it with the driver, mirrored as `record`, and send `prompt` as its first
98
- * message. A live session with nothing to do closes after `idleClose` ms.
99
- */
100
- open(record: RecordId, value: ClaudeSession, open: DriverOpen, prompt: string, idleClose: number): void {
101
- const listener = this.#listener(open.session);
102
- const entry: Entry = { record, value: { ...value, status: 'working' }, handle: this.#driver.open(open, listener), turnWaiters: new Set(), watchers: new Set(), idleClose };
103
- this.#live.set(open.session, entry);
104
- entry.handle.send(prompt);
105
- this.#write(entry);
106
- }
107
-
108
- /** Queue a message to a live session; it is working until the turn ends. */
109
- send(session: ClaudeSessionId, text: string): boolean {
110
- const entry = this.#live.get(session);
111
- if (entry === undefined) { return false; }
112
- clearTimeout(entry.idleTimer);
113
- entry.handle.send(text);
114
- this.#change(entry, { status: this.#busy(session) ? 'waiting' : 'working' });
115
- return true;
116
- }
117
-
118
- /**
119
- * Wait for the session's current turn to end, reporting each tool use and task line to `progress`. Resolves early
120
- * with `ended` when the session ends, and with the turn so far when `signal` aborts (the run was cancelled).
121
- */
122
- turn(session: ClaudeSessionId, progress: (line: string) => void, signal: AbortSignal): Promise<TurnEnd> {
123
- const entry = this.#live.get(session);
124
- if (entry === undefined) { return Promise.resolve({ ended: true }); }
125
- return new Promise((resolve) => {
126
- const done = (end: TurnEnd) => {
127
- entry.turnWaiters.delete(done);
128
- entry.watchers.delete(progress);
129
- signal.removeEventListener('abort', aborted);
130
- resolve(end);
131
- };
132
- const aborted = () => { done({ ok: false, text: entry.value.lastText ?? '', costUsd: entry.value.costUsd }); };
133
- entry.turnWaiters.add(done);
134
- entry.watchers.add(progress);
135
- signal.addEventListener('abort', aborted, { once: true });
136
- });
137
- }
138
-
139
- /** Stop the current turn of a live session. */
140
- async interrupt(session: ClaudeSessionId): Promise<boolean> {
141
- const entry = this.#live.get(session);
142
- if (entry === undefined) { return false; }
143
- await entry.handle.interrupt();
144
- return true;
145
- }
146
-
147
- /** Switch a live session's permission mode. */
148
- async setMode(session: ClaudeSessionId, mode: ClaudePermissionMode): Promise<boolean> {
149
- const entry = this.#live.get(session);
150
- if (entry === undefined) { return false; }
151
- await entry.handle.setMode(mode);
152
- this.#change(entry, { permissionMode: mode });
153
- return true;
154
- }
155
-
156
- /** Close a live session (it stays resumable); its waiting requests are withdrawn. */
157
- stop(session: ClaudeSessionId): boolean {
158
- const entry = this.#live.get(session);
159
- if (entry === undefined) { return false; }
160
- entry.handle.close();
161
- this.#end(session, entry, undefined);
162
- return true;
163
- }
164
-
165
- /** Close every live session (the process is stopping) and write their records now. */
166
- async stopAll(): Promise<void> {
167
- const writes = [...this.#live.entries()].map(([session, entry]) => {
168
- entry.handle.close();
169
- this.#end(session, entry, undefined);
170
- return this.#flush(entry);
171
- });
172
- await Promise.all(writes);
173
- }
174
-
175
- /**
176
- * The approved run of a waiting tool use of `session`: let Claude use it. False when the request is gone, or when
177
- * `run` is not the run proposed for it (a direct call never is, so nobody settles another person's request).
178
- */
179
- permit(session: ClaudeSessionId, request: string, run: RunId, always: boolean): boolean {
180
- if (!this.#waitingOf(session, request, 'permit', run)) { return false; }
181
- const waiting = this.#take(request);
182
- if (waiting?.kind !== 'permit') { return false; }
183
- waiting.resolve({ allow: true, always });
184
- return true;
185
- }
186
-
187
- /** The approved run of a waiting question of `session`, with the person's answer. False as `permit` is. */
188
- answer(session: ClaudeSessionId, request: string, run: RunId, answer: Json): boolean {
189
- if (!this.#waitingOf(session, request, 'answer', run)) { return false; }
190
- const waiting = this.#take(request);
191
- if (waiting?.kind !== 'answer') { return false; }
192
- waiting.resolve({ answer });
193
- return true;
194
- }
195
-
196
- /** A proposed run settled without running (declined, or cancelled): deny or decline what it stood for. */
197
- declined(run: RunId, reason: string): void {
198
- const request = this.#byRun.get(run);
199
- const waiting = request === undefined ? undefined : this.#take(request);
200
- if (waiting === undefined) { return; }
201
- if (waiting.kind === 'permit') { waiting.resolve({ allow: false, reason }); } else { waiting.resolve({ declined: reason }); }
202
- }
203
-
204
- #listener(session: ClaudeSessionId): SessionListener {
205
- return {
206
- event: (event) => { this.#event(session, event); },
207
- permit: (request, signal) => new Promise<PermitDecision>((resolve) => {
208
- this.#ask(session, { kind: 'permit', session, resolve }, (entry, id, key) => ({
209
- fn: 'permit', key, preview: permitPreview(request, this.#options.previewMax),
210
- args: { instance: this.#options.instance, session, request: id, tool: request.tool, input: request.input, always: false },
211
- for: entry.value.owner, chat: entry.value.chat, ask: alwaysAsk(request),
212
- }), signal, (reason) => { resolve({ allow: false, reason }); });
213
- }),
214
- question: (request, signal) => new Promise<QuestionReply>((resolve) => {
215
- this.#ask(session, { kind: 'answer', session, resolve }, (entry, id, key) => ({
216
- fn: 'answer', key, preview: questionPreview(request),
217
- args: { instance: this.#options.instance, session, request: id, from: request.from, answer: null },
218
- for: entry.value.owner, chat: entry.value.chat, ...(request.form === undefined ? {} : { ask: { type: request.form, into: 'answer' } }),
219
- }), signal, (reason) => { resolve({ declined: reason }); });
220
- }),
221
- };
222
- }
223
-
224
- /** Propose the run a request waits on, and keep the request until it is answered, declined or withdrawn. */
225
- #ask(session: ClaudeSessionId, waiting: Waiting, proposal: (entry: Entry, id: string, key: string) => Proposal, signal: AbortSignal, refuse: (reason: string) => void): void {
226
- const entry = this.#live.get(session);
227
- const hub = this.#hub();
228
- if (entry === undefined || hub === undefined) { refuse('The harness is not connected, so nobody can be asked.'); return; }
229
- const id = randomUUID();
230
- this.#waiting.set(id, waiting);
231
- signal.addEventListener('abort', () => {
232
- // Claude withdrew it (an interrupt): the card's run then finds nothing to answer
233
- if (this.#take(id) !== undefined) { refuse('Claude withdrew the request.'); }
234
- }, { once: true });
235
- // the key starts with the session's record: the hub accepts a proposal for the owner of that record only
236
- const key = proposalKeyFor(entry.record, `${waiting.kind}:${id}`);
237
- waiting.key = key;
238
- this.#change(entry, { asking: [...entry.value.asking, key] });
239
- const made = proposal(entry, id, key);
240
- hub.propose(made).then((run) => {
241
- if (!this.#waiting.has(id)) { return; }
242
- waiting.run = run;
243
- this.#byRun.set(run, id);
244
- this.#change(entry, { status: 'waiting', waiting: [...entry.value.waiting, run] });
245
- }).catch((error: unknown) => {
246
- this.#options.log.warn('claude.propose_failed', { session, problem: String(error) });
247
- if (this.#take(id) !== undefined) { refuse(`The person could not be asked: ${String(error)}`); }
248
- });
249
- }
250
-
251
- /** Take a waiting request out, and its run off its session's record. */
252
- #take(request: string): Waiting | undefined {
253
- const waiting = this.#waiting.get(request);
254
- if (waiting === undefined) { return undefined; }
255
- this.#waiting.delete(request);
256
- const run = waiting.run;
257
- if (run !== undefined) { this.#byRun.delete(run); }
258
- const entry = this.#live.get(waiting.session);
259
- if (entry !== undefined) {
260
- const left = entry.value.waiting.filter((r) => r !== run);
261
- const status = left.length > 0 ? 'waiting' : entry.value.status === 'waiting' ? 'working' : entry.value.status;
262
- this.#change(entry, { waiting: left, asking: entry.value.asking.filter((key) => key !== waiting.key), status });
263
- }
264
- return waiting;
265
- }
266
-
267
- /** Whether `request` is a request of this kind that `session` waits on, and `run` the run proposed for it. */
268
- #waitingOf(session: ClaudeSessionId, request: string, kind: Waiting['kind'], run: RunId): boolean {
269
- const waiting = this.#waiting.get(request);
270
- return waiting?.session === session && waiting.kind === kind && waiting.run === run;
271
- }
272
-
273
- /** Whether a session has requests waiting. */
274
- #busy(session: ClaudeSessionId): boolean {
275
- return [...this.#waiting.values()].some((waiting) => waiting.session === session);
276
- }
277
-
278
- #event(session: ClaudeSessionId, event: DriverEvent): void {
279
- const entry = this.#live.get(session);
280
- if (entry === undefined) { return; }
281
- switch (event.type) {
282
- case 'text':
283
- this.#change(entry, { lastText: oneLine(event.text, this.#options.lastTextMax) });
284
- return;
285
- case 'tool':
286
- for (const watcher of entry.watchers) { watcher(event.line); }
287
- return;
288
- case 'task': {
289
- const task = mergeTask(entry.value.tasks.find((t) => t.id === event.change.id), event.change, this.#options.now());
290
- for (const watcher of entry.watchers) { watcher(`${task.name ?? task.kind}: ${task.progress ?? task.description} (${task.status})`); }
291
- this.#change(entry, { tasks: [...entry.value.tasks.filter((t) => t.id !== task.id), task] });
292
- return;
293
- }
294
- case 'result': {
295
- const end: TurnEnd = { ok: event.ok, text: event.text, costUsd: event.costUsd };
296
- this.#change(entry, {
297
- status: this.#busy(session) ? 'waiting' : 'idle', turns: event.turns, costUsd: event.costUsd,
298
- ...(event.text === '' ? {} : { lastText: oneLine(event.text, this.#options.lastTextMax) }),
299
- ...(event.ok ? { problem: undefined } : { problem: oneLine(event.text, this.#options.lastTextMax) }),
300
- });
301
- for (const waiter of [...entry.turnWaiters]) { waiter(end); }
302
- clearTimeout(entry.idleTimer);
303
- entry.idleTimer = setTimeout(() => { this.stop(session); }, entry.idleClose);
304
- return;
305
- }
306
- case 'ended':
307
- this.#end(session, entry, event.problem);
308
- return;
309
- }
310
- }
311
-
312
- /** A session is no longer live: closed or failed, its requests withdrawn and its waiters told. */
313
- #end(session: ClaudeSessionId, entry: Entry, problem: string | undefined): void {
314
- if (this.#live.get(session) !== entry) { return; }
315
- this.#live.delete(session);
316
- clearTimeout(entry.idleTimer);
317
- for (const [id, waiting] of [...this.#waiting.entries()]) {
318
- if (waiting.session !== session) { continue; }
319
- this.#take(id);
320
- if (waiting.kind === 'permit') { waiting.resolve({ allow: false, reason: 'The session ended.' }); } else { waiting.resolve({ declined: 'The session ended.' }); }
321
- }
322
- this.#change(entry, { status: problem === undefined ? 'closed' : 'failed', waiting: [], asking: [], ...(problem === undefined ? {} : { problem }) });
323
- for (const waiter of [...entry.turnWaiters]) { waiter({ ended: true, problem }); }
324
- }
325
-
326
- #change(entry: Entry, patch: Partial<ClaudeSession>): void {
327
- const next: ClaudeSession = { ...entry.value, ...patch, updatedAt: this.#options.now() };
328
- if (patch.problem === undefined && 'problem' in patch) { delete next.problem; }
329
- entry.value = next;
330
- this.#write(entry);
331
- }
332
-
333
- /** Write the record a debounce from now, once for every change meanwhile. */
334
- #write(entry: Entry): void {
335
- if (entry.writeTimer !== undefined) { return; }
336
- entry.writeTimer = setTimeout(() => { void this.#flush(entry); }, this.#options.debounce);
337
- }
338
-
339
- async #flush(entry: Entry): Promise<void> {
340
- clearTimeout(entry.writeTimer);
341
- entry.writeTimer = undefined;
342
- const hub = this.#hub();
343
- if (hub === undefined) { return; }
344
- try {
345
- await hub.saveSession(entry.record, entry.value);
346
- } catch (error) {
347
- this.#options.log.warn('claude.record_failed', { session: entry.value.session, record: entry.record, problem: String(error) });
348
- }
349
- }
350
- }
351
-
352
- /** The "always allow" choice on a tool use's card, when Claude suggested a rule for it: optional, so Approve alone allows it once. */
353
- function alwaysAsk(request: PermitRequest): Proposal['ask'] {
354
- if (!request.canAlways) { return undefined; }
355
- return { type: wireType(g.optional(g.bool())), into: 'always' };
356
- }
357
-
358
- /** A task with a change applied; a new one starts now. */
359
- export function mergeTask(current: ClaudeTask | undefined, change: TaskChange, now: number): ClaudeTask {
360
- const base: ClaudeTask = current ?? { id: change.id, kind: 'other', description: '', status: 'running', startedAt: now, updatedAt: now };
361
- const merged: ClaudeTask = { ...base, updatedAt: now };
362
- if (change.kind !== undefined) { merged.kind = change.kind; }
363
- if (change.name !== undefined) { merged.name = change.name; }
364
- if (change.description !== undefined) { merged.description = change.description; }
365
- if (change.status !== undefined) { merged.status = change.status; }
366
- if (change.progress !== undefined) { merged.progress = change.progress; }
367
- if (change.parent !== undefined) { merged.parent = change.parent; }
368
- return merged;
369
- }
370
-
371
- /** Text as one line of at most `max` characters. */
372
- export function oneLine(text: string, max: number): string {
373
- const line = text.replace(/\s+/g, ' ').trim();
374
- return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
375
- }
376
-