jig-console 0.0.0-stage → 0.1.1

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -2
  3. package/dist/commands/config.d.ts +8 -0
  4. package/dist/commands/config.d.ts.map +1 -0
  5. package/dist/commands/config.js +224 -0
  6. package/dist/commands/config.js.map +1 -0
  7. package/dist/commands/convert.d.ts +10 -0
  8. package/dist/commands/convert.d.ts.map +1 -0
  9. package/dist/commands/convert.js +40 -0
  10. package/dist/commands/convert.js.map +1 -0
  11. package/dist/commands/history.d.ts +8 -0
  12. package/dist/commands/history.d.ts.map +1 -0
  13. package/dist/commands/history.js +112 -0
  14. package/dist/commands/history.js.map +1 -0
  15. package/dist/commands/init.d.ts +7 -0
  16. package/dist/commands/init.d.ts.map +1 -0
  17. package/dist/commands/init.js +225 -0
  18. package/dist/commands/init.js.map +1 -0
  19. package/dist/commands/pipeline.d.ts +17 -0
  20. package/dist/commands/pipeline.d.ts.map +1 -0
  21. package/dist/commands/pipeline.js +137 -0
  22. package/dist/commands/pipeline.js.map +1 -0
  23. package/dist/commands/play.d.ts +13 -0
  24. package/dist/commands/play.d.ts.map +1 -0
  25. package/dist/commands/play.js +109 -0
  26. package/dist/commands/play.js.map +1 -0
  27. package/dist/commands/providers.d.ts +17 -0
  28. package/dist/commands/providers.d.ts.map +1 -0
  29. package/dist/commands/providers.js +161 -0
  30. package/dist/commands/providers.js.map +1 -0
  31. package/dist/commands/recipes.d.ts +16 -0
  32. package/dist/commands/recipes.d.ts.map +1 -0
  33. package/dist/commands/recipes.js +135 -0
  34. package/dist/commands/recipes.js.map +1 -0
  35. package/dist/commands/replay.d.ts +40 -0
  36. package/dist/commands/replay.d.ts.map +1 -0
  37. package/dist/commands/replay.js +206 -0
  38. package/dist/commands/replay.js.map +1 -0
  39. package/dist/commands/run.d.ts +3 -0
  40. package/dist/commands/run.d.ts.map +1 -0
  41. package/dist/commands/run.js +14 -0
  42. package/dist/commands/run.js.map +1 -0
  43. package/dist/commands/show.d.ts +15 -0
  44. package/dist/commands/show.d.ts.map +1 -0
  45. package/dist/commands/show.js +39 -0
  46. package/dist/commands/show.js.map +1 -0
  47. package/dist/commands/status.d.ts +6 -0
  48. package/dist/commands/status.d.ts.map +1 -0
  49. package/dist/commands/status.js +77 -0
  50. package/dist/commands/status.js.map +1 -0
  51. package/dist/commands/validate.d.ts +6 -0
  52. package/dist/commands/validate.d.ts.map +1 -0
  53. package/dist/commands/validate.js +36 -0
  54. package/dist/commands/validate.js.map +1 -0
  55. package/dist/help/jig-help.d.ts +25 -0
  56. package/dist/help/jig-help.d.ts.map +1 -0
  57. package/dist/help/jig-help.js +147 -0
  58. package/dist/help/jig-help.js.map +1 -0
  59. package/dist/index.d.ts +3 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +216 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/keys.d.ts +14 -0
  64. package/dist/keys.d.ts.map +1 -0
  65. package/dist/keys.js +68 -0
  66. package/dist/keys.js.map +1 -0
  67. package/dist/live-view.d.ts +90 -0
  68. package/dist/live-view.d.ts.map +1 -0
  69. package/dist/live-view.js +239 -0
  70. package/dist/live-view.js.map +1 -0
  71. package/dist/permissions.d.ts +40 -0
  72. package/dist/permissions.d.ts.map +1 -0
  73. package/dist/permissions.js +88 -0
  74. package/dist/permissions.js.map +1 -0
  75. package/dist/providers.d.ts +68 -0
  76. package/dist/providers.d.ts.map +1 -0
  77. package/dist/providers.js +230 -0
  78. package/dist/providers.js.map +1 -0
  79. package/dist/session/app.d.ts +28 -0
  80. package/dist/session/app.d.ts.map +1 -0
  81. package/dist/session/app.js +458 -0
  82. package/dist/session/app.js.map +1 -0
  83. package/dist/session/ascii.d.ts +5 -0
  84. package/dist/session/ascii.d.ts.map +1 -0
  85. package/dist/session/ascii.js +39 -0
  86. package/dist/session/ascii.js.map +1 -0
  87. package/dist/session/commands.d.ts +26 -0
  88. package/dist/session/commands.d.ts.map +1 -0
  89. package/dist/session/commands.js +828 -0
  90. package/dist/session/commands.js.map +1 -0
  91. package/dist/session/controller.d.ts +291 -0
  92. package/dist/session/controller.d.ts.map +1 -0
  93. package/dist/session/controller.js +779 -0
  94. package/dist/session/controller.js.map +1 -0
  95. package/dist/session/editor.d.ts +60 -0
  96. package/dist/session/editor.d.ts.map +1 -0
  97. package/dist/session/editor.js +128 -0
  98. package/dist/session/editor.js.map +1 -0
  99. package/dist/session/jig-theme.json +1 -0
  100. package/dist/session/keys.d.ts +26 -0
  101. package/dist/session/keys.d.ts.map +1 -0
  102. package/dist/session/keys.js +95 -0
  103. package/dist/session/keys.js.map +1 -0
  104. package/dist/session/lines.d.ts +65 -0
  105. package/dist/session/lines.d.ts.map +1 -0
  106. package/dist/session/lines.js +370 -0
  107. package/dist/session/lines.js.map +1 -0
  108. package/dist/session/markdown.d.ts +13 -0
  109. package/dist/session/markdown.d.ts.map +1 -0
  110. package/dist/session/markdown.js +188 -0
  111. package/dist/session/markdown.js.map +1 -0
  112. package/dist/session/models.d.ts +24 -0
  113. package/dist/session/models.d.ts.map +1 -0
  114. package/dist/session/models.js +17 -0
  115. package/dist/session/models.js.map +1 -0
  116. package/dist/session/start.d.ts +27 -0
  117. package/dist/session/start.d.ts.map +1 -0
  118. package/dist/session/start.js +140 -0
  119. package/dist/session/start.js.map +1 -0
  120. package/dist/session/theme.d.ts +137 -0
  121. package/dist/session/theme.d.ts.map +1 -0
  122. package/dist/session/theme.js +129 -0
  123. package/dist/session/theme.js.map +1 -0
  124. package/dist/session-runner.d.ts +107 -0
  125. package/dist/session-runner.d.ts.map +1 -0
  126. package/dist/session-runner.js +463 -0
  127. package/dist/session-runner.js.map +1 -0
  128. package/dist/terminal-width.d.ts +7 -0
  129. package/dist/terminal-width.d.ts.map +1 -0
  130. package/dist/terminal-width.js +45 -0
  131. package/dist/terminal-width.js.map +1 -0
  132. package/dist/topology-arg.d.ts +12 -0
  133. package/dist/topology-arg.d.ts.map +1 -0
  134. package/dist/topology-arg.js +26 -0
  135. package/dist/topology-arg.js.map +1 -0
  136. package/docs/jig-help.md +70 -0
  137. package/package.json +73 -4
