@causyne/agent 1.20.12 → 1.20.14

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 (72) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/SmartTools.js +33 -0
  4. package/src/SmartTools.ts +37 -0
  5. package/src/acp/client.js +157 -4
  6. package/src/acp/client.ts +152 -5
  7. package/src/agentLoop.js +857 -178
  8. package/src/agentLoop.ts +865 -183
  9. package/src/browser/browserRuntime.js +8 -1
  10. package/src/browser/browserRuntime.ts +8 -1
  11. package/src/browser/causyneBrowser.js +20 -4
  12. package/src/browser/causyneBrowser.ts +20 -4
  13. package/src/browser/urlPolicy.js +35 -0
  14. package/src/browser/urlPolicy.ts +34 -0
  15. package/src/cliMode.js +6 -2
  16. package/src/commands.js +14 -0
  17. package/src/contextManager.d.ts +1 -0
  18. package/src/core/contextCompactor.js +277 -0
  19. package/src/core/contextCompactor.ts +353 -0
  20. package/src/decideTools.js +157 -0
  21. package/src/decideTools.ts +195 -0
  22. package/src/decisionPolicy.js +5 -3
  23. package/src/decisionPolicy.ts +5 -3
  24. package/src/implementationPlan.js +284 -0
  25. package/src/implementationPlan.ts +275 -0
  26. package/src/observer/coldObserver.js +10 -4
  27. package/src/observer/coldObserver.ts +15 -7
  28. package/src/observer/evidence.js +11 -5
  29. package/src/observer/evidence.ts +13 -6
  30. package/src/observer.js +196 -0
  31. package/src/observer.ts +287 -0
  32. package/src/providers/acp.js +362 -109
  33. package/src/providers/acp.ts +359 -111
  34. package/src/providers/antigravity.js +133 -105
  35. package/src/providers/antigravity.ts +130 -109
  36. package/src/providers/base.d.ts +3 -0
  37. package/src/providers/budgetEnforcer.js +13 -0
  38. package/src/providers/budgetEnforcer.ts +13 -3
  39. package/src/provisioning/capabilityProvisioner.js +14 -10
  40. package/src/sandbox.js +4 -2
  41. package/src/saveTools.js +146 -0
  42. package/src/saveTools.ts +169 -0
  43. package/src/session/cachePressure.js +77 -0
  44. package/src/session/cachePressure.ts +122 -0
  45. package/src/smartToolsUse.js +69 -12
  46. package/src/smartToolsUse.ts +103 -12
  47. package/src/taskShape.js +7 -7
  48. package/src/taskShape.ts +7 -7
  49. package/src/timeMachine.js +55 -20
  50. package/src/timeMachine.ts +64 -20
  51. package/src/toolPacks.js +217 -310
  52. package/src/toolPacks.ts +505 -0
  53. package/src/tools/deferredMcpSearch.js +21 -13
  54. package/src/tools/deferredMcpSearch.ts +23 -15
  55. package/src/tools/updatePlan.js +2 -2
  56. package/src/tools/updatePlan.ts +2 -2
  57. package/src/toolsList.js +203 -0
  58. package/src/toolsList.ts +224 -0
  59. package/src/tui/chatRenderer.js +49 -14
  60. package/src/tui/codeStreamRenderer.js +16 -5
  61. package/src/tui/codeStreamRenderer.ts +14 -4
  62. package/src/tui/prompt.js +4 -2
  63. package/src/tui/sessionSidebar.js +10 -2
  64. package/src/tui/sessionSidebar.ts +10 -3
  65. package/src/tui/stageSurface.js +27 -1
  66. package/src/tui/text.d.ts +1 -0
  67. package/src/tui/turnRail.js +274 -0
  68. package/src/tui/turnRail.ts +334 -0
  69. package/src/types/contracts.ts +103 -0
  70. package/src/verificationPlan.js +141 -0
  71. package/src/verificationPlan.ts +166 -0
  72. package/src/toolPacks.d.ts +0 -10
