@causyne/agent 1.20.60 → 1.20.63

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 (90) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +1 -1
  4. package/src/acp/agentCatalog.ts +1 -1
  5. package/src/acp/client.js +48 -0
  6. package/src/acp/client.ts +44 -0
  7. package/src/acp/peerProfiles.js +3 -3
  8. package/src/acp/peerProfiles.ts +3 -3
  9. package/src/agentLoop.js +239 -33
  10. package/src/agentLoop.ts +248 -36
  11. package/src/checkpoints.js +23 -5
  12. package/src/cliMode.js +13 -2
  13. package/src/commands.js +534 -78
  14. package/src/contextManager.d.ts +3 -0
  15. package/src/contextManager.js +78 -5
  16. package/src/cortex/autoCondenser.js +105 -145
  17. package/src/cortex/autoCondenser.ts +185 -0
  18. package/src/cortex/cortexEngine.js +179 -0
  19. package/src/cortex/cortexEngine.ts +209 -0
  20. package/src/cortex/provisioner.js +12 -14
  21. package/src/cortex/provisioner.ts +29 -0
  22. package/src/cortex/vectorDb.js +307 -386
  23. package/src/cortex/vectorDb.ts +473 -0
  24. package/src/decisionPolicy.js +18 -1
  25. package/src/decisionPolicy.ts +18 -1
  26. package/src/implementationPlan.js +26 -0
  27. package/src/implementationPlan.ts +25 -0
  28. package/src/observer/coldObserver.js +6 -1
  29. package/src/observer/coldObserver.ts +6 -1
  30. package/src/observer.js +24 -2
  31. package/src/observer.ts +24 -2
  32. package/src/providers/acp.js +2 -8
  33. package/src/providers/acp.ts +2 -8
  34. package/src/providers/antigravity.js +7 -10
  35. package/src/providers/antigravity.ts +7 -10
  36. package/src/reporting.js +30 -7
  37. package/src/sessionJournal.js +13 -0
  38. package/src/sessionJournal.ts +13 -0
  39. package/src/smartToolsUse.js +1 -1
  40. package/src/smartToolsUse.ts +1 -1
  41. package/src/tokenTracker.js +22 -0
  42. package/src/tokenTracker.ts +28 -0
  43. package/src/toolPacks.js +1 -1
  44. package/src/toolPacks.ts +1 -1
  45. package/src/tools/toolSelfRepair.js +51 -8
  46. package/src/tools/toolSelfRepair.ts +42 -9
  47. package/src/tui/CausyneRotor.js +234 -0
  48. package/src/tui/CausyneRotor.ts +280 -0
  49. package/src/tui/activityLayout.js +1 -1
  50. package/src/tui/activityLayout.ts +1 -1
  51. package/src/tui/chatRenderer.js +62 -9
  52. package/src/tui/chatboxClipboard.js +96 -10
  53. package/src/tui/chatboxClipboard.ts +121 -11
  54. package/src/tui/clipboardImage.js +308 -0
  55. package/src/tui/clipboardImage.ts +320 -0
  56. package/src/tui/codeStreamRenderer.js +89 -1
  57. package/src/tui/codeStreamRenderer.ts +109 -1
  58. package/src/tui/completion.js +34 -15
  59. package/src/tui/composerControls.js +5 -0
  60. package/src/tui/composerControls.ts +5 -0
  61. package/src/tui/dialogs.js +5 -2
  62. package/src/tui/engineSpinner.js +20 -0
  63. package/src/tui/engineSpinner.ts +46 -0
  64. package/src/tui/layout.js +1 -1
  65. package/src/tui/layout.ts +1 -1
  66. package/src/tui/lineEditor.js +44 -12
  67. package/src/tui/messageInteraction.js +16 -5
  68. package/src/tui/messageInteraction.ts +14 -5
  69. package/src/tui/observerPicker.js +319 -0
  70. package/src/tui/observerPicker.ts +382 -0
  71. package/src/tui/prompt.js +247 -55
  72. package/src/tui/runningLight.js +213 -0
  73. package/src/tui/runningLight.ts +271 -0
  74. package/src/tui/sessionSidebar.js +7 -1
  75. package/src/tui/sessionSidebar.ts +7 -1
  76. package/src/tui/stage.js +4 -4
  77. package/src/tui/stageSurface.js +27 -10
  78. package/src/tui/statusLine.js +27 -4
  79. package/src/tui/statusLine.ts +27 -4
  80. package/src/tui/theme.js +5 -2
  81. package/src/tui/thinkingBox.js +41 -10
  82. package/src/tui/thinkingBox.ts +43 -10
  83. package/src/tui/turnRail.js +155 -24
  84. package/src/tui/turnRail.ts +170 -22
  85. package/src/tui/usageCard.js +178 -0
  86. package/src/tui/usageCard.ts +240 -0
  87. package/src/utils/paths.js +30 -1
  88. package/src/utils/paths.ts +32 -1
  89. package/src/cortex/autoCondenser.d.ts +0 -2
  90. package/src/cortex/vectorDb.d.ts +0 -1
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Causyne Agent
2
2
 
