@andorra-labs/code 0.1.8 → 0.1.10

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 (187) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +57 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +120 -1
  8. package/dist/src/app-server/protocol.js +8 -1
  9. package/dist/src/app-server/reasoning.d.ts +0 -8
  10. package/dist/src/app-server/reasoning.js +15 -28
  11. package/dist/src/app-server.d.ts +32 -0
  12. package/dist/src/app-server.js +214 -21
  13. package/dist/src/auth/AuthManager.d.ts +15 -0
  14. package/dist/src/auth/AuthManager.js +66 -7
  15. package/dist/src/auth/index.d.ts +1 -1
  16. package/dist/src/auth/index.js +1 -1
  17. package/dist/src/auth/store.d.ts +17 -1
  18. package/dist/src/auth/store.js +25 -2
  19. package/dist/src/browser-runner.js +1 -2
  20. package/dist/src/browser-server.js +10 -2
  21. package/dist/src/browser-session.js +6 -2
  22. package/dist/src/browser-stealth.d.ts +29 -0
  23. package/dist/src/browser-stealth.js +166 -0
  24. package/dist/src/browser-ui/app.js +123 -28
  25. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  26. package/dist/src/browser-ui/index.html +8 -8
  27. package/dist/src/browser-ui/style.css +199 -171
  28. package/dist/src/browser-ui/tokens.css +198 -0
  29. package/dist/src/browser-view.d.ts +57 -9
  30. package/dist/src/browser-view.js +187 -36
  31. package/dist/src/cli.js +31 -9
  32. package/dist/src/coding-tools.js +9 -5
  33. package/dist/src/command-screens.js +4 -4
  34. package/dist/src/commands.d.ts +1 -1
  35. package/dist/src/commands.js +3 -2
  36. package/dist/src/completion-gates.d.ts +35 -0
  37. package/dist/src/completion-gates.js +25 -0
  38. package/dist/src/completion.d.ts +7 -1
  39. package/dist/src/completion.js +37 -4
  40. package/dist/src/config.d.ts +1 -1
  41. package/dist/src/config.js +2 -2
  42. package/dist/src/context-budget.d.ts +11 -0
  43. package/dist/src/context-budget.js +13 -0
  44. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  45. package/dist/src/decision/DecisionManager.d.ts +1 -0
  46. package/dist/src/decision/DecisionManager.js +14 -3
  47. package/dist/src/decision/FactContinuations.d.ts +6 -0
  48. package/dist/src/decision/FactContinuations.js +9 -1
  49. package/dist/src/decision/FactServiceGate.js +1 -1
  50. package/dist/src/decision/checks.js +1 -1
  51. package/dist/src/decision/hostedSkills.d.ts +37 -0
  52. package/dist/src/decision/hostedSkills.js +64 -0
  53. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  54. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  55. package/dist/src/default-graph.d.ts +11 -0
  56. package/dist/src/default-graph.js +20 -0
  57. package/dist/src/duration.d.ts +13 -2
  58. package/dist/src/duration.js +27 -3
  59. package/dist/src/file-diff.d.ts +105 -0
  60. package/dist/src/file-diff.js +244 -0
  61. package/dist/src/graph-manager-chat.d.ts +302 -0
  62. package/dist/src/graph-manager-chat.js +940 -0
  63. package/dist/src/graph-runner.js +6 -0
  64. package/dist/src/graph-server.d.ts +9 -0
  65. package/dist/src/graph-server.js +171 -20
  66. package/dist/src/graph-studio-features.js +2 -2
  67. package/dist/src/graph-sync.js +5 -2
  68. package/dist/src/graph-ui/app.js +369 -183
  69. package/dist/src/graph-ui/controls.css +55 -32
  70. package/dist/src/graph-ui/controls.js +85 -9
  71. package/dist/src/graph-ui/edge-router.js +114 -13
  72. package/dist/src/graph-ui/embed.js +32 -17
  73. package/dist/src/graph-ui/icons.js +1 -0
  74. package/dist/src/graph-ui/index.html +4 -4
  75. package/dist/src/graph-ui/library.css +4 -10
  76. package/dist/src/graph-ui/manager-markdown.js +155 -0
  77. package/dist/src/graph-ui/manager-state.js +191 -0
  78. package/dist/src/graph-ui/manager.css +161 -0
  79. package/dist/src/graph-ui/manager.js +700 -0
  80. package/dist/src/graph-ui/skill-picker.js +6 -6
  81. package/dist/src/graph-ui/studio-canvas.js +17 -15
  82. package/dist/src/graph-ui/studio.css +24 -23
  83. package/dist/src/graph-ui/studio.js +69 -48
  84. package/dist/src/graph-ui/style.css +128 -93
  85. package/dist/src/graph-ui/theme.js +2 -2
  86. package/dist/src/graph-ui/tokens.css +217 -151
  87. package/dist/src/graphs.d.ts +76 -2
  88. package/dist/src/graphs.js +172 -9
  89. package/dist/src/hardened-runtime.js +8 -2
  90. package/dist/src/mcp.d.ts +75 -0
  91. package/dist/src/mcp.js +240 -8
  92. package/dist/src/membership-errors.d.ts +14 -0
  93. package/dist/src/membership-errors.js +24 -1
  94. package/dist/src/membership.d.ts +20 -0
  95. package/dist/src/membership.js +45 -16
  96. package/dist/src/palette.d.ts +25 -8
  97. package/dist/src/palette.js +26 -8
  98. package/dist/src/provider-engine.d.ts +4 -4
  99. package/dist/src/provider-engine.js +39 -22
  100. package/dist/src/provider-keys.d.ts +5 -1
  101. package/dist/src/provider-keys.js +7 -3
  102. package/dist/src/provider-settings.d.ts +4 -1
  103. package/dist/src/provider-settings.js +46 -5
  104. package/dist/src/providers.d.ts +24 -0
  105. package/dist/src/providers.js +47 -2
  106. package/dist/src/qa/guidance.d.ts +26 -0
  107. package/dist/src/qa/guidance.js +46 -0
  108. package/dist/src/qa/index.d.ts +1 -8
  109. package/dist/src/qa/index.js +1 -16
  110. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  111. package/dist/src/qa/profile/QaProfile.js +6 -2
  112. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  113. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  114. package/dist/src/qa/tools.d.ts +19 -1
  115. package/dist/src/qa/tools.js +20 -145
  116. package/dist/src/react-runtime.d.ts +11 -0
  117. package/dist/src/react-runtime.js +203 -53
  118. package/dist/src/remote/engine-pool.js +21 -6
  119. package/dist/src/run-progress.d.ts +6 -0
  120. package/dist/src/run-progress.js +7 -0
  121. package/dist/src/runtime.d.ts +8 -0
  122. package/dist/src/screen-selection.d.ts +38 -0
  123. package/dist/src/screen-selection.js +103 -0
  124. package/dist/src/session-changes.d.ts +117 -0
  125. package/dist/src/session-changes.js +796 -0
  126. package/dist/src/session-skills.d.ts +75 -0
  127. package/dist/src/session-skills.js +151 -0
  128. package/dist/src/side-panel.d.ts +1 -1
  129. package/dist/src/side-panel.js +6 -12
  130. package/dist/src/skill-commands.js +1 -1
  131. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  132. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  133. package/dist/src/skills/bundled/provenance.json +3 -3
  134. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  135. package/dist/src/stall-recovery.d.ts +33 -0
  136. package/dist/src/stall-recovery.js +83 -0
  137. package/dist/src/subagent-run.js +1 -2
  138. package/dist/src/telemetry/schema.d.ts +1 -1
  139. package/dist/src/telemetry/schema.js +1 -2
  140. package/dist/src/terminal-ui.d.ts +66 -22
  141. package/dist/src/terminal-ui.js +327 -92
  142. package/dist/src/tool-diff-stats.d.ts +9 -0
  143. package/dist/src/tool-diff-stats.js +20 -0
  144. package/dist/src/tool-names.d.ts +1 -1
  145. package/dist/src/tool-result-filter.js +1 -1
  146. package/dist/src/tools.js +26 -2
  147. package/dist/src/transcript.d.ts +11 -0
  148. package/dist/src/transcript.js +23 -3
  149. package/dist/src/types.d.ts +24 -4
  150. package/dist/src/usage-analytics.d.ts +7 -0
  151. package/dist/src/usage-analytics.js +55 -15
  152. package/docs/concepts/README.md +1 -1
  153. package/docs/concepts/limits.md +9 -0
  154. package/docs/guides/desktop-app.md +1 -1
  155. package/docs/guides/graph-builder.md +16 -1
  156. package/docs/guides/tui.md +9 -9
  157. package/docs/reference/slash-commands.md +2 -1
  158. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  159. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  160. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  161. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  162. package/package.json +1 -1
  163. package/tests/chat-side-panel-test-plan.md +1 -1
  164. package/dist/src/qa/api/http-runner.d.ts +0 -3
  165. package/dist/src/qa/api/http-runner.js +0 -47
  166. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  167. package/dist/src/qa/git/ChangeDetector.js +0 -177
  168. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  169. package/dist/src/qa/git/DiffReviewer.js +0 -115
  170. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  171. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  172. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  173. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  174. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  175. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  176. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  177. package/dist/src/qa/runners/CommandRunner.js +0 -96
  178. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  179. package/dist/src/qa/runners/TestRunner.js +0 -66
  180. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  181. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  182. package/dist/src/qa/runtime-detect.d.ts +0 -10
  183. package/dist/src/qa/runtime-detect.js +0 -72
  184. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  185. package/dist/src/qa/security/DependencyScanner.js +0 -167
  186. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  187. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -0,0 +1,940 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { stopAutomationWorker } from './automation-worker-shutdown.js';