@@ -0,0 +1,334 @@
1
+ import { truncate, visibleWidth, wrapBlock, stripAnsi, padEnd } from './text.js';
2
+ // @ts-expect-error untyped local TUI theme
3
+ import { paint, bold, dim, GLYPHS } from './theme.js';
4
+
5
+ export interface SessionTurn {
6
+ turnIndex: number; // 1-based (1..N)
7
+ totalTurns: number;
8
+ userPrompt: string;
9
+ assistantSummary: string;
10
+ timestamp: number;
11
+ formattedDate: string;
12
+ frameId: number;
13
+ startRow: number;
14
+ }
15
+
16
+ export interface TurnRailLayout {
17
+ railX: number;
18
+ stageTop: number;
19
+ viewportHeight: number;
20
+ dotRows: Map<number, number>; // turnIndex -> screenY
21
+ rowToTurn: Map<number, number>; // screenY -> turnIndex
22
+ }
23
+
24
+ export function formatTurnTimestamp(ts: number): string {
25
+ if (!ts || !Number.isFinite(ts)) return '';
26
+ const date = new Date(ts);
27
+ const now = new Date();
28
+ const sameDay = date.getFullYear() === now.getFullYear() &&
29
+ date.getMonth() === now.getMonth() &&
30
+ date.getDate() === now.getDate();
31
+ const timeStr = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
32
+ if (sameDay) {
33
+ return timeStr;
34
+ }
35
+ const dateStr = date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
36
+ return `${dateStr} at ${timeStr}`;
37
+ }
38
+
39
+ /**
40
+ * Collect all user turns from transcript frames.
41
+ */
42
+ export function collectSessionTurns(transcript: any, contentWidth = 80): SessionTurn[] {
43
+ if (!transcript || !Array.isArray(transcript.frames) || transcript.frames.length === 0) {
44
+ return [];
45
+ }
46
+ const flat = typeof transcript.flatten === 'function' ? transcript.flatten(contentWidth) : null;
47
+ const markers: Array<{ id: number; row: number; kind: string }> = flat?.markers || [];
48
+ const frames: any[] = transcript.frames;
49
+
50
+ const userFrames: Array<{ frame: any; index: number }> = [];
51
+ for (let i = 0; i < frames.length; i++) {
52
+ const f = frames[i];
53
+ if (f && f.kind === 'user') {
54
+ userFrames.push({ frame: f, index: i });
55
+ }
56
+ }
57
+
58
+ const totalTurns = userFrames.length;
59
+ if (totalTurns === 0) return [];
60
+
61
+ const turns: SessionTurn[] = [];
62
+ for (let k = 0; k < userFrames.length; k++) {
63
+ const item = userFrames[k];
64
+ if (!item) continue;
65
+ const { frame, index } = item;
66
+ const turnIndex = k + 1;
67
+ const nextUserFrameIndex = k + 1 < userFrames.length ? userFrames[k + 1]!.index : frames.length;
68
+
69
+ let userPrompt = typeof frame.meta?.messageText === 'string' ? frame.meta.messageText : '';
70
+ if (!userPrompt && typeof frame.produce === 'function') {
71
+ const rows = frame.produce(contentWidth) || [];
72
+ userPrompt = stripAnsi(rows.join(' ')).trim();
73
+ }
74
+
75
+ let assistantSummary = '';
76
+ for (let j = index + 1; j < nextUserFrameIndex; j++) {
77
+ const cand = frames[j];
78
+ if (cand && (cand.kind === 'assistant' || typeof cand.meta?.messageText === 'string')) {
79
+ assistantSummary = typeof cand.meta?.messageText === 'string'
80
+ ? cand.meta.messageText
81
+ : stripAnsi((cand.produce?.(contentWidth) || []).join(' ')).trim();
82
+ break;
83
+ }
84
+ }
85
+
86
+ const marker = markers.find((m) => m.id === frame.id);
87
+ const startRow = marker ? marker.row : 0;
88
+
89
+ turns.push({
90
+ turnIndex,
91
+ totalTurns,
92
+ userPrompt: userPrompt.replace(/\s+/g, ' ').trim(),
93
+ assistantSummary: assistantSummary.replace(/\s+/g, ' ').trim(),
94
+ timestamp: frame.ts || Date.now(),
95
+ formattedDate: formatTurnTimestamp(frame.ts || Date.now()),
96
+ frameId: frame.id,
97
+ startRow
98
+ });
99
+ }
100
+
101
+ return turns;
102
+ }
103
+
104
+ /**
105
+ * Build the vertical column of turn rail cells.
106
+ */
107
+ export function buildTurnRailCells(
108
+ turns: SessionTurn[],
109
+ height: number,
110
+ activeTurnIndex: number,
111
+ hoveredTurnIndex: number | null
112
+ ): { cells: string[]; layout: { dotRows: Map<number, number>; rowToTurn: Map<number, number> } } {
113
+ const cells: string[] = new Array(Math.max(0, height)).fill(' ');
114
+ const dotRows = new Map<number, number>();
115
+ const rowToTurn = new Map<number, number>();
116
+
117
+ if (turns.length === 0 || height <= 0) {
118
+ return { cells, layout: { dotRows, rowToTurn } };
119
+ }
120
+
121
+ const count = turns.length;
122
+ // If count fits comfortably, stack consecutive dots centered or top-aligned
123
+ const startRow = count <= height
124
+ ? Math.max(0, Math.floor((height - count) / 3))
125
+ : 0;
126
+
127
+ for (let i = 0; i < count; i++) {
128
+ const turn = turns[i];
129
+ if (!turn) continue;
130
+ const turnNum = turn.turnIndex;
131
+
132
+ let rowIdx: number;
133
+ if (count <= height) {
134
+ rowIdx = startRow + i;
135
+ } else {
136
+ rowIdx = Math.round((i / (count - 1)) * (height - 1));
137
+ }
138
+ rowIdx = Math.max(0, Math.min(height - 1, rowIdx));
139
+
140
+ dotRows.set(turnNum, rowIdx);
141
+ rowToTurn.set(rowIdx, turnNum);
142
+
143
+ const isHovered = hoveredTurnIndex === turnNum;
144
+ const isActive = activeTurnIndex === turnNum || (turnNum === count && !hoveredTurnIndex);
145
+
146
+ if (isHovered) {
147
+ // Hovered dot: bright silver highlighted circle
148
+ cells[rowIdx] = '\x1b[1m\x1b[38;2;230;235;245m●\x1b[0m';
149
+ } else if (isActive) {
150
+ // Active / current turn: bright white circle
151
+ cells[rowIdx] = '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
152
+ } else {
153
+ // Muted inactive turns: subtle gray dot
154
+ cells[rowIdx] = '\x1b[38;2;115;115;120m•\x1b[0m';
155
+ }
156
+ }
157
+
158
+ return { cells, layout: { dotRows, rowToTurn } };
159
+ }
160
+
161
+ /**
162
+ * Render the Floating Turn Preview Card popover.
163
+ * Exactly matches the UX/UI in Screen Recording 2026-10-30 at 02.42.17:
164
+ * - Rounded elevated box (╭─╮ / ╰─╯) with dark translucent background
165
+ * - Line 1-2: User prompt in bold primary white
166
+ * - Line 3-4: Assistant preview in muted secondary text
167
+ * - Footer: Left 'X of Y', Right timestamp
168
+ */
169
+ export function renderTurnPreviewCard(turn: SessionTurn, maxCardWidth = 50): string[] {
170
+ const cardWidth = Math.max(38, Math.min(60, maxCardWidth));
171
+ const innerWidth = cardWidth - 4; // 2 border chars + 2 padding chars
172
+
173
+ const cardBg = '\x1b[48;2;28;28;32m';
174
+ const borderStyle = `${cardBg}\x1b[38;2;75;75;82m`;
175
+ const reset = '\x1b[0m';
176
+
177
+ // Format header: User Prompt (bold primary)
178
+ const rawPrompt = turn.userPrompt || 'User request';
179
+ const promptLines = wrapBlock(rawPrompt, innerWidth).slice(0, 2);
180
+ if (promptLines.length === 2 && promptLines[1]) {
181
+ promptLines[1] = truncate(promptLines[1], innerWidth - 3, '...');
182
+ }
183
+
184
+ // Format body: Assistant Summary (muted secondary)
185
+ let bodyLines: string[] = [];
186
+ if (turn.assistantSummary) {
187
+ bodyLines = wrapBlock(turn.assistantSummary, innerWidth).slice(0, 3);
188
+ if (bodyLines.length === 3 && bodyLines[2]) {
189
+ bodyLines[2] = truncate(bodyLines[2], innerWidth - 3, '...');
190
+ }
191
+ }
192
+
193
+ // Format footer: 'X of Y' on left, timestamp on right
194
+ const counterText = `${turn.turnIndex} of ${turn.totalTurns}`;
195
+ const dateText = turn.formattedDate;
196
+ const footerSpace = Math.max(2, innerWidth - counterText.length - dateText.length);
197
+ const footerLine = `${counterText}${' '.repeat(footerSpace)}${dateText}`;
198
+
199
+ // Assemble rows
200
+ const rows: string[] = [];
201
+ const topBorder = `${borderStyle}╭${'─'.repeat(cardWidth - 2)}╮${reset}`;
202
+ const bottomBorder = `${borderStyle}╰${'─'.repeat(cardWidth - 2)}╯${reset}`;
203
+
204
+ rows.push(topBorder);
205
+
206
+ // User prompt rows
207
+ for (const pl of promptLines) {
208
+ const padded = padEnd(pl, innerWidth);
209
+ rows.push(`${borderStyle}│${cardBg} \x1b[1m\x1b[38;2;240;240;245m${padded}${borderStyle} │${reset}`);
210
+ }
211
+
212
+ // Body rows if present
213
+ if (bodyLines.length > 0) {
214
+ rows.push(`${borderStyle}│${cardBg}${' '.repeat(innerWidth + 2)}${borderStyle}│${reset}`);
215
+ for (const bl of bodyLines) {
216
+ const padded = padEnd(bl, innerWidth);
217
+ rows.push(`${borderStyle}│${cardBg} \x1b[38;2;160;160;168m${padded}${borderStyle} │${reset}`);
218
+ }
219
+ }
220
+
221
+ // Empty spacing before footer
222
+ rows.push(`${borderStyle}│${cardBg}${' '.repeat(innerWidth + 2)}${borderStyle}│${reset}`);
223
+
224
+ // Footer row
225
+ const paddedFooter = padEnd(footerLine, innerWidth);
226
+ rows.push(`${borderStyle}│${cardBg} \x1b[38;2;125;125;132m${paddedFooter}${borderStyle} │${reset}`);
227
+
228
+ rows.push(bottomBorder);
229
+ return rows;
230
+ }
231
+
232
+ /**
233
+ * Overlay the floating preview card onto viewport rows at a specific anchorY.
234
+ */
235
+ export function overlayTurnPreviewCard(
236
+ viewportRows: string[],
237
+ cardRows: string[],
238
+ anchorY: number,
239
+ railX: number,
240
+ screenWidth: number
241
+ ): string[] {
242
+ if (cardRows.length === 0 || viewportRows.length === 0) return viewportRows;
243
+
244
+ const cardWidth = visibleWidth(cardRows[0] || '');
245
+ // Clamp card placement horizontally: preferably to the left of the rail, or to the right
246
+ let x = railX - cardWidth - 1;
247
+ if (x < 0 || (railX <= 4 && railX + 2 + cardWidth <= screenWidth)) {
248
+ x = Math.max(0, Math.min(screenWidth - cardWidth - 1, railX + 2));
249
+ }
250
+
251
+ // Center vertically around anchorY
252
+ const startY = Math.max(
253
+ 0,
254
+ Math.min(viewportRows.length - cardRows.length, anchorY - Math.floor(cardRows.length / 2))
255
+ );
256
+
257
+ const out = viewportRows.slice();
258
+ for (let i = 0; i < cardRows.length; i++) {
259
+ const targetY = startY + i;
260
+ if (targetY >= out.length) break;
261
+ const baseRow = out[targetY] || '';
262
+ const cardRow = cardRows[i] || '';
263
+
264
+ // Composite cardRow onto baseRow at column x
265
+ const beforePart = padEnd(truncate(baseRow, x, ''), x);
266
+ const afterPart = baseRow.length > x + cardWidth ? baseRow.slice(x + cardWidth) : '';
267
+ out[targetY] = `${beforePart}${cardRow}${afterPart}`;
268
+ }
269
+
270
+ return out;
271
+ }
272
+
273
+ export function isMouseMotion(sequence: string | undefined): boolean {
274
+ const code = Number(/^\x1b\[<(\d+);/.exec(sequence || '')?.[1]);
275
+ return Number.isFinite(code) && (code & 32) !== 0;
276
+ }
277
+
278
+ /**
279
+ * Handle mouse interaction (hover and click) for the Turn Rail.
280
+ */
281
+ export function handleTurnRailMouse(
282
+ event: { mouse?: { x: number; y: number; button?: number; pressed?: boolean }; sequence?: string },
283
+ surface: any,
284
+ host: any
285
+ ): boolean {
286
+ if (!surface?.turnRailLayout || !event.mouse) return false;
287
+ const layout = surface.turnRailLayout;
288
+ const mouseX = event.mouse.x;
289
+ const mouseY = event.mouse.y;
290
+ const stageTop = layout.stageTop ?? 0;
291
+ const relY = mouseY - stageTop;
292
+
293
+ const isRail = mouseX >= layout.railX - 1 && mouseX <= layout.railX + 1;
294
+ if (!isRail || relY < 0 || relY >= layout.viewportHeight) {
295
+ if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
296
+ surface.hoveredTurnIndex = null;
297
+ surface.hoveredTurnAnchorY = null;
298
+ if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
299
+ else if (typeof host?.draw === 'function') host.draw();
300
+ }
301
+ return false;
302
+ }
303
+
304
+ const turnNum = layout.rowToTurn?.get(relY);
305
+ if (turnNum) {
306
+ if (isMouseMotion(event.sequence)) {
307
+ if (surface.hoveredTurnIndex !== turnNum) {
308
+ surface.hoveredTurnIndex = turnNum;
309
+ surface.hoveredTurnAnchorY = relY;
310
+ if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
311
+ else if (typeof host?.draw === 'function') host.draw();
312
+ }
313
+ return true;
314
+ }
315
+ if (event.mouse.button === 0 && event.mouse.pressed) {
316
+ const turn = layout.turns?.find((t: SessionTurn) => t.turnIndex === turnNum);
317
+ if (turn && surface.viewport && typeof surface.viewport.scrollTo === 'function') {
318
+ surface.viewport.scrollTo(turn.startRow);
319
+ surface.hoveredTurnIndex = null;
320
+ surface.hoveredTurnAnchorY = null;
321
+ if (typeof host?.draw === 'function') host.draw();
322
+ else if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
323
+ return true;
324
+ }
325
+ }
326
+ } else if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
327
+ surface.hoveredTurnIndex = null;
328
+ surface.hoveredTurnAnchorY = null;
329
+ if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
330
+ else if (typeof host?.draw === 'function') host.draw();
331
+ }
332
+
333
+ return false;
334
+ }
@@ -298,6 +298,11 @@ export interface WorkspaceContext {
298
298
  projectType?: string;
299
299
  designSystem?: string;
300
300
  keyFiles?: string[];
301
+ applicationRoot?: string;
302
+ workspaceRoot?: string;
303
+ allowedReadRoots?: string[];
304
+ allowedWriteRoots?: string[];
305
+ capabilities?: string[];
301
306
  }
