@saturn-universe/runtime-host 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +472 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +471 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,699 @@
1
+ import { isLimited, maxModelReasoningSummaryLength, mergeAgentContextMetrics, modelReasoningSummary, modelTokenBudget, RUN_TIMELINE_PAGE_SIZE, RuntimeError, } from '@saturn-universe/core';
2
+ import path from 'node:path';
3
+ import { maxFrameBytes } from '@saturn-universe/protocol';
4
+ export function createLiveText() {
5
+ const agents = new Map();
6
+ const retainedBySession = new Map();
7
+ const retainedByRun = new Map();
8
+ const drafts = new Map();
9
+ const maxDraftLength = 32 * 1024;
10
+ const rememberMetrics = (runId, agentSessionId, source) => {
11
+ const merged = mergeAgentContextMetrics(retainedBySession.get(agentSessionId), source);
12
+ if (!merged)
13
+ return undefined;
14
+ retainedBySession.delete(agentSessionId);
15
+ retainedBySession.set(agentSessionId, merged);
16
+ while (retainedBySession.size > 128)
17
+ retainedBySession.delete(retainedBySession.keys().next().value);
18
+ let runMap = retainedByRun.get(runId);
19
+ if (!runMap) {
20
+ runMap = new Map();
21
+ retainedByRun.set(runId, runMap);
22
+ while (retainedByRun.size > 64)
23
+ retainedByRun.delete(retainedByRun.keys().next().value);
24
+ }
25
+ runMap.set(agentSessionId, merged);
26
+ return merged;
27
+ };
28
+ return {
29
+ update(input, { reasoningDelta, resetReasoning, ...patch }) {
30
+ const { runId, agentSessionId, turnId } = input;
31
+ let active = agents.get(runId);
32
+ if (!active)
33
+ agents.set(runId, (active = new Map()));
34
+ const previous = active.get(agentSessionId);
35
+ const retained = rememberMetrics(runId, agentSessionId, patch);
36
+ const snapshot = previous?.turnId === turnId
37
+ ? previous.snapshot
38
+ : { agentSessionId, phase: 'idle', stepCount: 0, ...(retained ?? {}) };
39
+ const reasoningSummary = ((resetReasoning ? '' : (snapshot.reasoningSummary ?? '')) + (reasoningDelta ?? '')).slice(0, maxModelReasoningSummaryLength);
40
+ const next = {
41
+ ...snapshot,
42
+ ...(retained ?? {}),
43
+ ...patch,
44
+ reasoningSummary: reasoningSummary || undefined,
45
+ };
46
+ active.set(agentSessionId, {
47
+ turnId,
48
+ snapshot: Object.fromEntries(Object.entries(next).filter(([, value]) => value !== undefined)),
49
+ });
50
+ },
51
+ clearAgent({ runId, agentSessionId, turnId }) {
52
+ const active = agents.get(runId);
53
+ if (active?.get(agentSessionId)?.turnId !== turnId)
54
+ return;
55
+ active.delete(agentSessionId);
56
+ if (!active.size)
57
+ agents.delete(runId);
58
+ },
59
+ agentSnapshots(runId) {
60
+ return agents.get(runId)?.entries() ?? [];
61
+ },
62
+ runMetrics(runId) {
63
+ return retainedByRun.get(runId)?.entries() ?? [];
64
+ },
65
+ sessionMetrics(agentSessionId) {
66
+ return retainedBySession.get(agentSessionId);
67
+ },
68
+ append(input, delta) {
69
+ if (!delta.text)
70
+ return;
71
+ let draft = drafts.get(delta.requestId);
72
+ if (!draft) {
73
+ draft = {
74
+ runId: input.runId,
75
+ agentSessionId: input.agentSessionId,
76
+ revision: 0,
77
+ length: 0,
78
+ parts: new Map(),
79
+ };
80
+ drafts.set(delta.requestId, draft);
81
+ }
82
+ const text = delta.text.slice(0, maxDraftLength - draft.length);
83
+ if (!text)
84
+ return;
85
+ draft.parts.set(delta.index, (draft.parts.get(delta.index) ?? '') + text);
86
+ draft.length += text.length;
87
+ draft.revision++;
88
+ },
89
+ clear(requestId) {
90
+ drafts.delete(requestId);
91
+ },
92
+ mainDraft(runId, members) {
93
+ for (const [requestId, draft] of drafts) {
94
+ if (draft.runId === runId && members.get(draft.agentSessionId) === 'main') {
95
+ const text = [...draft.parts]
96
+ .sort(([a], [b]) => a - b)
97
+ .map(([, part]) => part)
98
+ .join('\n');
99
+ return { requestId, revision: draft.revision, text };
100
+ }
101
+ }
102
+ return undefined;
103
+ },
104
+ };
105
+ }
106
+ export async function runProgress(store, command, liveText) {
107
+ const state = await store.stateReader.run(command.runId);
108
+ const head = await store.head();
109
+ if (BigInt(command.after) > BigInt(head))
110
+ throw new RuntimeError('INVALID_CURSOR', 'Cursor is ahead of EventLog');
111
+ // Bound the page by the observed Run projection. A terminal status can never overtake its events.
112
+ const through = state.throughPosition;
113
+ const hasRange = BigInt(command.after) < BigInt(through);
114
+ const events = hasRange
115
+ ? await store.readRunPage(command.runId, command.after, through, command.limit)
116
+ : [];
117
+ let cursor = !hasRange ? command.after : events.length < command.limit ? through : events.at(-1).position;
118
+ const { memberBySession, activeMembers } = await resolveMemberMap(store, command.runId, events);
119
+ const liveAgents = new Map();
120
+ if (state.status === 'running' || state.status === 'paused' || state.status === 'cancelling') {
121
+ for (const [agentSessionId, memberId] of activeMembers)
122
+ liveAgents.set(memberId, { memberId, agentSessionId, phase: 'idle', stepCount: 0 });
123
+ for (const [agentSessionId, { snapshot }] of liveText?.agentSnapshots(command.runId) ?? []) {
124
+ const memberId = memberBySession.get(agentSessionId);
125
+ if (memberId)
126
+ liveAgents.set(memberId, { ...snapshot, memberId });
127
+ }
128
+ }
129
+ const pendingApprovals = (await store.pendingApprovals(command.runId)).flatMap((tool) => {
130
+ if (tool.approval?.status !== 'pending')
131
+ return [];
132
+ const { approvalId, toolCallId, resources, reason, expiresAt } = tool.approval.request;
133
+ return [
134
+ {
135
+ approvalId,
136
+ toolCallId,
137
+ turnId: tool.turnId,
138
+ memberId: memberBySession.get(tool.agentSessionId) ?? 'main',
139
+ toolName: tool.call.toolName,
140
+ resources: [...resources],
141
+ reason,
142
+ expiresAt,
143
+ },
144
+ ];
145
+ });
146
+ for (const approval of pendingApprovals) {
147
+ const agent = liveAgents.get(approval.memberId);
148
+ if (!agent || agent.phase === 'waiting_approval')
149
+ continue;
150
+ const stepCount = agent.stepCount || (await store.stateReader.steps(approval.turnId)).at(-1)?.ordinal || 0;
151
+ const { requestStartedAt: _startedAt, ...snapshot } = agent;
152
+ liveAgents.set(approval.memberId, {
153
+ ...snapshot,
154
+ stepCount,
155
+ phase: 'waiting_approval',
156
+ currentTool: approval.toolName,
157
+ });
158
+ }
159
+ const calls = command.interactive ? await resolveToolCalls(store, events) : undefined;
160
+ const limits = command.interactive &&
161
+ events.some((event) => event.type === 'run.failed' && event.payload.error.code === 'LIMIT')
162
+ ? (await store.environmentReader.load(command.runId)).config.limits
163
+ : undefined;
164
+ const draft = command.interactive && state.status === 'running'
165
+ ? liveText?.mainDraft(command.runId, memberBySession)
166
+ : undefined;
167
+ const telemetryByMember = {};
168
+ for (const [agentSessionId, metrics] of liveText?.runMetrics(command.runId) ?? []) {
169
+ const memberId = memberBySession.get(agentSessionId);
170
+ if (memberId)
171
+ telemetryByMember[memberId] = metrics;
172
+ }
173
+ const rows = [];
174
+ let rowBytes = 0;
175
+ for (const event of events) {
176
+ const row = progressEvent(event, memberBySession);
177
+ if (calls) {
178
+ addInteractiveDetails(event, row, calls, state, limits);
179
+ // Leave room for the reply envelope, live telemetry and pending approvals.
180
+ const bytes = Buffer.byteLength(JSON.stringify(row)) + 1;
181
+ if (rows.length && rowBytes + bytes > maxFrameBytes / 2) {
182
+ cursor = events[rows.length - 1].position;
183
+ break;
184
+ }
185
+ rowBytes += bytes;
186
+ }
187
+ rows.push(row);
188
+ }
189
+ return {
190
+ runId: command.runId,
191
+ status: state.status,
192
+ ...(state.pauseReason ? { pauseReason: state.pauseReason } : {}),
193
+ ...(state.pluginBlock ? { pluginBlock: { ...state.pluginBlock } } : {}),
194
+ cursor,
195
+ through,
196
+ pendingApprovals,
197
+ liveAgents: Object.fromEntries(liveAgents),
198
+ ...(Object.keys(telemetryByMember).length ? { telemetry: telemetryByMember } : {}),
199
+ hasMore: BigInt(cursor) < BigInt(through),
200
+ events: rows,
201
+ ...(draft ? { draft } : {}),
202
+ };
203
+ }
204
+ export async function runTimeline(store, { runId, after }) {
205
+ const run = await store.stateReader.run(runId);
206
+ const matching = await store.readRunTimeline(runId, after, run.throughPosition, RUN_TIMELINE_PAGE_SIZE + 1);
207
+ const events = matching.slice(0, RUN_TIMELINE_PAGE_SIZE);
208
+ return {
209
+ runId,
210
+ status: run.status,
211
+ ...(run.pluginBlock ? { pluginBlock: { ...run.pluginBlock } } : {}),
212
+ events: events.map((event) => {
213
+ const row = progressEvent(event, new Map());
214
+ if (event.type === 'tool.call.settled') {
215
+ const outcome = event.payload.message.result.outcome;
216
+ const data = outcome.data;
217
+ if (data && typeof data === 'object' && 'todos' in data && Array.isArray(data.todos)) {
218
+ row.toolName =
219
+ 'kind' in data && data.kind === 'review_numeric_data' ? 'review_numeric_data' : 'todo_write';
220
+ row.toolStatus = outcome.status;
221
+ row.todos = data.todos;
222
+ }
223
+ if (data && typeof data === 'object' && 'rounds' in data && Array.isArray(data.rounds)) {
224
+ row.toolName = 'review_numeric_data';
225
+ row.dataReviewRounds = data.rounds;
226
+ }
227
+ }
228
+ return row;
229
+ }),
230
+ ...(matching.length > events.length ? { nextAfter: events.at(-1).position } : {}),
231
+ };
232
+ }
233
+ async function resolveMemberMap(store, runId, events) {
234
+ const memberBySession = new Map();
235
+ const activeMembers = new Map();
236
+ const mainEnv = await store.environmentReader.load(runId).catch(() => undefined);
237
+ if (mainEnv) {
238
+ memberBySession.set(mainEnv.route.agentSessionId, 'main');
239
+ activeMembers.set(mainEnv.route.agentSessionId, 'main');
240
+ }
241
+ const team = await store.stateReader.team?.(runId);
242
+ if (team) {
243
+ for (const member of team.members) {
244
+ memberBySession.set(member.agentSessionId, member.id);
245
+ if (member.status === 'running' || member.status === 'paused')
246
+ activeMembers.set(member.agentSessionId, member.id);
247
+ }
248
+ if (team.plan?.plannerAgentSessionId && !memberBySession.has(team.plan.plannerAgentSessionId))
249
+ memberBySession.set(team.plan.plannerAgentSessionId, 'planner');
250
+ }
251
+ const searches = await store.stateReader.searches?.(runId).catch(() => undefined);
252
+ if (searches) {
253
+ for (const search of searches) {
254
+ for (const branch of search.branches) {
255
+ memberBySession.set(branch.agentSessionId, branch.branchId);
256
+ }
257
+ }
258
+ }
259
+ const owned = await store.stateReader.ownedAgentSessions(runId);
260
+ for (const session of owned) {
261
+ if (memberBySession.has(session.id))
262
+ continue;
263
+ const env = await store.environmentReader.load(runId, session.id).catch(() => undefined);
264
+ if (env?.config.modeRef === 'planner@1') {
265
+ memberBySession.set(session.id, 'planner');
266
+ }
267
+ }
268
+ for (const event of events) {
269
+ if (event.type === 'run.search.branch.created') {
270
+ memberBySession.set(event.payload.agentSessionId, event.payload.branchId);
271
+ continue;
272
+ }
273
+ if (event.type !== 'run.agent.attached')
274
+ continue;
275
+ const { membership } = event.payload;
276
+ if (membership.teamMemberId)
277
+ memberBySession.set(membership.agentSessionId, membership.teamMemberId);
278
+ else if (membership.searchBranchId)
279
+ memberBySession.set(membership.agentSessionId, membership.searchBranchId);
280
+ else if (membership.role === 'main')
281
+ memberBySession.set(membership.agentSessionId, 'main');
282
+ else if (membership.config.modeRef === 'planner@1')
283
+ memberBySession.set(membership.agentSessionId, 'planner');
284
+ }
285
+ return { memberBySession, activeMembers };
286
+ }
287
+ function progressEvent(event, memberBySession) {
288
+ const summary = {
289
+ id: event.id,
290
+ position: event.position,
291
+ type: event.type,
292
+ occurredAt: event.occurredAt,
293
+ };
294
+ if (event.scope.kind === 'agent_session') {
295
+ summary.agentSessionId = event.scope.agentSessionId;
296
+ const memberId = memberBySession.get(event.scope.agentSessionId);
297
+ if (memberId)
298
+ summary.memberId = memberId;
299
+ }
300
+ if ('turnId' in event.payload)
301
+ summary.turnId = event.payload.turnId;
302
+ if ('stepId' in event.payload)
303
+ summary.stepId = event.payload.stepId;
304
+ if (event.type === 'step.started')
305
+ summary.step = JSON.parse(JSON.stringify(event.payload.step));
306
+ if (event.type === 'tool.call.requested') {
307
+ summary.toolCallId = event.payload.call.id;
308
+ summary.toolName = event.payload.call.toolName;
309
+ }
310
+ if (event.type === 'tool.call.started') {
311
+ summary.toolCallId = event.payload.attempt.toolCallId;
312
+ summary.stepId = event.payload.attempt.stepId;
313
+ }
314
+ if (event.type === 'tool.approval.requested')
315
+ summary.approval = JSON.parse(JSON.stringify(event.payload.request));
316
+ if (event.type === 'tool.approval.resolved') {
317
+ summary.approvalId = event.payload.decision.approvalId;
318
+ summary.approved = event.payload.decision.approved;
319
+ }
320
+ if (event.type === 'message.assistant.added') {
321
+ summary.messageId = event.payload.message.id;
322
+ summary.text = event.payload.message.content
323
+ .filter((part) => part.type === 'text')
324
+ .map((part) => part.text)
325
+ .join('\n');
326
+ }
327
+ if (event.type === 'run.team.planned') {
328
+ summary.decision = event.payload.decision;
329
+ summary.reason = event.payload.reason;
330
+ if (event.payload.fallback !== undefined)
331
+ summary.fallback = event.payload.fallback;
332
+ if (event.payload.summary !== undefined)
333
+ summary.summary = event.payload.summary;
334
+ if (event.payload.evidence !== undefined)
335
+ summary.evidence = [...event.payload.evidence];
336
+ if (event.payload.executionSteps !== undefined)
337
+ summary.executionSteps = [...event.payload.executionSteps];
338
+ if (event.payload.verificationCriteria !== undefined)
339
+ summary.verificationCriteria = [...event.payload.verificationCriteria];
340
+ if (event.payload.team !== undefined)
341
+ summary.team = JSON.parse(JSON.stringify(event.payload.team));
342
+ }
343
+ if (event.type === 'run.team.message.sent') {
344
+ summary.from = event.payload.from;
345
+ summary.to = event.payload.to;
346
+ summary.text = event.payload.text;
347
+ }
348
+ if (event.type === 'run.search.started') {
349
+ summary.searchId = event.payload.searchId;
350
+ summary.trigger = event.payload.trigger;
351
+ summary.goal = event.payload.goal;
352
+ summary.isolation = event.payload.isolation;
353
+ summary.maxRollouts = event.payload.maxRollouts;
354
+ summary.branchFactor = event.payload.branchFactor;
355
+ summary.maxDepth = event.payload.maxDepth;
356
+ summary.concurrency = event.payload.concurrency;
357
+ }
358
+ if (event.type === 'run.search.branch.created') {
359
+ summary.searchId = event.payload.searchId;
360
+ summary.branchId = event.payload.branchId;
361
+ summary.parentBranchId = event.payload.parentBranchId;
362
+ summary.depth = event.payload.depth;
363
+ summary.mode = event.payload.mode;
364
+ summary.hypothesis = event.payload.hypothesis;
365
+ summary.strategy = event.payload.strategy;
366
+ summary.workspaceKind = event.payload.workspaceKind;
367
+ if (event.payload.degradedToReadonly !== undefined)
368
+ summary.degradedToReadonly = event.payload.degradedToReadonly;
369
+ }
370
+ if (event.type === 'run.search.branch.evaluated') {
371
+ summary.searchId = event.payload.searchId;
372
+ summary.branchId = event.payload.branchId;
373
+ if (event.payload.hardScore !== undefined)
374
+ summary.hardScore = event.payload.hardScore;
375
+ summary.softScore = event.payload.softScore;
376
+ summary.combinedScore = event.payload.combinedScore;
377
+ summary.verdict = event.payload.verdict;
378
+ summary.summary = event.payload.summary;
379
+ if (event.payload.reflection !== undefined)
380
+ summary.reflection = event.payload.reflection;
381
+ }
382
+ if (event.type === 'run.search.converged') {
383
+ summary.searchId = event.payload.searchId;
384
+ summary.winnerBranchId = event.payload.winnerBranchId;
385
+ summary.outcome = event.payload.outcome;
386
+ summary.winnerSummary = event.payload.winnerSummary;
387
+ summary.mergedReflections = [...event.payload.mergedReflections];
388
+ if (event.payload.mergedFiles !== undefined)
389
+ summary.mergedFiles = [...event.payload.mergedFiles];
390
+ }
391
+ if (event.type === 'run.paused' || event.type === 'turn.paused')
392
+ summary.reason = event.payload.reason;
393
+ if (event.type === 'turn.resumed') {
394
+ summary.reason = event.payload.reason;
395
+ if (event.payload.deadlineAt)
396
+ summary.deadlineAt = event.payload.deadlineAt;
397
+ }
398
+ if (event.type === 'run.plugin.availability')
399
+ summary.pluginBlock = event.payload.block ? { ...event.payload.block } : null;
400
+ if (event.type === 'run.failed' || event.type === 'turn.failed' || event.type === 'step.failed')
401
+ summary.error = { code: event.payload.error.code, diagnosticId: event.id };
402
+ if (event.type === 'run.failed') {
403
+ const { budget, checkpoint } = event.payload.error;
404
+ if (budget)
405
+ summary.limit = { ...budget };
406
+ if (checkpoint)
407
+ summary.checkpoint = true;
408
+ }
409
+ if (event.type === 'model.failed') {
410
+ const { code, message, details, retryAfterMs } = event.payload.error;
411
+ summary.requestId = event.payload.requestId;
412
+ summary.error = {
413
+ code,
414
+ message,
415
+ diagnosticId: event.id,
416
+ ...(details
417
+ ? { ...details, ...(details.causes ? { causes: details.causes.map((cause) => ({ ...cause })) } : {}) }
418
+ : {}),
419
+ };
420
+ if (retryAfterMs !== undefined)
421
+ summary.retryAfterMs = retryAfterMs;
422
+ if (event.payload.retryAt)
423
+ summary.retryAt = event.payload.retryAt;
424
+ }
425
+ return summary;
426
+ }
427
+ function toolCallId(event) {
428
+ switch (event.type) {
429
+ case 'tool.call.requested':
430
+ return event.payload.call.id;
431
+ case 'tool.approval.requested':
432
+ return event.payload.request.toolCallId;
433
+ case 'tool.approval.resolved':
434
+ return event.payload.decision.toolCallId;
435
+ case 'tool.call.started':
436
+ return event.payload.attempt.toolCallId;
437
+ case 'tool.call.completed':
438
+ return event.payload.result.toolCallId;
439
+ case 'tool.call.settled':
440
+ return event.payload.message.result.toolCallId;
441
+ default:
442
+ return 'toolCallId' in event.payload ? event.payload.toolCallId : undefined;
443
+ }
444
+ }
445
+ async function resolveToolCalls(store, events) {
446
+ const calls = new Map();
447
+ const needed = new Set();
448
+ for (const event of events) {
449
+ if (event.type === 'tool.call.requested')
450
+ calls.set(event.payload.call.id, event.payload.call);
451
+ const id = toolCallId(event);
452
+ if (id)
453
+ needed.add(id);
454
+ }
455
+ await Promise.all([...needed]
456
+ .filter((id) => !calls.has(id))
457
+ .map(async (id) => {
458
+ calls.set(id, (await store.toolReader.read(id)).call);
459
+ }));
460
+ return calls;
461
+ }
462
+ function bounded(text, limit = 12 * 1024) {
463
+ return text.length <= limit ? text : `${text.slice(0, limit)}\n… (truncated)`;
464
+ }
465
+ const blockTools = new Set([
466
+ 'security_record_fact',
467
+ 'security_record_hypothesis',
468
+ 'ctf_record_fact',
469
+ 'ctf_record_hypothesis',
470
+ 'security_skill',
471
+ 'skill',
472
+ 'web_search',
473
+ 'web_fetch',
474
+ ]);
475
+ function blockDetail(text) {
476
+ // Normally keep the entire result. A materialized detail still has to fit a single IPC frame.
477
+ return Buffer.byteLength(JSON.stringify(text)) <= maxFrameBytes / 2 - 32 * 1024
478
+ ? text
479
+ : bounded(text, 512 * 1024);
480
+ }
481
+ function toolBlock(name, args, result, output) {
482
+ const fields = (value) => value && typeof value === 'object' && !Array.isArray(value)
483
+ ? value
484
+ : {};
485
+ const data = fields(result);
486
+ const input = fields(args);
487
+ const field = (value, limit) => typeof value === 'string'
488
+ ? value
489
+ .trim()
490
+ .slice(0, limit)
491
+ .replace(/[\uD800-\uDBFF]$/, '')
492
+ : '';
493
+ if (name === 'web_search') {
494
+ return {
495
+ kind: 'web_search',
496
+ query: field(input.query, 512),
497
+ ...(Array.isArray(result) ? { count: result.length } : {}),
498
+ };
499
+ }
500
+ if (name === 'web_fetch') {
501
+ return {
502
+ kind: 'web_fetch',
503
+ url: field(input.url, 2048),
504
+ };
505
+ }
506
+ if (name === 'security_record_fact' || name === 'ctf_record_fact') {
507
+ return {
508
+ kind: 'fact',
509
+ id: field(data.id, 80),
510
+ category: field(data.category, 80),
511
+ confidence: field(data.confidence, 80),
512
+ summary: field(data.summary, 2048),
513
+ };
514
+ }
515
+ if (name === 'security_record_hypothesis' || name === 'ctf_record_hypothesis') {
516
+ return {
517
+ kind: 'hypothesis',
518
+ id: field(data.id, 80),
519
+ status: field(data.status, 80),
520
+ title: field(data.title, 2048),
521
+ conclusion: field(data.conclusion ?? data.outcome, 2048),
522
+ };
523
+ }
524
+ const skill = field(data.skill ?? input.skill, 512);
525
+ switch (input.action) {
526
+ case 'list':
527
+ return { kind: 'skill', action: 'list', count: Array.isArray(data.skills) ? data.skills.length : 0 };
528
+ case 'load': {
529
+ const content = typeof data.content === 'string' ? data.content : output;
530
+ const lines = content ? content.replace(/(?:\r\n?|\n)$/, '').split(/\r\n?|\n/).length : 0;
531
+ return { kind: 'skill', action: 'load', skill, ...(lines ? { lines } : {}) };
532
+ }
533
+ case 'read_ref':
534
+ case 'read_resource':
535
+ return { kind: 'skill', action: 'read', skill, path: field(data.path ?? input.path, 1024) };
536
+ }
537
+ }
538
+ function addInteractiveDetails(event, summary, calls, state, limits) {
539
+ const id = toolCallId(event);
540
+ const call = id ? calls.get(id) : undefined;
541
+ if (call) {
542
+ summary.toolCallId = call.id;
543
+ summary.toolName = call.toolName;
544
+ }
545
+ switch (event.type) {
546
+ case 'tool.call.requested': {
547
+ const { call } = event.payload;
548
+ const args = JSON.stringify(call.arguments);
549
+ summary.toolArguments = blockTools.has(call.toolName) ? blockDetail(args) : bounded(args);
550
+ break;
551
+ }
552
+ case 'tool.call.denied':
553
+ case 'tool.call.outcome_unknown':
554
+ summary.reason = bounded(event.payload.reason, 512);
555
+ break;
556
+ case 'tool.call.failed':
557
+ case 'tool.call.rejected':
558
+ summary.error = {
559
+ code: event.payload.error.code,
560
+ diagnosticId: event.id,
561
+ message: bounded(event.payload.error.message, 512),
562
+ };
563
+ break;
564
+ case 'tool.call.settled': {
565
+ const { effect, outcome } = event.payload.message.result;
566
+ summary.toolStatus = outcome.status;
567
+ summary.effect = effect;
568
+ const isShell = call?.toolName === 'shell';
569
+ const args = call?.arguments.kind === 'json' ? call.arguments.value : undefined;
570
+ if (args && typeof args === 'object' && !Array.isArray(args)) {
571
+ if ((call?.toolName === 'edit_file' ||
572
+ call?.toolName === 'write_file' ||
573
+ call?.toolName === 'apply_patch') &&
574
+ 'path' in args &&
575
+ typeof args.path === 'string')
576
+ summary.toolTarget = bounded(args.path, 512);
577
+ if ((call?.toolName === 'run_process' || call?.toolName === 'run_readonly_command') &&
578
+ 'program' in args &&
579
+ typeof args.program === 'string')
580
+ summary.toolTarget = bounded(path.basename(args.program), 512);
581
+ if (isShell && 'command' in args && typeof args.command === 'string') {
582
+ const description = 'description' in args && typeof args.description === 'string' ? args.description.trim() : '';
583
+ summary.toolTarget = bounded((description || args.command).replace(/\s+/g, ' ').trim(), 512);
584
+ }
585
+ }
586
+ if (outcome.status === 'success') {
587
+ const output = outcome.content
588
+ .map((part) => (part.type === 'text' ? part.text : `[${part.type}]`))
589
+ .join('\n');
590
+ const hasBlock = call && blockTools.has(call.toolName);
591
+ summary.toolOutput = hasBlock ? blockDetail(output) : bounded(output);
592
+ if (hasBlock) {
593
+ const block = toolBlock(call.toolName, args, outcome.data, output);
594
+ if (block)
595
+ summary.toolBlock = block;
596
+ }
597
+ const data = outcome.data;
598
+ if ((isShell || call?.toolName === 'run_process' || call?.toolName === 'run_readonly_command') &&
599
+ data &&
600
+ typeof data === 'object' &&
601
+ !Array.isArray(data)) {
602
+ if ('exitCode' in data && typeof data.exitCode === 'number')
603
+ summary.exitCode = data.exitCode;
604
+ if ('signal' in data && typeof data.signal === 'string')
605
+ summary.exitSignal = data.signal;
606
+ }
607
+ if ((call?.toolName === 'todo_write' || call?.toolName === 'review_numeric_data') &&
608
+ data &&
609
+ typeof data === 'object' &&
610
+ !Array.isArray(data) &&
611
+ 'todos' in data &&
612
+ Array.isArray(data.todos)) {
613
+ summary.todos = data.todos;
614
+ }
615
+ if (call?.toolName === 'spawn_team' &&
616
+ data &&
617
+ typeof data === 'object' &&
618
+ !Array.isArray(data) &&
619
+ 'team' in data &&
620
+ data.team !== undefined) {
621
+ summary.team = data.team;
622
+ }
623
+ }
624
+ else {
625
+ summary.error = {
626
+ code: outcome.error.code,
627
+ diagnosticId: event.id,
628
+ message: bounded(outcome.error.message, 512),
629
+ };
630
+ if (call && (call.toolName === 'web_fetch' || call.toolName === 'web_search')) {
631
+ const block = toolBlock(call.toolName, args, undefined, '');
632
+ if (block)
633
+ summary.toolBlock = block;
634
+ }
635
+ const data = outcome.data;
636
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
637
+ const fields = data;
638
+ const output = ['stdout', 'stderr']
639
+ .flatMap((key) => (typeof fields[key] === 'string' ? [`${key}:\n${fields[key]}`] : []))
640
+ .join('\n');
641
+ if (output)
642
+ summary.toolOutput = bounded(output);
643
+ if (typeof fields.exitCode === 'number')
644
+ summary.exitCode = fields.exitCode;
645
+ if (typeof fields.signal === 'string')
646
+ summary.exitSignal = fields.signal;
647
+ }
648
+ }
649
+ break;
650
+ }
651
+ case 'model.requested':
652
+ summary.requestId = event.payload.request.id;
653
+ break;
654
+ case 'model.failed':
655
+ if (event.payload.reasoningSummary)
656
+ summary.reasoningSummary = event.payload.reasoningSummary;
657
+ break;
658
+ case 'model.responded': {
659
+ summary.requestId = event.payload.response.requestId;
660
+ const text = modelReasoningSummary(event.payload.response, event.payload.reasoningSummary);
661
+ if (text)
662
+ summary.text = bounded(text);
663
+ break;
664
+ }
665
+ case 'message.user.added':
666
+ if (event.payload.steering)
667
+ summary.steering = true;
668
+ summary.messageId = event.payload.message.id;
669
+ summary.text = bounded(event.payload.message.content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\n'));
670
+ break;
671
+ case 'message.assistant.added':
672
+ summary.requestId = event.payload.requestId;
673
+ break;
674
+ case 'run.cancelled':
675
+ summary.reason = event.payload.reason;
676
+ break;
677
+ case 'run.failed':
678
+ if (event.payload.error.code === 'LIMIT' && limits && !event.payload.error.budget) {
679
+ const counters = [
680
+ ...(isLimited(limits.maxModelAttempts)
681
+ ? [{ resource: 'modelAttempts', used: state.modelAttempts, max: limits.maxModelAttempts }]
682
+ : []),
683
+ ...(isLimited(limits.maxToolCalls)
684
+ ? [{ resource: 'toolCalls', used: state.toolCallsStarted, max: limits.maxToolCalls }]
685
+ : []),
686
+ ...(isLimited(limits.maxSteps)
687
+ ? [{ resource: 'steps', used: state.stepsStarted, max: limits.maxSteps }]
688
+ : []),
689
+ ...(isLimited(limits.maxTotalTokens)
690
+ ? [{ ...modelTokenBudget(state, limits.maxTotalTokens) }]
691
+ : []),
692
+ ];
693
+ const limit = counters.find(({ used, max }) => used >= max);
694
+ if (limit)
695
+ summary.limit = limit;
696
+ }
697
+ break;
698
+ }
699
+ }