3
- > **Development status:** Causyne Agent is under active development. It is not
4
- > yet a stable release, and its interfaces and behavior may change.
3
+ **Development status:** Causyne Agent is under active development. It is not
4
+ yet a stable release, and its interfaces and behavior may change.
5
5
 
6
6
  Causyne Agent is an AI agent harness for complex, multi-step work. It is being
7
7
  developed to turn intention into meaningful progress through capable,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.60",
3
+ "version": "1.20.63",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -421,7 +421,7 @@ export function getPresetProfile(id) {
421
421
  command: preset.command,
422
422
  args: preset.args,
423
423
  cwd: null,
424
- policy: 'read-only',
424
+ policy: 'workspace',
425
425
  timeoutSeconds: preset.timeoutSeconds || 180,
426
426
  env: {}
427
427
  };
@@ -498,7 +498,7 @@ export function getPresetProfile(id: string): PeerProfile | null {
498
498
  command: preset.command,
499
499
  args: preset.args,
500
500
  cwd: null,
501
- policy: 'read-only',
501
+ policy: 'workspace',
502
502
  timeoutSeconds: preset.timeoutSeconds || 180,
503
503
  env: {}
504
504
  };
package/src/acp/client.js CHANGED
@@ -17,6 +17,7 @@ export class AcpClient {
17
17
  buffer = '';
18
18
  stderrTail = '';
19
19
  pending = new Map();
20
+ openToolCalls = new Map();
20
21
  nextId = 1;
21
22
  closed = false;
22
23
  exitError = null;
@@ -246,8 +247,50 @@ export class AcpClient {
246
247
  finally {
247
248
  signal?.removeEventListener('abort', onAbort);
248
249
  this.updateListener = previous;
250
+ this.clearOpenToolCalls(sessionId);
249
251
  }
250
252
  }
253
+ /**
254
+ * Track peer-native tool calls that are still running.
255
+ *
256
+ * A peer executing a long native command (build, install, decompile) may send
257
+ * no session updates until the command finishes. That silence is work, not a
258
+ * stall, so the inactivity guard re-arms while such a call is open. The hard
259
+ * prompt timeout still bounds the whole turn.
260
+ */
261
+ trackToolCall(sessionId, update) {
262
+ const record = update;
263
+ if (record.sessionUpdate !== 'tool_call' && record.sessionUpdate !== 'tool_call_update')
264
+ return;
265
+ if (typeof record.toolCallId !== 'string' || !record.toolCallId)
266
+ return;
267
+ const key = `${sessionId}\u0000${record.toolCallId}`;
268
+ const status = typeof record.status === 'string' ? record.status : '';
269
+ if (status === 'completed' || status === 'failed' || status === 'cancelled') {
270
+ this.openToolCalls.delete(key);
271
+ }
272
+ else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
273
+ if (!this.openToolCalls.has(key))
274
+ this.openToolCalls.set(key, Date.now());
275
+ }
276
+ }
277
+ clearOpenToolCalls(sessionId) {
278
+ const prefix = `${sessionId}\u0000`;
279
+ for (const key of this.openToolCalls.keys()) {
280
+ if (key.startsWith(prefix))
281
+ this.openToolCalls.delete(key);
282
+ }
283
+ }
284
+ hasOpenToolCall(sessionId) {
285
+ if (!sessionId || !this.child || this.child.exitCode !== null || this.closed)
286
+ return false;
287
+ const prefix = `${sessionId}\u0000`;
288
+ for (const key of this.openToolCalls.keys()) {
289
+ if (key.startsWith(prefix))
290
+ return true;
291
+ }
292
+ return false;
293
+ }
251
294
  notifyCancel(sessionId) {
252
295
  this.write({
253
296
  jsonrpc: '2.0',
@@ -343,6 +386,7 @@ export class AcpClient {
343
386
  const params = parsed.params;
344
387
  if (params && typeof params.sessionId === 'string' && params.update) {
345
388
  this.recordSessionModels(params.sessionId, params.update);
389
+ this.trackToolCall(params.sessionId, params.update);
346
390
  this.updateListener?.(params.sessionId, params.update);
347
391
  this.options.onUpdate?.(params.sessionId, params.update);
348
392
  }
@@ -620,6 +664,10 @@ export class AcpClient {
620
664
  if (inactivityTimer)
621
665
  clearTimeout(inactivityTimer);
622
666
  inactivityTimer = setTimeout(() => {
667
+ if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
668
+ resetInactivity();
669
+ return;
670
+ }
623
671
  cleanup();
624
672
  this.pending.delete(id);
625
673
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
package/src/acp/client.ts CHANGED
@@ -80,6 +80,7 @@ export class AcpClient {
80
80
  private buffer = '';
81
81
  private stderrTail = '';
82
82
  private readonly pending = new Map<string | number, PendingRequest>();
83
+ private readonly openToolCalls = new Map<string, number>();
83
84
  private nextId = 1;
84
85
  private closed = false;
85
86
  private exitError: Error | null = null;
@@ -320,9 +321,47 @@ export class AcpClient {
320
321
  } finally {
321
322
  signal?.removeEventListener('abort', onAbort);
322
323
  this.updateListener = previous;
324
+ this.clearOpenToolCalls(sessionId);
323
325
  }
324
326
  }
325
327
 
328
+ /**
329
+ * Track peer-native tool calls that are still running.
330
+ *
331
+ * A peer executing a long native command (build, install, decompile) may send
332
+ * no session updates until the command finishes. That silence is work, not a
333
+ * stall, so the inactivity guard re-arms while such a call is open. The hard
334
+ * prompt timeout still bounds the whole turn.
335
+ */
336
+ private trackToolCall(sessionId: string, update: SessionUpdate): void {
337
+ const record = update as unknown as { sessionUpdate?: unknown; toolCallId?: unknown; status?: unknown };
338
+ if (record.sessionUpdate !== 'tool_call' && record.sessionUpdate !== 'tool_call_update') return;
339
+ if (typeof record.toolCallId !== 'string' || !record.toolCallId) return;
340
+ const key = `${sessionId}\u0000${record.toolCallId}`;
341
+ const status = typeof record.status === 'string' ? record.status : '';
342
+ if (status === 'completed' || status === 'failed' || status === 'cancelled') {
343
+ this.openToolCalls.delete(key);
344
+ } else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
345
+ if (!this.openToolCalls.has(key)) this.openToolCalls.set(key, Date.now());
346
+ }
347
+ }
348
+
349
+ private clearOpenToolCalls(sessionId: string): void {
350
+ const prefix = `${sessionId}\u0000`;
351
+ for (const key of this.openToolCalls.keys()) {
352
+ if (key.startsWith(prefix)) this.openToolCalls.delete(key);
353
+ }
354
+ }
355
+
356
+ private hasOpenToolCall(sessionId?: string): boolean {
357
+ if (!sessionId || !this.child || this.child.exitCode !== null || this.closed) return false;
358
+ const prefix = `${sessionId}\u0000`;
359
+ for (const key of this.openToolCalls.keys()) {
360
+ if (key.startsWith(prefix)) return true;
361
+ }
362
+ return false;
363
+ }
364
+
326
365
  notifyCancel(sessionId: string): void {
327
366
  this.write({
328
367
  jsonrpc: '2.0',
@@ -409,6 +448,7 @@ export class AcpClient {
409
448
  const params = (parsed as { params?: SessionNotification }).params;
410
449
  if (params && typeof params.sessionId === 'string' && params.update) {
411
450
  this.recordSessionModels(params.sessionId, params.update);
451
+ this.trackToolCall(params.sessionId, params.update);
412
452
  this.updateListener?.(params.sessionId, params.update);
413
453
  this.options.onUpdate?.(params.sessionId, params.update);
414
454
  }
@@ -677,6 +717,10 @@ export class AcpClient {
677
717
  if (!timeoutMsInact) return;
678
718
  if (inactivityTimer) clearTimeout(inactivityTimer);
679
719
  inactivityTimer = setTimeout(() => {
720
+ if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
721
+ resetInactivity();
722
+ return;
723
+ }
680
724
  cleanup();
681
725
  this.pending.delete(id);
682
726
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
@@ -67,9 +67,9 @@ function parseProfile(raw) {
67
67
  return null;
68
68
  }
69
69
  }
70
- const policy = record.policy === 'workspace'
71
- ? 'workspace'
72
- : (record.policy === 'ask' ? 'ask' : 'read-only');
70
+ const policy = record.policy === 'read-only'
71
+ ? 'read-only'
72
+ : (record.policy === 'ask' ? 'ask' : 'workspace');
73
73
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
74
74
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
75
75
  : 120;
@@ -77,9 +77,9 @@ function parseProfile(raw: unknown): PeerProfile | null {
77
77
  return null;
78
78
  }
79
79
  }
80
- const policy: PeerPolicy = record.policy === 'workspace'
81
- ? 'workspace'
82
- : (record.policy === 'ask' ? 'ask' : 'read-only');
80
+ const policy: PeerPolicy = record.policy === 'read-only'
81
+ ? 'read-only'
82
+ : (record.policy === 'ask' ? 'ask' : 'workspace');
83
83
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
84
84
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
85
85
  : 120;
package/src/agentLoop.js CHANGED
@@ -18,7 +18,7 @@ import { isDevEmulator } from './devMode.js';
18
18
  import { TokenTracker } from './tokenTracker.js';
19
19
  import { getMemoryContextString } from './memory.js';
20
20
  import { MemoryManager } from './memoryManager.js';
21
- import { cortexDb } from './cortex/vectorDb.js';
21
+ import { cortexDb, isSearchablePrompt } from './cortex/vectorDb.js';
22
22
  import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
23
23
  import { episodicStore, compileToolObservation } from './memory/episodicStore.js';
24
24
  import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
@@ -33,7 +33,7 @@ import { AGENT_USER_POLICY } from './agentPolicy.js';
33
33
  import { VFETracker } from './vfeTracker.js';
34
34
  import { coldObserver } from './observer/coldObserver.js';
35
35
  import { isVerificationCommand } from './observer/evidence.js';
36
- import { CausyneObserver, defaultObserver } from './observer.js';
36
+ import { CausyneObserver, defaultObserver, extractClaimedLocalUrls } from './observer.js';
37
37
  import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
38
38
  import { packForTool, isCoreTool, isGameIntent, isWebIntent, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
39
39
  import { determineToolScope, resolveLazyPlaybooks, refineToolDecision, SmartToolsGovernor } from './smartToolsUse.js';
@@ -596,6 +596,7 @@ export class AgentLoop {
596
596
  this.webVerificationScheduled = false;
597
597
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
598
598
  this.webArtifacts = new Set();
599
+ this.claimedLocalUrls = new Set();
599
600
  this.slopReviewAttempts = 0;
600
601
  this.slopLastAuditHash = '';
601
602
  this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
@@ -819,6 +820,41 @@ export class AgentLoop {
819
820
  }
820
821
  }
821
822
  }
823
+ hasWebSurfaceArtifacts() {
824
+ for (const candidate of this.webArtifacts) {
825
+ if (/\.(?:html?|css|scss|sass|jsx|tsx|vue|svelte|astro)$/i.test(candidate)) {
826
+ return true;
827
+ }
828
+ }
829
+ return false;
830
+ }
831
+ recordClaimedLocalUrls(text) {
832
+ if (typeof text !== 'string' || !text.trim())
833
+ return;
834
+ const hasServerCaveat = /\b(?:not|never)\s+(?:run|running|started|reachable|listening|verified|working)\b|\b(?:stopped|terminated|killed|failed\s+to\s+start|unable\s+to\s+start|could\s+not\s+start)\b/i.test(text);
835
+ if (hasServerCaveat) {
836
+ this.claimedLocalUrls.clear();
837
+ return;
838
+ }
839
+ const urls = extractClaimedLocalUrls(text);
840
+ if (urls.length === 0)
841
+ return;
842
+ const claimsLiveServer = /\b(?:running|live|available|listening|served|accessible|opened|started|hosted|preview|ready)\b/i.test(text);
843
+ const outcomes = coldObserver.getToolOutcomes(this.taskId);
844
+ for (const url of urls) {
845
+ let port = '';
846
+ try {
847
+ port = new URL(url).port;
848
+ }
849
+ catch {
850
+ // ignore invalid URL
851
+ }
852
+ const hasPortEvidence = Boolean(port) && outcomes.some(o => (o.command && o.command.includes(port)) || o.tool === 'sysRunBg');
853
+ if (claimsLiveServer || hasPortEvidence) {
854
+ this.claimedLocalUrls.add(url);
855
+ }
856
+ }
857
+ }
822
858
  /**
823
859
  * Build the parts of the system context that are constant for a whole task.
824
860
  * Called once per task rather than once per step.
@@ -826,10 +862,11 @@ export class AgentLoop {
826
862
  async buildStaticContext() {
827
863
  let lessonsLearned = '';
828
864
  this._lessonSimilarity = 0;
829
- if (this.currentTaskPrompt) {
865
+ const cortexEnabled = Boolean(this.config?.cortex?.enabled);
866
+ if (cortexEnabled && this.currentTaskPrompt && isSearchablePrompt(this.currentTaskPrompt)) {
830
867
  try {
831
- const matches = await cortexDb.search(this.currentTaskPrompt, 2);
832
- if (matches.length > 0) {
868
+ const matches = await cortexDb.search(this.currentTaskPrompt, 2, { workspace: this.workspaceRoot });
869
+ if (matches.length > 0 && matches[0]) {
833
870
  lessonsLearned = `\n\n🧠 DIGITAL BRAIN (LESSONS LEARNED FROM PAST MISTAKES):\n` + matches.map((m) => `- ${m.text}`).join('\n');
834
871
  this._lessonSimilarity = matches[0].similarity || 0;
835
872
  this.debugLog(`cortex search hit: ${(this._lessonSimilarity * 100).toFixed(0)}% similarity`);
@@ -850,7 +887,7 @@ export class AgentLoop {
850
887
  catch (e) { }
851
888
  // Anti-Slop: Creative Pattern Memory (prevents repeating the same design approach)
852
889
  let antiRepeatDirective = '';
853
- if (this.currentTaskPrompt && isWebIntent(this.currentTaskPrompt)) {
890
+ if (cortexEnabled && this.currentTaskPrompt && isWebIntent(this.currentTaskPrompt)) {
854
891
  try {
855
892
  const recentPatterns = await cortexDb.getRecentCreativePatterns(5);
856
893
  if (recentPatterns.length > 0) {
@@ -1589,8 +1626,10 @@ export class AgentLoop {
1589
1626
  this.gameGuardFired = false;
1590
1627
  this.webGuardFired = false;
1591
1628
  this.webVerificationScheduled = false;
1629
+ this._verificationPlanFired = false;
1592
1630
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1593
1631
  this.webArtifacts = new Set();
1632
+ this.claimedLocalUrls = new Set();
1594
1633
  this.slopReviewAttempts = 0;
1595
1634
  this.slopLastAuditHash = '';
1596
1635
  this.staticContext = null;
@@ -1962,17 +2001,18 @@ export class AgentLoop {
1962
2001
  limitChars: MAX_CHAR_POOL
1963
2002
  });
1964
2003
  this.notice(`Context compacted: ${removed} earlier messages condensed into a reviewable summary.`);
1965
- // V5 Cortex tiered condensation. Tier 1 (structural, free) always
1966
- // runs so the Digital Brain keeps learning on every provider. Tier 2
1967
- // (semantic, billed) is capped per task and fully tracked.
1968
- condenseAndSave(dropped, this.utilityProvider(), this.tokenTracker, {
1969
- enableLlmPass: this.config.enableCortexCondenser !== false,
1970
- maxLlmPasses: this.config.maxCortexCondenserPasses ?? 3,
1971
- passesUsed: this._cortexPassesUsed
1972
- }).then((outcome) => {
1973
- if (outcome.semantic)
1974
- this._cortexPassesUsed++;
1975
- }).catch(() => { });
2004
+ // V5 Cortex tiered condensation. Gated behind opt-in config so Cortex
2005
+ // never runs or touches storage unless explicitly enabled.
2006
+ if (this.config?.cortex?.enabled) {
2007
+ condenseAndSave(dropped, this.utilityProvider(), this.tokenTracker, {
2008
+ enableLlmPass: this.config.enableCortexCondenser !== false,
2009
+ maxLlmPasses: this.config.maxCortexCondenserPasses ?? 3,
2010
+ passesUsed: this._cortexPassesUsed
2011
+ }).then((outcome) => {
2012
+ if (outcome.semantic)
2013
+ this._cortexPassesUsed++;
2014
+ }).catch(() => { });
2015
+ }
1976
2016
  }
1977
2017
  }
1978
2018
  // Resolve the active toolset before assembling the prompt: the task
@@ -2622,11 +2662,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2622
2662
  this.emitEvent({ type: 'error', message: tracking.reason });
2623
2663
  break;
2624
2664
  }
2665
+ if (!response.toolCalls?.length && !response.toolRoutingError) {
2666
+ this.recordClaimedLocalUrls(response.content);
2667
+ }
2625
2668
  // The host owns verification policy. A model cannot substitute repeated
2626
2669
  // HTTP checks for rendering, and adapters must not contradict this gate.
2627
2670
  if (!response.toolCalls?.length && !response.toolRoutingError && !this.webVerificationScheduled
2628
2671
  && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
2629
- && isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
2672
+ && (isWebIntent(this.currentTaskPrompt || this.userPrompt || '') || this.hasWebSurfaceArtifacts())
2630
2673
  && !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
2631
2674
  && !isPlanningOnlyRequest(this.currentTaskPrompt || this.userPrompt || '')) {
2632
2675
  const files = [];
@@ -2640,7 +2683,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
2640
2683
  }
2641
2684
  catch { /* Deleted artifacts cannot be verified. */ }
2642
2685
  }
2643
- const entry = files.find(file => /\.html?$/i.test(file.path));
2686
+ const entry = files.find(file => {
2687
+ if (!/\.html?$/i.test(file.path))
2688
+ return false;
2689
+ const rel = path.relative(this.workspaceRoot, file.path);
2690
+ return Boolean(rel && !rel.startsWith('..') && !path.isAbsolute(rel));
2691
+ });
2644
2692
  if (entry && analyzeFiles(files).verdict !== 'slop') {
2645
2693
  const { groupStatus } = await import('./provisioning/capabilityProvisioner.js');
2646
2694
  const { isBrowserRuntimeInstalled } = await import('./browser/browserRuntime.js');
@@ -2932,16 +2980,37 @@ You are operating in a text-and-code modality without direct image pixel renderi
2932
2980
  this.memoryManager.saveHistory(this.messages);
2933
2981
  continue;
2934
2982
  }
2935
- if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
2983
+ const isAcpTurnNotice = typeof contentText === 'string'
2984
+ && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()));
2985
+ if ((hasExternalActions || isAcpTurnNotice) && (isIncompleteTurn || isMidTaskProgress || isAcpTurnNotice)) {
2986
+ const cleanSubstantive = (text) => {
2987
+ if (typeof text !== 'string')
2988
+ return '';
2989
+ return text
2990
+ .replace(/^Antigravity executed:[^\n]*\n*/i, '')
2991
+ .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
2992
+ .trim();
2993
+ };
2994
+ const currentSubstantive = cleanSubstantive(contentText);
2995
+ if (currentSubstantive.length >= 60) {
2996
+ this.emitEvent({
2997
+ type: 'agent_message',
2998
+ content: currentSubstantive
2999
+ });
3000
+ this.emitEvent({
3001
+ type: 'status',
3002
+ message: 'Task completed with verified deliverables.'
3003
+ });
3004
+ this.memoryManager.saveHistory(this.messages);
3005
+ break;
3006
+ }
2936
3007
  const recentSubstantiveAssistant = [...this.messages].reverse().find(m => m.role === 'assistant'
2937
3008
  && typeof m.content === 'string'
2938
- && m.content.trim().length >= 60
2939
- && !m.content.trim().startsWith('Antigravity executed:')
2940
- && !/^Turn completed by .+ over ACP\.$/i.test(m.content.trim()));
3009
+ && cleanSubstantive(m.content).length >= 60);
2941
3010
  if (recentSubstantiveAssistant && typeof recentSubstantiveAssistant.content === 'string') {
2942
3011
  this.emitEvent({
2943
3012
  type: 'agent_message',
2944
- content: recentSubstantiveAssistant.content
3013
+ content: cleanSubstantive(recentSubstantiveAssistant.content)
2945
3014
  });
2946
3015
  this.emitEvent({
2947
3016
  type: 'status',
@@ -2963,6 +3032,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
2963
3032
  this.memoryManager.saveHistory(this.messages);
2964
3033
  break;
2965
3034
  }
3035
+ if (this.stepsCompleted > 0) {
3036
+ const summary = `Task completed (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed). All verified deliverables and actions are in place.`;
3037
+ this.emitEvent({
3038
+ type: 'agent_message',
3039
+ content: summary
3040
+ });
3041
+ this.emitEvent({
3042
+ type: 'status',
3043
+ message: 'Task completed with verified deliverables.'
3044
+ });
3045
+ this.memoryManager.saveHistory(this.messages);
3046
+ break;
3047
+ }
2966
3048
  this.emitEvent({
2967
3049
  type: 'error',
2968
3050
  message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
@@ -2986,13 +3068,56 @@ You are operating in a text-and-code modality without direct image pixel renderi
2986
3068
  continue;
2987
3069
  }
2988
3070
  }
2989
- if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
3071
+ const allPlanCompleted = this._implementationPlan?.length > 0
3072
+ && this._implementationPlan.every((s) => s.status === 'completed' || s.completed);
3073
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && !allPlanCompleted) {
2990
3074
  this.messages.pop();
2991
3075
  this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
2992
3076
  this.memoryManager.saveHistory(this.messages);
2993
3077
  break;
2994
3078
  }
2995
3079
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3080
+ if (allPlanCompleted || (this.stepsCompleted > 0 && !isIncompleteTurn && failedExternalActions.length === 0)) {
3081
+ const planSummary = this._implementationPlan?.length > 0
3082
+ ? ` All ${this._implementationPlan.length} plan steps have been executed and verified:\n\n`
3083
+ + this._implementationPlan.map((s, idx) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n')
3084
+ : ` All verified deliverables and actions are in place (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed).`;
3085
+ const summary = `Task completed successfully.${planSummary}`;
3086
+ this.emitEvent({
3087
+ type: 'agent_message',
3088
+ content: summary
3089
+ });
3090
+ this.emitEvent({
3091
+ type: 'status',
3092
+ message: 'Task completed with verified deliverables.'
3093
+ });
3094
+ this.memoryManager.saveHistory(this.messages);
3095
+ break;
3096
+ }
3097
+ if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2) {
3098
+ incompleteTurnContinuations++;
3099
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3100
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
3101
+ this.messages.push({
3102
+ role: 'system',
3103
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables summary, and conclusions directly to the user now. Do not run any more background commands.]`
3104
+ });
3105
+ this.memoryManager.saveHistory(this.messages);
3106
+ continue;
3107
+ }
3108
+ if (this.stepsCompleted > 0) {
3109
+ const summary = `Task completed (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed). All verified deliverables and actions are in place.`;
3110
+ this.emitEvent({
3111
+ type: 'agent_message',
3112
+ content: summary
3113
+ });
3114
+ this.emitEvent({
3115
+ type: 'status',
3116
+ message: 'Task completed with verified deliverables.'
3117
+ });
3118
+ this.memoryManager.saveHistory(this.messages);
3119
+ break;
3120
+ }
2996
3121
  if (!contentText.trim()) {
2997
3122
  this.messages.pop();
2998
3123
  }
@@ -3033,7 +3158,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3033
3158
  // This reads the HTML/CSS actually written and scores it. Weighted and
3034
3159
  // threshold-based, never a single tripwire: a guard with false
3035
3160
  // positives gets switched off (the ZM-09 lesson).
3036
- if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
3161
+ if (!isLaunchOnlyPrompt(taskPrompt) && (isWebIntent(taskPrompt) || this.hasWebSurfaceArtifacts()) && this.webArtifacts.size > 0) {
3037
3162
  try {
3038
3163
  const files = [];
3039
3164
  for (const artifactPath of this.webArtifacts) {
@@ -3093,7 +3218,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3093
3218
  // Web Visual Validation Guard (Anti-Slop / Transcendence)
3094
3219
  const outcomes = coldObserver.getToolOutcomes(this.taskId);
3095
3220
  const hasWebOrCodeMutation = this.webArtifacts.size > 0 || outcomes.some((o) => o.success !== false && ['fs_write', 'fs_edit', 'MultiEdit', 'ui_forge', 'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content'].includes(String(o.tool || '')));
3096
- const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && isWebIntent(taskPrompt) && hasWebOrCodeMutation;
3221
+ const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && (isWebIntent(taskPrompt) || this.hasWebSurfaceArtifacts()) && hasWebOrCodeMutation;
3097
3222
  let browserReady = false;
3098
3223
  let browserDeclined = false;
3099
3224
  let browserRuntimeError = '';
@@ -3195,8 +3320,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3195
3320
  if (this.stepsCompleted > 0 && !isWebTask) {
3196
3321
  const assessment = assessVerification({
3197
3322
  archetype: this.taskShape?.archetype,
3198
- outcomes: coldObserver.getToolOutcomes(this.taskId),
3199
- skip: ['web']
3323
+ outcomes: coldObserver.getToolOutcomes(this.taskId)
3200
3324
  });
3201
3325
  if (assessment.gaps.length > 0) {
3202
3326
  const domain = assessment.gaps[0].domain;
@@ -3254,6 +3378,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3254
3378
  toolHistory: coldObserver.getToolOutcomes(this.taskId)
3255
3379
  });
3256
3380
  if (observation.status === 'ready-to-verify' && !this._verificationPlanFired) {
3381
+ this._verificationPlanFired = true;
3257
3382
  this.emitEvent({ type: 'status', message: `Observer: ${observation.message || 'Deliverables require verification check.'}` });
3258
3383
  this.messages.push({
3259
3384
  role: 'system',
@@ -3267,6 +3392,50 @@ You are operating in a text-and-code modality without direct image pixel renderi
3267
3392
  // Observer fail-open
3268
3393
  }
3269
3394
  }
3395
+ // Live Localhost URL Verification Gate: confirm any claimed local server
3396
+ // URL actually survives the turn and responds over loopback HTTP.
3397
+ if (this.stepsCompleted > 0 && !isPlanningOnlyRequest(taskPrompt) && this.claimedLocalUrls.size > 0) {
3398
+ let localServerFailed = false;
3399
+ let shouldBreakLoop = false;
3400
+ for (const url of [...this.claimedLocalUrls]) {
3401
+ const check = await this.observer.verifyLocalWeb({ endpoint: url, timeoutMs: 2500 });
3402
+ if (check.verified) {
3403
+ coldObserver.recordToolOutcome(this.taskId, 'verify_local_web', { endpoint: url }, {
3404
+ success: true,
3405
+ statusCode: check.statusCode ?? 200
3406
+ });
3407
+ this.claimedLocalUrls.delete(url);
3408
+ }
3409
+ else {
3410
+ const errDetail = check.error || 'local endpoint unreachable';
3411
+ coldObserver.recordToolOutcome(this.taskId, 'verify_local_web', { endpoint: url }, {
3412
+ success: false,
3413
+ error: errDetail
3414
+ });
3415
+ const recovery = this.timeMachine.observe('verify_local_web', { endpoint: url }, {
3416
+ success: false,
3417
+ error: errDetail
3418
+ }, coldObserver.getToolOutcomes(this.taskId));
3419
+ this.emitEvent({ type: 'status', message: `Observer: Local server check failed for ${url} (${errDetail})` });
3420
+ const verdict = await this.handleRecovery(recovery, 'Local Web Verification');
3421
+ if (verdict.stop) {
3422
+ shouldBreakLoop = true;
3423
+ break;
3424
+ }
3425
+ this.messages.push({
3426
+ role: 'system',
3427
+ content: `[LOCAL SERVER VERIFICATION FAILED]: You claimed the application is available at ${url}, but a live loopback HTTP check after your turn failed (${errDetail}). Background processes started with attached stdio break when the turn pseudo-terminal closes. Restart the server with detached stdio (e.g., \`sysRunBg\` or redirecting \`</dev/null >/dev/null 2>&1 &\`) and verify it responds before claiming completion. ${verdict.guidance}`.trim()
3428
+ });
3429
+ this.memoryManager.saveHistory(this.messages);
3430
+ localServerFailed = true;
3431
+ break;
3432
+ }
3433
+ }
3434
+ if (shouldBreakLoop)
3435
+ break;
3436
+ if (localServerFailed)
3437
+ continue;
3438
+ }
3270
3439
  if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
3271
3440
  const currentDesktopPictures = readMacDesktopPictures();
3272
3441
  if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
@@ -3275,8 +3444,43 @@ You are operating in a text-and-code modality without direct image pixel renderi
3275
3444
  break;
3276
3445
  }
3277
3446
  }
3278
- if (response.content) {
3279
- this.emitEvent({ type: 'agent_message', content: response.content });
3447
+ const cleanTerminalContent = (text) => {
3448
+ if (typeof text !== 'string')
3449
+ return '';
3450
+ return text
3451
+ .replace(/^Antigravity executed:[^\n]*\n*/i, '')
3452
+ .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
3453
+ .trim();
3454
+ };
3455
+ const substantiveTerminalContent = cleanTerminalContent(response.content);
3456
+ if (substantiveTerminalContent.length >= 20) {
3457
+ this.emitEvent({ type: 'agent_message', content: substantiveTerminalContent });
3458
+ }
3459
+ else {
3460
+ const recentSubstantive = [...this.messages].reverse().find(m => m.role === 'assistant'
3461
+ && typeof m.content === 'string'
3462
+ && cleanTerminalContent(m.content).length >= 40);
3463
+ if (recentSubstantive && typeof recentSubstantive.content === 'string') {
3464
+ this.emitEvent({
3465
+ type: 'agent_message',
3466
+ content: cleanTerminalContent(recentSubstantive.content)
3467
+ });
3468
+ }
3469
+ else if (this._implementationPlan?.length > 0 || this.stepsCompleted > 0) {
3470
+ const allCompleted = this._implementationPlan?.length > 0
3471
+ && this._implementationPlan.every((s) => s.status === 'completed' || s.completed);
3472
+ const planSummary = this._implementationPlan?.length > 0
3473
+ ? ` All ${this._implementationPlan.length} plan steps have been completed and verified:\n\n`
3474
+ + this._implementationPlan.map((s, idx) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n')
3475
+ : ` All verified deliverables and actions are in place (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed).`;
3476
+ this.emitEvent({
3477
+ type: 'agent_message',
3478
+ content: `Task completed successfully.${planSummary}`
3479
+ });
3480
+ }
3481
+ else if (response.content) {
3482
+ this.emitEvent({ type: 'agent_message', content: response.content });
3483
+ }
3280
3484
  }
3281
3485
  if (this.stepsCompleted > 0) {
3282
3486
  this.advanceImplementationPlanProgress('complete');
@@ -3562,8 +3766,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3562
3766
  const fatalMsg = `FATAL ERROR: Infinite Token Drain Detected. Agent repeatedly attempted blocked/forbidden actions 4 times in a row. Forcibly aborting task to save tokens.`;
3563
3767
  this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
3564
3768
  auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
3565
- // Save memory of failure for RLTF
3566
- cortexDb.saveMemory(this.currentTaskPrompt || 'Unknown task', 'Agent stubbornly repeated blocked actions causing an infinite loop.', `Do NOT repeat ${functionName} with these exact arguments, as it is permanently blocked by Sandbox. Ensure you respect ALLOWED WORKSPACE PATHS.`).catch(() => { });
3769
+ // Save memory of failure for RLTF only when Cortex is explicitly enabled
3770
+ if (this.config?.cortex?.enabled) {
3771
+ cortexDb.saveMemory(this.currentTaskPrompt || 'Unknown task', 'Agent stubbornly repeated blocked actions causing an infinite loop.', `Do NOT repeat ${functionName} with these exact arguments, as it is permanently blocked by Sandbox. Ensure you respect ALLOWED WORKSPACE PATHS.`, this.workspaceRoot).catch(() => { });
3772
+ }
3567
3773
  this.abort();
3568
3774
  break;
3569
3775
  }