@causyne/agent 1.20.5 → 1.20.8

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.
package/src/agentLoop.js CHANGED
@@ -34,6 +34,7 @@ import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore
34
34
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
35
35
  import fsSync from 'fs';
36
36
  import os from 'os';
37
+ import path from 'path';
37
38
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
38
39
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
39
40
  import { createProvider } from './providers/factory.js';
@@ -69,6 +70,78 @@ export function isDirectGameTask(text) {
69
70
  return /\b(three\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
70
71
  && !/\b(godot|unity|unreal|full engine)\b/i.test(text);
71
72
  }
73
+ /**
74
+ * Detects when an agent response is an intermediate mid-task progress note or
75
+ * transition announcement (e.g. "Real assets verified. Writing the Tesla-style
76
+ * redesign now." or "Let me look at the newer assets... Pulling their real
77
+ * stills and confirming embeddability.") rather than a finished answer.
78
+ */
79
+ export function isMidTaskProgressText(text) {
80
+ if (!text || typeof text !== 'string')
81
+ return false;
82
+ const trimmed = text.trim();
83
+ if (!trimmed || trimmed.length > 480)
84
+ return false;
85
+ const lower = trimmed.toLowerCase();
86
+ if (lower.includes('?') ||
87
+ lower.includes('let me know') ||
88
+ lower.includes('how can i help') ||
89
+ lower.includes('how may i help') ||
90
+ lower.includes('how can i assist') ||
91
+ lower.includes('what would you like') ||
92
+ lower.includes('what can i help') ||
93
+ lower.includes('feel free to')) {
94
+ return false;
95
+ }
96
+ if (trimmed.includes('```'))
97
+ return false;
98
+ const sentences = trimmed
99
+ .split(/(?:(?<=[.!])\s+|\n+)/)
100
+ .map(s => s.trim())
101
+ .filter(Boolean);
102
+ const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
103
+ const lastLower = lastSentence.toLowerCase();
104
+ if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
105
+ return true;
106
+ }
107
+ const intentPrefixes = [
108
+ 'let me ',
109
+ "i'll ",
110
+ 'i will ',
111
+ 'now i ',
112
+ 'now let me ',
113
+ "now i'll ",
114
+ 'now i will ',
115
+ 'next, i ',
116
+ 'next i ',
117
+ "next, i'll ",
118
+ "next i'll ",
119
+ 'first, i ',
120
+ 'first i ',
121
+ 'let us ',
122
+ "let's ",
123
+ 'i shall ',
124
+ 'we will ',
125
+ "we'll ",
126
+ 'i am going to ',
127
+ "i'm going to ",
128
+ 'going to '
129
+ ];
130
+ if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
131
+ if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
132
+ return true;
133
+ }
134
+ }
135
+ const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
136
+ if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
137
+ return true;
138
+ }
139
+ const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
140
+ if (actionNowSuffix.test(lastSentence)) {
141
+ return true;
142
+ }
143
+ return false;
144
+ }
72
145
  const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
73
146
 
74
147
  # Your Capabilities
@@ -554,6 +627,27 @@ export class AgentLoop {
554
627
  if (this.abortController) {
555
628
  this.abortController.abort();
556
629
  }
630
+ if (this.llm && typeof this.llm.abort === 'function') {
631
+ try {
632
+ this.llm.abort();
633
+ }
634
+ catch {
635
+ // ignore provider abort errors
636
+ }
637
+ }
638
+ else if (this.llm && typeof this.llm.close === 'function') {
639
+ try {
640
+ void this.llm.close();
641
+ }
642
+ catch {
643
+ // ignore provider close errors
644
+ }
645
+ }
646
+ if (this.pendingApprovals && this.pendingApprovals.size > 0) {
647
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
648
+ this.handleApprovalResponse(toolCallId, false);
649
+ }
650
+ }
557
651
  }
