@llm4ts/shell 3.4.0 → 4.0.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 (68) hide show
  1. package/dist/Cli.d.ts +4 -4
  2. package/dist/Cli.d.ts.map +1 -1
  3. package/dist/Cli.js +3 -3
  4. package/dist/Cli.js.map +1 -1
  5. package/dist/Config.d.ts +3 -3
  6. package/dist/Config.d.ts.map +1 -1
  7. package/dist/Config.js +8 -6
  8. package/dist/Config.js.map +1 -1
  9. package/dist/Costs.d.ts +52 -0
  10. package/dist/Costs.d.ts.map +1 -0
  11. package/dist/Costs.js +95 -0
  12. package/dist/Costs.js.map +1 -0
  13. package/dist/OperatorActTools.d.ts +1 -1
  14. package/dist/OperatorActTools.d.ts.map +1 -1
  15. package/dist/OperatorActTools.js +1 -1
  16. package/dist/OperatorActTools.js.map +1 -1
  17. package/dist/OperatorNode.js +2 -2
  18. package/dist/OperatorNode.js.map +1 -1
  19. package/dist/OperatorRuns.d.ts +1 -1
  20. package/dist/OperatorRuns.d.ts.map +1 -1
  21. package/dist/OperatorRuns.js +1 -1
  22. package/dist/OperatorRuns.js.map +1 -1
  23. package/dist/OperatorTools.d.ts +2 -2
  24. package/dist/OperatorTools.d.ts.map +1 -1
  25. package/dist/OperatorTools.js +4 -4
  26. package/dist/OperatorTools.js.map +1 -1
  27. package/dist/Profile.d.ts +313 -0
  28. package/dist/Profile.d.ts.map +1 -0
  29. package/dist/Profile.js +937 -0
  30. package/dist/Profile.js.map +1 -0
  31. package/dist/RunReaders.d.ts +70 -0
  32. package/dist/RunReaders.d.ts.map +1 -0
  33. package/dist/RunReaders.js +236 -0
  34. package/dist/RunReaders.js.map +1 -0
  35. package/dist/StoryReaders.d.ts +16 -0
  36. package/dist/StoryReaders.d.ts.map +1 -0
  37. package/dist/StoryReaders.js +107 -0
  38. package/dist/StoryReaders.js.map +1 -0
  39. package/dist/Watch.d.ts +68 -0
  40. package/dist/Watch.d.ts.map +1 -0
  41. package/dist/Watch.js +261 -0
  42. package/dist/Watch.js.map +1 -0
  43. package/flows/lib/epic-design.js +1 -1
  44. package/flows/lib/epic-stories.js +2 -6
  45. package/flows/lib/modernize-extract.js +3 -3
  46. package/flows/modernize-bench.js +7 -2
  47. package/flows/modernize-extract.js +1 -1
  48. package/flows/modernize-implement.js +2 -3
  49. package/flows/modernize-refine.js +1 -1
  50. package/flows/modernize-review.js +3 -4
  51. package/flows/modernize-survey.js +1 -1
  52. package/flows/modernize-verify.js +1 -1
  53. package/flows/pack-fork.js +1 -1
  54. package/flows/port-guide.js +1 -1
  55. package/flows/port-ledger.js +1 -1
  56. package/kits/j2ee-nextjs/flows/lib/convert.js +2 -3
  57. package/package.json +4 -24
  58. package/src/Cli.ts +3 -8
  59. package/src/Config.ts +9 -5
  60. package/src/Costs.ts +148 -0
  61. package/src/OperatorActTools.ts +1 -1
  62. package/src/OperatorNode.ts +2 -2
  63. package/src/OperatorRuns.ts +1 -1
  64. package/src/OperatorTools.ts +4 -4
  65. package/src/Profile.ts +1196 -0
  66. package/src/RunReaders.ts +370 -0
  67. package/src/StoryReaders.ts +157 -0
  68. package/src/Watch.ts +451 -0
