@llm4ts/shell 4.8.0 → 4.9.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.
@@ -0,0 +1,670 @@
1
+ // @internal: the chat loop behind `llm4ts chat`, run only by that verb
2
+ import { join } from "node:path";
3
+ import * as Cause from "effect/Cause";
4
+ import * as Duration from "effect/Duration";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Option from "effect/Option";
7
+ import * as Ref from "effect/Ref";
8
+ import * as Schema from "effect/Schema";
9
+ import { ChiefAction, ChiefContext, failedReply, maxReplyChars } from "@llm4ts/flow/ChiefAction";
10
+ import { describeFlowError } from "@llm4ts/flow/FlowError";
11
+ import { GwsLoginRequired } from "@llm4ts/flow/GoogleChatTool";
12
+ import { RunInProgress } from "@llm4ts/flow/OperatorSchemas";
13
+ import { defaultPlanPath, parsePlan } from "@llm4ts/flow/Plan";
14
+ import { emptyTree } from "@llm4ts/runner/AgentTree";
15
+ import { plainProgressLine, summarizeTree } from "@llm4ts/runner/RunSummary";
16
+ import { ChatRequest, ChatState, chatDir, loadRequests, loadState, notePosted, putRequest, saveState } from "./ChatState.js";
17
+ import { validateKnobs } from "./OperatorActTools.js";
18
+ import { discoveredRuns, transcriptsDir } from "./OperatorRuns.js";
19
+ import { foldTrace, meaningfulEventsAfter, runDiagnosisOf, runStatusOf } from "./RunReaders.js";
20
+ export const strangerReply = "Only the person who started me, or people they allowed, can ask me to do things here.";
21
+ export const helpReply = (options) => `Ask me about runs, or tell me to start one. Example: ${options.trigger} what is running? I may start: ${options.flows.join(", ")}.`;
22
+ // Chat's RFC 3339 times vary in fraction digits, so spelling order is not time order.
23
+ const timeKey = (time) => {
24
+ const ms = Date.parse(time);
25
+ const fraction = /\.(\d+)/u.exec(time)?.[1] ?? "";
26
+ return [Number.isNaN(ms) ? Number.NEGATIVE_INFINITY : ms, fraction.padEnd(9, "0")];
27
+ };
28
+ const isLater = (a, b) => {
29
+ const [aMs, aFraction] = timeKey(a);
30
+ const [bMs, bFraction] = timeKey(b);
31
+ return aMs !== bMs ? aMs > bMs : aFraction > bFraction;
32
+ };
33
+ /** The text after the trigger, or undefined when the trigger is not a whole word at the start. */
34
+ const bodyAfter = (text, trigger) => {
35
+ if (!text.startsWith(trigger))
36
+ return undefined;
37
+ const rest = text.slice(trigger.length);
38
+ return rest === "" || /^\s/u.test(rest) ? rest.trim() : undefined;
39
+ };
40
+ /**
41
+ * Which messages to act on. This decides who may start coding runs: only a
42
+ * person (`HUMAN`) who is the owner or named in `allow`, and with no owner id
43
+ * nobody at all, `allow` included. The Chief's own messages are known by
44
+ * name and by marker.
45
+ */
46
+ export const selectRequests = (state, messages, options) => {
47
+ let cursor = state.cursor;
48
+ const selected = [];
49
+ const posted = new Set(state.posted);
50
+ for (const message of messages) {
51
+ if (isLater(message.createTime, cursor))
52
+ cursor = message.createTime;
53
+ const sender = message.senderName;
54
+ if (posted.has(message.name) ||
55
+ message.text.startsWith(state.marker) ||
56
+ message.senderType !== "HUMAN" ||
57
+ sender === undefined ||
58
+ message.text.trim() === "") {
59
+ continue;
60
+ }
61
+ const body = bodyAfter(message.text, options.trigger);
62
+ if (body === undefined)
63
+ continue;
64
+ const allowed = state.ownerId !== undefined && (sender === state.ownerId || options.allow.includes(sender));
65
+ if (!allowed)
66
+ selected.push({ _tag: "Stranger", message });
67
+ else if (body === "")
68
+ selected.push({ _tag: "Help", message });
69
+ else
70
+ selected.push({ _tag: "Request", message, body });
71
+ }
72
+ return { selected, cursor };
73
+ };
74
+ // ---- Paths ---------------------------------------------------------------------------------
75
+ /** The last segment of a message name, safe as a file name. */
76
+ const messageId = (messageName) => {
77
+ const last = messageName.split("/").pop() ?? "";
78
+ const safe = last.replace(/[^A-Za-z0-9._-]/gu, "_");
79
+ return safe === "" || safe === "." || safe === ".." ? "_" : safe;
80
+ };
81
+ const pendingPath = (dir, messageName) => join(dir, "pending", `${messageId(messageName)}.json`);
82
+ const actionPath = (dir, messageName) => join(dir, "actions", `${messageId(messageName)}.json`);
83
+ const dirOf = (deps) => chatDir(deps.repo.path, deps.options.space.id);
84
+ // ---- The Chief's context -------------------------------------------------------------------
85
+ const runLimit = 20;
86
+ const recentLimit = 5;
87
+ const diagnosisBudget = 4_000;
88
+ const emptyFold = () => ({ lines: [], state: emptyTree(), seq: 0 });
89
+ const foldOf = (deps, run) => run.tracePath === undefined
90
+ ? Effect.succeed(emptyFold())
91
+ : foldTrace(deps.files, run.tracePath).pipe(Effect.catch(() => Effect.succeed(emptyFold())));
92
+ /** The repository's runs, newest first, without the Chief's own. */
93
+ const summarisedRuns = (deps) => Effect.gen(function* () {
94
+ const supervised = yield* deps.supervisor.list(deps.repo.id);
95
+ const disk = {
96
+ files: deps.files,
97
+ listTraces: deps.listTraces,
98
+ listEpics: deps.listEpics
99
+ };
100
+ const discovered = yield* discoveredRuns(disk, deps.repo, new Set(supervised.map((run) => run.runId)));
101
+ const now = yield* deps.now;
102
+ const runs = [...supervised, ...discovered]
103
+ .filter((run) => run.flow !== "chief")
104
+ .sort((a, b) => b.startedAt - a.startedAt)
105
+ .slice(0, runLimit);
106
+ return yield* Effect.forEach(runs, (run) => Effect.map(foldOf(deps, run), (fold) => {
107
+ const status = runStatusOf(fold, run, now);
108
+ return {
109
+ run,
110
+ state: status.ended ?? run.state,
111
+ summary: status.summary,
112
+ failed: status.ended === "failed" ||
113
+ (run.state === "exited" && run.exitCode !== undefined && run.exitCode !== 0)
114
+ };
115
+ }));
116
+ });
117
+ const diagnosisOf = (deps, run) => {
118
+ const tracePath = run.tracePath;
119
+ if (tracePath === undefined)
120
+ return Effect.succeed(undefined);
121
+ const task = run.knobs.task;
122
+ return runDiagnosisOf(deps.sources, {
123
+ runId: run.runId,
124
+ tracePath,
125
+ planPath: task === undefined ? undefined : join(deps.repo.path, defaultPlanPath(task)),
126
+ transcriptsDir: transcriptsDir(deps.repo, run.runId),
127
+ gateLogDir: undefined,
128
+ budget: diagnosisBudget
129
+ }).pipe(Effect.map((diagnosis) => [
130
+ `Run ${diagnosis.runId}`,
131
+ ...(diagnosis.failure === undefined
132
+ ? []
133
+ : [
134
+ `Failure: ${diagnosis.failure.stage === undefined ? "" : `${diagnosis.failure.stage}: `}${diagnosis.failure.message}`
135
+ ]),
136
+ diagnosis.digest,
137
+ ...diagnosis.transcriptTail
138
+ ]
139
+ .filter((line) => line.length > 0)
140
+ .join("\n")), Effect.catch(() => Effect.succeed(undefined)));
141
+ };
142
+ const requestLine = (request) => `${request.sender}: ${request.text} → ${request.status}${request.runId === undefined ? "" : ` (${request.runId})`}`;
143
+ const contextFor = (deps, message, body, sender) => Effect.gen(function* () {
144
+ const allowed = (yield* deps.flows).filter((flow) => deps.options.flows.includes(flow.name));
145
+ const runs = yield* summarisedRuns(deps);
146
+ const newestFailed = runs.find((entry) => entry.failed);
147
+ const diagnosis = newestFailed === undefined ? undefined : yield* diagnosisOf(deps, newestFailed.run);
148
+ const recent = (yield* loadRequests(deps.files, dirOf(deps)))
149
+ .filter((request) => request.messageName !== message.name)
150
+ .slice(-recentLimit)
151
+ .map(requestLine);
152
+ return ChiefContext.make({
153
+ messageName: message.name,
154
+ actionPath: actionPath(dirOf(deps), message.name),
155
+ request: { text: body, sender },
156
+ flows: allowed.map((flow) => ({ name: flow.name, description: flow.description })),
157
+ runs: runs.map((entry) => ({
158
+ runId: entry.run.runId,
159
+ flow: entry.run.flow,
160
+ state: entry.state,
161
+ summary: entry.summary
162
+ })),
163
+ ...(diagnosis === undefined ? {} : { diagnosis }),
164
+ recent
165
+ });
166
+ });
167
+ // ---- Acting --------------------------------------------------------------------------------
168
+ /** Flows that stop for a human between rounds unless told not to; nobody answers from chat. */
169
+ const pausingFlows = new Set(["roundtable", "taskforce"]);
170
+ const isActive = (run) => run.state === "starting" || run.state === "running";
171
+ const busyReply = (run) => `${run.flow} is already running (${run.runId}). Wait for it, or ask me to stop it.`;
172
+ const startRun = (deps, state, message, action) => Effect.gen(function* () {
173
+ const flow = (yield* deps.flows).find((candidate) => candidate.name === action.flow);
174
+ if (flow === undefined || !deps.options.flows.includes(action.flow)) {
175
+ return {
176
+ status: "refused",
177
+ reply: `I may not start ${action.flow} here. I may start: ${deps.options.flows.join(", ")}.`
178
+ };
179
+ }
180
+ const knobs = {
181
+ task: action.task,
182
+ requestId: message.name,
183
+ ...(pausingFlows.has(action.flow) ? { flags: ["--no-pause"] } : {})
184
+ };
185
+ const valid = yield* validateKnobs(knobs).pipe(Effect.result);
186
+ if (valid._tag === "Failure") {
187
+ return {
188
+ status: "refused",
189
+ reply: `I can't start that: ${valid.failure.message}.`
190
+ };
191
+ }
192
+ const runs = yield* deps.supervisor.list(deps.repo.id);
193
+ // A replayed request: its run exists, so git and the supervisor stay untouched.
194
+ const already = runs.find((run) => run.requestId === message.name);
195
+ if (already !== undefined) {
196
+ return {
197
+ status: "started",
198
+ reply: `${action.reply} (run ${already.runId})`,
199
+ runId: already.runId
200
+ };
201
+ }
202
+ // The checkout below would pull the tree from under a run that is working in it.
203
+ const busy = runs.find((run) => isActive(run) && run.flow !== "chief");
204
+ if (busy !== undefined) {
205
+ return { status: "refused", reply: busyReply(busy), runId: busy.runId };
206
+ }
207
+ const dirty = yield* deps.git.uncommittedFiles;
208
+ if (dirty.length > 0) {
209
+ return {
210
+ status: "refused",
211
+ reply: `I can't start ${action.flow}: the repository has ${dirty.length} uncommitted file${dirty.length === 1 ? "" : "s"}. Commit or stash them first.`
212
+ };
213
+ }
214
+ yield* deps.git.checkout(state.baseBranch);
215
+ const started = yield* deps.supervisor
216
+ .start({
217
+ repo: deps.repo,
218
+ flow: { name: flow.name, path: flow.path },
219
+ knobs: valid.success,
220
+ baseEnvironment: deps.environment
221
+ })
222
+ .pipe(Effect.result);
223
+ if (started._tag === "Failure") {
224
+ const error = started.failure;
225
+ if (error instanceof RunInProgress) {
226
+ const running = yield* deps.supervisor.get(error.runId);
227
+ return {
228
+ status: "refused",
229
+ reply: busyReply({ flow: running?.flow ?? "A run", runId: error.runId }),
230
+ runId: error.runId
231
+ };
232
+ }
233
+ return yield* Effect.fail(error);
234
+ }
235
+ return {
236
+ status: "started",
237
+ reply: `${action.reply} (run ${started.success.runId})`,
238
+ runId: started.success.runId
239
+ };
240
+ });
241
+ /** The reply says what the supervisor did, not what the Chief expected it to do. */
242
+ const stopRun = (deps, runId) => Effect.gen(function* () {
243
+ const before = yield* deps.supervisor.get(runId);
244
+ if (before === undefined || !isActive(before)) {
245
+ return { status: "answered", reply: `${runId} was not running.`, runId };
246
+ }
247
+ const after = yield* deps.supervisor.stop(runId);
248
+ return {
249
+ status: "answered",
250
+ reply: isActive(after) ? `${runId} has not stopped yet.` : `Stopped ${runId}.`,
251
+ runId
252
+ };
253
+ }).pipe(Effect.catchTag("UnknownRun", () => Effect.succeed({ status: "refused", reply: `There is no run ${runId}.` })));
254
+ const act = (deps, state, message, action) => {
255
+ switch (action._tag) {
256
+ case "Answer":
257
+ return Effect.succeed({ status: "answered", reply: action.reply });
258
+ case "Decline":
259
+ return Effect.succeed({ status: "refused", reply: action.reply });
260
+ case "Failed":
261
+ return Effect.succeed({ status: "failed", reply: action.reply });
262
+ case "StopRun":
263
+ return stopRun(deps, action.runId);
264
+ case "StartRun":
265
+ return startRun(deps, state, message, action);
266
+ }
267
+ };
268
+ /** What an action would do, for the terminal under `observe`. */
269
+ const wouldDo = (action) => {
270
+ switch (action._tag) {
271
+ case "StartRun":
272
+ return [`would start ${action.flow}: ${action.task}`];
273
+ case "StopRun":
274
+ return [`would stop ${action.runId}`];
275
+ default:
276
+ return [];
277
+ }
278
+ };
279
+ // ---- One beat ------------------------------------------------------------------------------
280
+ /** Posts a reply with the marker; under `observe` tells the terminal instead and posts nothing. */
281
+ const postMarked = (deps, text, threadName) => deps.options.observe
282
+ ? Effect.as(deps.say(`would reply: ${text}`), undefined)
283
+ : deps.chat.createMessage(deps.options.space, `${deps.options.marker} ${text}`.slice(0, maxReplyChars), threadName);
284
+ const failureKind = (cause) => {
285
+ const error = Cause.findErrorOption(cause);
286
+ if (Option.isNone(error))
287
+ return "defect";
288
+ const value = error.value;
289
+ return typeof value === "object" &&
290
+ value !== null &&
291
+ "_tag" in value &&
292
+ typeof value._tag === "string"
293
+ ? value._tag
294
+ : "error";
295
+ };
296
+ const isLoginRequired = (cause) => {
297
+ const error = Cause.findErrorOption(cause);
298
+ return Option.isSome(error) && error.value instanceof GwsLoginRequired ? error.value : undefined;
299
+ };
300
+ /** A failed post told to the terminal; only a lapsed login fails. */
301
+ const sayPostFailure = (deps) => (error) => error instanceof GwsLoginRequired
302
+ ? Effect.fail(error)
303
+ : deps.say(`could not post to ${deps.options.space.name}: ${error._tag}`);
304
+ /**
305
+ * One pass: list what is new since the cursor, then handle each selected
306
+ * message in order. Only a failed list and a lapsed login end the beat, so
307
+ * the caller can back off or stop; anything else is answered or told to the
308
+ * terminal, and the cursor moves past the message either way.
309
+ */
310
+ export const handleBeat = (deps, state) => Effect.flatMap(deps.chat.listMessages(deps.options.space, state.cursor), (messages) => handleMessages(deps, state, messages));
311
+ const handleMessages = (deps, state, messages) => Effect.gen(function* () {
312
+ const { options } = deps;
313
+ const dir = dirOf(deps);
314
+ const selection = selectRequests(state, messages, options);
315
+ const current = yield* Ref.make(ChatState.make({ ...state, cursor: selection.cursor }));
316
+ const post = (text, threadName) => postMarked(deps, text, threadName).pipe(Effect.flatMap((posted) => posted === undefined
317
+ ? Effect.void
318
+ : Ref.update(current, (now) => notePosted(now, posted.name))), Effect.catch(sayPostFailure(deps)));
319
+ for (const selected of selection.selected) {
320
+ const { message } = selected;
321
+ const sender = message.senderName ?? "";
322
+ if (options.observe) {
323
+ yield* deps.say(`${options.trigger} from ${sender} (${message.senderDisplayName ?? "?"})`);
324
+ }
325
+ if (selected._tag === "Help") {
326
+ yield* post(helpReply(options), message.threadName);
327
+ continue;
328
+ }
329
+ if (selected._tag === "Stranger") {
330
+ const told = yield* Ref.get(deps.strangers);
331
+ if (told.has(sender))
332
+ continue;
333
+ yield* Ref.set(deps.strangers, new Set([...told, sender]));
334
+ yield* post(strangerReply, message.threadName);
335
+ continue;
336
+ }
337
+ const received = ChatRequest.make({
338
+ messageName: message.name,
339
+ createTime: message.createTime,
340
+ sender,
341
+ text: selected.body,
342
+ status: "received",
343
+ ...(message.threadName === undefined ? {} : { threadName: message.threadName })
344
+ });
345
+ // Not recorded is told, never retried: deciding again would post again.
346
+ const put = (request) => options.observe
347
+ ? Effect.void
348
+ : putRequest(deps.files, dir, request).pipe(Effect.catch((error) => deps.say(`could not record ${message.name}: ${error.message}`)));
349
+ const record = (outcome, action) => put(ChatRequest.make({
350
+ ...received,
351
+ status: outcome.status,
352
+ reply: outcome.reply,
353
+ ...(action === undefined ? {} : { action }),
354
+ ...(outcome.runId === undefined ? {} : { runId: outcome.runId })
355
+ }));
356
+ const handle = Effect.gen(function* () {
357
+ yield* put(received);
358
+ const context = yield* contextFor(deps, message, selected.body, message.senderDisplayName ?? sender);
359
+ const action = yield* deps.decide(context);
360
+ if (options.observe) {
361
+ for (const line of wouldDo(action))
362
+ yield* deps.say(line);
363
+ return yield* post(action.reply, message.threadName);
364
+ }
365
+ const outcome = yield* act(deps, yield* Ref.get(current), message, action);
366
+ // Recorded first: a started run whose reply fails to post is still followed.
367
+ yield* record(outcome, action._tag);
368
+ yield* post(outcome.reply, message.threadName);
369
+ });
370
+ yield* handle.pipe(Effect.catchCause((cause) => {
371
+ const login = isLoginRequired(cause);
372
+ if (login !== undefined)
373
+ return Effect.fail(login);
374
+ if (Cause.hasInterrupts(cause))
375
+ return Effect.interrupt;
376
+ const failed = { status: "failed", reply: `That failed: ${failureKind(cause)}` };
377
+ return post(failed.reply, message.threadName).pipe(Effect.andThen(record(failed)));
378
+ }));
379
+ }
380
+ return yield* Ref.get(current);
381
+ });
382
+ // ---- Deciding through the chief flow -------------------------------------------------------
383
+ const pollInterval = "500 millis";
384
+ /** How long the loop waits for one decision before it stops the chief run. */
385
+ export const decideTimeoutMs = 120_000;
386
+ const ContextJson = Schema.fromJsonString(ChiefContext);
387
+ const ActionJson = Schema.fromJsonString(ChiefAction);
388
+ const failed = { _tag: "Failed", reply: failedReply };
389
+ /** Why no decision came; told to the terminal, never posted. */
390
+ class NoDecision extends Schema.TaggedError()("NoDecision", {
391
+ message: Schema.String
392
+ }) {
393
+ }
394
+ const noDecision = (message) => NoDecision.make({ message });
395
+ const endedAs = (run) => run === undefined
396
+ ? "lost"
397
+ : `${run.state}${run.exitCode === undefined ? "" : `, exit code ${run.exitCode}`}${run.signal === undefined ? "" : `, ${run.signal}`}`;
398
+ /**
399
+ * The Chief's decision made by the bundled `chief` flow: the context goes to
400
+ * a file, the flow runs as a read-only supervised run, and its action file is
401
+ * read once it exits. Anything short of a clean exit within `decideTimeoutMs`
402
+ * and a decodable action is `Failed`, and the terminal is told why, with the
403
+ * chief run's id and where its logs are.
404
+ */
405
+ export const decideThroughFlow = (deps) => (context) => Effect.gen(function* () {
406
+ const dir = dirOf(deps);
407
+ const pending = pendingPath(dir, context.messageName);
408
+ const action = actionPath(dir, context.messageName);
409
+ const chief = (yield* deps.flows).find((flow) => flow.name === "chief");
410
+ if (chief === undefined)
411
+ return yield* noDecision("no chief flow was found");
412
+ // A file left by an earlier attempt must not pass for this decision.
413
+ yield* deps.files.remove(action);
414
+ yield* deps.files.writeAtomic(pending, Schema.encodeSync(ContextJson)(ChiefContext.make({ ...context, actionPath: action })));
415
+ const run = yield* deps.supervisor
416
+ .start({
417
+ repo: deps.repo,
418
+ flow: { name: chief.name, path: chief.path },
419
+ knobs: { task: pending },
420
+ baseEnvironment: deps.environment
421
+ })
422
+ .pipe(Effect.mapError((error) => noDecision(`the chief run could not start: ${describeFlowError(error)}`)));
423
+ const where = `chief run ${run.runId}`;
424
+ const logs = `its logs are in ${run.logDir}`;
425
+ const stopChief = Effect.ignore(deps.supervisor.stop(run.runId));
426
+ const waited = yield* Effect.gen(function* () {
427
+ let latest = run;
428
+ while (latest !== undefined && isActive(latest)) {
429
+ yield* Effect.sleep(pollInterval);
430
+ latest = yield* deps.supervisor.get(run.runId);
431
+ }
432
+ return latest;
433
+ }).pipe(Effect.timeoutOption(decideTimeoutMs), Effect.onInterrupt(() => stopChief));
434
+ if (Option.isNone(waited)) {
435
+ yield* stopChief;
436
+ return yield* noDecision(`${where} gave no decision within ${decideTimeoutMs / 1_000} s; ${logs}`);
437
+ }
438
+ const latest = waited.value;
439
+ if (latest?.state !== "exited" || latest.exitCode !== 0) {
440
+ return yield* noDecision(`${where} ended ${endedAs(latest)}; ${logs}`);
441
+ }
442
+ const text = yield* deps.files.read(action);
443
+ if (text === undefined)
444
+ return yield* noDecision(`${where} wrote no action; ${logs}`);
445
+ const decided = yield* Schema.decodeUnknownEffect(ActionJson)(text).pipe(Effect.mapError(() => noDecision(`${where} wrote an action that does not decode; ${logs}`)));
446
+ if (decided._tag === "Failed") {
447
+ yield* deps.say(`The Chief could not decide on ${context.messageName}: ${where} found no valid proposal; ${logs}`);
448
+ }
449
+ return decided;
450
+ }).pipe(Effect.catch((error) => deps
451
+ .say(`The Chief could not decide on ${context.messageName}: ${error instanceof NoDecision ? error.message : describeFlowError(error)}`)
452
+ .pipe(Effect.as(failed))));
453
+ // ---- Run updates ---------------------------------------------------------------------------
454
+ /** At most one progress line per run in this window; the ending line is never held back. */
455
+ export const throttleMs = 30_000;
456
+ export const startFollowing = (runId) => ({
457
+ runId,
458
+ seq: 0,
459
+ progress: undefined,
460
+ lastPostedAt: Number.NEGATIVE_INFINITY,
461
+ done: false
462
+ });
463
+ const outcomeOf = (run) => {
464
+ if (run === undefined)
465
+ return "lost";
466
+ if (run.state === "exited")
467
+ return run.exitCode === 0 ? "completed" : "failed";
468
+ return run.state;
469
+ };
470
+ const planProgressOf = (deps, run) => Effect.gen(function* () {
471
+ const task = run?.knobs.task;
472
+ if (task === undefined)
473
+ return undefined;
474
+ const markdown = yield* deps.files.read(join(deps.repo.path, defaultPlanPath(task)));
475
+ if (markdown === undefined)
476
+ return undefined;
477
+ const plan = yield* parsePlan(markdown);
478
+ return {
479
+ tasksTotal: plan.tasks.length,
480
+ tasksDone: plan.tasks.filter((entry) => entry.completed).length
481
+ };
482
+ }).pipe(Effect.catch(() => Effect.succeed(undefined)));
483
+ /**
484
+ * One look at a run started from chat: post what changed into the thread of
485
+ * the request that started it, at most once per `throttleMs`, and its end
486
+ * always, once. A failed post is told to the terminal and tried again next
487
+ * time; only a lapsed login fails.
488
+ */
489
+ export const followRun = (deps, state, followed) => Effect.gen(function* () {
490
+ const unchanged = { followed, state };
491
+ if (followed.done)
492
+ return unchanged;
493
+ const dir = dirOf(deps);
494
+ const request = (yield* loadRequests(deps.files, dir)).find((entry) => entry.runId === followed.runId && (entry.status === "started" || entry.status === "ended"));
495
+ if (request === undefined || request.status === "ended") {
496
+ return { followed: { ...followed, done: true }, state };
497
+ }
498
+ const run = yield* deps.supervisor.get(followed.runId);
499
+ const fold = run === undefined ? emptyFold() : yield* foldOf(deps, run);
500
+ const now = yield* deps.now;
501
+ const ended = run === undefined || !isActive(run);
502
+ const post = (text) => postMarked(deps, text, request.threadName).pipe(Effect.map((posted) => (posted === undefined ? state : notePosted(state, posted.name))), Effect.catch((error) => error instanceof GwsLoginRequired
503
+ ? Effect.fail(error)
504
+ : Effect.as(deps.say(`could not post to ${deps.options.space.name}: ${error._tag}`), undefined)));
505
+ const progress = yield* planProgressOf(deps, run);
506
+ if (ended) {
507
+ const outcome = fold.state.ended ?? outcomeOf(run);
508
+ const startedAt = fold.state.startedAt ?? run?.startedAt ?? now;
509
+ const endedAt = fold.state.ended === undefined ? now : (fold.state.now ?? now);
510
+ // The checkout is read now: on the base branch, or for a lost run, it says nothing of this run.
511
+ const current = yield* deps.git.currentBranch.pipe(Effect.option);
512
+ const branch = run === undefined || run.state === "lost"
513
+ ? Option.none()
514
+ : Option.filter(current, (name) => name !== state.baseBranch);
515
+ const commits = Option.isNone(branch)
516
+ ? Option.none()
517
+ : yield* deps.git.commitsAhead(state.baseBranch).pipe(Effect.option);
518
+ const line = plainProgressLine(followed.runId, followed.progress, {
519
+ tasksTotal: progress?.tasksTotal ?? 0,
520
+ tasksDone: progress?.tasksDone ?? 0,
521
+ ended: {
522
+ outcome,
523
+ minutes: Math.max(0, Math.floor((endedAt - startedAt) / 60_000)),
524
+ costUsd: fold.state.costUsd,
525
+ ...(Option.isSome(branch) ? { branch: branch.value } : {}),
526
+ ...(Option.isSome(commits) ? { commits: commits.value } : {})
527
+ }
528
+ });
529
+ const posted = line === undefined ? state : yield* post(line);
530
+ if (posted === undefined)
531
+ return unchanged;
532
+ // Under --observe the request stays started, so an armed session still posts its end.
533
+ if (!deps.options.observe) {
534
+ yield* putRequest(deps.files, dir, ChatRequest.make({ ...request, status: "ended", outcome }));
535
+ }
536
+ return { followed: { ...followed, seq: fold.seq, done: true }, state: posted };
537
+ }
538
+ if (now - followed.lastPostedAt < throttleMs)
539
+ return unchanged;
540
+ if (fold.state.stories.length > 0) {
541
+ if (meaningfulEventsAfter(fold.lines, followed.seq).length === 0)
542
+ return unchanged;
543
+ const posted = yield* post(`${followed.runId}: ${summarizeTree(fold.state, run?.flow)}`);
544
+ if (posted === undefined)
545
+ return unchanged;
546
+ return { followed: { ...followed, seq: fold.seq, lastPostedAt: now }, state: posted };
547
+ }
548
+ const line = progress === undefined
549
+ ? undefined
550
+ : plainProgressLine(followed.runId, followed.progress, progress);
551
+ if (line === undefined)
552
+ return unchanged;
553
+ const posted = yield* post(line);
554
+ if (posted === undefined)
555
+ return unchanged;
556
+ return { followed: { ...followed, progress, lastPostedAt: now }, state: posted };
557
+ });
558
+ // ---- Starting and the loop -----------------------------------------------------------------
559
+ export class ChatStopped extends Schema.TaggedError()("ChatStopped", {
560
+ message: Schema.String
561
+ }) {
562
+ }
563
+ const stopped = (message) => ChatStopped.make({ message });
564
+ const loginExpired = stopped("Google login expired. Run: gws auth login");
565
+ const ignoreWarning = "Warning: .llm4ts/ is not ignored by git in this repository; add it to .gitignore.";
566
+ /** A Chat failure at start as a sentence; a lapsed login is always the same one. */
567
+ const stoppedBy = (doing) => (error) => error instanceof GwsLoginRequired
568
+ ? loginExpired
569
+ : stopped(`${doing}: ${describeFlowError(error)}`);
570
+ /**
571
+ * The start checks, then the state: `gws` answers its probe, the space can be
572
+ * listed, and the reasoning seat enforces read-only. A new state starts its
573
+ * cursor now, so old `/bot` messages are not replayed. Unless `observe`, the
574
+ * Chief says it is listening, and whoever that line is posted as is the owner.
575
+ */
576
+ export const startChat = (deps) => Effect.gen(function* () {
577
+ const { options } = deps;
578
+ yield* deps.chat.probe.pipe(Effect.mapError(stoppedBy("gws is not ready")));
579
+ const now = new Date(yield* deps.now).toISOString();
580
+ yield* deps.chat
581
+ .listMessages(options.space, now)
582
+ .pipe(Effect.mapError(stoppedBy(`Cannot list messages in ${options.space.name}`)));
583
+ const problem = yield* deps.seatProblem;
584
+ if (problem !== undefined)
585
+ return yield* stopped(`The Chief cannot use its seat: ${problem}.`);
586
+ const discovered = yield* deps.flows.pipe(Effect.catchDefect((defect) => Effect.fail(stopped(`Cannot discover the flows: ${String(defect)}.`))));
587
+ const names = new Set(discovered.map((flow) => flow.name));
588
+ if (!names.has("chief")) {
589
+ return yield* stopped("There is no chief flow here, so the Chief cannot decide anything.");
590
+ }
591
+ const unknown = options.flows.filter((name) => !names.has(name));
592
+ if (unknown.length > 0) {
593
+ return yield* stopped(`--flows names ${unknown.join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not a flow here; llm4ts list shows the flows.`);
594
+ }
595
+ const dir = dirOf(deps);
596
+ const loaded = yield* loadState(deps.files, dir);
597
+ const baseBranch = loaded?.baseBranch ??
598
+ (yield* deps.git.currentBranch.pipe(Effect.mapError((error) => stopped(`Cannot read the current branch: ${describeFlowError(error)}`))));
599
+ let state = ChatState.make({
600
+ space: options.space.name,
601
+ cursor: now,
602
+ posted: [],
603
+ ...loaded,
604
+ trigger: options.trigger,
605
+ marker: options.marker,
606
+ baseBranch
607
+ });
608
+ if (!(yield* deps.ignored))
609
+ yield* deps.say(ignoreWarning);
610
+ if (!options.observe) {
611
+ const listening = yield* deps.chat
612
+ .createMessage(options.space, `${options.marker} Listening. Repository ${deps.repo.id}. I may start: ${options.flows.join(", ")}.`)
613
+ .pipe(Effect.mapError(stoppedBy(`Cannot post to ${options.space.name}`)));
614
+ if (listening.senderName === undefined) {
615
+ return yield* stopped("Chat did not say who posted the listening line, so nobody could ask.");
616
+ }
617
+ state = ChatState.make({
618
+ ...notePosted(state, listening.name),
619
+ ownerId: listening.senderName
620
+ });
621
+ }
622
+ yield* saveState(deps.files, dir, state);
623
+ return state;
624
+ });
625
+ const backoffStartMs = 1_000;
626
+ const backoffCapMs = 60_000;
627
+ /**
628
+ * `startChat`, then forever: one beat, a look at every run started from chat,
629
+ * the state saved, a sleep. A failed list backs off, and a file that cannot
630
+ * be read or written is told to the terminal; neither ends the loop, a lapsed
631
+ * login does.
632
+ */
633
+ export const runChat = (deps) => Effect.gen(function* () {
634
+ const { options } = deps;
635
+ const dir = dirOf(deps);
636
+ let state = yield* startChat(deps);
637
+ // In memory only: after a restart a run's last line may be posted once more.
638
+ const follows = new Map();
639
+ let failures = 0;
640
+ while (true) {
641
+ const beat = yield* Effect.result(handleBeat(deps, state));
642
+ if (beat._tag === "Failure") {
643
+ if (beat.failure instanceof GwsLoginRequired)
644
+ return yield* loginExpired;
645
+ failures += 1;
646
+ const wait = Math.min(backoffStartMs * 2 ** (failures - 1), backoffCapMs);
647
+ yield* deps.say(`could not list messages in ${options.space.name}: ${beat.failure._tag}; retrying in ${wait / 1_000} s`);
648
+ yield* Effect.sleep(Duration.millis(wait));
649
+ continue;
650
+ }
651
+ failures = 0;
652
+ state = beat.success;
653
+ const requests = yield* loadRequests(deps.files, dir).pipe(Effect.catch((error) => Effect.as(deps.say(`could not follow runs: ${error.message}`), [])));
654
+ for (const request of requests) {
655
+ if (request.status !== "started" || request.runId === undefined)
656
+ continue;
657
+ const step = yield* followRun(deps, state, follows.get(request.runId) ?? startFollowing(request.runId)).pipe(Effect.mapError((error) => (error instanceof GwsLoginRequired ? loginExpired : error)), Effect.catchTag("Persistence", (error) => Effect.as(deps.say(`could not follow runs: ${error.message}`), undefined)));
658
+ if (step === undefined)
659
+ continue;
660
+ state = step.state;
661
+ if (step.followed.done)
662
+ follows.delete(request.runId);
663
+ else
664
+ follows.set(request.runId, step.followed);
665
+ }
666
+ yield* saveState(deps.files, dir, state).pipe(Effect.catch((error) => deps.say(`could not save the chat state: ${error.message}`)));
667
+ yield* Effect.sleep(Duration.seconds(options.intervalSeconds));
668
+ }
669
+ });
670
+ //# sourceMappingURL=ChatLoop.js.map