558
652
  setAutonomyMode(mode) {
559
653
  const normalized = String(mode || '').trim().toUpperCase();
@@ -794,8 +888,11 @@ export class AgentLoop {
794
888
  if (this.autonomyOverride)
795
889
  this.config.autonomyMode = this.autonomyOverride;
796
890
  if (typeof this.initializeProvider === 'function') {
797
- this.llm = this.initializeProvider();
798
- this._utilityLlm = null; // the route is derived from the model; re-derive it
891
+ const nextProvider = this.initializeProvider();
892
+ if (nextProvider) {
893
+ this.llm = nextProvider;
894
+ this._utilityLlm = null; // the route is derived from the model; re-derive it
895
+ }
799
896
  }
800
897
  if (this.tokenTracker) {
801
898
  this.tokenTracker.config = this.config;
@@ -891,6 +988,10 @@ export class AgentLoop {
891
988
  this.debugLog(`workspace scan failed: ${perceptionError.message}`);
892
989
  this.workspaceContext = null;
893
990
  }
991
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
992
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
993
+ return;
994
+ }
894
995
  // 2. ANALYSE TASK SHAPE & PRE-WARM CAPABILITY PACKS.
895
996
  // A game request gets the full game toolset from step one with no discovery
896
997
  // round trip, while a "rename my files" request never pays the 7,282 tokens
@@ -1107,7 +1208,13 @@ export class AgentLoop {
1107
1208
  this.messages.push({ role: 'user', content: contentArray });
1108
1209
  }
1109
1210
  else {
1110
- this.messages.push({ role: 'user', content: this.userPrompt });
1211
+ const lastMsg = this.messages[this.messages.length - 1];
1212
+ if (lastMsg && lastMsg.role === 'user' && typeof lastMsg.content === 'string' && lastMsg.content.trim() === this.userPrompt.trim()) {
1213
+ lastMsg.content = this.userPrompt;
1214
+ }
1215
+ else {
1216
+ this.messages.push({ role: 'user', content: this.userPrompt });
1217
+ }
1111
1218
  }
1112
1219
  this.userPrompt = null; // Clear so we don't push it again
1113
1220
  this.attachments = null; // Clear attachments
@@ -1440,7 +1547,7 @@ export class AgentLoop {
1440
1547
  const planStepStart = performance.now();
1441
1548
  const response = await this.llm.chat(prunedMessages, {
1442
1549
  taskId: this.taskId,
1443
- conversationId: this.taskId,
1550
+ conversationId: this.memoryManager?.sessionId || this.taskId,
1444
1551
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1445
1552
  workspaceRoot: this.workspaceRoot,
1446
1553
  tools: dynamicTools,
@@ -1450,6 +1557,8 @@ export class AgentLoop {
1450
1557
  coreToolCount: dynamicTools.filter((t) => isCoreTool(t.name)).length,
1451
1558
  signal: this.abortController?.signal,
1452
1559
  onReasoningChunk: (chunk) => {
1560
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1561
+ return;
1453
1562
  if (!thoughtStartedAt)
1454
1563
  thoughtStartedAt = Date.now();
1455
1564
  reasoningAccumulated += chunk;
@@ -1462,6 +1571,8 @@ export class AgentLoop {
1462
1571
  });
1463
1572
  },
1464
1573
  onChunk: (_chunk) => {
1574
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1575
+ return;
1465
1576
  if (!hasStreamedChunk) {
1466
1577
  hasStreamedChunk = true;
1467
1578
  this.emitEvent({ type: 'status', message: 'Responding…' });
@@ -1472,6 +1583,8 @@ export class AgentLoop {
1472
1583
  this.emitEvent(preview);
1473
1584
  },
1474
1585
  onNativeAction: (action) => {
1586
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1587
+ return;
1475
1588
  if (!action || typeof action.name !== 'string')
1476
1589
  return;
1477
1590
  const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
@@ -1486,7 +1599,7 @@ export class AgentLoop {
1486
1599
  this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
1487
1600
  }
1488
1601
  else if (action.status === 'completed') {
1489
- this.emitEvent({ type: 'notice', tone: 'muted', message: `Antigravity ${action.name}${detail}` });
1602
+ this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `Antigravity ${action.name}${detail}` });
1490
1603
  }
1491
1604
  else if (action.status === 'failed') {
1492
1605
  this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
@@ -1494,6 +1607,10 @@ export class AgentLoop {
1494
1607
  }
1495
1608
  }).finally(() => nativeCodeObserver.dispose());
1496
1609
  this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
1610
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
1611
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
1612
+ break;
1613
+ }
1497
1614
  const finalCodePreview = streamingCode.flush();
1498
1615
  if (finalCodePreview)
1499
1616
  this.emitEvent(finalCodePreview);
@@ -1585,6 +1702,26 @@ export class AgentLoop {
1585
1702
  const completedExternalActions = externalActions.filter((a) => a && a.status === 'completed');
1586
1703
  const failedExternalActions = externalActions.filter((a) => a && a.status === 'failed');
1587
1704
  const hasExternalActions = completedExternalActions.length > 0;
1705
+ const isIncompleteTurn = Boolean(response.incompleteTurn);
1706
+ if (hasExternalActions) {
1707
+ this.stepsCompleted += completedExternalActions.length;
1708
+ for (const extAction of completedExternalActions) {
1709
+ const actionName = String(extAction.name || '').toLowerCase();
1710
+ const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
1711
+ if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1712
+ const resolvedPath = path.isAbsolute(detailPath)
1713
+ ? detailPath
1714
+ : path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
1715
+ if (isScannableFile(resolvedPath)) {
1716
+ this.webArtifacts.add(resolvedPath);
1717
+ }
1718
+ }
1719
+ if (['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1720
+ ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))) {
1721
+ this.webVerificationState.screenshotTaken = true;
1722
+ }
1723
+ }
1724
+ }
1588
1725
  // If no tool calls, check if the agent is just thinking/planning or actually done
1589
1726
  if (!response.toolCalls || response.toolCalls.length === 0) {
1590
1727
  const contentText = response.content || '';
@@ -1639,8 +1776,9 @@ export class AgentLoop {
1639
1776
  continue;
1640
1777
  }
1641
1778
  const thinkingKeywords = ['let me ', "i'll ", 'i will ', 'now i ', 'next, i ', 'first, i ', 'checking ', 'trying to ', 'let us ', 'going to ', 'i shall', 'we will', 'i am going to'];
1642
- const isThinking = !isQuestionOrGreeting && thinkingKeywords.some(kw => lower.includes(kw));
1643
- if (!hasExternalActions && isThinking && this.consecutiveThinkingSteps < 3) {
1779
+ const isMidTaskProgress = !isQuestionOrGreeting && isMidTaskProgressText(contentText);
1780
+ const isThinking = !isQuestionOrGreeting && (isMidTaskProgress || thinkingKeywords.some(kw => lower.includes(kw)));
1781
+ if (!hasExternalActions && (isThinking || isIncompleteTurn) && this.consecutiveThinkingSteps < 3) {
1644
1782
  this.consecutiveThinkingSteps++;
1645
1783
  this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
1646
1784
  this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
@@ -1648,11 +1786,32 @@ export class AgentLoop {
1648
1786
  // duplicated the whole turn in history on every nudge.
1649
1787
  this.messages.push({
1650
1788
  role: 'system',
1651
- content: '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1789
+ content: isIncompleteTurn
1790
+ ? '[SYSTEM NOTICE: Your previous turn ended before completion. Continue immediately from where you left off and invoke the next appropriate tool to complete the task.]'
1791
+ : '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1652
1792
  });
1653
1793
  this.memoryManager.saveHistory(this.messages);
1654
1794
  continue;
1655
1795
  }
1796
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && this.consecutiveThinkingSteps < 3) {
1797
+ this.consecutiveThinkingSteps++;
1798
+ if (response.content) {
1799
+ this.emitEvent({ type: 'agent_message', content: response.content });
1800
+ }
1801
+ this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
1802
+ this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
1803
+ this.messages.push({
1804
+ role: 'system',
1805
+ content: isIncompleteTurn
1806
+ ? '[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.]'
1807
+ : '[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.]'
1808
+ });
1809
+ this.memoryManager.saveHistory(this.messages);
1810
+ continue;
1811
+ }
1812
+ if (hasExternalActions) {
1813
+ this.consecutiveThinkingSteps = 0;
1814
+ }
1656
1815
  if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
1657
1816
  if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
1658
1817
  this.consecutiveThinkingSteps++;
@@ -1877,6 +2036,8 @@ export class AgentLoop {
1877
2036
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
1878
2037
  // 3. ACT (Execute tool calls)
1879
2038
  for (const toolCall of response.toolCalls) {
2039
+ if (this.stopRequested || this.abortController?.signal?.aborted)
2040
+ break;
1880
2041
  // Canonicalise once, here. Every downstream comparison — the sandbox's
1881
2042
  // risk classification, the approval gates, the game cascade lists —
1882
2043
  // matches on this string, so if it is not the catalogue name those
@@ -2230,6 +2391,8 @@ export class AgentLoop {
2230
2391
  this.emitEvent({ type: 'approval_request', toolCallId: toolCall.id, tool: functionName, args, risk: validation.risk });
2231
2392
  const approved = await this.waitForApproval(toolCall.id);
2232
2393
  if (!approved) {
2394
+ if (this.stopRequested || this.abortController?.signal?.aborted)
2395
+ break;
2233
2396
  coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2234
2397
  success: false,
2235
2398
  error: 'User denied this action'
@@ -2293,6 +2456,10 @@ export class AgentLoop {
2293
2456
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
2294
2457
  }
2295
2458
  catch (toolError) {
2459
+ if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
2460
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
2461
+ break;
2462
+ }
2296
2463
  duration = 0;
2297
2464
  const errorType = this.classifyError(toolError);
2298
2465
  const failure = { success: false, error: String(toolError?.message || toolError) };
@@ -2658,6 +2825,11 @@ export class AgentLoop {
2658
2825
  }
2659
2826
  }
2660
2827
  catch (e) {
2828
+ if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
2829
+ this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
2830
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
2831
+ break;
2832
+ }
2661
2833
  // A real failure. It reaches the user as an `error` frame further down
2662
2834
  // this same catch; the stack is a diagnostic and stays behind the flag.
2663
2835
  this.debugLog(`agent loop error: ${e && e.stack ? e.stack : e}`);
package/src/agentLoop.ts CHANGED
@@ -66,6 +66,7 @@ import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore
66
66
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
67
67
  import fsSync from 'fs';
68
68
  import os from 'os';
69
+ import path from 'path';
69
70
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
70
71
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
71
72
  import { createProvider } from './providers/factory.js';
@@ -137,6 +138,86 @@ export function isDirectGameTask(text: string): boolean {
137
138
  && !/\b(godot|unity|unreal|full engine)\b/i.test(text);
138
139
  }
139
140
 
141
+ /**
142
+ * Detects when an agent response is an intermediate mid-task progress note or
143
+ * transition announcement (e.g. "Real assets verified. Writing the Tesla-style
144
+ * redesign now." or "Let me look at the newer assets... Pulling their real
145
+ * stills and confirming embeddability.") rather than a finished answer.
146
+ */
147
+ export function isMidTaskProgressText(text: string): boolean {
148
+ if (!text || typeof text !== 'string') return false;
149
+ const trimmed = text.trim();
150
+ if (!trimmed || trimmed.length > 480) return false;
151
+
152
+ const lower = trimmed.toLowerCase();
153
+ if (
154
+ lower.includes('?') ||
155
+ lower.includes('let me know') ||
156
+ lower.includes('how can i help') ||
157
+ lower.includes('how may i help') ||
158
+ lower.includes('how can i assist') ||
159
+ lower.includes('what would you like') ||
160
+ lower.includes('what can i help') ||
161
+ lower.includes('feel free to')
162
+ ) {
163
+ return false;
164
+ }
165
+
166
+ if (trimmed.includes('```')) return false;
167
+
168
+ const sentences = trimmed
169
+ .split(/(?:(?<=[.!])\s+|\n+)/)
170
+ .map(s => s.trim())
171
+ .filter(Boolean);
172
+ const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
173
+ const lastLower = lastSentence.toLowerCase();
174
+
175
+ if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
176
+ return true;
177
+ }
178
+
179
+ const intentPrefixes = [
180
+ 'let me ',
181
+ "i'll ",
182
+ 'i will ',
183
+ 'now i ',
184
+ 'now let me ',
185
+ "now i'll ",
186
+ 'now i will ',
187
+ 'next, i ',
188
+ 'next i ',
189
+ "next, i'll ",
190
+ "next i'll ",
191
+ 'first, i ',
192
+ 'first i ',
193
+ 'let us ',
194
+ "let's ",
195
+ 'i shall ',
196
+ 'we will ',
197
+ "we'll ",
198
+ 'i am going to ',
199
+ "i'm going to ",
200
+ 'going to '
201
+ ];
202
+ if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
203
+ if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
204
+ return true;
205
+ }
206
+ }
207
+
208
+ const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
209
+ if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
210
+ return true;
211
+ }
212
+
213
+ const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
214
+ if (actionNowSuffix.test(lastSentence)) {
215
+ return true;
216
+ }
217
+
218
+ return false;
219
+ }
220
+
140
221
  const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
141
222
 
142
223
  # Your Capabilities
@@ -650,6 +731,24 @@ export class AgentLoop {
650
731
  if (this.abortController) {
651
732
  this.abortController.abort();
652
733
  }
734
+ if (this.llm && typeof (this.llm as any).abort === 'function') {
735
+ try {
736
+ (this.llm as any).abort();
737
+ } catch {
738
+ // ignore provider abort errors
739
+ }
740
+ } else if (this.llm && typeof (this.llm as any).close === 'function') {
741
+ try {
742
+ void (this.llm as any).close();
743
+ } catch {
744
+ // ignore provider close errors
745
+ }
746
+ }
747
+ if (this.pendingApprovals && this.pendingApprovals.size > 0) {
748
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
749
+ this.handleApprovalResponse(toolCallId, false);
750
+ }
751
+ }
653
752
  }
654
753
 
655
754
  setAutonomyMode(mode: string) {
@@ -895,8 +994,11 @@ export class AgentLoop {
895
994
  this.config = loadConfig();
896
995
  if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
897
996
  if (typeof this.initializeProvider === 'function') {
898
- this.llm = this.initializeProvider();
899
- this._utilityLlm = null; // the route is derived from the model; re-derive it
997
+ const nextProvider = this.initializeProvider();
998
+ if (nextProvider) {
999
+ this.llm = nextProvider;
1000
+ this._utilityLlm = null; // the route is derived from the model; re-derive it
1001
+ }
900
1002
  }
901
1003
  if (this.tokenTracker) {
902
1004
  this.tokenTracker.config = this.config;
@@ -994,6 +1096,10 @@ export class AgentLoop {
994
1096
  this.debugLog(`workspace scan failed: ${perceptionError.message}`);
995
1097
  this.workspaceContext = null;
996
1098
  }
1099
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
1100
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
1101
+ return;
1102
+ }
997
1103
 
998
1104
  // 2. ANALYSE TASK SHAPE & PRE-WARM CAPABILITY PACKS.
999
1105
  // A game request gets the full game toolset from step one with no discovery
@@ -1223,7 +1329,12 @@ export class AgentLoop {
1223
1329
  }
1224
1330
  this.messages.push({ role: 'user', content: contentArray });
1225
1331
  } else {
1226
- this.messages.push({ role: 'user', content: this.userPrompt });
1332
+ const lastMsg = this.messages[this.messages.length - 1];
1333
+ if (lastMsg && lastMsg.role === 'user' && typeof lastMsg.content === 'string' && lastMsg.content.trim() === this.userPrompt.trim()) {
1334
+ lastMsg.content = this.userPrompt;
1335
+ } else {
1336
+ this.messages.push({ role: 'user', content: this.userPrompt });
1337
+ }
1227
1338
  }
1228
1339
 
1229
1340
  this.userPrompt = null; // Clear so we don't push it again
@@ -1580,7 +1691,7 @@ export class AgentLoop {
1580
1691
  const planStepStart = performance.now();
1581
1692
  const response = await this.llm.chat(prunedMessages, {
1582
1693
  taskId: this.taskId,
1583
- conversationId: this.taskId,
1694
+ conversationId: this.memoryManager?.sessionId || this.taskId,
1584
1695
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1585
1696
  workspaceRoot: this.workspaceRoot,
1586
1697
  tools: dynamicTools,
@@ -1590,6 +1701,7 @@ export class AgentLoop {
1590
1701
  coreToolCount: dynamicTools.filter((t: any) => isCoreTool(t.name)).length,
1591
1702
  signal: this.abortController?.signal,
1592
1703
  onReasoningChunk: (chunk: string) => {
1704
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1593
1705
  if (!thoughtStartedAt) thoughtStartedAt = Date.now();
1594
1706
  reasoningAccumulated += chunk;
1595
1707
  this.emitEvent({
@@ -1601,6 +1713,7 @@ export class AgentLoop {
1601
1713
  });
1602
1714
  },
1603
1715
  onChunk: (_chunk: string) => {
1716
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1604
1717
  if (!hasStreamedChunk) {
1605
1718
  hasStreamedChunk = true;
1606
1719
  this.emitEvent({ type: 'status', message: 'Responding…' });
@@ -1610,6 +1723,7 @@ export class AgentLoop {
1610
1723
  if (preview) this.emitEvent(preview);
1611
1724
  },
1612
1725
  onNativeAction: (action: any) => {
1726
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1613
1727
  if (!action || typeof action.name !== 'string') return;
1614
1728
  const nativeCode = codeProgressFromAction(
1615
1729
  action.name,
@@ -1628,7 +1742,7 @@ export class AgentLoop {
1628
1742
  this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
1629
1743
  this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
1630
1744
  } else if (action.status === 'completed') {
1631
- this.emitEvent({ type: 'notice', tone: 'muted', message: `Antigravity ${action.name}${detail}` });
1745
+ this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `Antigravity ${action.name}${detail}` });
1632
1746
  } else if (action.status === 'failed') {
1633
1747
  this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
1634
1748
  }
@@ -1636,6 +1750,11 @@ export class AgentLoop {
1636
1750
  }).finally(() => nativeCodeObserver.dispose());
1637
1751
  this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
1638
1752
 
1753
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
1754
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
1755
+ break;
1756
+ }
1757
+
1639
1758
  const finalCodePreview = streamingCode.flush();
1640
1759
  if (finalCodePreview) this.emitEvent(finalCodePreview);
1641
1760
 
@@ -1742,6 +1861,29 @@ export class AgentLoop {
1742
1861
  const completedExternalActions = externalActions.filter((a: any) => a && a.status === 'completed');
1743
1862
  const failedExternalActions = externalActions.filter((a: any) => a && a.status === 'failed');
1744
1863
  const hasExternalActions = completedExternalActions.length > 0;
1864
+ const isIncompleteTurn = Boolean((response as any).incompleteTurn);
1865
+
1866
+ if (hasExternalActions) {
1867
+ this.stepsCompleted += completedExternalActions.length;
1868
+ for (const extAction of completedExternalActions) {
1869
+ const actionName = String(extAction.name || '').toLowerCase();
1870
+ const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
1871
+ if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1872
+ const resolvedPath = path.isAbsolute(detailPath)
1873
+ ? detailPath
1874
+ : path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
1875
+ if (isScannableFile(resolvedPath)) {
1876
+ this.webArtifacts.add(resolvedPath);
1877
+ }
1878
+ }
1879
+ if (
1880
+ ['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1881
+ ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))
1882
+ ) {
1883
+ this.webVerificationState.screenshotTaken = true;
1884
+ }
1885
+ }
1886
+ }
1745
1887
 
1746
1888
  // If no tool calls, check if the agent is just thinking/planning or actually done
1747
1889
  if (!response.toolCalls || response.toolCalls.length === 0) {
@@ -1801,9 +1943,10 @@ export class AgentLoop {
1801
1943
  }
1802
1944
 
1803
1945
  const thinkingKeywords = ['let me ', "i'll ", 'i will ', 'now i ', 'next, i ', 'first, i ', 'checking ', 'trying to ', 'let us ', 'going to ', 'i shall', 'we will', 'i am going to'];
1804
- const isThinking = !isQuestionOrGreeting && thinkingKeywords.some(kw => lower.includes(kw));
1946
+ const isMidTaskProgress = !isQuestionOrGreeting && isMidTaskProgressText(contentText);
1947
+ const isThinking = !isQuestionOrGreeting && (isMidTaskProgress || thinkingKeywords.some(kw => lower.includes(kw)));
1805
1948
 
1806
- if (!hasExternalActions && isThinking && this.consecutiveThinkingSteps < 3) {
1949
+ if (!hasExternalActions && (isThinking || isIncompleteTurn) && this.consecutiveThinkingSteps < 3) {
1807
1950
  this.consecutiveThinkingSteps++;
1808
1951
  this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
1809
1952
  this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
@@ -1811,12 +1954,35 @@ export class AgentLoop {
1811
1954
  // duplicated the whole turn in history on every nudge.
1812
1955
  this.messages.push({
1813
1956
  role: 'system',
1814
- content: '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1957
+ content: isIncompleteTurn
1958
+ ? '[SYSTEM NOTICE: Your previous turn ended before completion. Continue immediately from where you left off and invoke the next appropriate tool to complete the task.]'
1959
+ : '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1815
1960
  });
1816
1961
  this.memoryManager.saveHistory(this.messages);
1817
1962
  continue;
1818
1963
  }
1819
1964
 
1965
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && this.consecutiveThinkingSteps < 3) {
1966
+ this.consecutiveThinkingSteps++;
1967
+ if (response.content) {
1968
+ this.emitEvent({ type: 'agent_message', content: response.content });
1969
+ }
1970
+ this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
1971
+ this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
1972
+ this.messages.push({
1973
+ role: 'system',
1974
+ content: isIncompleteTurn
1975
+ ? '[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.]'
1976
+ : '[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.]'
1977
+ });
1978
+ this.memoryManager.saveHistory(this.messages);
1979
+ continue;
1980
+ }
1981
+
1982
+ if (hasExternalActions) {
1983
+ this.consecutiveThinkingSteps = 0;
1984
+ }
1985
+
1820
1986
  if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
1821
1987
  if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
1822
1988
  this.consecutiveThinkingSteps++;
@@ -2058,6 +2224,7 @@ export class AgentLoop {
2058
2224
 
2059
2225
  // 3. ACT (Execute tool calls)
2060
2226
  for (const toolCall of response.toolCalls) {
2227
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
2061
2228
  // Canonicalise once, here. Every downstream comparison — the sandbox's
2062
2229
  // risk classification, the approval gates, the game cascade lists —
2063
2230
  // matches on this string, so if it is not the catalogue name those
@@ -2445,6 +2612,7 @@ export class AgentLoop {
2445
2612
  const approved = await this.waitForApproval(toolCall.id);
2446
2613
 
2447
2614
  if (!approved) {
2615
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
2448
2616
  coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2449
2617
  success: false,
2450
2618
  error: 'User denied this action'
@@ -2513,6 +2681,10 @@ export class AgentLoop {
2513
2681
  duration = Date.now() - startTime;
2514
2682
  this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
2515
2683
  } catch (toolError: any) {
2684
+ if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
2685
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
2686
+ break;
2687
+ }
2516
2688
  duration = 0;
2517
2689
  const errorType = this.classifyError(toolError);
2518
2690
  const failure = { success: false, error: String(toolError?.message || toolError) };
@@ -2900,6 +3072,11 @@ export class AgentLoop {
2900
3072
  }
2901
3073
 
2902
3074
  } catch (e: any) {
3075
+ if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
3076
+ this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
3077
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
3078
+ break;
3079
+ }
2903
3080
  // A real failure. It reaches the user as an `error` frame further down
2904
3081
  // this same catch; the stack is a diagnostic and stays behind the flag.
2905
3082
  this.debugLog(`agent loop error: ${e && e.stack ? e.stack : e}`);