@llm4ts/shell 4.8.0 → 4.10.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,981 @@
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, type FlowError, type PersistenceError } from "@llm4ts/flow/FlowError"
11
+ import type { GitToolShape } from "@llm4ts/flow/GitTool"
12
+ import {
13
+ GwsLoginRequired,
14
+ type ChatMessage,
15
+ type GoogleChatToolShape,
16
+ type SpaceRef
17
+ } from "@llm4ts/flow/GoogleChatTool"
18
+ import { RunInProgress, type OperatorKnobs, type OperatorRun } from "@llm4ts/flow/OperatorSchemas"
19
+ import type { PlainFileStoreShape } from "@llm4ts/flow/Persistence"
20
+ import { defaultPlanPath, parsePlan } from "@llm4ts/flow/Plan"
21
+ import { emptyTree } from "@llm4ts/runner/AgentTree"
22
+ import { plainProgressLine, summarizeTree, type PlainProgress } from "@llm4ts/runner/RunSummary"
23
+ import {
24
+ ChatRequest,
25
+ ChatState,
26
+ chatDir,
27
+ loadRequests,
28
+ loadState,
29
+ notePosted,
30
+ putRequest,
31
+ saveState
32
+ } from "./ChatState.ts"
33
+ import { validateKnobs } from "./OperatorActTools.ts"
34
+ import { discoveredRuns, transcriptsDir, type DiskRunDeps } from "./OperatorRuns.ts"
35
+ import {
36
+ foldTrace,
37
+ meaningfulEventsAfter,
38
+ runDiagnosisOf,
39
+ runStatusOf,
40
+ type RunSources,
41
+ type TraceFold
42
+ } from "./RunReaders.ts"
43
+ import type { RunSupervisorShape, SupervisorRepo } from "./RunSupervisor.ts"
44
+
45
+ /**
46
+ * The chat loop (`llm4ts chat`): one beat lists the space's new messages,
47
+ * keeps the `/bot` requests of allowed people, has the Chief decide one typed
48
+ * action per request, acts on it and replies in the request's thread.
49
+ */
50
+
51
+ export interface ChatOptions {
52
+ readonly space: SpaceRef
53
+ readonly trigger: string
54
+ readonly marker: string
55
+ /** User resource names (`users/…`) allowed besides the owner. */
56
+ readonly allow: ReadonlyArray<string>
57
+ /** The flows the Chief may start. */
58
+ readonly flows: ReadonlyArray<string>
59
+ readonly intervalSeconds: number
60
+ /** Post and start nothing; tell the terminal what would happen. */
61
+ readonly observe: boolean
62
+ }
63
+
64
+ export interface ChatLoopDeps {
65
+ readonly chat: GoogleChatToolShape
66
+ readonly files: PlainFileStoreShape
67
+ readonly supervisor: RunSupervisorShape
68
+ readonly git: GitToolShape
69
+ readonly repo: SupervisorRepo
70
+ readonly flows: Effect.Effect<
71
+ ReadonlyArray<{ readonly name: string; readonly path: string; readonly description: string }>
72
+ >
73
+ readonly sources: RunSources
74
+ /** Absolute trace paths under one `.llm4ts/` directory. */
75
+ readonly listTraces: (directory: string) => ReadonlyArray<string>
76
+ /** Folder names under `.llm4ts/epics/`. */
77
+ readonly listEpics: (directory: string) => ReadonlyArray<string>
78
+ readonly decide: (context: ChiefContext) => Effect.Effect<ChiefAction>
79
+ readonly environment: Readonly<Record<string, string | undefined>>
80
+ readonly now: Effect.Effect<number>
81
+ /** The verb's terminal. */
82
+ readonly say: (line: string) => Effect.Effect<void>
83
+ /** Senders already told who may ask; one reply each per process. */
84
+ readonly strangers: Ref.Ref<ReadonlySet<string>>
85
+ /** Why the reasoning seat may not hold the Chief (`readOnlySeatProblem`), or undefined. */
86
+ readonly seatProblem: Effect.Effect<string | undefined>
87
+ /** Whether the repository's git ignores `.llm4ts/`. */
88
+ readonly ignored: Effect.Effect<boolean>
89
+ readonly options: ChatOptions
90
+ }
91
+
92
+ // ---- Selecting requests -------------------------------------------------------------------
93
+
94
+ export type Selected =
95
+ | { readonly _tag: "Request"; readonly message: ChatMessage; readonly body: string }
96
+ | { readonly _tag: "Help"; readonly message: ChatMessage }
97
+ | { readonly _tag: "Stranger"; readonly message: ChatMessage }
98
+
99
+ export const strangerReply =
100
+ "Only the person who started me, or people they allowed, can ask me to do things here."
101
+
102
+ export const helpReply = (options: ChatOptions): string =>
103
+ `Ask me about runs, or tell me to start one. Example: ${options.trigger} what is running? I may start: ${options.flows.join(", ")}.`
104
+
105
+ // Chat's RFC 3339 times vary in fraction digits, so spelling order is not time order.
106
+ const timeKey = (time: string): readonly [number, string] => {
107
+ const ms = Date.parse(time)
108
+ const fraction = /\.(\d+)/u.exec(time)?.[1] ?? ""
109
+ return [Number.isNaN(ms) ? Number.NEGATIVE_INFINITY : ms, fraction.padEnd(9, "0")]
110
+ }
111
+
112
+ const isLater = (a: string, b: string): boolean => {
113
+ const [aMs, aFraction] = timeKey(a)
114
+ const [bMs, bFraction] = timeKey(b)
115
+ return aMs !== bMs ? aMs > bMs : aFraction > bFraction
116
+ }
117
+
118
+ /** The text after the trigger, or undefined when the trigger is not a whole word at the start. */
119
+ const bodyAfter = (text: string, trigger: string): string | undefined => {
120
+ if (!text.startsWith(trigger)) return undefined
121
+ const rest = text.slice(trigger.length)
122
+ return rest === "" || /^\s/u.test(rest) ? rest.trim() : undefined
123
+ }
124
+
125
+ /**
126
+ * Which messages to act on. This decides who may start coding runs: only a
127
+ * person (`HUMAN`) who is the owner or named in `allow`, and with no owner id
128
+ * nobody at all, `allow` included. The Chief's own messages are known by
129
+ * name and by marker.
130
+ */
131
+ export const selectRequests = (
132
+ state: ChatState,
133
+ messages: ReadonlyArray<ChatMessage>,
134
+ options: ChatOptions
135
+ ): { readonly selected: ReadonlyArray<Selected>; readonly cursor: string } => {
136
+ let cursor = state.cursor
137
+ const selected: Array<Selected> = []
138
+ const posted = new Set(state.posted)
139
+ for (const message of messages) {
140
+ if (isLater(message.createTime, cursor)) cursor = message.createTime
141
+ const sender = message.senderName
142
+ if (
143
+ posted.has(message.name) ||
144
+ message.text.startsWith(state.marker) ||
145
+ message.senderType !== "HUMAN" ||
146
+ sender === undefined ||
147
+ message.text.trim() === ""
148
+ ) {
149
+ continue
150
+ }
151
+ const body = bodyAfter(message.text, options.trigger)
152
+ if (body === undefined) continue
153
+ const allowed =
154
+ state.ownerId !== undefined && (sender === state.ownerId || options.allow.includes(sender))
155
+ if (!allowed) selected.push({ _tag: "Stranger", message })
156
+ else if (body === "") selected.push({ _tag: "Help", message })
157
+ else selected.push({ _tag: "Request", message, body })
158
+ }
159
+ return { selected, cursor }
160
+ }
161
+
162
+ // ---- Paths ---------------------------------------------------------------------------------
163
+
164
+ /** The last segment of a message name, safe as a file name. */
165
+ const messageId = (messageName: string): string => {
166
+ const last = messageName.split("/").pop() ?? ""
167
+ const safe = last.replace(/[^A-Za-z0-9._-]/gu, "_")
168
+ return safe === "" || safe === "." || safe === ".." ? "_" : safe
169
+ }
170
+
171
+ const pendingPath = (dir: string, messageName: string): string =>
172
+ join(dir, "pending", `${messageId(messageName)}.json`)
173
+
174
+ const actionPath = (dir: string, messageName: string): string =>
175
+ join(dir, "actions", `${messageId(messageName)}.json`)
176
+
177
+ const dirOf = (deps: Pick<ChatLoopDeps, "repo" | "options">): string =>
178
+ chatDir(deps.repo.path, deps.options.space.id)
179
+
180
+ // ---- The Chief's context -------------------------------------------------------------------
181
+
182
+ const runLimit = 20
183
+ const recentLimit = 5
184
+ const diagnosisBudget = 4_000
185
+
186
+ const emptyFold = (): TraceFold => ({ lines: [], state: emptyTree(), seq: 0 })
187
+
188
+ const foldOf = (deps: ChatLoopDeps, run: OperatorRun): Effect.Effect<TraceFold> =>
189
+ run.tracePath === undefined
190
+ ? Effect.succeed(emptyFold())
191
+ : foldTrace(deps.files, run.tracePath).pipe(Effect.catch(() => Effect.succeed(emptyFold())))
192
+
193
+ interface SummarisedRun {
194
+ readonly run: OperatorRun
195
+ readonly state: string
196
+ readonly summary: string
197
+ readonly failed: boolean
198
+ }
199
+
200
+ /** The repository's runs, newest first, without the Chief's own. */
201
+ const summarisedRuns = (deps: ChatLoopDeps) =>
202
+ Effect.gen(function* () {
203
+ const supervised = yield* deps.supervisor.list(deps.repo.id)
204
+ const disk: DiskRunDeps = {
205
+ files: deps.files,
206
+ listTraces: deps.listTraces,
207
+ listEpics: deps.listEpics
208
+ }
209
+ const discovered = yield* discoveredRuns(
210
+ disk,
211
+ deps.repo,
212
+ new Set(supervised.map((run) => run.runId))
213
+ )
214
+ const now = yield* deps.now
215
+ const runs = [...supervised, ...discovered]
216
+ .filter((run) => run.flow !== "chief")
217
+ .sort((a, b) => b.startedAt - a.startedAt)
218
+ .slice(0, runLimit)
219
+ return yield* Effect.forEach(runs, (run) =>
220
+ Effect.map(foldOf(deps, run), (fold): SummarisedRun => {
221
+ const status = runStatusOf(fold, run, now)
222
+ return {
223
+ run,
224
+ state: status.ended ?? run.state,
225
+ summary: status.summary,
226
+ failed:
227
+ status.ended === "failed" ||
228
+ (run.state === "exited" && run.exitCode !== undefined && run.exitCode !== 0)
229
+ }
230
+ })
231
+ )
232
+ })
233
+
234
+ const diagnosisOf = (deps: ChatLoopDeps, run: OperatorRun): Effect.Effect<string | undefined> => {
235
+ const tracePath = run.tracePath
236
+ if (tracePath === undefined) return Effect.succeed(undefined)
237
+ const task = run.knobs.task
238
+ return runDiagnosisOf(deps.sources, {
239
+ runId: run.runId,
240
+ tracePath,
241
+ planPath: task === undefined ? undefined : join(deps.repo.path, defaultPlanPath(task)),
242
+ transcriptsDir: transcriptsDir(deps.repo, run.runId),
243
+ gateLogDir: undefined,
244
+ budget: diagnosisBudget
245
+ }).pipe(
246
+ Effect.map((diagnosis) =>
247
+ [
248
+ `Run ${diagnosis.runId}`,
249
+ ...(diagnosis.failure === undefined
250
+ ? []
251
+ : [
252
+ `Failure: ${diagnosis.failure.stage === undefined ? "" : `${diagnosis.failure.stage}: `}${diagnosis.failure.message}`
253
+ ]),
254
+ diagnosis.digest,
255
+ ...diagnosis.transcriptTail
256
+ ]
257
+ .filter((line) => line.length > 0)
258
+ .join("\n")
259
+ ),
260
+ Effect.catch(() => Effect.succeed(undefined))
261
+ )
262
+ }
263
+
264
+ const requestLine = (request: ChatRequest): string =>
265
+ `${request.sender}: ${request.text} → ${request.status}${request.runId === undefined ? "" : ` (${request.runId})`}`
266
+
267
+ const contextFor = (deps: ChatLoopDeps, message: ChatMessage, body: string, sender: string) =>
268
+ Effect.gen(function* () {
269
+ const allowed = (yield* deps.flows).filter((flow) => deps.options.flows.includes(flow.name))
270
+ const runs = yield* summarisedRuns(deps)
271
+ const newestFailed = runs.find((entry) => entry.failed)
272
+ const diagnosis =
273
+ newestFailed === undefined ? undefined : yield* diagnosisOf(deps, newestFailed.run)
274
+ const recent = (yield* loadRequests(deps.files, dirOf(deps)))
275
+ .filter((request) => request.messageName !== message.name)
276
+ .slice(-recentLimit)
277
+ .map(requestLine)
278
+ return ChiefContext.make({
279
+ messageName: message.name,
280
+ actionPath: actionPath(dirOf(deps), message.name),
281
+ request: { text: body, sender },
282
+ flows: allowed.map((flow) => ({ name: flow.name, description: flow.description })),
283
+ runs: runs.map((entry) => ({
284
+ runId: entry.run.runId,
285
+ flow: entry.run.flow,
286
+ state: entry.state,
287
+ summary: entry.summary
288
+ })),
289
+ ...(diagnosis === undefined ? {} : { diagnosis }),
290
+ recent
291
+ })
292
+ })
293
+
294
+ // ---- Acting --------------------------------------------------------------------------------
295
+
296
+ /** Flows that stop for a human between rounds unless told not to; nobody answers from chat. */
297
+ const pausingFlows: ReadonlySet<string> = new Set(["roundtable", "taskforce"])
298
+
299
+ interface Outcome {
300
+ readonly status: ChatRequest["status"]
301
+ readonly reply: string
302
+ readonly runId?: string
303
+ }
304
+
305
+ const isActive = (run: OperatorRun): boolean => run.state === "starting" || run.state === "running"
306
+
307
+ const busyReply = (run: { readonly flow: string; readonly runId: string }): string =>
308
+ `${run.flow} is already running (${run.runId}). Wait for it, or ask me to stop it.`
309
+
310
+ const startRun = (
311
+ deps: ChatLoopDeps,
312
+ state: ChatState,
313
+ message: ChatMessage,
314
+ action: Extract<ChiefAction, { readonly _tag: "StartRun" }>
315
+ ) =>
316
+ Effect.gen(function* () {
317
+ const flow = (yield* deps.flows).find((candidate) => candidate.name === action.flow)
318
+ if (flow === undefined || !deps.options.flows.includes(action.flow)) {
319
+ return {
320
+ status: "refused",
321
+ reply: `I may not start ${action.flow} here. I may start: ${deps.options.flows.join(", ")}.`
322
+ } satisfies Outcome
323
+ }
324
+ const knobs: OperatorKnobs = {
325
+ task: action.task,
326
+ requestId: message.name,
327
+ ...(pausingFlows.has(action.flow) ? { flags: ["--no-pause"] } : {})
328
+ }
329
+ const valid = yield* validateKnobs(knobs).pipe(Effect.result)
330
+ if (valid._tag === "Failure") {
331
+ return {
332
+ status: "refused",
333
+ reply: `I can't start that: ${valid.failure.message}.`
334
+ } satisfies Outcome
335
+ }
336
+ const runs = yield* deps.supervisor.list(deps.repo.id)
337
+ // A replayed request: its run exists, so git and the supervisor stay untouched.
338
+ const already = runs.find((run) => run.requestId === message.name)
339
+ if (already !== undefined) {
340
+ return {
341
+ status: "started",
342
+ reply: `${action.reply} (run ${already.runId})`,
343
+ runId: already.runId
344
+ } satisfies Outcome
345
+ }
346
+ // The checkout below would pull the tree from under a run that is working in it.
347
+ const busy = runs.find((run) => isActive(run) && run.flow !== "chief")
348
+ if (busy !== undefined) {
349
+ return { status: "refused", reply: busyReply(busy), runId: busy.runId } satisfies Outcome
350
+ }
351
+ const dirty = yield* deps.git.uncommittedFiles
352
+ if (dirty.length > 0) {
353
+ return {
354
+ status: "refused",
355
+ reply: `I can't start ${action.flow}: the repository has ${dirty.length} uncommitted file${dirty.length === 1 ? "" : "s"}. Commit or stash them first.`
356
+ } satisfies Outcome
357
+ }
358
+ yield* deps.git.checkout(state.baseBranch)
359
+ const started = yield* deps.supervisor
360
+ .start({
361
+ repo: deps.repo,
362
+ flow: { name: flow.name, path: flow.path },
363
+ knobs: valid.success,
364
+ baseEnvironment: deps.environment
365
+ })
366
+ .pipe(Effect.result)
367
+ if (started._tag === "Failure") {
368
+ const error = started.failure
369
+ if (error instanceof RunInProgress) {
370
+ const running = yield* deps.supervisor.get(error.runId)
371
+ return {
372
+ status: "refused",
373
+ reply: busyReply({ flow: running?.flow ?? "A run", runId: error.runId }),
374
+ runId: error.runId
375
+ } satisfies Outcome
376
+ }
377
+ return yield* Effect.fail(error)
378
+ }
379
+ return {
380
+ status: "started",
381
+ reply: `${action.reply} (run ${started.success.runId})`,
382
+ runId: started.success.runId
383
+ } satisfies Outcome
384
+ })
385
+
386
+ /** The reply says what the supervisor did, not what the Chief expected it to do. */
387
+ const stopRun = (deps: ChatLoopDeps, runId: string): Effect.Effect<Outcome> =>
388
+ Effect.gen(function* () {
389
+ const before = yield* deps.supervisor.get(runId)
390
+ if (before === undefined || !isActive(before)) {
391
+ return { status: "answered", reply: `${runId} was not running.`, runId } satisfies Outcome
392
+ }
393
+ const after = yield* deps.supervisor.stop(runId)
394
+ return {
395
+ status: "answered",
396
+ reply: isActive(after) ? `${runId} has not stopped yet.` : `Stopped ${runId}.`,
397
+ runId
398
+ } satisfies Outcome
399
+ }).pipe(
400
+ Effect.catchTag("UnknownRun", () =>
401
+ Effect.succeed<Outcome>({ status: "refused", reply: `There is no run ${runId}.` })
402
+ )
403
+ )
404
+
405
+ const act = (deps: ChatLoopDeps, state: ChatState, message: ChatMessage, action: ChiefAction) => {
406
+ switch (action._tag) {
407
+ case "Answer":
408
+ return Effect.succeed<Outcome>({ status: "answered", reply: action.reply })
409
+ case "Decline":
410
+ return Effect.succeed<Outcome>({ status: "refused", reply: action.reply })
411
+ case "Failed":
412
+ return Effect.succeed<Outcome>({ status: "failed", reply: action.reply })
413
+ case "StopRun":
414
+ return stopRun(deps, action.runId)
415
+ case "StartRun":
416
+ return startRun(deps, state, message, action)
417
+ }
418
+ }
419
+
420
+ /** What an action would do, for the terminal under `observe`. */
421
+ const wouldDo = (action: ChiefAction): ReadonlyArray<string> => {
422
+ switch (action._tag) {
423
+ case "StartRun":
424
+ return [`would start ${action.flow}: ${action.task}`]
425
+ case "StopRun":
426
+ return [`would stop ${action.runId}`]
427
+ default:
428
+ return []
429
+ }
430
+ }
431
+
432
+ // ---- One beat ------------------------------------------------------------------------------
433
+
434
+ /** Posts a reply with the marker; under `observe` tells the terminal instead and posts nothing. */
435
+ const postMarked = (
436
+ deps: ChatLoopDeps,
437
+ text: string,
438
+ threadName: string | undefined
439
+ ): Effect.Effect<ChatMessage | undefined, FlowError | GwsLoginRequired> =>
440
+ deps.options.observe
441
+ ? Effect.as(deps.say(`would reply: ${text}`), undefined)
442
+ : deps.chat.createMessage(
443
+ deps.options.space,
444
+ `${deps.options.marker} ${text}`.slice(0, maxReplyChars),
445
+ threadName
446
+ )
447
+
448
+ const failureKind = (cause: Cause.Cause<unknown>): string => {
449
+ const error = Cause.findErrorOption(cause)
450
+ if (Option.isNone(error)) return "defect"
451
+ const value: unknown = error.value
452
+ return typeof value === "object" &&
453
+ value !== null &&
454
+ "_tag" in value &&
455
+ typeof value._tag === "string"
456
+ ? value._tag
457
+ : "error"
458
+ }
459
+
460
+ const isLoginRequired = (cause: Cause.Cause<unknown>): GwsLoginRequired | undefined => {
461
+ const error = Cause.findErrorOption(cause)
462
+ return Option.isSome(error) && error.value instanceof GwsLoginRequired ? error.value : undefined
463
+ }
464
+
465
+ /** A failed post told to the terminal; only a lapsed login fails. */
466
+ const sayPostFailure =
467
+ (deps: ChatLoopDeps) =>
468
+ (error: FlowError | GwsLoginRequired): Effect.Effect<void, GwsLoginRequired> =>
469
+ error instanceof GwsLoginRequired
470
+ ? Effect.fail(error)
471
+ : deps.say(`could not post to ${deps.options.space.name}: ${error._tag}`)
472
+
473
+ /**
474
+ * One pass: list what is new since the cursor, then handle each selected
475
+ * message in order. Only a failed list and a lapsed login end the beat, so
476
+ * the caller can back off or stop; anything else is answered or told to the
477
+ * terminal, and the cursor moves past the message either way.
478
+ */
479
+ export const handleBeat = (
480
+ deps: ChatLoopDeps,
481
+ state: ChatState
482
+ ): Effect.Effect<ChatState, GwsLoginRequired | FlowError> =>
483
+ Effect.flatMap(deps.chat.listMessages(deps.options.space, state.cursor), (messages) =>
484
+ handleMessages(deps, state, messages)
485
+ )
486
+
487
+ const handleMessages = (
488
+ deps: ChatLoopDeps,
489
+ state: ChatState,
490
+ messages: ReadonlyArray<ChatMessage>
491
+ ): Effect.Effect<ChatState, GwsLoginRequired> =>
492
+ Effect.gen(function* () {
493
+ const { options } = deps
494
+ const dir = dirOf(deps)
495
+ const selection = selectRequests(state, messages, options)
496
+ const current = yield* Ref.make(ChatState.make({ ...state, cursor: selection.cursor }))
497
+
498
+ const post = (text: string, threadName: string | undefined) =>
499
+ postMarked(deps, text, threadName).pipe(
500
+ Effect.flatMap((posted) =>
501
+ posted === undefined
502
+ ? Effect.void
503
+ : Ref.update(current, (now) => notePosted(now, posted.name))
504
+ ),
505
+ Effect.catch(sayPostFailure(deps))
506
+ )
507
+
508
+ for (const selected of selection.selected) {
509
+ const { message } = selected
510
+ const sender = message.senderName ?? ""
511
+ if (options.observe) {
512
+ yield* deps.say(`${options.trigger} from ${sender} (${message.senderDisplayName ?? "?"})`)
513
+ }
514
+ if (selected._tag === "Help") {
515
+ yield* post(helpReply(options), message.threadName)
516
+ continue
517
+ }
518
+ if (selected._tag === "Stranger") {
519
+ const told = yield* Ref.get(deps.strangers)
520
+ if (told.has(sender)) continue
521
+ yield* Ref.set(deps.strangers, new Set([...told, sender]))
522
+ yield* post(strangerReply, message.threadName)
523
+ continue
524
+ }
525
+
526
+ const received = ChatRequest.make({
527
+ messageName: message.name,
528
+ createTime: message.createTime,
529
+ sender,
530
+ text: selected.body,
531
+ status: "received",
532
+ ...(message.threadName === undefined ? {} : { threadName: message.threadName })
533
+ })
534
+ // Not recorded is told, never retried: deciding again would post again.
535
+ const put = (request: ChatRequest) =>
536
+ options.observe
537
+ ? Effect.void
538
+ : putRequest(deps.files, dir, request).pipe(
539
+ Effect.catch((error) =>
540
+ deps.say(`could not record ${message.name}: ${error.message}`)
541
+ )
542
+ )
543
+ const record = (outcome: Outcome, action?: string) =>
544
+ put(
545
+ ChatRequest.make({
546
+ ...received,
547
+ status: outcome.status,
548
+ reply: outcome.reply,
549
+ ...(action === undefined ? {} : { action }),
550
+ ...(outcome.runId === undefined ? {} : { runId: outcome.runId })
551
+ })
552
+ )
553
+
554
+ const handle = Effect.gen(function* () {
555
+ yield* put(received)
556
+ const context = yield* contextFor(
557
+ deps,
558
+ message,
559
+ selected.body,
560
+ message.senderDisplayName ?? sender
561
+ )
562
+ const action = yield* deps.decide(context)
563
+ if (options.observe) {
564
+ for (const line of wouldDo(action)) yield* deps.say(line)
565
+ return yield* post(action.reply, message.threadName)
566
+ }
567
+ const outcome = yield* act(deps, yield* Ref.get(current), message, action)
568
+ // Recorded first: a started run whose reply fails to post is still followed.
569
+ yield* record(outcome, action._tag)
570
+ yield* post(outcome.reply, message.threadName)
571
+ })
572
+
573
+ yield* handle.pipe(
574
+ Effect.catchCause((cause) => {
575
+ const login = isLoginRequired(cause)
576
+ if (login !== undefined) return Effect.fail(login)
577
+ if (Cause.hasInterrupts(cause)) return Effect.interrupt
578
+ const failed: Outcome = { status: "failed", reply: `That failed: ${failureKind(cause)}` }
579
+ return post(failed.reply, message.threadName).pipe(Effect.andThen(record(failed)))
580
+ })
581
+ )
582
+ }
583
+ return yield* Ref.get(current)
584
+ })
585
+
586
+ // ---- Deciding through the chief flow -------------------------------------------------------
587
+
588
+ const pollInterval = "500 millis"
589
+
590
+ /** How long the loop waits for one decision before it stops the chief run. */
591
+ export const decideTimeoutMs = 120_000
592
+
593
+ const ContextJson = Schema.fromJsonString(ChiefContext)
594
+ const ActionJson = Schema.fromJsonString(ChiefAction)
595
+
596
+ const failed: ChiefAction = { _tag: "Failed", reply: failedReply }
597
+
598
+ /** Why no decision came; told to the terminal, never posted. */
599
+ class NoDecision extends Schema.TaggedError<NoDecision>()("NoDecision", {
600
+ message: Schema.String
601
+ }) {}
602
+
603
+ const noDecision = (message: string): NoDecision => NoDecision.make({ message })
604
+
605
+ const endedAs = (run: OperatorRun | undefined): string =>
606
+ run === undefined
607
+ ? "lost"
608
+ : `${run.state}${run.exitCode === undefined ? "" : `, exit code ${run.exitCode}`}${run.signal === undefined ? "" : `, ${run.signal}`}`
609
+
610
+ /**
611
+ * The Chief's decision made by the bundled `chief` flow: the context goes to
612
+ * a file, the flow runs as a read-only supervised run, and its action file is
613
+ * read once it exits. Anything short of a clean exit within `decideTimeoutMs`
614
+ * and a decodable action is `Failed`, and the terminal is told why, with the
615
+ * chief run's id and where its logs are.
616
+ */
617
+ export const decideThroughFlow =
618
+ (deps: Omit<ChatLoopDeps, "decide">) =>
619
+ (context: ChiefContext): Effect.Effect<ChiefAction> =>
620
+ Effect.gen(function* () {
621
+ const dir = dirOf(deps)
622
+ const pending = pendingPath(dir, context.messageName)
623
+ const action = actionPath(dir, context.messageName)
624
+ const chief = (yield* deps.flows).find((flow) => flow.name === "chief")
625
+ if (chief === undefined) return yield* noDecision("no chief flow was found")
626
+ // A file left by an earlier attempt must not pass for this decision.
627
+ yield* deps.files.remove(action)
628
+ yield* deps.files.writeAtomic(
629
+ pending,
630
+ Schema.encodeSync(ContextJson)(ChiefContext.make({ ...context, actionPath: action }))
631
+ )
632
+ const run = yield* deps.supervisor
633
+ .start({
634
+ repo: deps.repo,
635
+ flow: { name: chief.name, path: chief.path },
636
+ knobs: { task: pending },
637
+ baseEnvironment: deps.environment
638
+ })
639
+ .pipe(
640
+ Effect.mapError((error) =>
641
+ noDecision(`the chief run could not start: ${describeFlowError(error)}`)
642
+ )
643
+ )
644
+ const where = `chief run ${run.runId}`
645
+ const logs = `its logs are in ${run.logDir}`
646
+ const stopChief = Effect.ignore(deps.supervisor.stop(run.runId))
647
+ const waited = yield* Effect.gen(function* () {
648
+ let latest: OperatorRun | undefined = run
649
+ while (latest !== undefined && isActive(latest)) {
650
+ yield* Effect.sleep(pollInterval)
651
+ latest = yield* deps.supervisor.get(run.runId)
652
+ }
653
+ return latest
654
+ }).pipe(
655
+ Effect.timeoutOption(decideTimeoutMs),
656
+ Effect.onInterrupt(() => stopChief)
657
+ )
658
+ if (Option.isNone(waited)) {
659
+ yield* stopChief
660
+ return yield* noDecision(
661
+ `${where} gave no decision within ${decideTimeoutMs / 1_000} s; ${logs}`
662
+ )
663
+ }
664
+ const latest = waited.value
665
+ if (latest?.state !== "exited" || latest.exitCode !== 0) {
666
+ return yield* noDecision(`${where} ended ${endedAs(latest)}; ${logs}`)
667
+ }
668
+ const text = yield* deps.files.read(action)
669
+ if (text === undefined) return yield* noDecision(`${where} wrote no action; ${logs}`)
670
+ const decided = yield* Schema.decodeUnknownEffect(ActionJson)(text).pipe(
671
+ Effect.mapError(() => noDecision(`${where} wrote an action that does not decode; ${logs}`))
672
+ )
673
+ if (decided._tag === "Failed") {
674
+ yield* deps.say(
675
+ `The Chief could not decide on ${context.messageName}: ${where} found no valid proposal; ${logs}`
676
+ )
677
+ }
678
+ return decided
679
+ }).pipe(
680
+ Effect.catch((error) =>
681
+ deps
682
+ .say(
683
+ `The Chief could not decide on ${context.messageName}: ${error instanceof NoDecision ? error.message : describeFlowError(error)}`
684
+ )
685
+ .pipe(Effect.as(failed))
686
+ )
687
+ )
688
+
689
+ // ---- Run updates ---------------------------------------------------------------------------
690
+
691
+ /** At most one progress line per run in this window; the ending line is never held back. */
692
+ export const throttleMs = 30_000
693
+
694
+ /** Where the loop stands with one run started from chat. */
695
+ export interface Followed {
696
+ readonly runId: string
697
+ /** The trace seq the last story-shaped line covered. */
698
+ readonly seq: number
699
+ /** The plan progress the last plain line reported. */
700
+ readonly progress: PlainProgress | undefined
701
+ readonly lastPostedAt: number
702
+ readonly done: boolean
703
+ }
704
+
705
+ export const startFollowing = (runId: string): Followed => ({
706
+ runId,
707
+ seq: 0,
708
+ progress: undefined,
709
+ lastPostedAt: Number.NEGATIVE_INFINITY,
710
+ done: false
711
+ })
712
+
713
+ const outcomeOf = (run: OperatorRun | undefined): string => {
714
+ if (run === undefined) return "lost"
715
+ if (run.state === "exited") return run.exitCode === 0 ? "completed" : "failed"
716
+ return run.state
717
+ }
718
+
719
+ const planProgressOf = (deps: ChatLoopDeps, run: OperatorRun | undefined) =>
720
+ Effect.gen(function* () {
721
+ const task = run?.knobs.task
722
+ if (task === undefined) return undefined
723
+ const markdown = yield* deps.files.read(join(deps.repo.path, defaultPlanPath(task)))
724
+ if (markdown === undefined) return undefined
725
+ const plan = yield* parsePlan(markdown)
726
+ return {
727
+ tasksTotal: plan.tasks.length,
728
+ tasksDone: plan.tasks.filter((entry) => entry.completed).length
729
+ } satisfies PlainProgress
730
+ }).pipe(Effect.catch(() => Effect.succeed(undefined)))
731
+
732
+ /**
733
+ * One look at a run started from chat: post what changed into the thread of
734
+ * the request that started it, at most once per `throttleMs`, and its end
735
+ * always, once. A failed post is told to the terminal and tried again next
736
+ * time; only a lapsed login fails.
737
+ */
738
+ export const followRun = (
739
+ deps: ChatLoopDeps,
740
+ state: ChatState,
741
+ followed: Followed
742
+ ): Effect.Effect<
743
+ { readonly followed: Followed; readonly state: ChatState },
744
+ GwsLoginRequired | PersistenceError
745
+ > =>
746
+ Effect.gen(function* () {
747
+ const unchanged = { followed, state }
748
+ if (followed.done) return unchanged
749
+ const dir = dirOf(deps)
750
+ const request = (yield* loadRequests(deps.files, dir)).find(
751
+ (entry) =>
752
+ entry.runId === followed.runId && (entry.status === "started" || entry.status === "ended")
753
+ )
754
+ if (request === undefined || request.status === "ended") {
755
+ return { followed: { ...followed, done: true }, state }
756
+ }
757
+ const run = yield* deps.supervisor.get(followed.runId)
758
+ const fold = run === undefined ? emptyFold() : yield* foldOf(deps, run)
759
+ const now = yield* deps.now
760
+ const ended = run === undefined || !isActive(run)
761
+
762
+ const post = (text: string) =>
763
+ postMarked(deps, text, request.threadName).pipe(
764
+ Effect.map((posted) => (posted === undefined ? state : notePosted(state, posted.name))),
765
+ Effect.catch((error) =>
766
+ error instanceof GwsLoginRequired
767
+ ? Effect.fail(error)
768
+ : Effect.as(
769
+ deps.say(`could not post to ${deps.options.space.name}: ${error._tag}`),
770
+ undefined
771
+ )
772
+ )
773
+ )
774
+
775
+ const progress = yield* planProgressOf(deps, run)
776
+ if (ended) {
777
+ const outcome = fold.state.ended ?? outcomeOf(run)
778
+ const startedAt = fold.state.startedAt ?? run?.startedAt ?? now
779
+ const endedAt = fold.state.ended === undefined ? now : (fold.state.now ?? now)
780
+ // The checkout is read now: on the base branch, or for a lost run, it says nothing of this run.
781
+ const current = yield* deps.git.currentBranch.pipe(Effect.option)
782
+ const branch =
783
+ run === undefined || run.state === "lost"
784
+ ? Option.none()
785
+ : Option.filter(current, (name) => name !== state.baseBranch)
786
+ const commits = Option.isNone(branch)
787
+ ? Option.none()
788
+ : yield* deps.git.commitsAhead(state.baseBranch).pipe(Effect.option)
789
+ const line = plainProgressLine(followed.runId, followed.progress, {
790
+ tasksTotal: progress?.tasksTotal ?? 0,
791
+ tasksDone: progress?.tasksDone ?? 0,
792
+ ended: {
793
+ outcome,
794
+ minutes: Math.max(0, Math.floor((endedAt - startedAt) / 60_000)),
795
+ costUsd: fold.state.costUsd,
796
+ ...(Option.isSome(branch) ? { branch: branch.value } : {}),
797
+ ...(Option.isSome(commits) ? { commits: commits.value } : {})
798
+ }
799
+ })
800
+ const posted = line === undefined ? state : yield* post(line)
801
+ if (posted === undefined) return unchanged
802
+ // Under --observe the request stays started, so an armed session still posts its end.
803
+ if (!deps.options.observe) {
804
+ yield* putRequest(
805
+ deps.files,
806
+ dir,
807
+ ChatRequest.make({ ...request, status: "ended", outcome })
808
+ )
809
+ }
810
+ return { followed: { ...followed, seq: fold.seq, done: true }, state: posted }
811
+ }
812
+
813
+ if (now - followed.lastPostedAt < throttleMs) return unchanged
814
+ if (fold.state.stories.length > 0) {
815
+ if (meaningfulEventsAfter(fold.lines, followed.seq).length === 0) return unchanged
816
+ const posted = yield* post(`${followed.runId}: ${summarizeTree(fold.state, run?.flow)}`)
817
+ if (posted === undefined) return unchanged
818
+ return { followed: { ...followed, seq: fold.seq, lastPostedAt: now }, state: posted }
819
+ }
820
+ const line =
821
+ progress === undefined
822
+ ? undefined
823
+ : plainProgressLine(followed.runId, followed.progress, progress)
824
+ if (line === undefined) return unchanged
825
+ const posted = yield* post(line)
826
+ if (posted === undefined) return unchanged
827
+ return { followed: { ...followed, progress, lastPostedAt: now }, state: posted }
828
+ })
829
+
830
+ // ---- Starting and the loop -----------------------------------------------------------------
831
+
832
+ export class ChatStopped extends Schema.TaggedError<ChatStopped>()("ChatStopped", {
833
+ message: Schema.String
834
+ }) {}
835
+
836
+ const stopped = (message: string): ChatStopped => ChatStopped.make({ message })
837
+
838
+ const loginExpired = stopped("Google login expired. Run: gws auth login")
839
+
840
+ const ignoreWarning =
841
+ "Warning: .llm4ts/ is not ignored by git in this repository; add it to .gitignore."
842
+
843
+ /** A Chat failure at start as a sentence; a lapsed login is always the same one. */
844
+ const stoppedBy =
845
+ (doing: string) =>
846
+ (error: FlowError | GwsLoginRequired): ChatStopped =>
847
+ error instanceof GwsLoginRequired
848
+ ? loginExpired
849
+ : stopped(`${doing}: ${describeFlowError(error)}`)
850
+
851
+ /**
852
+ * The start checks, then the state: `gws` answers its probe, the space can be
853
+ * listed, and the reasoning seat enforces read-only. A new state starts its
854
+ * cursor now, so old `/bot` messages are not replayed. Unless `observe`, the
855
+ * Chief says it is listening, and whoever that line is posted as is the owner.
856
+ */
857
+ export const startChat = (
858
+ deps: ChatLoopDeps
859
+ ): Effect.Effect<ChatState, ChatStopped | PersistenceError> =>
860
+ Effect.gen(function* () {
861
+ const { options } = deps
862
+ yield* deps.chat.probe.pipe(Effect.mapError(stoppedBy("gws is not ready")))
863
+ const now = new Date(yield* deps.now).toISOString()
864
+ yield* deps.chat
865
+ .listMessages(options.space, now)
866
+ .pipe(Effect.mapError(stoppedBy(`Cannot list messages in ${options.space.name}`)))
867
+ const problem = yield* deps.seatProblem
868
+ if (problem !== undefined) return yield* stopped(`The Chief cannot use its seat: ${problem}.`)
869
+ const discovered = yield* deps.flows.pipe(
870
+ Effect.catchDefect((defect) =>
871
+ Effect.fail(stopped(`Cannot discover the flows: ${String(defect)}.`))
872
+ )
873
+ )
874
+ const names = new Set(discovered.map((flow) => flow.name))
875
+ if (!names.has("chief")) {
876
+ return yield* stopped("There is no chief flow here, so the Chief cannot decide anything.")
877
+ }
878
+ const unknown = options.flows.filter((name) => !names.has(name))
879
+ if (unknown.length > 0) {
880
+ return yield* stopped(
881
+ `--flows names ${unknown.join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not a flow here; llm4ts list shows the flows.`
882
+ )
883
+ }
884
+
885
+ const dir = dirOf(deps)
886
+ const loaded = yield* loadState(deps.files, dir)
887
+ const baseBranch =
888
+ loaded?.baseBranch ??
889
+ (yield* deps.git.currentBranch.pipe(
890
+ Effect.mapError((error) =>
891
+ stopped(`Cannot read the current branch: ${describeFlowError(error)}`)
892
+ )
893
+ ))
894
+ let state = ChatState.make({
895
+ space: options.space.name,
896
+ cursor: now,
897
+ posted: [],
898
+ ...loaded,
899
+ trigger: options.trigger,
900
+ marker: options.marker,
901
+ baseBranch
902
+ })
903
+ if (!(yield* deps.ignored)) yield* deps.say(ignoreWarning)
904
+ if (!options.observe) {
905
+ const listening = yield* deps.chat
906
+ .createMessage(
907
+ options.space,
908
+ `${options.marker} Listening. Repository ${deps.repo.id}. I may start: ${options.flows.join(", ")}.`
909
+ )
910
+ .pipe(Effect.mapError(stoppedBy(`Cannot post to ${options.space.name}`)))
911
+ if (listening.senderName === undefined) {
912
+ return yield* stopped(
913
+ "Chat did not say who posted the listening line, so nobody could ask."
914
+ )
915
+ }
916
+ state = ChatState.make({
917
+ ...notePosted(state, listening.name),
918
+ ownerId: listening.senderName
919
+ })
920
+ }
921
+ yield* saveState(deps.files, dir, state)
922
+ return state
923
+ })
924
+
925
+ const backoffStartMs = 1_000
926
+ const backoffCapMs = 60_000
927
+
928
+ /**
929
+ * `startChat`, then forever: one beat, a look at every run started from chat,
930
+ * the state saved, a sleep. A failed list backs off, and a file that cannot
931
+ * be read or written is told to the terminal; neither ends the loop, a lapsed
932
+ * login does.
933
+ */
934
+ export const runChat = (deps: ChatLoopDeps): Effect.Effect<never, ChatStopped | PersistenceError> =>
935
+ Effect.gen(function* () {
936
+ const { options } = deps
937
+ const dir = dirOf(deps)
938
+ let state = yield* startChat(deps)
939
+ // In memory only: after a restart a run's last line may be posted once more.
940
+ const follows = new Map<string, Followed>()
941
+ let failures = 0
942
+ while (true) {
943
+ const beat = yield* Effect.result(handleBeat(deps, state))
944
+ if (beat._tag === "Failure") {
945
+ if (beat.failure instanceof GwsLoginRequired) return yield* loginExpired
946
+ failures += 1
947
+ const wait = Math.min(backoffStartMs * 2 ** (failures - 1), backoffCapMs)
948
+ yield* deps.say(
949
+ `could not list messages in ${options.space.name}: ${beat.failure._tag}; retrying in ${wait / 1_000} s`
950
+ )
951
+ yield* Effect.sleep(Duration.millis(wait))
952
+ continue
953
+ }
954
+ failures = 0
955
+ state = beat.success
956
+ const requests = yield* loadRequests(deps.files, dir).pipe(
957
+ Effect.catch((error) => Effect.as(deps.say(`could not follow runs: ${error.message}`), []))
958
+ )
959
+ for (const request of requests) {
960
+ if (request.status !== "started" || request.runId === undefined) continue
961
+ const step = yield* followRun(
962
+ deps,
963
+ state,
964
+ follows.get(request.runId) ?? startFollowing(request.runId)
965
+ ).pipe(
966
+ Effect.mapError((error) => (error instanceof GwsLoginRequired ? loginExpired : error)),
967
+ Effect.catchTag("Persistence", (error) =>
968
+ Effect.as(deps.say(`could not follow runs: ${error.message}`), undefined)
969
+ )
970
+ )
971
+ if (step === undefined) continue
972
+ state = step.state
973
+ if (step.followed.done) follows.delete(request.runId)
974
+ else follows.set(request.runId, step.followed)
975
+ }
976
+ yield* saveState(deps.files, dir, state).pipe(
977
+ Effect.catch((error) => deps.say(`could not save the chat state: ${error.message}`))
978
+ )
979
+ yield* Effect.sleep(Duration.seconds(options.intervalSeconds))
980
+ }
981
+ })