302
307
 
303
308
  export interface TaskShape {
@@ -315,3 +320,101 @@ export type AgentEvent =
315
320
  | { type: 'tool.completed'; callId?: string; result: ToolResult }
316
321
  | { type: 'approval.required'; toolName: string; risk: RiskLevel; reason?: string }
317
322
  | { type: 'session.notice'; message: string };
323
+
324
+ export type RunMode = 'direct' | 'plan' | 'plan-execute';
325
+
326
+ export type RunStatus =
327
+ | 'created'
328
+ | 'preparing'
329
+ | 'running'
330
+ | 'planning'
331
+ | 'awaiting-user'
332
+ | 'awaiting-approval'
333
+ | 'executing'
334
+ | 'verifying'
335
+ | 'recovering'
336
+ | 'completed'
337
+ | 'blocked'
338
+ | 'failed'
339
+ | 'cancelled';
340
+
341
+ export type ToolAvailability = 'available' | 'disabled' | 'unimplemented' | 'unavailable';
342
+
343
+ export type EffectClass =
344
+ | 'read'
345
+ | 'workspace-write'
346
+ | 'external-write'
347
+ | 'privileged'
348
+ | 'destructive';
349
+
350
+ export type RetryDisposition = 'safe' | 'reconcile-first' | 'never-auto';
351
+
352
+ export interface ToolDescriptor {
353
+ id: string;
354
+ version: string;
355
+ summary: string;
356
+ category: string;
357
+ availability: ToolAvailability;
358
+ effect: EffectClass;
359
+ requiredCapabilities: string[];
360
+ schemaId: string;
361
+ retryDisposition: RetryDisposition;
362
+ source: 'builtin' | 'mcp' | 'plugin';
363
+ sourceId?: string;
364
+ }
365
+
366
+ export interface RunBudget {
367
+ maxModelCalls: number;
368
+ maxToolCalls: number;
369
+ maxElapsedMs: number;
370
+ maxOutputTokens?: number;
371
+ maxEstimatedCost?: number;
372
+ }
373
+
374
+ export interface AgentSession {
375
+ runId: string;
376
+ sessionId: string;
377
+ userGoal: string;
378
+ mode: RunMode;
379
+ workspace: WorkspaceContext | string;
380
+ providerId: string;
381
+ modelId: string;
382
+ state: RunStatus;
383
+ activeStepId?: string;
384
+ planVersion?: number;
385
+ selectedTools: Array<{ id: string; version: string }>;
386
+ catalogRevision: string;
387
+ budgets: RunBudget;
388
+ repairAttemptsByFailureKey: Record<string, number>;
389
+ pendingApprovalId?: string;
390
+ checkpointId?: string;
391
+ eventSeq: number;
392
+ }
393
+
394
+ export type RunEventType =
395
+ | 'run.created'
396
+ | 'plan.created'
397
+ | 'plan.step.started'
398
+ | 'tool.discovered'
399
+ | 'tool.selected'
400
+ | 'approval.requested'
401
+ | 'approval.granted'
402
+ | 'tool.started'
403
+ | 'tool.finished'
404
+ | 'verification.started'
405
+ | 'verification.finished'
406
+ | 'checkpoint.created'
407
+ | 'repair.started'
408
+ | 'repair.finished'
409
+ | 'run.completed'
410
+ | 'run.blocked'
411
+ | 'run.cancelled';
412
+
413
+ export interface RunEvent {
414
+ type: RunEventType;
415
+ runId: string;
416
+ seq: number;
417
+ timestamp: number;
418
+ payload?: JsonObject;
419
+ }
420
+
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @file src/verificationPlan.ts
3
+ * Verification stage of the pipeline.
4
+ *
5
+ * ... AgentLoop -> near completion -> verify -> Observer -> TimeMachine
6
+ *
7
+ * Work is not finished when the model says so; it is finished when evidence of
8
+ * the right KIND exists. What counts depends on what was produced: code is run
9
+ * or checked, a page is rendered and looked at, a render or image is viewed, a
10
+ * document is read back. File moves, deletes and the like are not here on
11
+ * purpose: the tool's own success result is already their evidence.
12
+ *
13
+ * Everything here reads the observer's journal — what actually ran — and never
14
+ * the model's account of it.
15
+ *
16
+ * Authorship: Strict TypeScript (Causyne Agent).
17
+ */
18
+ import { isVerificationCommand } from './observer/evidence.js';
19
+ const CODE_MUTATORS = new Set([
20
+ 'fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'write_to_file', 'edit_file',
21
+ 'replace_file_content', 'multi_replace_file_content', 'write', 'edit', 'multiedit'
22
+ ]);
23
+ const CREATIVE_MUTATORS = new Set([
24
+ 'blender_act', 'creative_apps', 'execute_procedural_media', 'generate_media_via_api',
25
+ 'native_engine', 'resolve_act', 'palmier_act', 'game_audio_synth'
26
+ ]);
27
+ const WEB_PATH = /\.(?:html?|css|scss|jsx|tsx|vue|svelte)$/i;
28
+ const CODE_PATH = /\.(?:[cm]?[jt]s|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|sh|sql)$/i;
29
+ const DOCUMENT_PATH = /\.(?:pdf|docx?|pptx?|odt|rtf|epub)$/i;
30
+ const IMAGE_PATH = /\.(?:png|jpe?g|webp|gif|bmp)$/i;
31
+ const RUN_COMMAND = /^\s*(?:node|python3?|ruby|php|deno|bun|go\s+run|cargo\s+run|dotnet\s+run|swift\s+run|java|npm\s+(?:start|run\s+(?:dev|start)))\b/i;
32
+ const MEDIA_PROBE = /\b(?:ffprobe|afinfo|soxi|identify|mediainfo|exiftool)\b/i;
33
+ const READBACK_TOOLS = new Set(['pdf_read', 'fs_read', 'view_image', 'vision_inspect_ui', 'screenshot']);
34
+ const LOOK_TOOLS = new Set(['view_image', 'vision_inspect_ui', 'screenshot']);
35
+ function isMutation(outcome) {
36
+ if (!outcome.success)
37
+ return false;
38
+ const tool = outcome.tool;
39
+ if (CODE_MUTATORS.has(tool) || CREATIVE_MUTATORS.has(tool))
40
+ return true;
41
+ if (tool === 'document_forge')
42
+ return true;
43
+ return false;
44
+ }
45
+ function domainsOf(input, mutations) {
46
+ const found = new Set();
47
+ for (const outcome of mutations) {
48
+ const tool = outcome.tool;
49
+ const target = outcome.path || '';
50
+ if (CREATIVE_MUTATORS.has(tool))
51
+ found.add('creative');
52
+ else if (tool === 'document_forge' || DOCUMENT_PATH.test(target))
53
+ found.add('document');
54
+ else if (CODE_MUTATORS.has(tool)) {
55
+ if (WEB_PATH.test(target))
56
+ found.add('web');
57
+ else if (CODE_PATH.test(target))
58
+ found.add('code');
59
+ }
60
+ }
61
+ if (input.archetype === 'web_engineering' && found.has('code'))
62
+ found.add('web');
63
+ return [...found];
64
+ }
65
+ function after(outcomes, domain) {
66
+ const matches = (outcome) => {
67
+ if (!isMutation(outcome))
68
+ return false;
69
+ const target = outcome.path || '';
70
+ switch (domain) {
71
+ case 'creative': return CREATIVE_MUTATORS.has(outcome.tool);
72
+ case 'document': return outcome.tool === 'document_forge' || DOCUMENT_PATH.test(target);
73
+ case 'web': return CODE_MUTATORS.has(outcome.tool) && WEB_PATH.test(target);
74
+ case 'code': return CODE_MUTATORS.has(outcome.tool) && CODE_PATH.test(target);
75
+ }
76
+ };
77
+ return outcomes.slice(outcomes.findLastIndex(matches) + 1);
78
+ }
79
+ function satisfied(domain, evidence) {
80
+ const ok = evidence.filter((outcome) => outcome.success);
81
+ switch (domain) {
82
+ case 'code':
83
+ return ok.some((outcome) => outcome.tool === 'code_verify_syntax'
84
+ || isVerificationCommand(outcome.command)
85
+ || (RUN_COMMAND.test(outcome.command) && outcome.exitCode === 0));
86
+ case 'web':
87
+ return ok.some((outcome) => outcome.rendered === true);
88
+ case 'creative':
89
+ return ok.some((outcome) => outcome.observedImage === true
90
+ || MEDIA_PROBE.test(outcome.command));
91
+ case 'document':
92
+ return ok.some((outcome) => outcome.observedImage === true
93
+ || (['pdf_read', 'fs_read'].includes(outcome.tool) && DOCUMENT_PATH.test(outcome.path)));
94
+ }
95
+ }
96
+ const NEEDS = {
97
+ code: {
98
+ need: 'run the code or its tests, build, or a syntax check (sysRun, code_verify_syntax)',
99
+ tools: ['sysRun', 'code_verify_syntax']
100
+ },
101
+ web: {
102
+ need: 'render the page (browser_act preview, then snapshot) and look at it (screenshot or vision_inspect_ui)',
103
+ tools: ['browser_act', 'screenshot']
104
+ },
105
+ creative: {
106
+ need: 'look at the produced image, render or frame (view_image or vision_inspect_ui) and probe audio or video output',
107
+ tools: ['view_image', 'vision_inspect_ui']
108
+ },
109
+ document: {
110
+ need: 'read the produced document back (pdf_read, fs_read or view_image) and confirm it matches the request',
111
+ tools: ['pdf_read', 'view_image']
112
+ }
113
+ };
114
+ /**
115
+ * What evidence is still missing for what this task actually produced. Nothing
116
+ * produced means nothing to verify: research and conversation are never nagged.
117
+ */
118
+ export function assessVerification(input) {
119
+ const mutations = input.outcomes.filter(isMutation);
120
+ if (mutations.length === 0)
121
+ return { domains: [], gaps: [], directive: '' };
122
+ const skip = new Set(input.skip ?? []);
123
+ const domains = domainsOf(input, mutations);
124
+ const gaps = [];
125
+ for (const domain of domains) {
126
+ if (skip.has(domain))
127
+ continue;
128
+ if (satisfied(domain, after(input.outcomes, domain)))
129
+ continue;
130
+ gaps.push({ domain, ...NEEDS[domain] });
131
+ }
132
+ if (gaps.length === 0)
133
+ return { domains, gaps, directive: '' };
134
+ const needs = gaps.map((gap) => `${gap.domain}: ${gap.need}`).join('; ');
135
+ return {
136
+ domains,
137
+ gaps,
138
+ directive: `[VERIFY] You changed things but no evidence of the right kind exists yet. Before you finish — ${needs}. `
139
+ + 'If a check cannot be run, say so plainly instead of claiming success.'
140
+ };
141
+ }