@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. package/src/utils/paths.ts +5 -5
@@ -259,6 +259,20 @@ export function titleFrom(text: unknown): string {
259
259
  return clean.length > 60 ? `${clean.slice(0, 57)}…` : clean;
260
260
  }
261
261
 
262
+ const PLACEHOLDER_TITLE = /^(?:untitled|hi|hello|hey|halo|hai|continue|lanjut|open it(?: for me)?|new session\b.*)$/i;
263
+ const NON_TASK_MESSAGE = /^(?:hi|hello|hey|halo|hai|continue|lanjut|open it|open it for me|thanks|thank you)[.!?\s]*$/i;
264
+
265
+ /** Recover a useful title when a session began with a greeting or placeholder. */
266
+ function sessionTitle(title: string, messages: SessionMessage[], createdAt: number): string {
267
+ if (title.trim() && !PLACEHOLDER_TITLE.test(title.trim())) return title;
268
+ const prompt = messages.find((message) => {
269
+ if (message.role !== 'user' || typeof message.content !== 'string') return false;
270
+ const text = message.content.trim();
271
+ return text.length > 12 && !NON_TASK_MESSAGE.test(text) && !text.startsWith('[decayed]');
272
+ });
273
+ return prompt ? titleFrom(prompt.content) : `New session - ${new Date(createdAt).toISOString().replace('T', ' ').slice(0, 16)} UTC`;
274
+ }
275
+
262
276
  export function listSessions(): Array<Omit<SessionRecord, 'messages'> & { messageCount: number }> {
263
277
  try {
264
278
  ensureDir();
@@ -272,7 +286,7 @@ export function listSessions(): Array<Omit<SessionRecord, 'messages'> & { messag
272
286
  const session = readSession(id);
273
287
  if (!session) continue;
274
288
  const { messages, ...metadata } = session;
275
- rows.push({ ...metadata, messageCount: messages.length });
289
+ rows.push({ ...metadata, title: sessionTitle(metadata.title, messages, metadata.createdAt), messageCount: messages.length });
276
290
  }
277
291
  return rows.sort((left, right) => right.updatedAt - left.updatedAt);
278
292
  } catch {
@@ -311,8 +325,9 @@ export function createSession(workspace: unknown, title = 'Untitled', makeActive
311
325
  // user from starting an otherwise usable foreground session.
312
326
  writeNewTranscript(session);
313
327
  if (makeActive) setActiveSession(session.id);
314
- pruneSessions();
315
- return session;
328
+ // Session creation must never silently delete older conversations. Retention
329
+ // is an explicit maintenance operation, separate from starting a chat.
330
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
316
331
  }
317
332
 
318
333
  /**
@@ -322,7 +337,8 @@ export function createSession(workspace: unknown, title = 'Untitled', makeActive
322
337
  * they only need the transcript that belongs to their own id.
323
338
  */
324
339
  export function getSession(id: unknown): SessionRecord | null {
325
- return readSession(id);
340
+ const session = readSession(id);
341
+ return session ? { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) } : null;
326
342
  }
327
343
 
328
344
  export function getActiveSessionId(): string | null {
@@ -367,7 +383,7 @@ export function resolveSession(workspace: unknown, options: ResolveSessionOption
367
383
  const active = readSession(targetId);
368
384
  if (active && (!active.workspace || active.workspaceKey === key) && now - active.updatedAt < RESUME_WINDOW_MS) {
369
385
  setActiveSession(active.id);
370
- return active;
386
+ return { ...active, title: sessionTitle(active.title, active.messages, active.createdAt) };
371
387
  }
372
388
  }
373
389
 
@@ -379,7 +395,7 @@ export function resolveSession(workspace: unknown, options: ResolveSessionOption
379
395
  const session = readSession(candidate.id);
380
396
  if (session) {
381
397
  setActiveSession(session.id);
382
- return session;
398
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
383
399
  }
384
400
  }
385
401
  return createSession(workspaceText);
@@ -389,7 +405,46 @@ export function switchSession(id: unknown): SessionRecord | null {
389
405
  const session = readSession(id);
390
406
  if (!session) return null;
391
407
  setActiveSession(session.id);
392
- return session;
408
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
409
+ }
410
+
411
+ export interface ForkSessionOptions {
412
+ title?: string | undefined;
413
+ makeActive?: boolean | undefined;
414
+ upToMessageIndex?: number | undefined;
415
+ workspace?: string | undefined;
416
+ }
417
+
418
+ /**
419
+ * Fork an existing session into a new conversation in the same workspace.
420
+ *
421
+ * CRITICAL TRUST & PERMISSION INVARIANT (Claude Code Architecture, p. 24):
422
+ * Forking copies conversation history up to the designated turn, creating a
423
+ * distinct trajectory. Permissions, standing approvals, and tool allowlists
424
+ * are strictly bound to the originating session lifecycle and must NEVER be
425
+ * inherited into a fork. The forked session starts with fresh, ungranted
426
+ * permissions so that user authorization and trust are freshly established.
427
+ */
428
+ export function forkSession(sourceId: unknown, options: ForkSessionOptions = {}): SessionRecord | null {
429
+ const source = getSession(sourceId);
430
+ if (!source) return null;
431
+
432
+ const targetWorkspace = options.workspace || source.workspace || process.cwd();
433
+ const sourceTitle = source.title && source.title !== 'Untitled' ? source.title : 'Conversation';
434
+ const newTitle = options.title || `Fork of ${sourceTitle}`;
435
+ const newSession = createSession(targetWorkspace, newTitle, options.makeActive ?? true);
436
+
437
+ let messagesToCopy = Array.isArray(source.messages) ? source.messages : [];
438
+ if (typeof options.upToMessageIndex === 'number' && options.upToMessageIndex >= 0) {
439
+ messagesToCopy = messagesToCopy.slice(0, options.upToMessageIndex + 1);
440
+ }
441
+
442
+ if (messagesToCopy.length > 0) {
443
+ const clonedMessages: SessionMessage[] = JSON.parse(JSON.stringify(messagesToCopy));
444
+ saveSessionMessages(newSession.id, clonedMessages);
445
+ }
446
+
447
+ return readSession(newSession.id);
393
448
  }
394
449
 
395
450
  function messageEqual(left: SessionMessage, right: SessionMessage): boolean {
@@ -419,9 +474,8 @@ export function saveSessionMessages(id: unknown, messages: unknown): boolean {
419
474
  if (!session || !validMessages(messages)) return false;
420
475
  const nextMessages = messages.slice();
421
476
  const firstUser = nextMessages.find((message) => message.role === 'user' && typeof message.content === 'string');
422
- const nextTitle = (!session.title || session.title === 'Untitled') && firstUser
423
- ? titleFrom(firstUser.content)
424
- : session.title;
477
+ const nextTitle = sessionTitle(session.title, nextMessages, session.createdAt)
478
+ || (firstUser ? titleFrom(firstUser.content) : session.title);
425
479
  const prefix = session.messages.length <= nextMessages.length
426
480
  && session.messages.every((message, index) => {
427
481
  const next = nextMessages[index];
package/src/taskShape.js CHANGED
@@ -31,7 +31,7 @@ const ARCHETYPES = {
31
31
  integrate: {
32
32
  label: 'Build an application that integrates live external data',
33
33
  match: {
34
- strong: ['realtime', 'real-time', 'real time', 'api', 'rest', 'webhook', 'integration', 'integrasi', 'sync', 'sinkron', 'automation', 'automasi', 'otomasi', 'automate', 'otomatis', 'booking', 'tiket', 'ticket', 'calendar', 'kalender', 'jadwal', 'schedule', 'payment', 'pembayaran'],
34
+ strong: ['realtime', 'real-time', 'real time', 'api', 'rest', 'webhook', 'integration', 'sync', 'automation', 'automate', 'booking', 'ticket', 'calendar', 'schedule', 'payment'],
35
35
  weak: ['live', 'stream', 'fetch', 'data', 'third party', 'oauth', 'token']
36
36
  },
37
37
  phases: [
@@ -45,8 +45,8 @@ const ARCHETYPES = {
45
45
  build_app: {
46
46
  label: 'Build a new application from scratch',
47
47
  match: {
48
- strong: ['build me', 'buatkan', 'buat aku', 'create a', 'make me', 'bikin', 'develop a', 'new app', 'from scratch'],
49
- weak: ['app', 'aplikasi', 'project', 'proyek', 'tool', 'system', 'sistem']
48
+ strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch'],
49
+ weak: ['app', 'project', 'tool', 'system']
50
50
  },
51
51
  phases: [
52
52
  { name: 'Plan', tools: ['update_plan'], note: 'Create a visible atomic implementation plan before touching the filesystem.' },
@@ -58,8 +58,8 @@ const ARCHETYPES = {
58
58
  debug: {
59
59
  label: 'Diagnose and fix a defect in existing code',
60
60
  match: {
61
- strong: ['bug', 'error', 'crash', 'fix', 'perbaiki', 'benerin', 'broken', 'rusak', 'not working', 'gagal', 'failing', 'exception', 'stack trace', 'regression'],
62
- weak: ['issue', 'masalah', 'problem', 'wrong', 'salah', 'debug']
61
+ strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression'],
62
+ weak: ['issue', 'problem', 'wrong', 'debug']
63
63
  },
64
64
  phases: [
65
65
  { name: 'Reproduce', tools: ['sysRun', 'fs_read'], note: 'Reproduce the failure and capture the exact error before changing anything.' },
@@ -71,8 +71,8 @@ const ARCHETYPES = {
71
71
  research: {
72
72
  label: 'Investigate and report, without changing the system',
73
73
  match: {
74
- strong: ['explain', 'jelaskan', 'analyse', 'analyze', 'analisa', 'research', 'riset', 'compare', 'bandingkan', 'what is', 'apa itu', 'how does', 'bagaimana', 'review', 'audit'],
75
- weak: ['understand', 'pahami', 'find out', 'cari tahu', 'summarize', 'ringkas']
74
+ strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit'],
75
+ weak: ['understand', 'find out', 'summarize']
76
76
  },
77
77
  phases: [
78
78
  { name: 'Gather', tools: ['code_search_ripgrep', 'fs_read', 'web_search', 'web_fetch'], note: 'Search broadly with several phrasings in parallel before concluding.' },
@@ -82,8 +82,8 @@ const ARCHETYPES = {
82
82
  maintain: {
83
83
  label: 'Operate on files, processes or the machine itself',
84
84
  match: {
85
- strong: ['organize', 'rapikan', 'clean up', 'bersihkan', 'rename', 'ganti nama', 'move', 'pindahkan', 'backup', 'cadangkan', 'delete', 'hapus', 'install', 'deploy', 'commit', 'merge'],
86
- weak: ['folder', 'directory', 'file', 'berkas', 'desktop', 'downloads']
85
+ strong: ['organize', 'clean up', 'rename', 'move', 'backup', 'delete', 'install', 'deploy', 'commit', 'merge'],
86
+ weak: ['folder', 'directory', 'file', 'desktop', 'downloads']
87
87
  },
88
88
  phases: [
89
89
  { name: 'Survey', tools: ['fs_list', 'fs_find'], note: 'List and count what you are about to touch, and report it, before acting.' },
package/src/taskShape.ts CHANGED
@@ -52,7 +52,7 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
52
52
  integrate: {
53
53
  label: 'Build an application that integrates live external data',
54
54
  match: {
55
- strong: ['realtime', 'real-time', 'real time', 'api', 'rest', 'webhook', 'integration', 'integrasi', 'sync', 'sinkron', 'automation', 'automasi', 'otomasi', 'automate', 'otomatis', 'booking', 'tiket', 'ticket', 'calendar', 'kalender', 'jadwal', 'schedule', 'payment', 'pembayaran'],
55
+ strong: ['realtime', 'real-time', 'real time', 'api', 'rest', 'webhook', 'integration', 'sync', 'automation', 'automate', 'booking', 'ticket', 'calendar', 'schedule', 'payment'],
56
56
  weak: ['live', 'stream', 'fetch', 'data', 'third party', 'oauth', 'token']
57
57
  },
58
58
  phases: [
@@ -66,8 +66,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
66
66
  build_app: {
67
67
  label: 'Build a new application from scratch',
68
68
  match: {
69
- strong: ['build me', 'buatkan', 'buat aku', 'create a', 'make me', 'bikin', 'develop a', 'new app', 'from scratch'],
70
- weak: ['app', 'aplikasi', 'project', 'proyek', 'tool', 'system', 'sistem']
69
+ strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch'],
70
+ weak: ['app', 'project', 'tool', 'system']
71
71
  },
72
72
  phases: [
73
73
  { name: 'Plan', tools: ['update_plan'], note: 'Create a visible atomic implementation plan before touching the filesystem.' },
@@ -79,8 +79,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
79
79
  debug: {
80
80
  label: 'Diagnose and fix a defect in existing code',
81
81
  match: {
82
- strong: ['bug', 'error', 'crash', 'fix', 'perbaiki', 'benerin', 'broken', 'rusak', 'not working', 'gagal', 'failing', 'exception', 'stack trace', 'regression'],
83
- weak: ['issue', 'masalah', 'problem', 'wrong', 'salah', 'debug']
82
+ strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression'],
83
+ weak: ['issue', 'problem', 'wrong', 'debug']
84
84
  },
85
85
  phases: [
86
86
  { name: 'Reproduce', tools: ['sysRun', 'fs_read'], note: 'Reproduce the failure and capture the exact error before changing anything.' },
@@ -92,8 +92,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
92
92
  research: {
93
93
  label: 'Investigate and report, without changing the system',
94
94
  match: {
95
- strong: ['explain', 'jelaskan', 'analyse', 'analyze', 'analisa', 'research', 'riset', 'compare', 'bandingkan', 'what is', 'apa itu', 'how does', 'bagaimana', 'review', 'audit'],
96
- weak: ['understand', 'pahami', 'find out', 'cari tahu', 'summarize', 'ringkas']
95
+ strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit'],
96
+ weak: ['understand', 'find out', 'summarize']
97
97
  },
98
98
  phases: [
99
99
  { name: 'Gather', tools: ['code_search_ripgrep', 'fs_read', 'web_search', 'web_fetch'], note: 'Search broadly with several phrasings in parallel before concluding.' },
@@ -103,8 +103,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
103
103
  maintain: {
104
104
  label: 'Operate on files, processes or the machine itself',
105
105
  match: {
106
- strong: ['organize', 'rapikan', 'clean up', 'bersihkan', 'rename', 'ganti nama', 'move', 'pindahkan', 'backup', 'cadangkan', 'delete', 'hapus', 'install', 'deploy', 'commit', 'merge'],
107
- weak: ['folder', 'directory', 'file', 'berkas', 'desktop', 'downloads']
106
+ strong: ['organize', 'clean up', 'rename', 'move', 'backup', 'delete', 'install', 'deploy', 'commit', 'merge'],
107
+ weak: ['folder', 'directory', 'file', 'desktop', 'downloads']
108
108
  },
109
109
  phases: [
110
110
  { name: 'Survey', tools: ['fs_list', 'fs_find'], note: 'List and count what you are about to touch, and report it, before acting.' },
@@ -0,0 +1,124 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { failureClass } from './planCache.js';
3
+ import { isVerificationCommand } from './observer/evidence.js';
4
+ export const TIME_MACHINE_MAX_ATTEMPTS = 6;
5
+ export const TIME_MACHINE_REPLAN_AT = 3;
6
+ export function recoveryUserMessage(decision, tool) {
7
+ if (decision.kind === 'human') {
8
+ return `${tool} needs approval or authentication. Review the last tool error, then provide the needed access or choose another route. No success is claimed.`;
9
+ }
10
+ return `${tool} still failed after ${decision.attempt} attempts (${decision.failureClass}). The task stopped without verified success.`;
11
+ }
12
+ function record(value) {
13
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
14
+ ? value : {};
15
+ }
16
+ function operationFamily(args) {
17
+ const command = typeof args.command === 'string' ? args.command
18
+ : typeof args.cmd === 'string' ? args.cmd : '';
19
+ if (!command) {
20
+ if (typeof args.url === 'string') {
21
+ try {
22
+ return new URL(args.url).hostname.toLowerCase();
23
+ }
24
+ catch {
25
+ return '';
26
+ }
27
+ }
28
+ return '';
29
+ }
30
+ const words = command.trim().split(/\s+/).slice(0, 3);
31
+ // Keep common verification commands distinct without retaining paths,
32
+ // source text, environment variables, or credentials in the journal.
33
+ if (/^(npm|pnpm|yarn|bun)$/.test(words[0] || '')) {
34
+ return words.slice(0, words[1] === 'run' ? 3 : 2).join(' ').toLowerCase();
35
+ }
36
+ return (words[0] || '').replace(/^.*[\\/]/, '').toLowerCase().slice(0, 32);
37
+ }
38
+ function issueKey(tool, args, classification) {
39
+ const family = operationFamily(args);
40
+ return createHash('sha256').update(`${tool}\0${family}\0${classification}`).digest('hex');
41
+ }
42
+ function lastGoodTool(outcomes) {
43
+ for (let index = outcomes.length - 1; index >= 0; index--) {
44
+ const outcome = outcomes[index];
45
+ if (outcome?.success)
46
+ return outcome.tool;
47
+ }
48
+ return null;
49
+ }
50
+ function nextDiagnostic(classification) {
51
+ switch (classification) {
52
+ case 'not_found': return 'Check the actual path or command availability.';
53
+ case 'syntax': return 'Inspect the parser location and the changed source.';
54
+ case 'invalid_args': return 'Compare arguments with the tool schema.';
55
+ case 'timeout': return 'Check whether the operation is still running before retrying.';
56
+ case 'network': return 'Check connectivity or service status before another request.';
57
+ case 'rate_limited': return 'Honor the provider retry window; do not send immediate repeats.';
58
+ case 'exit_nonzero': return 'Inspect exit status and stderr; rerun the check after a change.';
59
+ default: return 'Inspect the original tool output and the most recent change.';
60
+ }
61
+ }
62
+ /** Per-task, deterministic recovery budget. Never replays actions or approvals. */
63
+ export class TimeMachine {
64
+ failures = new Map();
65
+ reset() {
66
+ this.failures.clear();
67
+ }
68
+ observe(tool, args, result, outcomes = []) {
69
+ const value = record(result);
70
+ const failed = value.success === false || typeof value.error === 'string';
71
+ const classification = failed ? failureClass(value) || 'failed' : '';
72
+ const key = issueKey(tool, args, classification);
73
+ const good = lastGoodTool(outcomes);
74
+ if (!failed) {
75
+ // A successful check only clears its own failure family. A successful
76
+ // read/write cannot prove that a failing build or test was repaired.
77
+ const possibleKeys = ['failed', 'exit_nonzero', 'syntax', 'invalid_args',
78
+ 'not_found', 'timeout', 'network', 'rate_limited', 'permission'];
79
+ const hadFailure = possibleKeys.some((item) => this.failures.has(issueKey(tool, args, item)));
80
+ if (hadFailure) {
81
+ for (const item of possibleKeys)
82
+ this.failures.delete(issueKey(tool, args, item));
83
+ }
84
+ return {
85
+ kind: hadFailure ? 'resolved' : 'none', attempt: 0,
86
+ maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, failureClass: '',
87
+ lastGoodTool: good,
88
+ guidance: hadFailure
89
+ ? isVerificationCommand(String(args.command || args.cmd || ''))
90
+ ? 'The same verification command now passed. Report that check as evidence; assess the rest of the task separately.'
91
+ : 'This tool call succeeded. Verify the intended task outcome before reporting success.'
92
+ : ''
93
+ };
94
+ }
95
+ const error = typeof value.error === 'string' ? value.error : '';
96
+ const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
97
+ const attempt = (this.failures.get(key) || 0) + 1;
98
+ this.failures.set(key, attempt);
99
+ const checkpoint = good ? ` Last successful tool: ${good}.` : '';
100
+ if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
101
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
102
+ failureClass: classification, lastGoodTool: good,
103
+ guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
104
+ }
105
+ if (needsHuman) {
106
+ return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
107
+ failureClass: classification, lastGoodTool: good,
108
+ guidance: `Permission or authentication is required. Stop retrying and explain the exact user action needed.${checkpoint}` };
109
+ }
110
+ if (attempt >= TIME_MACHINE_MAX_ATTEMPTS) {
111
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
112
+ failureClass: classification, lastGoodTool: good,
113
+ guidance: `The same failure class persisted through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
114
+ }
115
+ if (attempt >= TIME_MACHINE_REPLAN_AT) {
116
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
117
+ failureClass: classification, lastGoodTool: good,
118
+ guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check.${checkpoint}` };
119
+ }
120
+ return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
121
+ failureClass: classification, lastGoodTool: good,
122
+ guidance: `Inspect this failure before retrying. Attempt ${attempt}/${TIME_MACHINE_MAX_ATTEMPTS}.${checkpoint}` };
123
+ }
124
+ }
@@ -0,0 +1,141 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { failureClass } from './planCache.js';
3
+ import { isVerificationCommand, type ToolOutcome } from './observer/evidence.js';
4
+
5
+ export const TIME_MACHINE_MAX_ATTEMPTS = 6;
6
+ export const TIME_MACHINE_REPLAN_AT = 3;
7
+
8
+ export interface RecoveryDecision {
9
+ kind: 'continue' | 'replan' | 'stop' | 'human' | 'resolved' | 'none';
10
+ attempt: number;
11
+ maxAttempts: number;
12
+ failureClass: string;
13
+ lastGoodTool: string | null;
14
+ guidance: string;
15
+ }
16
+
17
+ export function recoveryUserMessage(decision: RecoveryDecision, tool: string): string {
18
+ if (decision.kind === 'human') {
19
+ return `${tool} needs approval or authentication. Review the last tool error, then provide the needed access or choose another route. No success is claimed.`;
20
+ }
21
+ return `${tool} still failed after ${decision.attempt} attempts (${decision.failureClass}). The task stopped without verified success.`;
22
+ }
23
+
24
+ function record(value: unknown): Record<string, unknown> {
25
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
26
+ ? value as Record<string, unknown> : {};
27
+ }
28
+
29
+ function operationFamily(args: Record<string, unknown>): string {
30
+ const command = typeof args.command === 'string' ? args.command
31
+ : typeof args.cmd === 'string' ? args.cmd : '';
32
+ if (!command) {
33
+ if (typeof args.url === 'string') {
34
+ try { return new URL(args.url).hostname.toLowerCase(); } catch { return ''; }
35
+ }
36
+ return '';
37
+ }
38
+ const words = command.trim().split(/\s+/).slice(0, 3);
39
+ // Keep common verification commands distinct without retaining paths,
40
+ // source text, environment variables, or credentials in the journal.
41
+ if (/^(npm|pnpm|yarn|bun)$/.test(words[0] || '')) {
42
+ return words.slice(0, words[1] === 'run' ? 3 : 2).join(' ').toLowerCase();
43
+ }
44
+ return (words[0] || '').replace(/^.*[\\/]/, '').toLowerCase().slice(0, 32);
45
+ }
46
+
47
+ function issueKey(tool: string, args: Record<string, unknown>, classification: string): string {
48
+ const family = operationFamily(args);
49
+ return createHash('sha256').update(`${tool}\0${family}\0${classification}`).digest('hex');
50
+ }
51
+
52
+ function lastGoodTool(outcomes: readonly ToolOutcome[]): string | null {
53
+ for (let index = outcomes.length - 1; index >= 0; index--) {
54
+ const outcome = outcomes[index];
55
+ if (outcome?.success) return outcome.tool;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function nextDiagnostic(classification: string): string {
61
+ switch (classification) {
62
+ case 'not_found': return 'Check the actual path or command availability.';
63
+ case 'syntax': return 'Inspect the parser location and the changed source.';
64
+ case 'invalid_args': return 'Compare arguments with the tool schema.';
65
+ case 'timeout': return 'Check whether the operation is still running before retrying.';
66
+ case 'network': return 'Check connectivity or service status before another request.';
67
+ case 'rate_limited': return 'Honor the provider retry window; do not send immediate repeats.';
68
+ case 'exit_nonzero': return 'Inspect exit status and stderr; rerun the check after a change.';
69
+ default: return 'Inspect the original tool output and the most recent change.';
70
+ }
71
+ }
72
+
73
+ /** Per-task, deterministic recovery budget. Never replays actions or approvals. */
74
+ export class TimeMachine {
75
+ private readonly failures = new Map<string, number>();
76
+
77
+ reset(): void {
78
+ this.failures.clear();
79
+ }
80
+
81
+ observe(tool: string, args: Record<string, unknown>, result: unknown,
82
+ outcomes: readonly ToolOutcome[] = []): RecoveryDecision {
83
+ const value = record(result);
84
+ const failed = value.success === false || typeof value.error === 'string';
85
+ const classification = failed ? failureClass(value) || 'failed' : '';
86
+ const key = issueKey(tool, args, classification);
87
+ const good = lastGoodTool(outcomes);
88
+
89
+ if (!failed) {
90
+ // A successful check only clears its own failure family. A successful
91
+ // read/write cannot prove that a failing build or test was repaired.
92
+ const possibleKeys = ['failed', 'exit_nonzero', 'syntax', 'invalid_args',
93
+ 'not_found', 'timeout', 'network', 'rate_limited', 'permission'];
94
+ const hadFailure = possibleKeys.some((item) => this.failures.has(issueKey(tool, args, item)));
95
+ if (hadFailure) {
96
+ for (const item of possibleKeys) this.failures.delete(issueKey(tool, args, item));
97
+ }
98
+ return {
99
+ kind: hadFailure ? 'resolved' : 'none', attempt: 0,
100
+ maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, failureClass: '',
101
+ lastGoodTool: good,
102
+ guidance: hadFailure
103
+ ? isVerificationCommand(String(args.command || args.cmd || ''))
104
+ ? 'The same verification command now passed. Report that check as evidence; assess the rest of the task separately.'
105
+ : 'This tool call succeeded. Verify the intended task outcome before reporting success.'
106
+ : ''
107
+ };
108
+ }
109
+
110
+ const error = typeof value.error === 'string' ? value.error : '';
111
+ const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
112
+ const attempt = (this.failures.get(key) || 0) + 1;
113
+ this.failures.set(key, attempt);
114
+ const checkpoint = good ? ` Last successful tool: ${good}.` : '';
115
+
116
+ if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
117
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
118
+ failureClass: classification, lastGoodTool: good,
119
+ guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
120
+ }
121
+
122
+ if (needsHuman) {
123
+ return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
124
+ failureClass: classification, lastGoodTool: good,
125
+ guidance: `Permission or authentication is required. Stop retrying and explain the exact user action needed.${checkpoint}` };
126
+ }
127
+ if (attempt >= TIME_MACHINE_MAX_ATTEMPTS) {
128
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
129
+ failureClass: classification, lastGoodTool: good,
130
+ guidance: `The same failure class persisted through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
131
+ }
132
+ if (attempt >= TIME_MACHINE_REPLAN_AT) {
133
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
134
+ failureClass: classification, lastGoodTool: good,
135
+ guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check.${checkpoint}` };
136
+ }
137
+ return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
138
+ failureClass: classification, lastGoodTool: good,
139
+ guidance: `Inspect this failure before retrying. Attempt ${attempt}/${TIME_MACHINE_MAX_ATTEMPTS}.${checkpoint}` };
140
+ }
141
+ }
package/src/toolPacks.js CHANGED
@@ -348,16 +348,10 @@ download on your own initiative.
348
348
  `,
349
349
 
350
350
  game: `# Sovereign Game Development Cascade & Enforcement Engine
351
- When the user asks you to build, create, test, expand, or develop ANY game, you MUST strictly follow this mandatory 7-stage production methodology using specialized game tools. YOU MUST NOT SKIP STAGES.
352
- **CRITICAL MANDATE**: You are building a **FULL PRODUCTION GAME**. It is completely unacceptable to finish a game in under 50-100 steps. A full game requires multiple levels, complex AI states, numerous sound effects, shaders, and rich tilemaps. You MUST iterate heavily and expand the scope to reach production scale.
353
-
354
- 1. **Stage 1 (Engine Verification)**: Run \`check_system_specs\` (\`engine: 'godot'\`). If valid, use \`godot_act\` for project creation/validation.
355
- 2. **Stage 2 (Narrative & Worldbuilding)**: Use \`game_lore_forge\`, \`game_dialogue_tree_gen\`, and \`game_quest_arc_builder\`. Expand this stage massively.
356
- 3. **Stage 3 (Character Rigging & AI)**: Use \`game_animation_rig\`, \`game_ai_behavior_tree\`, and \`game_cinematic_sequencer\`. Create 5+ enemy types.
357
- 4. **Stage 4 (Harvesting, Audio & VFX)**: Use \`game_asset_harvest\`, \`game_audio_synth\`, and \`game_vfx_emitter_gen\`.
358
- 5. **Stage 5 (Shaders, Scenes & Spawners)**: Use \`game_shader_forge\`, \`game_scene_build\`, and \`game_entity_spawner\`. Design at least 3 sprawling levels.
359
- 6. **Stage 6 (Maps, UI & Economy)**: Use \`game_tilemap_gen\`, \`game_ui_hud_builder\`, and \`game_economy_balancer\`.
360
- 7. **Stage 7 (Assembly & Verification)**: If building a browser/WebGL game, invoke \`game_build_html5\`. **CRITICAL**: You MUST NOT inject 200+ lines of monolithic physics/logic inside \`game_build_html5.customScript\` until you have modularly completed Stages 1-6. After Assembly, you MUST execute \`game_web_runtime_inspector\` and \`game_canvas_audit\` to verify runtime integrity (FPS >= 30, no syntax errors, visual canvas rendering) before declaring Task completed.`
351
+ When the user asks you to build, create, test, expand, or develop a game, follow these rules:
352
+
353
+ - **Browser / Three.js / WebGL / Python Games**: If the user explicitly requests a Three.js, WebGL, Canvas, HTML5, or Python game (or mentions libraries like Three.js, 3js, NumPy, Pygame), you do NOT need Godot. Build the game directly in HTML/JS/CSS or Python using \`fs_write\` (or \`file_write\`) and run/verify using \`sysRun\` or \`game_build_html5\`.
354
+ - **Godot / Full Engine Games**: When building a full engine game (Godot), follow the 7-stage production methodology using \`godot_act\`, \`game_lore_forge\`, \`game_asset_harvest\`, \`game_scene_build\`, and verify with \`game_web_runtime_inspector\` and \`game_canvas_audit\`.`
361
355
  };
362
356
 
363
357
  // ---------------------------------------------------------------------------