package/src/Watch.ts ADDED
@@ -0,0 +1,451 @@
1
+ import { readdirSync, existsSync, statSync } from "node:fs"
2
+ import { join } from "node:path"
3
+ import * as Clock from "effect/Clock"
4
+ import * as Duration from "effect/Duration"
5
+ import * as Effect from "effect/Effect"
6
+ import * as Queue from "effect/Queue"
7
+ import * as Ref from "effect/Ref"
8
+ import * as Schema from "effect/Schema"
9
+ import * as Stream from "effect/Stream"
10
+ import { Board, BoardVersion } from "@llm4ts/flow/BoardSync"
11
+ import { readEpicRuns, type EpicRun } from "@llm4ts/flow/EpicRuns"
12
+ import type { FlowError } from "@llm4ts/flow/FlowError"
13
+ import { loadVersioned, type PlainFileStoreShape } from "@llm4ts/flow/Persistence"
14
+ import { readTrace } from "@llm4ts/flow/Replay"
15
+ import {
16
+ emptyTree,
17
+ initialView,
18
+ onTreeKey,
19
+ reduceTree,
20
+ renderTree,
21
+ tailTargetOf,
22
+ treeInputsOfTrace,
23
+ type TreeInput,
24
+ type TreeState,
25
+ type TreeView
26
+ } from "@llm4ts/runner/AgentTree"
27
+ import {
28
+ enterScreen,
29
+ leaveScreen,
30
+ makeScreenPainter,
31
+ nodeTreeKeys
32
+ } from "@llm4ts/runner/AgentTreeSurface"
33
+ import {
34
+ loadTranscript,
35
+ nodeTranscriptFiles,
36
+ renderTranscript,
37
+ tailLinesOf,
38
+ transcriptFileOf,
39
+ type TailTarget,
40
+ type TranscriptFiles
41
+ } from "@llm4ts/runner/Transcripts"
42
+ import { nodeListTraces, TraceDirectoryName } from "./Costs.ts"
43
+ import { nodePlainFileStore } from "@llm4ts/runner/NodePlainFileStore"
44
+
45
+ /**
46
+ * `llm4ts watch` (ADR 0022): the agent tree over a trace file — a live run
47
+ * followed as it grows, a finished run's last frame, or a replay on the
48
+ * trace's own timestamps. The trace is the only source; the epic's board
49
+ * adds the stories that have not started.
50
+ */
51
+
52
+ export interface WatchOptions {
53
+ readonly repo: string
54
+ /** A trace file; the newest in the repository's `.llm4ts/` when omitted. */
55
+ readonly trace?: string
56
+ /** An epic id: its latest recorded run. */
57
+ readonly epic?: string
58
+ readonly replay?: boolean
59
+ /** Replay speed-up (default 10). */
60
+ readonly speed?: number
61
+ /** A live lane with no event for this long is marked idle (`LLM4TS_IDLE_AFTER`). */
62
+ readonly idleAfterMs?: number
63
+ /** Print this story's or executor's transcript as it grows, instead of the tree. */
64
+ readonly tail?: string
65
+ }
66
+
67
+ export interface WatchOutput {
68
+ readonly write: (text: string) => Effect.Effect<void>
69
+ readonly columns: () => number | undefined
70
+ readonly rows: () => number | undefined
71
+ /** A terminal a person looks at: full-screen, keys, following. */
72
+ readonly interactive: boolean
73
+ readonly colour: boolean
74
+ }
75
+
76
+ export interface WatchDependencies {
77
+ readonly files: PlainFileStoreShape
78
+ readonly listTraces: (directory: string) => ReadonlyArray<string>
79
+ /** Epic folder names under `.llm4ts/epics/`. */
80
+ readonly listEpics: (directory: string) => ReadonlyArray<string>
81
+ readonly output: WatchOutput
82
+ /** Key names as `onTreeKey` reads them: "up", "enter", "q", … */
83
+ readonly keys: Stream.Stream<string>
84
+ /** A run's transcript files (`--transcript`); the disk by default. */
85
+ readonly transcripts?: TranscriptFiles
86
+ }
87
+
88
+ export class WatchTargetMissing extends Schema.TaggedError<WatchTargetMissing>()(
89
+ "WatchTargetMissing",
90
+ { message: Schema.String }
91
+ ) {}
92
+
93
+ /** Where a run's trace and its epic are read from. */
94
+ export type TraceSources = Pick<WatchDependencies, "files" | "listTraces" | "listEpics">
95
+
96
+ /** A trace to read: given, an epic's latest run, or the newest in the repository. */
97
+ export type TraceChoice = Pick<WatchOptions, "repo" | "trace" | "epic">
98
+
99
+ export interface WatchTarget {
100
+ readonly tracePath: string
101
+ readonly epicDir: string | undefined
102
+ readonly run: EpicRun | undefined
103
+ }
104
+
105
+ const epicsDirOf = (repo: string): string => join(repo, TraceDirectoryName, "epics")
106
+
107
+ /** The epic whose `runs.jsonl` names this trace, if one does. */
108
+ const epicOfTrace = (
109
+ tracePath: string,
110
+ repo: string,
111
+ dependencies: TraceSources
112
+ ): Effect.Effect<{ readonly dir: string; readonly run: EpicRun } | undefined, FlowError> =>
113
+ Effect.gen(function* () {
114
+ const epicsDir = epicsDirOf(repo)
115
+ for (const epic of dependencies.listEpics(epicsDir)) {
116
+ const dir = join(epicsDir, epic)
117
+ const run = [...(yield* readEpicRuns(dependencies.files, dir))]
118
+ .reverse()
119
+ .find((candidate) => candidate.tracePath === tracePath)
120
+ if (run !== undefined) {
121
+ return { dir, run }
122
+ }
123
+ }
124
+ return undefined
125
+ })
126
+
127
+ export const resolveTraceTarget = (
128
+ options: TraceChoice,
129
+ dependencies: TraceSources
130
+ ): Effect.Effect<WatchTarget, FlowError | WatchTargetMissing> =>
131
+ Effect.gen(function* () {
132
+ if (options.epic !== undefined) {
133
+ const dir = join(epicsDirOf(options.repo), options.epic)
134
+ const run = (yield* readEpicRuns(dependencies.files, dir)).at(-1)
135
+ if (run === undefined) {
136
+ return yield* WatchTargetMissing.make({
137
+ message: `epic ${options.epic} has no recorded run in ${dir}/runs.jsonl`
138
+ })
139
+ }
140
+ return { tracePath: run.tracePath, epicDir: dir, run }
141
+ }
142
+ const tracePath =
143
+ options.trace ?? dependencies.listTraces(join(options.repo, TraceDirectoryName)).at(-1)
144
+ if (tracePath === undefined) {
145
+ return yield* WatchTargetMissing.make({
146
+ message: `no trace in ${join(options.repo, TraceDirectoryName)}; pass a trace file or --epic`
147
+ })
148
+ }
149
+ const epic = yield* epicOfTrace(tracePath, options.repo, dependencies)
150
+ return { tracePath, epicDir: epic?.dir, run: epic?.run }
151
+ })
152
+
153
+ const actionWords = (run: EpicRun | undefined): string | undefined => {
154
+ if (run === undefined) {
155
+ return undefined
156
+ }
157
+ switch (run.action) {
158
+ case "RunPlan":
159
+ return "run plan"
160
+ case "RunRound":
161
+ return `round ${run.round ?? "?"}`
162
+ case "PlanRound":
163
+ return `plan round ${run.round ?? "?"}`
164
+ case "Land":
165
+ return "land"
166
+ default:
167
+ return run.action
168
+ }
169
+ }
170
+
171
+ /** The tree before any event: the epic's board, when the trace belongs to one. */
172
+ const startingTree = (
173
+ target: WatchTarget,
174
+ files: PlainFileStoreShape,
175
+ idleAfterMs: number | undefined
176
+ ): Effect.Effect<TreeState, FlowError> =>
177
+ Effect.gen(function* () {
178
+ const action = actionWords(target.run)
179
+ const idle = idleAfterMs === undefined ? {} : { idleAfterMs }
180
+ if (target.epicDir === undefined) {
181
+ return emptyTree({ ...idle, ...(action === undefined ? {} : { action }) })
182
+ }
183
+ const boardDir =
184
+ target.run?.round === undefined
185
+ ? target.epicDir
186
+ : join(target.epicDir, "rounds", String(target.run.round))
187
+ const board = yield* loadVersioned(files, join(boardDir, "board.json"), BoardVersion, Board)
188
+ const epicId = target.epicDir.split("/").at(-1) ?? "epic"
189
+ return emptyTree({
190
+ title: board === undefined ? `epic ${epicId}` : board.title.replace(/^Epic:\s*/u, "epic "),
191
+ stories: (board?.items ?? []).map((item) => ({ id: item.id, status: item.status })),
192
+ ...idle,
193
+ ...(action === undefined ? {} : { action })
194
+ })
195
+ })
196
+
197
+ const readInputs = (
198
+ target: WatchTarget,
199
+ files: PlainFileStoreShape
200
+ ): Effect.Effect<ReadonlyArray<TreeInput>, FlowError> =>
201
+ Effect.map(readTrace(files, target.tracePath), treeInputsOfTrace)
202
+
203
+ const pollInterval = Duration.millis(500)
204
+ const replayGapCap = 2_000
205
+
206
+ const draw = (
207
+ state: TreeState,
208
+ view: TreeView,
209
+ output: WatchOutput,
210
+ height?: number,
211
+ tail?: ReadonlyArray<string>
212
+ ): string =>
213
+ renderTree(state, {
214
+ width: Math.max(90, output.columns() ?? 90),
215
+ colour: output.colour,
216
+ view,
217
+ ...(height === undefined ? {} : { height }),
218
+ ...(tail === undefined ? {} : { tail })
219
+ }).join("\n")
220
+
221
+ /** A full-screen frame: no taller than the terminal. */
222
+ const screenLines = (
223
+ state: TreeState,
224
+ view: TreeView,
225
+ output: WatchOutput,
226
+ tail?: ReadonlyArray<string>
227
+ ): ReadonlyArray<string> => draw(state, view, output, output.rows(), tail).split("\n")
228
+
229
+ /** Rows the tail pane shows. */
230
+ const tailRows = 16
231
+
232
+ /** Where a trace's run kept its transcript: `.llm4ts/transcripts/<run-id>/`. */
233
+ const transcriptDirOf = (
234
+ repo: string,
235
+ target: WatchTarget,
236
+ files: PlainFileStoreShape
237
+ ): Effect.Effect<string | undefined, FlowError> =>
238
+ Effect.map(readTrace(files, target.tracePath), (lines) => {
239
+ const runId = lines[0]?.runId
240
+ return runId === undefined ? undefined : join(repo, TraceDirectoryName, "transcripts", runId)
241
+ })
242
+
243
+ export const makeWatchProgram = Effect.fn("@llm4ts/shell/Watch.make")(function* (
244
+ options: WatchOptions,
245
+ dependencies: WatchDependencies
246
+ ): Effect.fn.Return<void, FlowError | WatchTargetMissing> {
247
+ const target = yield* resolveTraceTarget(options, dependencies)
248
+ const { files, output } = dependencies
249
+ const fold = (inputs: ReadonlyArray<TreeInput>): Effect.Effect<TreeState, FlowError> =>
250
+ Effect.map(startingTree(target, files, options.idleAfterMs), (start) =>
251
+ inputs.reduce(reduceTree, start)
252
+ )
253
+
254
+ const transcripts = dependencies.transcripts ?? nodeTranscriptFiles
255
+ const transcriptDir = yield* transcriptDirOf(options.repo, target, files)
256
+
257
+ if (options.tail !== undefined) {
258
+ if (transcriptDir === undefined || transcripts.list(transcriptDir).length === 0) {
259
+ return yield* WatchTargetMissing.make({
260
+ message: "no transcript for this run — start it with llm4ts run … --transcript"
261
+ })
262
+ }
263
+ return yield* followTail(options.tail, transcriptDir, transcripts, output, () =>
264
+ Effect.map(readInputs(target, files), (inputs) =>
265
+ inputs.some((input) => input._tag === "RunEnded")
266
+ )
267
+ )
268
+ }
269
+
270
+ /** The open tail's lines, for the view's selection. */
271
+ const tailFor = (view: TreeView): Effect.Effect<ReadonlyArray<string> | undefined> => {
272
+ const selected = tailTargetOf(view)
273
+ return !view.tail || selected === undefined || transcriptDir === undefined
274
+ ? Effect.succeed(undefined)
275
+ : Effect.map(loadTranscript(transcripts, transcriptDir, selected), (entries) =>
276
+ tailLinesOf(
277
+ entries,
278
+ selected,
279
+ view.tailRole,
280
+ Math.max(90, output.columns() ?? 90) - 32,
281
+ tailRows,
282
+ view.tailBack
283
+ )
284
+ )
285
+ }
286
+
287
+ if (!output.interactive) {
288
+ const state = yield* Effect.flatMap(readInputs(target, files), fold)
289
+ return yield* output.write(`${draw(state, initialView, output)}\n`)
290
+ }
291
+
292
+ yield* Effect.scoped(
293
+ Effect.gen(function* () {
294
+ const keys = yield* Queue.unbounded<string>()
295
+ yield* Effect.forkScoped(
296
+ Stream.runForEach(dependencies.keys, (key) => Queue.offer(keys, key))
297
+ )
298
+ const view = yield* Ref.make<TreeView>(initialView)
299
+ const all = yield* readInputs(target, files)
300
+ // Replay steps through the inputs on their timestamps; otherwise the
301
+ // whole trace is shown and re-read while the run goes on.
302
+ const shown = yield* Ref.make(options.replay === true ? Math.min(1, all.length) : all.length)
303
+ const inputs = yield* Ref.make(all)
304
+ const speed = Math.max(1, options.speed ?? 10)
305
+
306
+ /** Waits for a key or for `wait`; true when the key was `q`. */
307
+ const awaitKey = (wait: Duration.Duration): Effect.Effect<boolean> =>
308
+ Effect.raceFirst(
309
+ Effect.flatMap(Queue.take(keys), (key) =>
310
+ Effect.gen(function* () {
311
+ const state = yield* Effect.orDie(
312
+ Effect.flatMap(Ref.get(inputs), (current) =>
313
+ Effect.flatMap(Ref.get(shown), (count) => fold(current.slice(0, count)))
314
+ )
315
+ )
316
+ const next = onTreeKey(yield* Ref.get(view), key, state)
317
+ if (next === "quit") {
318
+ return true
319
+ }
320
+ yield* Ref.set(view, next)
321
+ return false
322
+ })
323
+ ),
324
+ Effect.as(Effect.sleep(wait), false)
325
+ )
326
+
327
+ const painter = yield* makeScreenPainter
328
+ yield* output.write(enterScreen)
329
+ yield* Effect.gen(function* () {
330
+ while (true) {
331
+ const current = yield* Ref.get(inputs)
332
+ const count = yield* Ref.get(shown)
333
+ const folded = yield* fold(current.slice(0, count))
334
+ // Following a live run, the clock moves between events; a replay
335
+ // and a finished run keep the trace's own time.
336
+ const state =
337
+ options.replay !== true && folded.ended === undefined
338
+ ? reduceTree(folded, { _tag: "Tick", at: yield* Clock.currentTimeMillis })
339
+ : folded
340
+ const text = yield* painter.paint(
341
+ screenLines(state, yield* Ref.get(view), output, yield* tailFor(yield* Ref.get(view))),
342
+ `${output.columns()}x${output.rows()}`
343
+ )
344
+ if (text.length > 0) {
345
+ yield* output.write(text)
346
+ }
347
+ const replaying = options.replay === true && count < current.length
348
+ const gap = replaying
349
+ ? Math.min(replayGapCap, (current[count]?.at ?? 0) - (current[count - 1]?.at ?? 0)) /
350
+ speed
351
+ : Duration.toMillis(pollInterval)
352
+ if (yield* awaitKey(Duration.millis(Math.max(0, gap)))) {
353
+ return
354
+ }
355
+ if (replaying) {
356
+ yield* Ref.update(shown, (shownCount) => shownCount + 1)
357
+ } else if (state.ended === undefined) {
358
+ const reread = yield* readInputs(target, files)
359
+ yield* Ref.set(inputs, reread)
360
+ yield* Ref.set(shown, reread.length)
361
+ }
362
+ }
363
+ }).pipe(Effect.ensuring(output.write(leaveScreen)))
364
+ })
365
+ )
366
+ })
367
+
368
+ // ── node wiring ─────────────────────────────────────────────────────────────
369
+
370
+ /** Folder names under an `epics/` directory; none when it is absent. */
371
+ export const nodeListEpics = (directory: string): ReadonlyArray<string> =>
372
+ existsSync(directory)
373
+ ? readdirSync(directory).filter((name) => statSync(join(directory, name)).isDirectory())
374
+ : []
375
+
376
+ export const nodeTraceSources: TraceSources = {
377
+ files: nodePlainFileStore,
378
+ listTraces: nodeListTraces,
379
+ listEpics: nodeListEpics
380
+ }
381
+
382
+ export const nodeWatchDependencies = (
383
+ environment: Readonly<Record<string, string | undefined>> = process.env
384
+ ): WatchDependencies => {
385
+ const interactive = process.stdout.isTTY === true && process.stdin.isTTY === true
386
+ return {
387
+ files: nodePlainFileStore,
388
+ listTraces: nodeListTraces,
389
+ listEpics: nodeListEpics,
390
+ output: {
391
+ write: (text) => Effect.sync(() => void process.stdout.write(text)),
392
+ columns: () => process.stdout.columns,
393
+ rows: () => process.stdout.rows,
394
+ interactive,
395
+ colour: process.stdout.isTTY === true && environment.NO_COLOR === undefined
396
+ },
397
+ keys: nodeTreeKeys("detach")
398
+ }
399
+ }
400
+
401
+ // ── tail ────────────────────────────────────────────────────────────────────
402
+
403
+ /**
404
+ * `llm4ts watch --tail <story|executor>`: the transcript printed as it grows,
405
+ * like `tail -f` — a call's reply streams in as written — until the run ends.
406
+ * A name with its own file is a story; any other is an executor.
407
+ */
408
+ const followTail = (
409
+ name: string,
410
+ directory: string,
411
+ transcripts: TranscriptFiles,
412
+ output: WatchOutput,
413
+ ended: () => Effect.Effect<boolean, FlowError>
414
+ ): Effect.Effect<void, FlowError> =>
415
+ Effect.gen(function* () {
416
+ const target: TailTarget = transcripts.list(directory).includes(transcriptFileOf(name))
417
+ ? { lane: name }
418
+ : { executor: name }
419
+ const width = Math.max(60, output.columns() ?? 100)
420
+ let shown = 0
421
+ let start: number | undefined
422
+ const wanted = new Set<string>()
423
+ let replying: string | undefined
424
+ while (true) {
425
+ const done = yield* ended()
426
+ const entries = (yield* loadTranscript(transcripts, directory, target)) ?? []
427
+ for (const entry of entries.slice(shown)) {
428
+ start = start ?? entry.at
429
+ if (entry._tag === "Call" && ("lane" in target || entry.executor === target.executor)) {
430
+ wanted.add(entry.call)
431
+ }
432
+ if (!wanted.has(entry.call)) {
433
+ continue
434
+ }
435
+ if (entry._tag === "Reply") {
436
+ // A reply streams: its text as it arrived, on one growing paragraph.
437
+ yield* output.write(`${replying === entry.call ? "" : "◀ "}${entry.text}`)
438
+ replying = entry.call
439
+ continue
440
+ }
441
+ const lines = renderTranscript([entry], { width, since: start })
442
+ yield* output.write(`${replying === undefined ? "" : "\n"}${lines.join("\n")}\n`)
443
+ replying = undefined
444
+ }
445
+ shown = entries.length
446
+ if (done) {
447
+ return
448
+ }
449
+ yield* Effect.sleep(pollInterval)
450
+ }
451
+ })