@@ -0,0 +1,779 @@
1
+ // ============================================
2
+ // The session: a conversation where each message is a task
3
+ // ============================================
4
+ // Everything the screen shows comes from here, and nothing here draws. Each
5
+ // message you send runs the chosen topology through AgentSession, with the
6
+ // conversation so far as its input and memory scoped to this session; the
7
+ // answer streams in as Do's model writes it; typing during a run steers it;
8
+ // a shell command off a role's list waits here for your answer. Settings
9
+ // (the topology, a model per role, the budget, memory, tools, the advisor)
10
+ // and the conversation are kept in .jig/sessions/<id>.json, so --resume
11
+ // opens the session again. A past run can be replayed on the same screen.
12
+ import { EventEmitter } from "eventemitter3";
13
+ import { readFile, writeFile } from "node:fs/promises";
14
+ import { existsSync } from "node:fs";
15
+ import * as path from "node:path";
16
+ import { nanoid } from "nanoid";
17
+ import { AgentSession, InMemoryStorage, createDefaultToolkit, discoverLocal, drawingOf, ensureProjectDir, environmentBlock, eventsFromSteps, initialRunState, listProjectEntries, readablePaths, reduceRun, } from "jig-core";
18
+ import { resolveTopology } from "../topology-arg.js";
19
+ import { saveHistory, saveLocalRecord } from "../session-runner.js";
20
+ import { loadPermissions, nextMode, saveLocalRules } from "../permissions.js";
21
+ import { loadRecordedRun } from "../commands/replay.js";
22
+ import { splitRef } from "./models.js";
23
+ import { JIG_HELP, JigHelpTool, aboutJig, offerJigHelp } from "../help/jig-help.js";
24
+ /** The items a picker shows through its filter. */
25
+ export const pickerItems = (p) => {
26
+ const f = p.filter.toLowerCase();
27
+ return f ? p.items.filter((i) => `${i.label} ${i.detail ?? ""}`.toLowerCase().includes(f)) : p.items;
28
+ };
29
+ /** A role's brain config for a choice: a brain's name, a chain ("a/x,b/y"), or one model. */
30
+ function brainFor(choice, defaultEntry, keep) {
31
+ const { provider: _p, model: _m, brain: _b, chain: _c, ...rest } = keep ?? {};
32
+ if (choice.includes(","))
33
+ return { ...rest, chain: choice.split(",").map((c) => c.trim()) };
34
+ if (!choice.includes("/"))
35
+ return { ...rest, brain: choice };
36
+ return { ...rest, provider: splitRef(choice, defaultEntry).entry, model: splitRef(choice, defaultEntry).model };
37
+ }
38
+ export const DEFAULT_SETTINGS = {
39
+ topology: "exec-eval",
40
+ roleModels: {},
41
+ memoryScope: "session",
42
+ toolsOff: [],
43
+ checks: [],
44
+ checkFiles: [],
45
+ advisor: {},
46
+ };
47
+ const ACTIVITY = 5;
48
+ /** The earlier messages a run reads, as the conversation. */
49
+ const CONVERSATION_TURNS = 8;
50
+ export class SessionController extends EventEmitter {
51
+ options;
52
+ id;
53
+ createdAt;
54
+ workingDir;
55
+ models;
56
+ /** A key being typed for the keychain: what it is for, and where it goes. */
57
+ secret = null;
58
+ /** The picker open now, if any (pick). */
59
+ picker = null;
60
+ settings;
61
+ messages = [];
62
+ topology = null;
63
+ topologySource = "";
64
+ drawing = null;
65
+ runState;
66
+ running = null;
67
+ approvals = [];
68
+ /** The person's permissions: the mode (Shift+Tab), the rules, the working directories. */
69
+ permissions;
70
+ /** What the person allowed for the rest of this session: every edit, or shell rules kept for the project. */
71
+ grants = { edits: false, rules: [] };
72
+ /** Only a session started with --dangerously-skip-permissions has bypass in its cycle. */
73
+ bypassAvailable = false;
74
+ replay = null;
75
+ folded = false;
76
+ /** What the engine is doing now, for the header's pose, the status line and the footer. */
77
+ state = "idle";
78
+ /** When the current activity began: a one-shot pose plays from here, then holds. */
79
+ activitySince = 0;
80
+ get activity() {
81
+ return this.state;
82
+ }
83
+ /** A new state starts its pose and indicator from their first frame; the same state goes on. */
84
+ set activity(next) {
85
+ if (next === this.state)
86
+ return;
87
+ this.state = next;
88
+ this.activitySince = this.clock();
89
+ }
90
+ storage;
91
+ /** The run under way, and whether its run:end has arrived. */
92
+ current = null;
93
+ ended = false;
94
+ clock;
95
+ every;
96
+ replayTimer = null;
97
+ persist;
98
+ constructor(options) {
99
+ super();
100
+ this.options = options;
101
+ this.clock = options.clock ?? Date.now;
102
+ this.every =
103
+ options.every ??
104
+ ((fn, ms) => {
105
+ const t = setInterval(fn, ms);
106
+ return { stop: () => clearInterval(t) };
107
+ });
108
+ this.workingDir = options.workingDir;
109
+ this.models = options.models;
110
+ this.storage = options.storage ?? new InMemoryStorage();
111
+ this.persist = options.persist ?? true;
112
+ const saved = options.resume;
113
+ this.id = saved?.id ?? `session-${new Date(this.clock()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}-${nanoid(4)}`;
114
+ this.createdAt = saved?.createdAt ?? new Date(this.clock()).toISOString();
115
+ this.settings = { ...DEFAULT_SETTINGS, ...(saved?.settings ?? {}), ...(options.settings ?? {}) };
116
+ // Checks are for the next task only, so a resumed session starts without them.
117
+ if (saved)
118
+ this.settings = { ...this.settings, checks: options.settings?.checks ?? [], checkFiles: options.settings?.checkFiles ?? [] };
119
+ this.messages = saved ? saved.messages.filter((m) => m.kind !== "info") : [];
120
+ this.runState = initialRunState(this.clock());
121
+ this.permissions = options.permissions ?? loadPermissions(this.workingDir);
122
+ this.bypassAvailable = this.permissions.mode === "bypassPermissions";
123
+ }
124
+ /** Read the topology the settings name; an error goes into the conversation. */
125
+ async load() {
126
+ try {
127
+ const resolved = await resolveTopology(this.settings.topology, this.workingDir);
128
+ this.topology = resolved.topology;
129
+ this.topologySource = resolved.source;
130
+ this.drawing = this.drawingFor(resolved.topology);
131
+ for (const w of resolved.warnings)
132
+ this.say("error", `${w.path}: ${w.message}`);
133
+ }
134
+ catch (e) {
135
+ this.say("error", e.message);
136
+ if (this.settings.topology !== DEFAULT_SETTINGS.topology) {
137
+ this.settings.topology = DEFAULT_SETTINGS.topology;
138
+ await this.load();
139
+ return;
140
+ }
141
+ }
142
+ this.changed();
143
+ }
144
+ /** The drawing of a topology with the models this session gives its roles. */
145
+ drawingFor(t) {
146
+ // The boxes are narrow: they name the model, and the footer and /models say which entry serves it.
147
+ // A role on a brain is drawn with the model its brain would try first.
148
+ const shown = this.configured(t);
149
+ for (const n of shown.nodes) {
150
+ const b = n.config.brain;
151
+ const first = b?.brain && !b.model ? this.models.chain?.(b.brain)[0] : b?.chain?.[0];
152
+ if (first && !b?.model)
153
+ n.config = { ...n.config, brain: { ...b, model: splitRef(first, "").model } };
154
+ }
155
+ for (const c of shown.consults) {
156
+ const b = c.role.brain;
157
+ const first = b?.brain && !b.model ? this.models.chain?.(b.brain)[0] : undefined;
158
+ if (first)
159
+ c.role.brain = { ...b, model: splitRef(first, "").model };
160
+ }
161
+ return drawingOf(shown, { source: this.topologySource, model: splitRef(this.modelOf(""), "").model });
162
+ }
163
+ /** The model a role runs on in this session. */
164
+ modelOf(roleId) {
165
+ return this.settings.roleModels[roleId] ?? this.settings.defaultModel ?? this.models.defaultRef;
166
+ }
167
+ /** The topology as this session runs it: each role's model, the advisor's overrides. */
168
+ configured(t) {
169
+ // Every role may ask Jig's own documentation, whatever its tool list says.
170
+ const copy = offerJigHelp(t);
171
+ const def = splitRef(this.models.defaultRef, "").entry;
172
+ for (const node of copy.nodes) {
173
+ // A role the session names, else the session's default, else the definition's own model or brain, else the default.
174
+ const own = node.config.brain;
175
+ const ref = this.settings.roleModels[node.id] ?? this.settings.defaultModel ?? (own?.model || own?.brain || own?.chain?.length ? undefined : this.models.defaultRef);
176
+ if (ref)
177
+ node.config = { ...node.config, brain: brainFor(ref, def, own) };
178
+ // Tools turned off for this role in the session join its policy's deny list.
179
+ const off = this.settings.roleToolsOff?.[node.id] ?? [];
180
+ if (off.length) {
181
+ const policy = node.config.toolPolicy ?? (node.config.enabledTools?.length ? { allow: node.config.enabledTools } : {});
182
+ node.config = { ...node.config, toolPolicy: { ...policy, deny: [...new Set([...(policy.deny ?? []), ...off])] } };
183
+ }
184
+ }
185
+ for (const c of copy.consults) {
186
+ const ref = this.settings.advisor.model ?? this.settings.roleModels[c.role.id] ?? this.settings.defaultModel ?? (c.role.brain?.model ? undefined : this.models.defaultRef);
187
+ if (ref)
188
+ c.role.brain = brainFor(ref, def, c.role.brain);
189
+ if (this.settings.advisor.limit) {
190
+ c.limit = this.settings.advisor.limit;
191
+ c.label = c.label.replace(/\d+ a turn/, `${c.limit} a turn`);
192
+ }
193
+ if (this.settings.advisor.sees?.length)
194
+ c.sees = [...this.settings.advisor.sees];
195
+ }
196
+ return copy;
197
+ }
198
+ changed() {
199
+ this.emit("change");
200
+ }
201
+ say(kind, text) {
202
+ this.messages.push({ kind, text, at: this.clock() });
203
+ this.changed();
204
+ }
205
+ info(lines, title) {
206
+ this.messages.push({ kind: "info", lines, at: this.clock(), ...(title ? { title } : {}) });
207
+ this.changed();
208
+ }
209
+ /** A message from the input: a task, a note for a run, or a slash command (the caller sends those to commands). */
210
+ async send(text) {
211
+ const task = text.trim();
212
+ if (!task)
213
+ return;
214
+ // A run that has ended but not yet been put away takes no notes: the task waits for it.
215
+ if (this.running && this.ended)
216
+ await this.current;
217
+ if (this.running) {
218
+ this.running.steer(task);
219
+ this.messages.push({ kind: "note", text: task, at: this.clock() });
220
+ this.changed();
221
+ return;
222
+ }
223
+ this.current = this.runTask(task);
224
+ await this.current;
225
+ }
226
+ /** What the conversation so far gives the next run: your turns and the answers, which a model wrote. */
227
+ conversation() {
228
+ const turns = [];
229
+ for (const m of this.messages) {
230
+ if (m.kind === "you")
231
+ turns.push(`you: ${m.text.slice(0, 1500)}`);
232
+ else if (m.kind === "run" && m.outcome && m.text)
233
+ turns.push(`jig (${m.outcome}): ${m.text.slice(0, 1500)}`);
234
+ }
235
+ const recent = turns.slice(-CONVERSATION_TURNS * 2);
236
+ if (!recent.length)
237
+ return [];
238
+ return [{ name: "conversation", provenance: "written", content: `## Earlier in this conversation\n\n${recent.join("\n\n")}` }];
239
+ }
240
+ /** Run a task through the topology. Resolves when the run ends. */
241
+ async runTask(task) {
242
+ if (!this.topology)
243
+ await this.load();
244
+ const base = this.topology;
245
+ if (!base)
246
+ return;
247
+ const topology = this.configured(base);
248
+ this.drawing = this.drawingFor(base);
249
+ const inputs = this.conversation();
250
+ this.messages.push({ kind: "you", text: task, at: this.clock() });
251
+ const msg = { kind: "run", id: nanoid(6), task, topology: topology.id, at: this.clock(), text: "", activity: [] };
252
+ this.messages.push(msg);
253
+ const checks = this.settings.checks;
254
+ const checkFiles = this.settings.checkFiles;
255
+ // Checks are for the next task: they go with this one and are cleared.
256
+ this.settings = { ...this.settings, checks: [], checkFiles: [] };
257
+ let session;
258
+ try {
259
+ const provider = this.models.provider(this.modelOf(""));
260
+ session = new AgentSession({
261
+ provider,
262
+ // A role's brain or chain falls back along its models; a model is itself.
263
+ providerFactory: (brain) => this.models.provider(brain.chain?.length ? brain.chain.join(",") : brain.brain ? brain.brain : `${brain.provider ?? splitRef(this.models.defaultRef, "").entry}/${brain.model ?? splitRef(this.models.defaultRef, "").model}`),
264
+ tools: this.toolkit(),
265
+ environment: `${environmentBlock(this.workingDir)}\n\n${aboutJig()}`,
266
+ skipUnverifiable: this.options.skipUnverifiable ?? true,
267
+ topology,
268
+ workingDir: this.workingDir,
269
+ delayMs: 0,
270
+ tokenBudget: this.settings.tokenBudget,
271
+ memoryScope: this.settings.memoryScope,
272
+ memory: this.storage.memory,
273
+ sessionId: this.id,
274
+ storage: this.storage,
275
+ streamText: true,
276
+ permissions: {
277
+ settings: this.permissions,
278
+ grants: this.grants,
279
+ ask: (q) => this.ask(q),
280
+ saveRules: (rules) => {
281
+ saveLocalRules(this.workingDir, { add: { list: "allow", rules } });
282
+ this.permissions.rules.allow.push(...rules.filter((r) => !this.permissions.rules.allow.includes(r)));
283
+ },
284
+ },
285
+ runInfo: { provider: splitRef(this.modelOf(""), "").entry, model: splitRef(this.modelOf(""), "").model, tags: [topology.id, "jig", "session"], config: { source: "jig", sessionId: this.id } },
286
+ });
287
+ }
288
+ catch (e) {
289
+ msg.outcome = "failed";
290
+ msg.reason = e.message;
291
+ this.changed();
292
+ await this.save();
293
+ return;
294
+ }
295
+ this.running = session;
296
+ this.ended = false;
297
+ this.runState = initialRunState(this.clock());
298
+ this.activity = "team";
299
+ const drawing = this.drawing;
300
+ session.on("event", (e) => this.onEvent(e, msg, drawing));
301
+ this.changed();
302
+ try {
303
+ const run = await session.run({ task, ...(inputs.length ? { inputs } : {}), ...(checks.length ? { checks } : {}), ...(checkFiles.length ? { checkFiles } : {}) });
304
+ msg.runId = run.runId;
305
+ msg.text = run.answer || msg.text;
306
+ await saveLocalRecord(this.workingDir, run, {
307
+ topology: topology.id,
308
+ ...(this.topologySource.startsWith("topologies/") || this.topologySource === "registered in code" ? {} : { definition: path.resolve(this.workingDir, this.settings.topology) }),
309
+ task,
310
+ provider: splitRef(this.modelOf(""), "").entry,
311
+ model: splitRef(this.modelOf(""), "").model,
312
+ sessionId: this.id,
313
+ ...(this.runState.limits ? { limits: this.runState.limits } : {}),
314
+ }).catch(() => { });
315
+ await saveHistory(this.workingDir, run, { topology: topology.id }, splitRef(this.modelOf(""), "").entry, splitRef(this.modelOf(""), "").model).catch(() => { });
316
+ // The task and its answer, kept where a role recalling within this session finds them.
317
+ if (run.answer && this.settings.memoryScope !== "off") {
318
+ await this.storage.memory.put(["session", this.id], `task-${run.runId}`, { text: task, role: "user", messageType: "task" }).catch(() => { });
319
+ await this.storage.memory.put(["session", this.id], `result-${run.runId}`, { text: run.answer.slice(0, 4000), role: "agent", messageType: "result", outcome: run.outcome }).catch(() => { });
320
+ }
321
+ }
322
+ catch (e) {
323
+ msg.outcome = "failed";
324
+ msg.reason = e.message;
325
+ }
326
+ finally {
327
+ // The session is written before the run is put away, so whoever waits for the run's end reads it whole.
328
+ await this.save();
329
+ this.running = null;
330
+ for (const a of this.approvals.splice(0))
331
+ a.resolve({ answer: "deny" });
332
+ // A note reaches Do on its next turn; when the run ends first, say so.
333
+ if (this.runState.notes.length) {
334
+ this.info([[[` ¦ ${this.runState.notes.length === 1 ? "the note was" : `${this.runState.notes.length} notes were`} not read: Do had no turn after it`, "you"]]]);
335
+ }
336
+ this.activity = msg.outcome === "passed" ? "passed" : msg.outcome === "failed" ? "failed" : "idle";
337
+ this.changed();
338
+ }
339
+ }
340
+ onEvent(e, msg, drawing) {
341
+ const now = this.clock();
342
+ if (e.type === "text") {
343
+ // Do's answer as it is written; a later call of the turn starts it again.
344
+ const doer = drawing.roles.find((r) => r.id === e.role);
345
+ if (doer && this.topology?.nodes.find((n) => n.id === e.role)?.category === "execution") {
346
+ if (msg.seq !== e.seq) {
347
+ msg.text = "";
348
+ msg.seq = e.seq;
349
+ }
350
+ msg.text += e.delta;
351
+ this.activity = "thinking";
352
+ this.changed();
353
+ }
354
+ return;
355
+ }
356
+ this.runState = reduceRun(this.runState, e, now);
357
+ switch (e.type) {
358
+ case "role:start":
359
+ this.activity = "working";
360
+ // Do's new turn writes a new answer: the text of its last turn gives way to it.
361
+ if (this.topology?.nodes.find((n) => n.id === e.role)?.category === "execution") {
362
+ msg.text = "";
363
+ msg.seq = undefined;
364
+ }
365
+ break;
366
+ case "call":
367
+ this.activity = e.tools.length ? "tool" : "working";
368
+ break;
369
+ case "consult:start":
370
+ this.activity = "consulting";
371
+ break;
372
+ case "consult:end":
373
+ this.activity = "working";
374
+ break;
375
+ case "tool:start":
376
+ this.activity = "tool";
377
+ break;
378
+ case "tool:end":
379
+ this.activity = "working";
380
+ break;
381
+ case "approval:asked":
382
+ this.activity = "waiting";
383
+ break;
384
+ case "approval:answered":
385
+ this.activity = "tool";
386
+ break;
387
+ case "round:start":
388
+ if (e.round > 1 && drawing.roles[0]?.id !== e.startAt)
389
+ this.activity = "back";
390
+ break;
391
+ case "round:end":
392
+ if (e.next)
393
+ this.activity = "back";
394
+ break;
395
+ case "run:end":
396
+ this.ended = true;
397
+ msg.outcome = e.outcome;
398
+ msg.reason = e.reason;
399
+ msg.tokens = e.tokens.totalTokens;
400
+ msg.durationMs = e.durationMs;
401
+ msg.rounds = e.rounds;
402
+ msg.runId = e.runId;
403
+ if (e.answer)
404
+ msg.text = e.answer;
405
+ if (e.measured)
406
+ msg.checks = { passed: e.measured.results.filter((r) => r.passed).length, total: e.measured.results.length };
407
+ if (e.fallbacks?.length)
408
+ msg.fallbacks = e.fallbacks;
409
+ if (e.unverified)
410
+ msg.unverified = e.unverifiedReason ?? "nothing to verify";
411
+ this.activity = e.outcome === "passed" ? "passed" : e.outcome === "failed" ? "failed" : "idle";
412
+ break;
413
+ }
414
+ msg.events = this.runState.log.length;
415
+ this.changed();
416
+ }
417
+ /** The person's answer to the oldest open question; a no can carry what to do instead. */
418
+ answer(choice, feedback) {
419
+ const a = this.approvals.shift();
420
+ if (!a)
421
+ return;
422
+ const words = feedback?.trim();
423
+ a.resolve({ answer: choice, ...(words ? { feedback: words } : {}) });
424
+ // A plain no stops the run, as Claude Code stops the turn; a no with words lets the role go on with them.
425
+ if (choice === "deny" && !words && this.running) {
426
+ for (const b of this.approvals.splice(0))
427
+ b.resolve({ answer: "deny" });
428
+ this.running.stop("you said no");
429
+ }
430
+ this.changed();
431
+ }
432
+ ask(q) {
433
+ return new Promise((resolve) => {
434
+ this.approvals.push({ id: nanoid(6), question: q, resolve });
435
+ this.changed();
436
+ });
437
+ }
438
+ /** Shift+Tab: default, accept edits, plan, and round (bypass after plan, in a session started with it). */
439
+ cycleMode() {
440
+ this.permissions.mode = nextMode(this.permissions.mode, this.bypassAvailable);
441
+ this.changed();
442
+ }
443
+ /** Open a picker; resolves with the values chosen, in the list's order, or null on Esc. */
444
+ pick(title, items, o = {}) {
445
+ this.picker?.resolve(null);
446
+ return new Promise((resolve) => {
447
+ this.picker = {
448
+ id: nanoid(6),
449
+ title,
450
+ items,
451
+ multi: Boolean(o.multi),
452
+ at: Math.max(0, items.findIndex((i) => i.current)),
453
+ checked: new Set(o.checked ?? []),
454
+ filter: "",
455
+ ...(o.hint ? { hint: o.hint } : {}),
456
+ resolve: (values) => {
457
+ this.picker = null;
458
+ this.changed();
459
+ resolve(values);
460
+ },
461
+ };
462
+ this.changed();
463
+ });
464
+ }
465
+ /** One choice, or null on Esc. */
466
+ async pickOne(title, items, o = {}) {
467
+ return (await this.pick(title, items, o))?.[0] ?? null;
468
+ }
469
+ /** A key while a picker is open: move, check, choose, cancel, or filter. */
470
+ pickerKey(key) {
471
+ const p = this.picker;
472
+ if (!p)
473
+ return;
474
+ const shown = pickerItems(p);
475
+ const move = (to) => {
476
+ p.at = Math.max(0, Math.min(shown.length - 1, to));
477
+ };
478
+ // Digits choose in a short single list with no filter, as numbered; elsewhere they filter.
479
+ const numbered = !p.multi && !p.filter && shown.length <= 9;
480
+ if (key.kind === "escape" || (key.kind === "ctrl" && key.letter === "c"))
481
+ return p.resolve(null);
482
+ if (key.kind === "up")
483
+ move(p.at - 1);
484
+ else if (key.kind === "down")
485
+ move(p.at + 1);
486
+ else if (key.kind === "pageup")
487
+ move(p.at - 8);
488
+ else if (key.kind === "pagedown")
489
+ move(p.at + 8);
490
+ else if (key.kind === "home")
491
+ move(0);
492
+ else if (key.kind === "end")
493
+ move(shown.length - 1);
494
+ else if (key.kind === "enter") {
495
+ if (p.multi)
496
+ return p.resolve(p.items.filter((i) => p.checked.has(i.value)).map((i) => i.value));
497
+ if (shown[p.at])
498
+ return p.resolve([shown[p.at].value]);
499
+ }
500
+ else if (key.kind === "text" && key.text === " " && p.multi) {
501
+ const v = shown[p.at]?.value;
502
+ if (v !== undefined)
503
+ p.checked.has(v) ? p.checked.delete(v) : p.checked.add(v);
504
+ }
505
+ else if (key.kind === "text" && numbered && /^[1-9]$/.test(key.text)) {
506
+ const item = shown[Number(key.text) - 1];
507
+ if (item)
508
+ return p.resolve([item.value]);
509
+ }
510
+ else if (key.kind === "backspace") {
511
+ p.filter = p.filter.slice(0, -1);
512
+ p.at = 0;
513
+ }
514
+ else if (key.kind === "text" || key.kind === "paste") {
515
+ p.filter += key.text.replace(/[\r\n]+/g, "");
516
+ p.at = 0;
517
+ }
518
+ this.changed();
519
+ }
520
+ /** Ask for a key without showing it; null when the person cancels. */
521
+ askSecret(label) {
522
+ return new Promise((resolve) => {
523
+ this.secret = {
524
+ label,
525
+ resolve: (v) => {
526
+ this.secret = null;
527
+ this.changed();
528
+ resolve(v);
529
+ },
530
+ };
531
+ this.changed();
532
+ });
533
+ }
534
+ async reload() {
535
+ const found = this.models.discovery?.found;
536
+ if (this.options.reloadModels)
537
+ this.models = await this.options.reloadModels();
538
+ // What discovery found stays for the session: a reload keeps it until /providers discover asks again.
539
+ if (found)
540
+ this.models.applyDiscovery?.(found);
541
+ if (this.topology)
542
+ this.drawing = this.drawingFor(this.topology);
543
+ this.changed();
544
+ }
545
+ /** Ask this machine's model servers, in the background; the header and /providers say what answered. */
546
+ async discover() {
547
+ const m = this.models;
548
+ if (!m.applyDiscovery)
549
+ return;
550
+ const found = await discoverLocal(this.options.discovery);
551
+ m.applyDiscovery(found);
552
+ if (this.topology)
553
+ this.drawing = this.drawingFor(this.topology);
554
+ this.changed();
555
+ }
556
+ /** Esc: deny an open question, else stop the run, else close a replay. Returns whether it did something. */
557
+ interrupt() {
558
+ if (this.approvals.length) {
559
+ this.answer("deny");
560
+ return true;
561
+ }
562
+ if (this.running) {
563
+ this.running.stop("interrupted with Esc");
564
+ return true;
565
+ }
566
+ if (this.replay) {
567
+ this.closeReplay();
568
+ return true;
569
+ }
570
+ return false;
571
+ }
572
+ toggleFold() {
573
+ this.folded = !this.folded;
574
+ this.changed();
575
+ }
576
+ /** The tools a run gets: the defaults the session leaves on, and jig_help unless it is turned off. */
577
+ toolkit() {
578
+ const tools = createDefaultToolkit(this.enabledTools(), { unescapeNewlines: this.options.unescapeNewlines !== false });
579
+ if (!this.settings.toolsOff.includes(JIG_HELP))
580
+ tools.register(new JigHelpTool());
581
+ return tools;
582
+ }
583
+ enabledTools() {
584
+ if (!this.settings.toolsOff.length)
585
+ return undefined;
586
+ return createDefaultToolkit()
587
+ .getAll()
588
+ .map((t) => t.definition.name)
589
+ .filter((n) => !this.settings.toolsOff.includes(n));
590
+ }
591
+ /** Switch the topology; it takes effect on the next task. */
592
+ async useTopology(arg) {
593
+ const before = this.settings.topology;
594
+ this.settings = { ...this.settings, topology: arg };
595
+ try {
596
+ const resolved = await resolveTopology(arg, this.workingDir);
597
+ this.topology = resolved.topology;
598
+ this.topologySource = resolved.source;
599
+ this.drawing = this.drawingFor(resolved.topology);
600
+ this.runState = initialRunState(this.clock());
601
+ for (const w of resolved.warnings)
602
+ this.say("error", `${w.path}: ${w.message}`);
603
+ await this.save();
604
+ this.changed();
605
+ return true;
606
+ }
607
+ catch (e) {
608
+ this.settings = { ...this.settings, topology: before };
609
+ this.say("error", e.message);
610
+ return false;
611
+ }
612
+ }
613
+ /** Settings changed: redraw with them, and keep them. */
614
+ async update(patch) {
615
+ this.settings = { ...this.settings, ...patch };
616
+ if (this.topology)
617
+ this.drawing = this.drawingFor(this.topology);
618
+ await this.save();
619
+ this.changed();
620
+ }
621
+ /** Forget the conversation; settings stay. */
622
+ async clear() {
623
+ this.messages = [];
624
+ this.runState = initialRunState(this.clock());
625
+ this.activity = "idle";
626
+ await this.save();
627
+ this.changed();
628
+ }
629
+ // ---- Replay ----
630
+ async openReplay(runId, speed = 4) {
631
+ const loaded = await loadRecordedRun(runId, this.workingDir, this.storage);
632
+ const resolved = await resolveTopology(loaded.topology || this.settings.topology, this.workingDir);
633
+ const events = eventsFromSteps(loaded.steps, {
634
+ runId,
635
+ topology: resolved.topology,
636
+ ...(loaded.task ? { task: loaded.task } : {}),
637
+ ...(loaded.outcome ? { outcome: loaded.outcome } : {}),
638
+ ...(loaded.reason ? { reason: loaded.reason } : {}),
639
+ ...(loaded.limits ? { limits: loaded.limits } : {}),
640
+ });
641
+ this.closeReplay();
642
+ const t0 = events[0]?.at ?? this.clock();
643
+ this.replay = {
644
+ runId,
645
+ drawing: drawingOf(resolved.topology, { source: loaded.from, model: loaded.model ?? "" }),
646
+ state: initialRunState(t0),
647
+ events,
648
+ next: 0,
649
+ t0,
650
+ total: (events.at(-1)?.at ?? t0) - t0,
651
+ pos: t0,
652
+ playing: true,
653
+ speed,
654
+ finished: events.length === 0,
655
+ };
656
+ const steps = `${loaded.steps.length} step${loaded.steps.length === 1 ? "" : "s"}`;
657
+ this.info([[[`replaying ${runId}: ${steps} from ${loaded.from}, ${events.length} events ∙ space pauses ∙ ⇢ steps ∙ esc closes`, "dim"]]], "replay");
658
+ let last = this.clock();
659
+ this.replayTimer = this.every(() => {
660
+ const r = this.replay;
661
+ if (!r)
662
+ return;
663
+ const now = this.clock();
664
+ if (r.playing && !r.finished)
665
+ r.pos += (now - last) * r.speed;
666
+ last = now;
667
+ let moved = false;
668
+ while (r.playing && r.next < r.events.length && r.events[r.next].at <= r.pos) {
669
+ this.replayStep(false);
670
+ moved = true;
671
+ }
672
+ if (r.next >= r.events.length && !r.finished) {
673
+ r.finished = true;
674
+ r.pos = r.t0 + r.total;
675
+ moved = true;
676
+ }
677
+ if (moved || r.playing)
678
+ this.changed();
679
+ }, 40);
680
+ this.changed();
681
+ }
682
+ /** The next recorded event, now. */
683
+ replayStep(pause = true) {
684
+ const r = this.replay;
685
+ if (!r || r.next >= r.events.length)
686
+ return;
687
+ const { at, event } = r.events[r.next++];
688
+ r.pos = Math.max(r.pos, at);
689
+ r.state = reduceRun(r.state, event, at);
690
+ if (pause)
691
+ r.playing = false;
692
+ this.changed();
693
+ }
694
+ toggleReplay() {
695
+ if (!this.replay || this.replay.finished)
696
+ return;
697
+ this.replay.playing = !this.replay.playing;
698
+ this.changed();
699
+ }
700
+ closeReplay() {
701
+ this.replayTimer?.stop();
702
+ this.replayTimer = null;
703
+ if (this.replay) {
704
+ this.replay = null;
705
+ this.changed();
706
+ }
707
+ }
708
+ /** Past runs in this working directory, newest first: from .jig/runs and .agentic-lab/runs. */
709
+ async pastRuns(limit = 15) {
710
+ const entries = await listProjectEntries(this.workingDir, "runs");
711
+ const out = [];
712
+ for (const e of entries) {
713
+ const rec = path.join(e.dir, "record.json");
714
+ if (!existsSync(rec) || !existsSync(path.join(e.dir, "steps.json")))
715
+ continue;
716
+ try {
717
+ const r = JSON.parse(await readFile(rec, "utf-8"));
718
+ const stamp = /^run-(\d+)-/.exec(e.name);
719
+ out.push({ runId: e.name, topology: String(r.topology ?? ""), ...(typeof r.outcome === "string" ? { outcome: r.outcome } : {}), ...(typeof r.task === "string" ? { task: r.task } : {}), at: stamp ? Number(stamp[1]) : 0 });
720
+ }
721
+ catch {
722
+ /* an unreadable record is skipped */
723
+ }
724
+ }
725
+ return out.sort((a, b) => b.at - a.at).slice(0, limit);
726
+ }
727
+ // ---- Persistence ----
728
+ get file() {
729
+ return path.join(readablePaths(this.workingDir, "sessions")[0], `${this.id}.json`);
730
+ }
731
+ /** Saves one at a time, in order: two writes of the same file at once could interleave. */
732
+ saving = Promise.resolve();
733
+ save() {
734
+ if (!this.persist)
735
+ return Promise.resolve();
736
+ this.saving = this.saving.then(() => this.write()).catch(() => { });
737
+ return this.saving;
738
+ }
739
+ async write() {
740
+ const saved = {
741
+ id: this.id,
742
+ version: 1,
743
+ createdAt: this.createdAt,
744
+ updatedAt: new Date(this.clock()).toISOString(),
745
+ workingDir: this.workingDir,
746
+ settings: this.settings,
747
+ // What a person wrote and what the runs answered; command output is not kept.
748
+ messages: this.messages.filter((m) => m.kind !== "info").map((m) => (m.kind === "run" ? { ...m, activity: [] } : m)),
749
+ };
750
+ await ensureProjectDir(this.workingDir, "sessions");
751
+ await writeFile(this.file, JSON.stringify(saved, null, 1));
752
+ }
753
+ /** Stop what runs, close a replay. */
754
+ shutdown() {
755
+ this.running?.stop("the session was closed");
756
+ for (const a of this.approvals.splice(0))
757
+ a.resolve({ answer: "deny" });
758
+ this.closeReplay();
759
+ }
760
+ /** The run's latest log lines, for the message under way. */
761
+ recentActivity(lines) {
762
+ return lines.slice(-ACTIVITY);
763
+ }
764
+ }
765
+ /** The saved sessions in a working directory, newest first. */
766
+ export async function savedSessions(workingDir) {
767
+ const entries = await listProjectEntries(workingDir, "sessions");
768
+ const out = [];
769
+ for (const e of entries.filter((x) => x.name.endsWith(".json"))) {
770
+ try {
771
+ out.push(JSON.parse(await readFile(e.dir, "utf-8")));
772
+ }
773
+ catch {
774
+ /* skipped */
775
+ }
776
+ }
777
+ return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
778
+ }
779
+ //# sourceMappingURL=controller.js.map