7
+ import { configDirectory } from './config.js';
8
+ import { GRAPH_MANAGER_GRAPH_ID } from './graphs.js';
9
+ import { clipText } from './text.js';
10
+ import { describeTool } from './transcript.js';
11
+ const STARTUP_MS = 60_000;
12
+ /** How long a new chat waits for a cancelled run to end before it stops the engine instead. */
13
+ const RESET_WAIT_MS = 10_000;
14
+ /** How long a message waits for a run that is already ending before it is reported instead of sent. */
15
+ const ENDING_WAIT_MS = 30_000;
16
+ /** Mirrors `MAX_TASK_CHARS` in `app-server.ts`: the engine refuses a longer `run.start` task or `run.steer` text. */
17
+ export const MANAGER_TASK_MAX_CHARS = 100_000;
18
+ const UPDATE_MESSAGE = 'Update Andorra Code to use Workflow Manager.';
19
+ const TOO_LARGE_MESSAGE = 'This workflow is too large to send to Workflow Manager.';
20
+ /** The longest tool or approval line the panel is given. */
21
+ const TOOL_LINE_MAX = 120;
22
+ /** How many draft-to-graph pairings are remembered; an agent holds a handful of drafts at most. */
23
+ const DRAFTS_MAX = 64;
24
+ /** The bundled preset every installation has. Nothing can be saved under its id. */
25
+ const BUNDLED_GRAPH_ID = 'default';
26
+ /** The engine went away, deliberately or not; whoever stopped it has already said what there is to say. */
27
+ class EngineStopped extends Error {
28
+ }
29
+ /** The engine answered a request with an error; `code` is its own classification. */
30
+ class EngineRefusal extends Error {
31
+ code;
32
+ constructor(message, code) {
33
+ super(message);
34
+ this.code = code;
35
+ }
36
+ }
37
+ const graphName = (graph) => (typeof graph.name === 'string' ? graph.name.replace(/\s+/g, ' ').trim() : '') || 'Untitled graph';
38
+ const graphId = (graph) => typeof graph.id === 'string' ? graph.id : '';
39
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
40
+ const toolArguments = (value) => {
41
+ try {
42
+ return record(typeof value === 'string' ? JSON.parse(value) : value);
43
+ }
44
+ catch {
45
+ return {};
46
+ }
47
+ };
48
+ /** Plain text on one line: control characters and line breaks become single spaces. */
49
+ const oneLine = (value) => typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069\s]+/g, ' ').trim() : '';
50
+ const toolLine = (...parts) => clipText(parts.map(oneLine).filter(Boolean).join(' \u00b7 '), TOOL_LINE_MAX);
51
+ /**
52
+ * One line saying what a tool call or an approval is about, for the tools Graph Manager works with:
53
+ * the `graphs` action and the graph it names, the skill being read, the server being connected.
54
+ * A publish names only its draft, so `graphOfDraft` supplies the graph when the caller knows it.
55
+ * Every other tool keeps the transcript's wording. The line is at most 120 characters.
56
+ */
57
+ export function describeManagerTool(name, value, graphOfDraft = () => undefined) {
58
+ const args = toolArguments(value);
59
+ if (name === 'graphs') {
60
+ const input = record(args.args);
61
+ const graph = typeof input.id === 'string' ? input.id : typeof input.draftId === 'string' ? graphOfDraft(input.draftId) : undefined;
62
+ return toolLine('graphs', args.action, graph);
63
+ }
64
+ if (name === 'Skill')
65
+ return toolLine('Skill', args.skill ?? args.name);
66
+ if (name === 'read_skill_resource')
67
+ return toolLine(name, args.skill, args.path);
68
+ if (name === 'mcp_connect')
69
+ return toolLine(name, args.server);
70
+ return clipText(describeTool(name, value), TOOL_LINE_MAX);
71
+ }
72
+ /** What each `graphs` action does, as the row's verb. An action not named here shows its own name. */
73
+ const GRAPH_ACTION_VERBS = {
74
+ andorra_graph_begin: 'Open draft', andorra_graph_get: 'Read workflow', andorra_graph_guide: 'Read guide',
75
+ andorra_graph_node_upsert: 'Set step', andorra_graph_node_patch: 'Edit step', andorra_graph_node_remove: 'Remove step',
76
+ andorra_graph_edge_upsert: 'Connect', andorra_graph_edge_remove: 'Remove connection', andorra_graph_patch: 'Edit workflow',
77
+ andorra_graph_validate: 'Validate draft', andorra_graph_publish: 'Save version', andorra_graph_discard: 'Discard draft',
78
+ andorra_graph_delete: 'Delete workflow', andorra_graph_restore: 'Restore workflow',
79
+ };
80
+ /**
81
+ * A tool call split the way the app's transcript draws it: the verb, and the thing it acted on.
82
+ * A node is named by its name when the call carries one; a connection reads `source → target`
83
+ * with its outcome. The graph the call is about is left out when it is the open one, which every
84
+ * call of a conversation usually is. Any other tool keeps the transcript's one line as its verb.
85
+ */
86
+ export function managerToolParts(name, value, openGraphId) {
87
+ const args = toolArguments(value);
88
+ const clip = (text) => text ? clipText(text, TOOL_LINE_MAX) : undefined;
89
+ const parts = (verb, target) => { const clipped = clip(oneLine(target)); return clipped ? { verb, target: clipped } : { verb }; };
90
+ if (name === 'graphs') {
91
+ const action = typeof args.action === 'string' ? args.action : '';
92
+ const input = record(args.args);
93
+ const verb = GRAPH_ACTION_VERBS[action] ?? (action || 'graphs');
94
+ const node = record(input.node), edge = record(input.edge);
95
+ const other = typeof input.id === 'string' && input.id !== openGraphId ? input.id : undefined;
96
+ if (action === 'andorra_graph_node_upsert')
97
+ return parts(verb, oneLine(node.name) || oneLine(node.id));
98
+ if (action === 'andorra_graph_node_patch' || action === 'andorra_graph_node_remove')
99
+ return parts(verb, oneLine(input.nodeId));
100
+ if (action === 'andorra_graph_edge_upsert') {
101
+ const route = [oneLine(edge.source), oneLine(edge.target)].filter(Boolean).join(' → ');
102
+ const outcome = oneLine(edge.outcome);
103
+ return parts(verb, route ? `${route}${outcome ? ` (${outcome})` : ''}` : oneLine(edge.id));
104
+ }
105
+ if (action === 'andorra_graph_edge_remove')
106
+ return parts(verb, oneLine(input.edgeId));
107
+ if (action === 'andorra_graph_begin')
108
+ return parts(verb, other && (oneLine(input.name) || other));
109
+ return parts(verb, other);
110
+ }
111
+ if (name === 'Skill')
112
+ return parts('Load skill', oneLine(args.skill ?? args.name));
113
+ if (name === 'read_skill_resource')
114
+ return parts('Read skill file', oneLine(args.path) || oneLine(args.skill));
115
+ if (name === 'mcp_connect')
116
+ return parts('Connect server', oneLine(args.server));
117
+ return { verb: clipText(describeTool(name, value), TOOL_LINE_MAX) };
118
+ }
119
+ /** Bookkeeping calls the runtime handles itself; a conversation shows what the agent did, not these. */
120
+ const HIDDEN_TOOLS = new Set(['update_todos', 'update_widget', 'prepare_steps', 'restore_tools', 'complete_agent']);
121
+ const STOPPED_UNREAD_MESSAGE = 'Workflow Manager was stopped before it read your last message. Send it again to continue.';
122
+ /**
123
+ * The environment the chat's engine starts in: the parent's own, so the engine is signed in as the
124
+ * parent is. Stored credentials are scoped to an explicitly named home (`credentialIdentity`), so
125
+ * naming even the default home would move the engine to an empty credential slot. The home is
126
+ * named only when the chat runs against a different one than the environment already selects.
127
+ *
128
+ * The engine is marked as a worker, as the automation runner marks its own. An unmarked engine is a
129
+ * window's: it runs the user's automations, watches their pull requests and archives old sessions.
130
+ * This one is stopped when idle and when the editor closes, which would interrupt an automation it
131
+ * had claimed. The mark switches off those three background services and nothing else.
132
+ *
133
+ * A relative inherited home means the parent's working directory, and the engine starts in its own
134
+ * workspace, where the same words would name another folder with another configuration and another
135
+ * credential slot. It is handed the absolute path instead, which `credentialIdentity` resolves to
136
+ * the scope the parent reads.
137
+ */
138
+ export function managerEngineEnvironment(directory, environment = process.env) {
139
+ const inherited = environment.ANDORRACODE_HOME;
140
+ const worker = { ...environment, ...(inherited && !isAbsolute(inherited) ? { ANDORRACODE_HOME: resolve(inherited) } : {}), ANDORRA_AUTOMATION_WORKER: '1' };
141
+ if (resolve(directory) === resolve(configDirectory(environment)))
142
+ return worker;
143
+ return { ...worker, ANDORRACODE_HOME: resolve(directory) };
144
+ }
145
+ /**
146
+ * What the agent is given with every message: which graph is open, the canvas as the user sees it
147
+ * now (unsaved edits included), the model the panel has selected, and the user's own words.
148
+ */
149
+ export function managerTask(turn) {
150
+ const saved = !turn.saved ? 'not saved yet' : turn.revision === undefined ? 'saved' : `saved revision ${turn.revision}`;
151
+ return [
152
+ `You are helping in Graph Studio. Open graph: "${graphName(turn.graph)}", id ${graphId(turn.graph)} (${saved}).`,
153
+ // A save under the preset's id is refused, so the agent is told before it tries.
154
+ graphId(turn.graph) === BUNDLED_GRAPH_ID
155
+ ? `The open graph is the bundled preset, which cannot be changed: nothing can be saved under the id "${BUNDLED_GRAPH_ID}". The canvas below is what the user sees now. Do not edit this graph; create a new graph with a new id and its own name (mode "create"), based on the canvas, and make your changes there.`
156
+ : 'The canvas below is what the user sees now, including edits not yet saved. Work from it, and save your changes under this same graph id (mode "create" when it is not saved yet, "edit" otherwise).',
157
+ `Selected model: ${turn.provider}/${turn.model}. Use it for new agent nodes unless the user asks otherwise.`,
158
+ '',
159
+ 'Canvas:',
160
+ '```json',
161
+ JSON.stringify(turn.graph, null, 2),
162
+ '```',
163
+ '',
164
+ 'User message:',
165
+ turn.text,
166
+ ].join('\n');
167
+ }
168
+ /**
169
+ * One Graph Manager conversation, run on an engine of its own.
170
+ *
171
+ * The engine that hosts Graph Studio may be busy with the user's task and runs one task at a time,
172
+ * so the chat spawns a dedicated `app-server --stdio` child in an empty workspace and speaks the
173
+ * same line protocol the automation runner does. Every panel connected to the graph server shares
174
+ * this one conversation: each subscriber is caught up with a snapshot and then receives the stream.
175
+ *
176
+ * Failures on the engine's side are reported as `error` events rather than rejections, because the
177
+ * message that failed is already on every panel's transcript and the stream is where panels listen.
178
+ */
179
+ export class GraphManagerChat {
180
+ options;
181
+ directory;
182
+ workspace;
183
+ idleMs;
184
+ listeners = new Set();
185
+ transcript = [];
186
+ state = 'idle';
187
+ engine;
188
+ sessionId;
189
+ runId;
190
+ /** The run whose terminal event has been handled; its late `run.start` answer must not revive it. */
191
+ finishedRunId;
192
+ /** Approvals and questions the panel has been shown and nobody has settled yet. */
193
+ prompts = new Set();
194
+ /** `graphs` calls in flight, by tool call id: the line shown for each, and the graph a begin opens or a publish saves. */
195
+ graphCalls = new Map();
196
+ /** Which graph each draft is of, learned from `andorra_graph_begin`, so a publish can name its graph. */
197
+ drafts = new Map();
198
+ /** The latest revision reported for each graph the agent saved other than the open one. */
199
+ otherRevisions = new Map();
200
+ /** The model the latest message chose, for a steering message that has to be sent again as a run. */
201
+ lastModel;
202
+ /**
203
+ * Messages a run ended without reading, oldest first, each already a whole task. The engine keeps
204
+ * them out of the session's history, so they stay here until an engine has accepted them.
205
+ */
206
+ unread = [];
207
+ /** The pair the latest run was started on or last switched to, to tell when a message changes it. */
208
+ runModel;
209
+ openGraphId;
210
+ lastRevision = 0;
211
+ revisionCheck = Promise.resolve();
212
+ cancelling = false;
213
+ /** How many times Stop was pressed, so a message still waiting to be sent can tell it was stopped too. */
214
+ stops = 0;
215
+ closed = false;
216
+ /** Messages and resets are delivered one at a time, in the order they were asked for. */
217
+ queue = Promise.resolve();
218
+ idleTimer;
219
+ idleWaiters = [];
220
+ now;
221
+ /** Names the rows of tool calls the engine reported without an id of their own. */
222
+ toolRows = 0;
223
+ constructor(options) {
224
+ this.options = options;
225
+ // Resolved now: the engine is started in another working directory.
226
+ this.directory = resolve(options.directory);
227
+ this.workspace = join(this.directory, 'graph-manager', 'workspace');
228
+ this.idleMs = options.idleMs ?? 600_000;
229
+ this.now = options.now ?? Date.now;
230
+ }
231
+ /** The listener is first handed the conversation so far as one snapshot, then every later event. */
232
+ subscribe(listener) {
233
+ this.listeners.add(listener);
234
+ this.armIdleStop();
235
+ this.deliverTo(listener, { type: 'snapshot', events: [...this.transcript], state: this.state });
236
+ return () => { this.listeners.delete(listener); this.armIdleStop(); };
237
+ }
238
+ /** Start the conversation, continue it, or steer the run that is working. */
239
+ send(turn) {
240
+ if (this.closed)
241
+ return Promise.resolve();
242
+ this.emit({ type: 'user', text: turn.text });
243
+ const stops = this.stops;
244
+ return this.enqueue(() => this.deliver(turn, stops));
245
+ }
246
+ async approve(id, approved) {
247
+ if (!this.engine || !this.prompts.has(id))
248
+ return;
249
+ // A refusal means the engine no longer holds the prompt, which settles it just the same.
250
+ await this.request(this.engine, 'run.approve', { id, approved }).catch(() => { });
251
+ this.resolvePrompt(id);
252
+ }
253
+ async answer(id, value) {
254
+ if (!this.engine || !this.prompts.has(id))
255
+ return;
256
+ await this.request(this.engine, 'run.answer', { id, answer: value }).catch(() => { });
257
+ this.resolvePrompt(id);
258
+ }
259
+ async cancel() {
260
+ // A live run is cancelled at once, whatever is queued behind it. A start still on its way has
261
+ // no run to name yet, so the cancel follows it; every queued step is bounded, so this ends.
262
+ this.stops++;
263
+ // Stop covers a message no run has read yet, as it covers one still waiting to be sent.
264
+ if (this.unread.splice(0).length)
265
+ this.emit({ type: 'error', message: STOPPED_UNREAD_MESSAGE });
266
+ if (this.runId === undefined)
267
+ await this.queue;
268
+ await this.cancelRun();
269
+ }
270
+ /** Forget the session and the transcript. The engine stays for the next conversation. */
271
+ reset() {
272
+ if (this.closed)
273
+ return Promise.resolve();
274
+ return this.enqueue(async () => {
275
+ await this.cancelRun();
276
+ // The engine runs one task at a time, so the next conversation waits for this one to end.
277
+ if (this.state !== 'idle')
278
+ await this.whenIdle(RESET_WAIT_MS);
279
+ if (this.state !== 'idle') {
280
+ if (this.engine)
281
+ await this.stopEngine(this.engine);
282
+ this.finish(this.runId);
283
+ }
284
+ this.sessionId = undefined;
285
+ this.transcript = [];
286
+ this.unread = [];
287
+ this.prompts.clear();
288
+ this.graphCalls.clear();
289
+ this.drafts.clear();
290
+ this.otherRevisions.clear();
291
+ this.openGraphId = undefined;
292
+ this.lastRevision = 0;
293
+ const snapshot = { type: 'snapshot', events: [], state: this.state };
294
+ for (const listener of this.listeners)
295
+ this.deliverTo(listener, snapshot);
296
+ });
297
+ }
298
+ /** Cancel the run, stop the child and clear the timers. Nothing is started afterwards. */
299
+ async close() {
300
+ if (this.closed)
301
+ return;
302
+ this.closed = true;
303
+ clearTimeout(this.idleTimer);
304
+ this.listeners.clear();
305
+ for (const wake of this.idleWaiters.splice(0))
306
+ wake();
307
+ const engine = this.engine;
308
+ if (!engine)
309
+ return;
310
+ if (this.runId)
311
+ void this.request(engine, 'run.cancel', { runId: this.runId }).catch(() => { });
312
+ await this.stopEngine(engine);
313
+ }
314
+ enqueue(step) {
315
+ // A step reports its own failures, so the chain never rejects and never stalls.
316
+ const next = this.queue.then(step).catch(() => { });
317
+ this.queue = next;
318
+ return next;
319
+ }
320
+ async deliver(turn, stops) {
321
+ if (this.closed)
322
+ return;
323
+ // Stop was pressed after this message was sent, while it waited its turn behind another. Stop
324
+ // covers everything sent before it: delivering it now would start a run the user just stopped.
325
+ if (this.stops !== stops) {
326
+ this.emit({ type: 'error', message: STOPPED_UNREAD_MESSAGE });
327
+ return;
328
+ }
329
+ const id = graphId(turn.graph);
330
+ const known = turn.saved ? turn.revision ?? 0 : 0;
331
+ this.lastRevision = id === this.openGraphId ? Math.max(this.lastRevision, known) : known;
332
+ this.openGraphId = id;
333
+ this.lastModel = { provider: turn.provider, model: turn.model };
334
+ const task = managerTask(turn);
335
+ // The canvas travels inside the task, so a large graph can pass the engine's limit. Refused here,
336
+ // before anything is sent, with words about the graph rather than the engine's about a field.
337
+ if (task.length > MANAGER_TASK_MAX_CHARS) {
338
+ this.emit({ type: 'error', message: TOO_LARGE_MESSAGE });
339
+ return;
340
+ }
341
+ if (this.runId !== undefined && this.state !== 'idle' && this.engine) {
342
+ const engine = this.engine, runId = this.runId;
343
+ // A steer carries words only, so a model chosen since the run began is applied to the run first.
344
+ // A refusal is held until the steer is answered: a run that is ending refuses both, and the
345
+ // message then starts the next run on the new model with nothing to report.
346
+ const keptModel = await this.switchRunModel(engine, runId, turn.provider, turn.model);
347
+ if (keptModel === 'stopped')
348
+ return;
349
+ try {
350
+ await this.request(engine, 'run.steer', { runId, sessionId: this.sessionId, text: task });
351
+ if (keptModel !== undefined)
352
+ this.emit({ type: 'error', message: `Workflow Manager could not switch to ${turn.provider}/${turn.model}, so this run keeps its model: ${keptModel.reason}` });
353
+ return;
354
+ }
355
+ catch (error) {
356
+ if (error instanceof EngineStopped)
357
+ return;
358
+ // `not-found` and `busy` are how the engine says the run is already ending and will not read
359
+ // another message. Anything else is a refusal of the message itself, with the run still live.
360
+ const ending = error instanceof EngineRefusal && (error.code === 'not-found' || error.code === 'busy');
361
+ if (!ending) {
362
+ this.emit({ type: 'error', message: error instanceof Error ? error.message : String(error) });
363
+ return;
364
+ }
365
+ // The message becomes the next run. The wait ends with the run, with the engine (an exit sets
366
+ // idle), or at the bound, so nothing queued behind it is held indefinitely.
367
+ await this.whenIdle(ENDING_WAIT_MS);
368
+ if (this.closed)
369
+ return;
370
+ // Stop was pressed after this message was sent. It covers the message too: starting a run for
371
+ // it now would set Graph Manager working again right after the user stopped it.
372
+ if (this.stops !== stops) {
373
+ this.emit({ type: 'error', message: STOPPED_UNREAD_MESSAGE });
374
+ return;
375
+ }
376
+ if (!this.isIdle()) {
377
+ this.emit({ type: 'error', message: 'Workflow Manager is still finishing its last run. Send your message again.' });
378
+ return;
379
+ }
380
+ }
381
+ }
382
+ // Messages the last run never read come first, so the agent takes them in the order they were
383
+ // sent. When they do not fit in one task with this one they stay queued, and are steered into
384
+ // the run this message starts.
385
+ const carried = [...this.unread, task].join('\n\n');
386
+ if (this.unread.length && carried.length <= MANAGER_TASK_MAX_CHARS) {
387
+ this.unread = [];
388
+ await this.start(carried, turn.provider, turn.model, graphName(turn.graph));
389
+ return;
390
+ }
391
+ await this.start(task, turn.provider, turn.model, graphName(turn.graph));
392
+ }
393
+ /**
394
+ * Hands the engine every message a run ended without reading. A message leaves `unread` only when
395
+ * it is on its way to an engine: as the next run when nothing is working, else steered into the run
396
+ * that is. A run that is itself ending refuses the steer, and the message then waits for the run after it.
397
+ */
398
+ async deliverUnread() {
399
+ while (this.unread.length && !this.closed) {
400
+ const chosen = this.lastModel;
401
+ if (!chosen)
402
+ return;
403
+ if (this.isIdle()) {
404
+ // As many as one task holds, and always at least the oldest.
405
+ let taken = 1;
406
+ while (taken < this.unread.length && this.unread.slice(0, taken + 1).join('\n\n').length <= MANAGER_TASK_MAX_CHARS)
407
+ taken++;
408
+ await this.start(this.unread.splice(0, taken).join('\n\n'), chosen.provider, chosen.model, 'Untitled graph');
409
+ continue;
410
+ }
411
+ const text = this.unread[0];
412
+ const engine = this.engine;
413
+ if (this.runId === undefined || !engine) {
414
+ // A run is starting or its engine is going: the message waits for whichever comes of it.
415
+ await this.whenIdle(ENDING_WAIT_MS);
416
+ if (!this.isIdle())
417
+ return;
418
+ continue;
419
+ }
420
+ try {
421
+ await this.request(engine, 'run.steer', { runId: this.runId, sessionId: this.sessionId, text });
422
+ // Stop may have taken the message while the engine was answering.
423
+ if (this.unread[0] === text)
424
+ this.unread.shift();
425
+ }
426
+ catch (error) {
427
+ if (this.unread[0] !== text)
428
+ continue;
429
+ if (error instanceof EngineStopped) {
430
+ // A deliberate stop keeps the message for the next run; a crash has set the chat idle.
431
+ if (!this.isIdle())
432
+ return;
433
+ continue;
434
+ }
435
+ if (!(error instanceof EngineRefusal && (error.code === 'not-found' || error.code === 'busy'))) {
436
+ // A refusal of the message itself: no engine will take it, and the user is told.
437
+ this.unread.shift();
438
+ this.emit({ type: 'error', message: error instanceof Error ? error.message : String(error) });
439
+ continue;
440
+ }
441
+ await this.whenIdle(ENDING_WAIT_MS);
442
+ // Still not over at the bound: the message stays for the next message's run to carry.
443
+ if (!this.isIdle())
444
+ return;
445
+ }
446
+ }
447
+ }
448
+ /**
449
+ * Moves the working run to the pair a message chose, when it differs from the pair the run is on.
450
+ * `overrideAllNodes: false` is the scope `run.start` gave the first pair: the run's own, which
451
+ * Graph Manager's one agent node (it names no model) and whatever it delegates to answer from.
452
+ * Undefined when the run is on the pair; otherwise why it is not.
453
+ */
454
+ async switchRunModel(engine, runId, provider, model) {
455
+ const running = this.runModel;
456
+ if (running === undefined || (running.provider === provider && running.model === model))
457
+ return undefined;
458
+ try {
459
+ await this.request(engine, 'run.setModel', { runId, provider, model, overrideAllNodes: false });
460
+ this.runModel = { provider, model };
461
+ return undefined;
462
+ }
463
+ catch (error) {
464
+ if (error instanceof EngineStopped)
465
+ return 'stopped';
466
+ return { reason: error instanceof Error ? error.message : String(error) };
467
+ }
468
+ }
469
+ async start(task, provider, model, name) {
470
+ this.cancelling = false;
471
+ this.finishedRunId = undefined;
472
+ this.setState('starting');
473
+ try {
474
+ const engine = await this.ensureEngine();
475
+ if (this.sessionId === undefined) {
476
+ const title = `Workflow Manager: ${name}`.slice(0, 200);
477
+ const created = await this.request(engine, 'sessions.create', { workspace: this.workspace, name: title });
478
+ const id = record(created.session).id;
479
+ if (typeof id !== 'string')
480
+ throw new Error('Workflow Manager could not start its conversation.');
481
+ // The rename pins the name, so the engine's automatic titling leaves it alone.
482
+ await this.request(engine, 'sessions.rename', { id, name: title });
483
+ this.sessionId = id;
484
+ }
485
+ // `continueSession` extends the session just created instead of forking it, which a start
486
+ // that only names a session would do, leaving an empty copy behind for every conversation.
487
+ const started = await this.request(engine, 'run.start', {
488
+ workspace: this.workspace, sessionId: this.sessionId, continueSession: true, task,
489
+ provider, model, graph: GRAPH_MANAGER_GRAPH_ID, runPermissions: 'ask-for-approval',
490
+ });
491
+ if (typeof started.sessionId === 'string')
492
+ this.sessionId = started.sessionId;
493
+ this.runModel = { provider, model };
494
+ // A run that already ended has reported it; only a live one is still working.
495
+ if (typeof started.runId === 'string' && started.runId !== this.finishedRunId) {
496
+ this.runId = started.runId;
497
+ if (this.state === 'starting')
498
+ this.setState('working');
499
+ }
500
+ }
501
+ catch (error) {
502
+ if (!(error instanceof EngineStopped) && !this.closed)
503
+ this.emit({ type: 'error', message: error instanceof Error ? error.message : String(error) });
504
+ }
505
+ if (this.state === 'starting' && this.runId === undefined)
506
+ this.setState('idle');
507
+ }
508
+ async cancelRun() {
509
+ if (this.runId === undefined || !this.engine)
510
+ return;
511
+ this.cancelling = true;
512
+ await this.request(this.engine, 'run.cancel', { runId: this.runId }).catch(() => { });
513
+ }
514
+ async ensureEngine() {
515
+ if (this.closed)
516
+ throw new EngineStopped();
517
+ if (!this.engine) {
518
+ await mkdir(this.workspace, { recursive: true });
519
+ if (this.closed)
520
+ throw new EngineStopped();
521
+ this.engine = this.wire((this.options.spawnEngine ?? (cwd => this.spawnDefault(cwd)))(this.workspace));
522
+ }
523
+ const engine = this.engine;
524
+ await engine.ready;
525
+ return engine;
526
+ }
527
+ spawnDefault(cwd) {
528
+ const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
529
+ return spawn(process.execPath, [cli, 'app-server', '--stdio'], {
530
+ cwd, env: managerEngineEnvironment(this.directory), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
531
+ });
532
+ }
533
+ wire(child) {
534
+ let markReady;
535
+ let failReady;
536
+ let markClosed;
537
+ const ready = new Promise((done, fail) => { markReady = done; failReady = fail; });
538
+ // Awaited by whoever starts a run; a stop nobody is waiting on must not be an unhandled rejection.
539
+ ready.catch(() => { });
540
+ const engine = {
541
+ child, lines: createInterface({ input: child.stdout }), ready,
542
+ closed: new Promise(done => { markClosed = done; }),
543
+ pending: new Map(), nextId: 1, stderr: '', stopping: false, gone: false,
544
+ };
545
+ const refuse = (reason) => {
546
+ failReady(new Error(reason));
547
+ void this.stopEngine(engine);
548
+ };
549
+ const startup = setTimeout(() => refuse('Workflow Manager did not start within 60 seconds.'), STARTUP_MS);
550
+ startup.unref();
551
+ const gone = (detail) => {
552
+ if (engine.gone)
553
+ return;
554
+ engine.gone = true;
555
+ clearTimeout(startup);
556
+ engine.lines.close();
557
+ failReady(new EngineStopped());
558
+ for (const waiter of engine.pending.values())
559
+ waiter.reject(new EngineStopped());
560
+ engine.pending.clear();
561
+ markClosed();
562
+ if (this.engine !== engine)
563
+ return;
564
+ this.engine = undefined;
565
+ if (engine.stopping || this.closed)
566
+ return;
567
+ // The run died with the engine, and its session may still carry that run's claim, so the next
568
+ // message begins a new session on a new engine.
569
+ this.sessionId = undefined;
570
+ const tail = engine.stderr.trim().split('\n').at(-1)?.trim();
571
+ this.emit({ type: 'error', message: `Workflow Manager stopped unexpectedly (${detail}). Send your message again to restart it.${tail ? `\n${tail}` : ''}` });
572
+ this.finish(this.runId);
573
+ };
574
+ child.stderr.on('data', chunk => { engine.stderr = (engine.stderr + String(chunk)).slice(-8_192); });
575
+ // A write into a pipe whose reader has gone is followed by the close that reports it.
576
+ child.stdin.on('error', () => { });
577
+ child.on('error', error => gone(error.message));
578
+ child.once('close', code => gone(`exit ${code ?? 'signal'}`));
579
+ engine.lines.on('line', line => {
580
+ let message;
581
+ try {
582
+ message = JSON.parse(line);
583
+ }
584
+ catch {
585
+ return;
586
+ }
587
+ if (message === null || typeof message !== 'object')
588
+ return;
589
+ if (typeof message.id === 'number') {
590
+ const waiter = engine.pending.get(message.id);
591
+ engine.pending.delete(message.id);
592
+ if (message.error)
593
+ waiter?.reject(new EngineRefusal(typeof message.error.message === 'string' ? message.error.message : 'Workflow Manager refused the request.', typeof message.error.code === 'string' ? message.error.code : undefined));
594
+ else
595
+ waiter?.resolve(record(message.result));
596
+ return;
597
+ }
598
+ if (typeof message.event !== 'string')
599
+ return;
600
+ const data = record(message.data);
601
+ if (message.event === 'ready') {
602
+ clearTimeout(startup);
603
+ // Without run-scoped permissions the run would take the workspace's saved mode, not Ask for approval.
604
+ if (Array.isArray(data.capabilities) && data.capabilities.includes('run.start.runPermissions'))
605
+ markReady();
606
+ else
607
+ refuse(UPDATE_MESSAGE);
608
+ return;
609
+ }
610
+ if (this.engine === engine)
611
+ this.onEngineEvent(message.event, data);
612
+ });
613
+ return engine;
614
+ }
615
+ request(engine, method, params) {
616
+ return new Promise((done, fail) => {
617
+ if (engine.gone || !engine.child.stdin.writable || engine.child.stdin.destroyed) {
618
+ fail(new EngineStopped());
619
+ return;
620
+ }
621
+ const id = engine.nextId++;
622
+ engine.pending.set(id, { resolve: done, reject: fail });
623
+ engine.child.stdin.write(JSON.stringify({ id, method, params }) + '\n');
624
+ });
625
+ }
626
+ /** A deliberate stop: EOF lets the engine finish its own cleanup, and it is reaped if it does not. */
627
+ async stopEngine(engine) {
628
+ engine.stopping = true;
629
+ if (this.engine === engine)
630
+ this.engine = undefined;
631
+ await stopAutomationWorker(engine.child, engine.closed);
632
+ }
633
+ onEngineEvent(event, data) {
634
+ if (event === 'run.started' && typeof data.runId === 'string' && this.state === 'starting')
635
+ this.runId = data.runId;
636
+ else if (event === 'run.event')
637
+ this.onRunEvent(record(data.event));
638
+ else if (event === 'run.approval' && typeof data.id === 'string') {
639
+ this.prompts.add(data.id);
640
+ this.emit({ type: 'approval', id: data.id, text: this.describe(String(data.name), data.arguments) });
641
+ }
642
+ else if (event === 'run.question' && typeof data.id === 'string') {
643
+ this.prompts.add(data.id);
644
+ const choices = Array.isArray(data.choices) ? data.choices.filter((choice) => typeof choice === 'string') : undefined;
645
+ this.emit({ type: 'question', id: data.id, question: String(data.question ?? ''), ...(choices === undefined ? {} : { choices }) });
646
+ }
647
+ else if (event === 'run.state' && this.state !== 'idle') {
648
+ if (data.state === 'awaiting-approval' || data.state === 'awaiting-input')
649
+ this.setState('awaiting');
650
+ else if (data.state === 'running') {
651
+ // The engine reports running again only once nothing is pending, however each prompt was settled.
652
+ this.resolvePrompts();
653
+ this.setState('working');
654
+ }
655
+ }
656
+ else if ((event === 'run.completed' || event === 'run.failed') && (this.runId === undefined ? this.state === 'starting' : data.runId === this.runId)) {
657
+ const cancelled = this.cancelling;
658
+ const runId = typeof data.runId === 'string' ? data.runId : this.runId;
659
+ this.resolvePrompts();
660
+ if (event === 'run.failed' && !cancelled)
661
+ this.emit({ type: 'error', message: String(data.message ?? 'The run failed.') });
662
+ this.finish(runId);
663
+ // A message queued too late for the run to read is still the user's request: it becomes the next run.
664
+ const unread = Array.isArray(data.undeliveredSteers)
665
+ ? data.undeliveredSteers.map(entry => record(entry).text).filter((text) => typeof text === 'string')
666
+ : [];
667
+ if (unread.length && !cancelled && !this.closed) {
668
+ // Queued behind whatever is already being delivered. A message whose steer this run refused
669
+ // starts the next run first, and takes these with it.
670
+ this.unread.push(...unread);
671
+ void this.enqueue(() => this.deliverUnread());
672
+ }
673
+ }
674
+ }
675
+ onRunEvent(event) {
676
+ const data = record(event.data);
677
+ if (event.type === 'agent.message') {
678
+ const text = typeof data.text === 'string' ? data.text.trim() : '';
679
+ if (text)
680
+ this.emit({ type: 'assistant', text });
681
+ }
682
+ else if (event.type === 'agent.reasoning.started' || event.type === 'agent.reasoning.delta' || event.type === 'agent.reasoning.completed') {
683
+ this.onReasoning(event.type, data);
684
+ }
685
+ else if (event.type === 'node.tool.started') {
686
+ if (HIDDEN_TOOLS.has(String(data.name)))
687
+ return;
688
+ const line = this.describe(String(data.name), data.arguments);
689
+ const id = typeof data.toolCallId === 'string' && data.toolCallId ? data.toolCallId : `tool-${++this.toolRows}`;
690
+ // A call id the engine reuses (a resumed call) reopens its row rather than adding a second one.
691
+ const opened = { type: 'tool', id, text: line, ...managerToolParts(String(data.name), data.arguments, this.openGraphId), status: 'running', startedAt: this.now() };
692
+ if (!this.replace(entry => entry.type === 'tool' && entry.id === id, () => opened, opened))
693
+ this.emit(opened);
694
+ if (data.name === 'graphs' && typeof data.toolCallId === 'string') {
695
+ const args = toolArguments(data.arguments);
696
+ const input = record(args.args);
697
+ const name = oneLine(input.name).slice(0, TOOL_LINE_MAX);
698
+ const begins = args.action === 'andorra_graph_begin' && typeof input.id === 'string' ? { id: input.id, ...(name ? { name } : {}) } : undefined;
699
+ const publishes = args.action === 'andorra_graph_publish' && typeof input.draftId === 'string' ? this.drafts.get(input.draftId) : undefined;
700
+ const removes = (args.action === 'andorra_graph_delete' || args.action === 'andorra_graph_restore') && typeof input.id === 'string' ? { id: input.id } : undefined;
701
+ this.graphCalls.set(data.toolCallId, { line, ...(begins ? { begins } : {}), ...(publishes ? { publishes } : {}), ...(removes ? { removes } : {}) });
702
+ }
703
+ }
704
+ else if (event.type === 'node.tool.failed') {
705
+ this.endGraphCall(data.toolCallId);
706
+ const reason = String(data.output ?? '').split('\n').map(row => row.trim()).find(Boolean)?.slice(0, 240);
707
+ this.settleTool(data.toolCallId, 'failed', reason);
708
+ }
709
+ else if (event.type === 'node.tool.completed' && data.name !== 'graphs') {
710
+ this.settleTool(data.toolCallId, 'done');
711
+ }
712
+ else if (event.type === 'node.tool.completed') {
713
+ this.settleTool(data.toolCallId, 'done');
714
+ const call = this.endGraphCall(data.toolCallId);
715
+ // The reply may be clipped, or quoted inside a preview, so the draft id is found rather than parsed.
716
+ const draft = call?.begins === undefined ? undefined : /\\*"draftId\\*"\s*:\s*\\*"([a-f0-9-]{36})\\*"/i.exec(String(data.output ?? ''))?.[1];
717
+ if (draft !== undefined && call?.begins !== undefined) {
718
+ this.drafts.delete(draft);
719
+ this.drafts.set(draft, call.begins);
720
+ if (this.drafts.size > DRAFTS_MAX)
721
+ this.drafts.delete(this.drafts.keys().next().value);
722
+ }
723
+ this.checkRevision(call?.publishes ?? call?.removes);
724
+ }
725
+ }
726
+ /** Settles a tool row in place. A call reported without an id, or never opened, has no row to settle. */
727
+ settleTool(toolCallId, status, reason) {
728
+ if (typeof toolCallId !== 'string' || !toolCallId)
729
+ return;
730
+ if (!this.transcript.some(entry => entry.type === 'tool' && entry.id === toolCallId && entry.status === 'running'))
731
+ return;
732
+ const endedAt = this.now();
733
+ const detail = reason ? { reason } : {};
734
+ this.replace(entry => entry.type === 'tool' && entry.id === toolCallId && entry.status === 'running', entry => ({ ...entry, status, ...detail, endedAt }), { type: 'tool.settled', id: toolCallId, status, ...detail, endedAt });
735
+ }
736
+ /**
737
+ * One model call's reasoning, folded into a single row the way the app's transcript folds it: a
738
+ * retried request restarts the row, deltas grow it, and the completion settles it with the
739
+ * authoritative text, or takes it away when the call streamed no reasoning at all.
740
+ */
741
+ onReasoning(type, data) {
742
+ const reasoningId = typeof data.reasoningId === 'string' && data.reasoningId ? data.reasoningId : undefined;
743
+ if (!reasoningId)
744
+ return;
745
+ const id = `thought-${reasoningId}`;
746
+ const mine = (entry) => entry.type === 'thought' && entry.id === id;
747
+ const text = typeof data.text === 'string' ? data.text : '';
748
+ if (type === 'agent.reasoning.started') {
749
+ const opened = { type: 'thought', id, text: '', status: 'thinking', startedAt: this.now() };
750
+ if (!this.replace(mine, () => opened, opened))
751
+ this.emit(opened);
752
+ }
753
+ else if (type === 'agent.reasoning.delta') {
754
+ if (!text)
755
+ return;
756
+ // A delta past the row's completion belongs to a stream the engine already closed.
757
+ if (!this.replace(entry => mine(entry) && entry.type === 'thought' && entry.status === 'thinking', entry => ({ ...entry, text: entry.text + text }), { type: 'thought.delta', id, text })) {
758
+ if (!this.transcript.some(mine))
759
+ this.emit({ type: 'thought', id, text, status: 'thinking', startedAt: this.now() });
760
+ }
761
+ }
762
+ else {
763
+ const index = this.transcript.findIndex(mine);
764
+ if (!text) {
765
+ if (index >= 0) {
766
+ this.transcript.splice(index, 1);
767
+ this.broadcast({ type: 'thought.removed', id });
768
+ }
769
+ return;
770
+ }
771
+ const opened = index >= 0 ? this.transcript[index] : undefined;
772
+ const durationMs = typeof data.durationMs === 'number' ? data.durationMs : undefined;
773
+ const settled = {
774
+ type: 'thought', id, text, status: 'done', startedAt: opened?.startedAt ?? this.now() - (durationMs ?? 0),
775
+ ...(durationMs === undefined ? {} : { durationMs }), ...(data.truncated === true ? { truncated: true } : {}),
776
+ };
777
+ if (opened) {
778
+ this.transcript[index] = settled;
779
+ this.broadcast(settled);
780
+ }
781
+ else
782
+ this.emit(settled);
783
+ }
784
+ }
785
+ /**
786
+ * Rows a run left open when it ended: a call it never reported the end of is stopped, a thought
787
+ * still streaming keeps what it streamed, and one that streamed nothing is taken away.
788
+ */
789
+ settleOpenRows() {
790
+ const endedAt = this.now();
791
+ for (const entry of [...this.transcript]) {
792
+ if (entry.type === 'tool' && entry.status === 'running') {
793
+ this.replace(row => row === entry, () => ({ ...entry, status: 'stopped', endedAt }), { type: 'tool.settled', id: entry.id, status: 'stopped', endedAt });
794
+ }
795
+ else if (entry.type === 'thought' && entry.status === 'thinking') {
796
+ if (!entry.text) {
797
+ this.transcript.splice(this.transcript.indexOf(entry), 1);
798
+ this.broadcast({ type: 'thought.removed', id: entry.id });
799
+ }
800
+ else {
801
+ const settled = { ...entry, status: 'done', durationMs: Math.max(0, endedAt - entry.startedAt) };
802
+ this.replace(row => row === entry, () => settled, settled);
803
+ }
804
+ }
805
+ }
806
+ }
807
+ describe(name, value) {
808
+ return describeManagerTool(name, value, draft => this.drafts.get(draft)?.id);
809
+ }
810
+ endGraphCall(toolCallId) {
811
+ if (typeof toolCallId !== 'string')
812
+ return undefined;
813
+ const call = this.graphCalls.get(toolCallId);
814
+ this.graphCalls.delete(toolCallId);
815
+ return call;
816
+ }
817
+ /**
818
+ * The `graphs` tool also lists and reads, so a save is told by the stored revision rising. The
819
+ * open graph is checked after every call. A publish of another graph (the only way the agent can
820
+ * save its work on the bundled preset) is checked under that graph's id, and reported with the
821
+ * name it was begun with so the panel can offer to open it; so is a delete or a restore of one.
822
+ *
823
+ * Deleting a graph also raises its revision: the new one carries `metadata.deletedAt`. That is
824
+ * reported as `graph.deleted`, never as a save, so no panel loads a deleted graph as an editable
825
+ * one. A restore publishes a live revision above it, which is a save like any other.
826
+ */
827
+ checkRevision(published) {
828
+ const other = published !== undefined && published.id !== this.openGraphId ? published : undefined;
829
+ const id = other?.id ?? this.openGraphId;
830
+ if (!id)
831
+ return;
832
+ this.revisionCheck = this.revisionCheck.then(async () => {
833
+ const latest = await this.options.readRevision(id).catch(() => undefined);
834
+ if (latest === undefined || this.closed)
835
+ return;
836
+ const { revision } = latest;
837
+ if (other) {
838
+ // The user may have opened that graph since: its saves are then the open graph's to report.
839
+ if (id === this.openGraphId || revision <= (this.otherRevisions.get(id) ?? 0))
840
+ return;
841
+ this.otherRevisions.set(id, revision);
842
+ this.emit(latest.deleted ? { type: 'graph.deleted', graphId: id } : { type: 'graph.saved', graphId: id, revision, ...(other.name ? { name: other.name } : {}) });
843
+ return;
844
+ }
845
+ if (id !== this.openGraphId || revision <= this.lastRevision)
846
+ return;
847
+ this.lastRevision = revision;
848
+ this.emit(latest.deleted ? { type: 'graph.deleted', graphId: id } : { type: 'graph.saved', graphId: id, revision });
849
+ });
850
+ }
851
+ /** The run is over, however it ended. */
852
+ finish(runId) {
853
+ if (runId !== undefined)
854
+ this.finishedRunId = runId;
855
+ // A call the run never reported the end of ended with the run.
856
+ this.graphCalls.clear();
857
+ this.settleOpenRows();
858
+ this.runId = undefined;
859
+ this.cancelling = false;
860
+ this.resolvePrompts();
861
+ this.setState('idle');
862
+ }
863
+ resolvePrompt(id) {
864
+ if (this.prompts.delete(id))
865
+ this.emit({ type: 'resolved', id });
866
+ }
867
+ resolvePrompts() {
868
+ for (const id of [...this.prompts])
869
+ this.resolvePrompt(id);
870
+ }
871
+ setState(state) {
872
+ if (this.state === state)
873
+ return;
874
+ this.state = state;
875
+ this.emit({ type: 'state', state });
876
+ if (state === 'idle')
877
+ for (const wake of this.idleWaiters.splice(0))
878
+ wake();
879
+ this.armIdleStop();
880
+ }
881
+ /** Read through a call so a check after an await sees the state as it is then. */
882
+ isIdle() { return this.state === 'idle'; }
883
+ whenIdle(ms) {
884
+ if (this.state === 'idle' || this.closed)
885
+ return Promise.resolve();
886
+ return new Promise(done => {
887
+ const timer = setTimeout(done, ms);
888
+ timer.unref();
889
+ this.idleWaiters.push(() => { clearTimeout(timer); done(); });
890
+ });
891
+ }
892
+ /** An engine is kept while a run is working or waiting on the user, and while any panel is connected. */
893
+ armIdleStop() {
894
+ clearTimeout(this.idleTimer);
895
+ this.idleTimer = undefined;
896
+ if (this.closed || !this.engine || this.state !== 'idle' || this.listeners.size > 0)
897
+ return;
898
+ const engine = this.engine;
899
+ this.idleTimer = setTimeout(() => {
900
+ // The session is on disk, so the conversation continues on the next engine.
901
+ if (this.engine === engine && this.state === 'idle' && this.listeners.size === 0)
902
+ void this.stopEngine(engine);
903
+ }, this.idleMs);
904
+ this.idleTimer.unref();
905
+ }
906
+ emit(event) {
907
+ if (this.closed)
908
+ return;
909
+ this.transcript.push(event);
910
+ this.broadcast(event);
911
+ }
912
+ /** Sends an event without adding a row: it changes a row the transcript already holds. */
913
+ broadcast(event) {
914
+ if (this.closed)
915
+ return;
916
+ for (const listener of [...this.listeners])
917
+ this.deliverTo(listener, event);
918
+ }
919
+ /**
920
+ * Replaces the latest row `match` finds with `next` of it, and tells the panels with `event`.
921
+ * False when no row matches, so the caller can add one instead.
922
+ */
923
+ replace(match, next, event) {
924
+ for (let index = this.transcript.length - 1; index >= 0; index--) {
925
+ if (!match(this.transcript[index]))
926
+ continue;
927
+ this.transcript[index] = next(this.transcript[index]);
928
+ this.broadcast(event);
929
+ return true;
930
+ }
931
+ return false;
932
+ }
933
+ deliverTo(listener, event) {
934
+ // One panel's broken connection must not cost the others the event.
935
+ try {
936
+ listener(event);
937
+ }
938
+ catch { /* The subscriber owns its own failures. */ }
939
+ }
940
+ }