mstro-app 0.1.58 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PRIVACY.md +126 -0
- package/README.md +24 -23
- package/bin/commands/login.js +85 -42
- package/bin/commands/logout.js +35 -1
- package/bin/commands/status.js +1 -1
- package/bin/mstro.js +231 -131
- package/dist/server/cli/headless/claude-invoker.d.ts.map +1 -1
- package/dist/server/cli/headless/claude-invoker.js +550 -115
- package/dist/server/cli/headless/claude-invoker.js.map +1 -1
- package/dist/server/cli/headless/index.d.ts +2 -1
- package/dist/server/cli/headless/index.d.ts.map +1 -1
- package/dist/server/cli/headless/index.js +2 -0
- package/dist/server/cli/headless/index.js.map +1 -1
- package/dist/server/cli/headless/prompt-utils.d.ts +5 -8
- package/dist/server/cli/headless/prompt-utils.d.ts.map +1 -1
- package/dist/server/cli/headless/prompt-utils.js +40 -5
- package/dist/server/cli/headless/prompt-utils.js.map +1 -1
- package/dist/server/cli/headless/runner.d.ts +1 -1
- package/dist/server/cli/headless/runner.d.ts.map +1 -1
- package/dist/server/cli/headless/runner.js +52 -7
- package/dist/server/cli/headless/runner.js.map +1 -1
- package/dist/server/cli/headless/stall-assessor.d.ts +79 -1
- package/dist/server/cli/headless/stall-assessor.d.ts.map +1 -1
- package/dist/server/cli/headless/stall-assessor.js +355 -20
- package/dist/server/cli/headless/stall-assessor.js.map +1 -1
- package/dist/server/cli/headless/tool-watchdog.d.ts +70 -0
- package/dist/server/cli/headless/tool-watchdog.d.ts.map +1 -0
- package/dist/server/cli/headless/tool-watchdog.js +302 -0
- package/dist/server/cli/headless/tool-watchdog.js.map +1 -0
- package/dist/server/cli/headless/types.d.ts +98 -1
- package/dist/server/cli/headless/types.d.ts.map +1 -1
- package/dist/server/cli/improvisation-session-manager.d.ts +136 -2
- package/dist/server/cli/improvisation-session-manager.d.ts.map +1 -1
- package/dist/server/cli/improvisation-session-manager.js +929 -132
- package/dist/server/cli/improvisation-session-manager.js.map +1 -1
- package/dist/server/index.js +5 -13
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp/bouncer-integration.d.ts.map +1 -1
- package/dist/server/mcp/bouncer-integration.js +18 -0
- package/dist/server/mcp/bouncer-integration.js.map +1 -1
- package/dist/server/mcp/security-audit.d.ts +2 -2
- package/dist/server/mcp/security-audit.d.ts.map +1 -1
- package/dist/server/mcp/security-audit.js +12 -8
- package/dist/server/mcp/security-audit.js.map +1 -1
- package/dist/server/mcp/security-patterns.d.ts.map +1 -1
- package/dist/server/mcp/security-patterns.js +9 -4
- package/dist/server/mcp/security-patterns.js.map +1 -1
- package/dist/server/routes/improvise.js +6 -6
- package/dist/server/routes/improvise.js.map +1 -1
- package/dist/server/services/analytics.d.ts +2 -0
- package/dist/server/services/analytics.d.ts.map +1 -1
- package/dist/server/services/analytics.js +26 -4
- package/dist/server/services/analytics.js.map +1 -1
- package/dist/server/services/platform.d.ts.map +1 -1
- package/dist/server/services/platform.js +17 -10
- package/dist/server/services/platform.js.map +1 -1
- package/dist/server/services/sandbox-utils.d.ts +6 -0
- package/dist/server/services/sandbox-utils.d.ts.map +1 -0
- package/dist/server/services/sandbox-utils.js +72 -0
- package/dist/server/services/sandbox-utils.js.map +1 -0
- package/dist/server/services/settings.d.ts +6 -0
- package/dist/server/services/settings.d.ts.map +1 -1
- package/dist/server/services/settings.js +21 -0
- package/dist/server/services/settings.js.map +1 -1
- package/dist/server/services/terminal/pty-manager.d.ts +5 -51
- package/dist/server/services/terminal/pty-manager.d.ts.map +1 -1
- package/dist/server/services/terminal/pty-manager.js +63 -102
- package/dist/server/services/terminal/pty-manager.js.map +1 -1
- package/dist/server/services/websocket/file-explorer-handlers.d.ts +5 -0
- package/dist/server/services/websocket/file-explorer-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/file-explorer-handlers.js +518 -0
- package/dist/server/services/websocket/file-explorer-handlers.js.map +1 -0
- package/dist/server/services/websocket/git-handlers.d.ts +36 -0
- package/dist/server/services/websocket/git-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/git-handlers.js +797 -0
- package/dist/server/services/websocket/git-handlers.js.map +1 -0
- package/dist/server/services/websocket/git-pr-handlers.d.ts +4 -0
- package/dist/server/services/websocket/git-pr-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/git-pr-handlers.js +299 -0
- package/dist/server/services/websocket/git-pr-handlers.js.map +1 -0
- package/dist/server/services/websocket/git-worktree-handlers.d.ts +4 -0
- package/dist/server/services/websocket/git-worktree-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/git-worktree-handlers.js +353 -0
- package/dist/server/services/websocket/git-worktree-handlers.js.map +1 -0
- package/dist/server/services/websocket/handler-context.d.ts +32 -0
- package/dist/server/services/websocket/handler-context.d.ts.map +1 -0
- package/dist/server/services/websocket/handler-context.js +4 -0
- package/dist/server/services/websocket/handler-context.js.map +1 -0
- package/dist/server/services/websocket/handler.d.ts +27 -338
- package/dist/server/services/websocket/handler.d.ts.map +1 -1
- package/dist/server/services/websocket/handler.js +74 -2106
- package/dist/server/services/websocket/handler.js.map +1 -1
- package/dist/server/services/websocket/index.d.ts +1 -1
- package/dist/server/services/websocket/index.d.ts.map +1 -1
- package/dist/server/services/websocket/index.js.map +1 -1
- package/dist/server/services/websocket/session-handlers.d.ts +10 -0
- package/dist/server/services/websocket/session-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/session-handlers.js +507 -0
- package/dist/server/services/websocket/session-handlers.js.map +1 -0
- package/dist/server/services/websocket/settings-handlers.d.ts +6 -0
- package/dist/server/services/websocket/settings-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/settings-handlers.js +125 -0
- package/dist/server/services/websocket/settings-handlers.js.map +1 -0
- package/dist/server/services/websocket/tab-handlers.d.ts +10 -0
- package/dist/server/services/websocket/tab-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/tab-handlers.js +131 -0
- package/dist/server/services/websocket/tab-handlers.js.map +1 -0
- package/dist/server/services/websocket/terminal-handlers.d.ts +9 -0
- package/dist/server/services/websocket/terminal-handlers.d.ts.map +1 -0
- package/dist/server/services/websocket/terminal-handlers.js +220 -0
- package/dist/server/services/websocket/terminal-handlers.js.map +1 -0
- package/dist/server/services/websocket/types.d.ts +67 -2
- package/dist/server/services/websocket/types.d.ts.map +1 -1
- package/hooks/bouncer.sh +11 -4
- package/package.json +7 -2
- package/server/README.md +176 -159
- package/server/cli/headless/claude-invoker.ts +740 -133
- package/server/cli/headless/index.ts +7 -1
- package/server/cli/headless/output-utils.test.ts +225 -0
- package/server/cli/headless/prompt-utils.ts +37 -5
- package/server/cli/headless/runner.ts +55 -8
- package/server/cli/headless/stall-assessor.test.ts +165 -0
- package/server/cli/headless/stall-assessor.ts +478 -22
- package/server/cli/headless/tool-watchdog.test.ts +429 -0
- package/server/cli/headless/tool-watchdog.ts +398 -0
- package/server/cli/headless/types.ts +93 -1
- package/server/cli/improvisation-session-manager.ts +1133 -145
- package/server/index.ts +5 -14
- package/server/mcp/README.md +59 -67
- package/server/mcp/bouncer-integration.test.ts +161 -0
- package/server/mcp/bouncer-integration.ts +28 -0
- package/server/mcp/security-audit.ts +12 -8
- package/server/mcp/security-patterns.test.ts +258 -0
- package/server/mcp/security-patterns.ts +8 -2
- package/server/routes/improvise.ts +6 -6
- package/server/services/analytics.ts +26 -4
- package/server/services/platform.test.ts +0 -10
- package/server/services/platform.ts +16 -11
- package/server/services/sandbox-utils.ts +78 -0
- package/server/services/settings.ts +25 -0
- package/server/services/terminal/pty-manager.ts +68 -129
- package/server/services/websocket/autocomplete.test.ts +194 -0
- package/server/services/websocket/file-explorer-handlers.ts +587 -0
- package/server/services/websocket/git-handlers.ts +924 -0
- package/server/services/websocket/git-pr-handlers.ts +363 -0
- package/server/services/websocket/git-worktree-handlers.ts +403 -0
- package/server/services/websocket/handler-context.ts +44 -0
- package/server/services/websocket/handler.test.ts +1 -1
- package/server/services/websocket/handler.ts +90 -2421
- package/server/services/websocket/index.ts +1 -1
- package/server/services/websocket/session-handlers.ts +574 -0
- package/server/services/websocket/settings-handlers.ts +150 -0
- package/server/services/websocket/tab-handlers.ts +150 -0
- package/server/services/websocket/terminal-handlers.ts +277 -0
- package/server/services/websocket/types.ts +145 -4
- package/bin/release.sh +0 -110
- package/dist/server/services/terminal/tmux-manager.d.ts +0 -82
- package/dist/server/services/terminal/tmux-manager.d.ts.map +0 -1
- package/dist/server/services/terminal/tmux-manager.js +0 -352
- package/dist/server/services/terminal/tmux-manager.js.map +0 -1
- package/server/services/terminal/tmux-manager.ts +0 -426
|
@@ -7,10 +7,18 @@
|
|
|
7
7
|
* For complex multi-part prompts with parallel/sequential movements, use Compose tab instead.
|
|
8
8
|
*/
|
|
9
9
|
import { EventEmitter } from 'node:events';
|
|
10
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
import { AnalyticsEvents, trackEvent } from '../services/analytics.js';
|
|
13
13
|
import { HeadlessRunner } from './headless/index.js';
|
|
14
|
+
import { assessBestResult, assessContextLoss } from './headless/stall-assessor.js';
|
|
15
|
+
/** Score a run result for best-result tracking (higher = more productive) */
|
|
16
|
+
function scoreRunResult(r) {
|
|
17
|
+
const toolCount = r.toolUseHistory?.filter(t => t.result !== undefined && !t.isError).length ?? 0;
|
|
18
|
+
const responseLen = Math.min((r.assistantResponse?.length ?? 0) / 50, 100);
|
|
19
|
+
const hasThinking = r.thinkingOutput ? 20 : 0;
|
|
20
|
+
return toolCount * 10 + responseLen + hasThinking;
|
|
21
|
+
}
|
|
14
22
|
export class ImprovisationSessionManager extends EventEmitter {
|
|
15
23
|
sessionId;
|
|
16
24
|
improviseDir;
|
|
@@ -27,18 +35,22 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
27
35
|
accumulatedKnowledge = '';
|
|
28
36
|
/** Whether a prompt is currently executing */
|
|
29
37
|
_isExecuting = false;
|
|
38
|
+
/** Timestamp when current execution started (for accurate elapsed time across reconnects) */
|
|
39
|
+
_executionStartTimestamp;
|
|
30
40
|
/** Buffered events during current execution, for replay on reconnect */
|
|
31
41
|
executionEventLog = [];
|
|
42
|
+
/** Set by cancel() to signal the retry loop to exit */
|
|
43
|
+
_cancelled = false;
|
|
32
44
|
/**
|
|
33
45
|
* Resume from a historical session.
|
|
34
46
|
* Creates a new session manager that continues the conversation from a previous session.
|
|
35
47
|
* The first prompt will include context from the historical session.
|
|
36
48
|
*/
|
|
37
49
|
static resumeFromHistory(workingDir, historicalSessionId, overrides) {
|
|
38
|
-
const
|
|
50
|
+
const historyDir = join(workingDir, '.mstro', 'history');
|
|
39
51
|
// Extract timestamp from session ID (format: improv-1234567890123 or just 1234567890123)
|
|
40
52
|
const timestamp = historicalSessionId.replace('improv-', '');
|
|
41
|
-
const historyPath = join(
|
|
53
|
+
const historyPath = join(historyDir, `${timestamp}.json`);
|
|
42
54
|
if (!existsSync(historyPath)) {
|
|
43
55
|
throw new Error(`Historical session not found: ${historicalSessionId}`);
|
|
44
56
|
}
|
|
@@ -80,9 +92,9 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
80
92
|
model: options.model,
|
|
81
93
|
};
|
|
82
94
|
this.sessionId = this.options.sessionId;
|
|
83
|
-
this.improviseDir = join(this.options.workingDir, '.mstro', '
|
|
84
|
-
this.historyPath = join(this.improviseDir,
|
|
85
|
-
// Ensure
|
|
95
|
+
this.improviseDir = join(this.options.workingDir, '.mstro', 'history');
|
|
96
|
+
this.historyPath = join(this.improviseDir, `${this.sessionId.replace('improv-', '')}.json`);
|
|
97
|
+
// Ensure history directory exists
|
|
86
98
|
if (!existsSync(this.improviseDir)) {
|
|
87
99
|
mkdirSync(this.improviseDir, { recursive: true });
|
|
88
100
|
}
|
|
@@ -117,24 +129,68 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
117
129
|
}
|
|
118
130
|
}
|
|
119
131
|
/**
|
|
120
|
-
* Build prompt with text file attachments prepended
|
|
132
|
+
* Build prompt with text file attachments prepended and disk path references
|
|
121
133
|
* Format: each text file is shown as @path followed by content in code block
|
|
122
134
|
*/
|
|
123
|
-
buildPromptWithAttachments(userPrompt, attachments) {
|
|
124
|
-
if (!attachments || attachments.length === 0) {
|
|
135
|
+
buildPromptWithAttachments(userPrompt, attachments, diskPaths) {
|
|
136
|
+
if ((!attachments || attachments.length === 0) && (!diskPaths || diskPaths.length === 0)) {
|
|
125
137
|
return userPrompt;
|
|
126
138
|
}
|
|
139
|
+
const parts = [];
|
|
127
140
|
// Filter to text files only (non-images)
|
|
128
|
-
|
|
129
|
-
|
|
141
|
+
if (attachments) {
|
|
142
|
+
const textFiles = attachments.filter(a => !a.isImage);
|
|
143
|
+
for (const file of textFiles) {
|
|
144
|
+
parts.push(`@${file.filePath}\n\`\`\`\n${file.content}\n\`\`\``);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Add disk path references for all persisted files
|
|
148
|
+
if (diskPaths && diskPaths.length > 0) {
|
|
149
|
+
parts.push(`Attached files saved to disk:\n${diskPaths.map(p => `- ${p}`).join('\n')}`);
|
|
150
|
+
}
|
|
151
|
+
if (parts.length === 0) {
|
|
130
152
|
return userPrompt;
|
|
131
153
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
154
|
+
return `${parts.join('\n\n')}\n\n${userPrompt}`;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Write attachments to disk at .mstro/tmp/attachments/{sessionId}/
|
|
158
|
+
* Returns array of absolute file paths for each persisted attachment.
|
|
159
|
+
*/
|
|
160
|
+
persistAttachments(attachments) {
|
|
161
|
+
if (attachments.length === 0)
|
|
162
|
+
return [];
|
|
163
|
+
const attachDir = join(this.options.workingDir, '.mstro', 'tmp', 'attachments', this.sessionId);
|
|
164
|
+
if (!existsSync(attachDir)) {
|
|
165
|
+
mkdirSync(attachDir, { recursive: true });
|
|
166
|
+
}
|
|
167
|
+
const paths = [];
|
|
168
|
+
for (const attachment of attachments) {
|
|
169
|
+
const filePath = join(attachDir, attachment.fileName);
|
|
170
|
+
try {
|
|
171
|
+
// All paste content arrives as base64 — decode to binary
|
|
172
|
+
writeFileSync(filePath, Buffer.from(attachment.content, 'base64'));
|
|
173
|
+
paths.push(filePath);
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
console.error(`Failed to persist attachment ${attachment.fileName}:`, err);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return paths;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Clean up persisted attachments for this session
|
|
183
|
+
*/
|
|
184
|
+
cleanupAttachments() {
|
|
185
|
+
const attachDir = join(this.options.workingDir, '.mstro', 'tmp', 'attachments', this.sessionId);
|
|
186
|
+
if (existsSync(attachDir)) {
|
|
187
|
+
try {
|
|
188
|
+
rmSync(attachDir, { recursive: true, force: true });
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Ignore cleanup errors
|
|
192
|
+
}
|
|
193
|
+
}
|
|
138
194
|
}
|
|
139
195
|
/**
|
|
140
196
|
* Execute a user prompt directly (Improvise mode - no score decomposition)
|
|
@@ -142,144 +198,67 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
142
198
|
* Each tab maintains its own claudeSessionId for proper isolation
|
|
143
199
|
* Supports file attachments: text files prepended to prompt, images via stream-json multimodal
|
|
144
200
|
*/
|
|
145
|
-
async executePrompt(userPrompt, attachments) {
|
|
201
|
+
async executePrompt(userPrompt, attachments, options) {
|
|
146
202
|
const _execStart = Date.now();
|
|
147
|
-
// Start execution event log for reconnect replay
|
|
148
203
|
this._isExecuting = true;
|
|
204
|
+
this._cancelled = false;
|
|
205
|
+
this._executionStartTimestamp = _execStart;
|
|
149
206
|
this.executionEventLog = [];
|
|
150
|
-
|
|
207
|
+
const sequenceNumber = this.history.movements.length + 1;
|
|
208
|
+
this.emit('onMovementStart', sequenceNumber, userPrompt);
|
|
151
209
|
trackEvent(AnalyticsEvents.IMPROVISE_PROMPT_RECEIVED, {
|
|
152
210
|
prompt_length: userPrompt.length,
|
|
153
211
|
has_attachments: !!(attachments && attachments.length > 0),
|
|
154
212
|
attachment_count: attachments?.length || 0,
|
|
155
213
|
image_attachment_count: attachments?.filter(a => a.isImage).length || 0,
|
|
156
|
-
sequence_number:
|
|
214
|
+
sequence_number: sequenceNumber,
|
|
157
215
|
is_resumed_session: this.isResumedSession,
|
|
158
216
|
model: this.options.model || 'default',
|
|
159
217
|
});
|
|
160
218
|
try {
|
|
161
|
-
const sequenceNumber = this.history.movements.length + 1;
|
|
162
|
-
// Log the movement start event
|
|
163
219
|
this.executionEventLog.push({
|
|
164
220
|
type: 'movementStart',
|
|
165
|
-
data: { sequenceNumber, prompt: userPrompt, timestamp: Date.now() },
|
|
221
|
+
data: { sequenceNumber, prompt: userPrompt, timestamp: Date.now(), executionStartTimestamp: this._executionStartTimestamp },
|
|
166
222
|
timestamp: Date.now(),
|
|
167
223
|
});
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
workingDir: this.options.workingDir,
|
|
182
|
-
tokenBudgetThreshold: this.options.tokenBudgetThreshold,
|
|
183
|
-
maxSessions: this.options.maxSessions,
|
|
184
|
-
verbose: this.options.verbose,
|
|
185
|
-
noColor: this.options.noColor,
|
|
186
|
-
model: this.options.model,
|
|
187
|
-
improvisationMode: true,
|
|
188
|
-
movementNumber: sequenceNumber,
|
|
189
|
-
continueSession: !this.isFirstPrompt, // Used as fallback only if claudeSessionId is missing
|
|
190
|
-
claudeSessionId: this.claudeSessionId, // Resume specific session for tab isolation
|
|
191
|
-
outputCallback: (text) => {
|
|
192
|
-
this.executionEventLog.push({ type: 'output', data: { text, timestamp: Date.now() }, timestamp: Date.now() });
|
|
193
|
-
this.queueOutput(text);
|
|
194
|
-
this.flushOutputQueue();
|
|
195
|
-
},
|
|
196
|
-
thinkingCallback: (text) => {
|
|
197
|
-
this.executionEventLog.push({ type: 'thinking', data: { text }, timestamp: Date.now() });
|
|
198
|
-
this.emit('onThinking', text);
|
|
199
|
-
this.flushOutputQueue();
|
|
200
|
-
},
|
|
201
|
-
toolUseCallback: (event) => {
|
|
202
|
-
this.executionEventLog.push({ type: 'toolUse', data: { ...event, timestamp: Date.now() }, timestamp: Date.now() });
|
|
203
|
-
this.emit('onToolUse', event);
|
|
204
|
-
this.flushOutputQueue();
|
|
205
|
-
},
|
|
206
|
-
directPrompt: promptWithAttachments,
|
|
207
|
-
// Pass image attachments for multimodal handling via stream-json
|
|
208
|
-
imageAttachments: attachments?.filter(a => a.isImage),
|
|
209
|
-
// Inject historical context on first prompt of a resumed session
|
|
210
|
-
// This serves as both the primary context mechanism (no claudeSessionId)
|
|
211
|
-
// and a fallback if claudeSessionId is stale (client restarted since original session)
|
|
212
|
-
promptContext: (this.isResumedSession && this.isFirstPrompt)
|
|
213
|
-
? { accumulatedKnowledge: this.buildHistoricalContext(), filesModified: [] }
|
|
214
|
-
: undefined
|
|
215
|
-
});
|
|
216
|
-
this.currentRunner = runner;
|
|
217
|
-
const result = await runner.run();
|
|
218
|
-
this.currentRunner = null;
|
|
219
|
-
// Capture Claude session ID for future prompts in this tab
|
|
220
|
-
// This is critical for tab isolation - each tab maintains its own Claude session
|
|
221
|
-
if (result.claudeSessionId) {
|
|
222
|
-
this.claudeSessionId = result.claudeSessionId;
|
|
223
|
-
this.history.claudeSessionId = result.claudeSessionId;
|
|
224
|
-
}
|
|
225
|
-
// Mark that we've executed at least one prompt
|
|
226
|
-
this.isFirstPrompt = false;
|
|
227
|
-
// Create movement record with accumulated output for persistence
|
|
228
|
-
const movement = {
|
|
229
|
-
id: `prompt-${sequenceNumber}`,
|
|
230
|
-
sequenceNumber,
|
|
231
|
-
userPrompt,
|
|
232
|
-
timestamp: new Date().toISOString(),
|
|
233
|
-
tokensUsed: result.totalTokens,
|
|
234
|
-
summary: '', // No summary needed - Claude session maintains context
|
|
235
|
-
filesModified: [],
|
|
236
|
-
// Persist accumulated output for history replay
|
|
237
|
-
assistantResponse: result.assistantResponse,
|
|
238
|
-
thinkingOutput: result.thinkingOutput,
|
|
239
|
-
toolUseHistory: result.toolUseHistory?.map(t => ({
|
|
240
|
-
toolName: t.toolName,
|
|
241
|
-
toolId: t.toolId,
|
|
242
|
-
toolInput: t.toolInput,
|
|
243
|
-
result: t.result,
|
|
244
|
-
isError: t.isError,
|
|
245
|
-
duration: t.duration
|
|
246
|
-
})),
|
|
247
|
-
errorOutput: result.error
|
|
224
|
+
const { prompt: promptWithAttachments, imageAttachments } = this.preparePromptAndAttachments(userPrompt, attachments);
|
|
225
|
+
const state = {
|
|
226
|
+
currentPrompt: promptWithAttachments,
|
|
227
|
+
retryNumber: 0,
|
|
228
|
+
checkpointRef: { value: null },
|
|
229
|
+
contextRecoverySessionId: undefined,
|
|
230
|
+
freshRecoveryMode: false,
|
|
231
|
+
accumulatedToolResults: [],
|
|
232
|
+
contextLost: false,
|
|
233
|
+
lastWatchdogCheckpoint: null,
|
|
234
|
+
timedOutTools: [],
|
|
235
|
+
bestResult: null,
|
|
236
|
+
retryLog: [],
|
|
248
237
|
};
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
this.queueOutput(` - ${c.filePath} (modified by: ${c.modifiedBy.join(', ')})`);
|
|
254
|
-
if (c.backupPath) {
|
|
255
|
-
this.queueOutput(` Backup created: ${c.backupPath}`);
|
|
256
|
-
}
|
|
257
|
-
});
|
|
258
|
-
this.flushOutputQueue();
|
|
238
|
+
let result = await this.runRetryLoop(state, sequenceNumber, promptWithAttachments, imageAttachments, options?.sandboxed, options?.workingDir);
|
|
239
|
+
// If cancelled, emit a minimal movement and return early
|
|
240
|
+
if (this._cancelled) {
|
|
241
|
+
return this.handleCancelledExecution(result, userPrompt, sequenceNumber, _execStart);
|
|
259
242
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
//
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
243
|
+
if (state.contextLost)
|
|
244
|
+
this.claudeSessionId = undefined;
|
|
245
|
+
// result is guaranteed assigned here: the loop always runs at least once (if _cancelled was
|
|
246
|
+
// true before the loop, we returned in the block above; otherwise runner.run() assigned it).
|
|
247
|
+
result = await this.selectBestResult(state, result, userPrompt);
|
|
248
|
+
this.captureSessionAndSurfaceErrors(result);
|
|
249
|
+
this.isFirstPrompt = false;
|
|
250
|
+
const movement = this.buildMovementRecord(result, userPrompt, sequenceNumber, _execStart, state.retryLog);
|
|
251
|
+
this.handleConflicts(result);
|
|
252
|
+
this.persistMovement(movement);
|
|
268
253
|
this._isExecuting = false;
|
|
254
|
+
this._executionStartTimestamp = undefined;
|
|
269
255
|
this.executionEventLog = [];
|
|
270
|
-
this.
|
|
271
|
-
trackEvent(AnalyticsEvents.IMPROVISE_MOVEMENT_COMPLETED, {
|
|
272
|
-
tokens_used: movement.tokensUsed,
|
|
273
|
-
duration_ms: Date.now() - _execStart,
|
|
274
|
-
sequence_number: sequenceNumber,
|
|
275
|
-
tool_count: result.toolUseHistory?.length || 0,
|
|
276
|
-
model: this.options.model || 'default',
|
|
277
|
-
});
|
|
278
|
-
this.emit('onSessionUpdate', this.getHistory());
|
|
256
|
+
this.emitMovementComplete(movement, result, _execStart, sequenceNumber);
|
|
279
257
|
return movement;
|
|
280
258
|
}
|
|
281
259
|
catch (error) {
|
|
282
260
|
this._isExecuting = false;
|
|
261
|
+
this._executionStartTimestamp = undefined;
|
|
283
262
|
this.executionEventLog = [];
|
|
284
263
|
this.currentRunner = null;
|
|
285
264
|
this.emit('onMovementError', error);
|
|
@@ -294,10 +273,573 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
294
273
|
throw error;
|
|
295
274
|
}
|
|
296
275
|
finally {
|
|
297
|
-
// Ensure final flush
|
|
298
276
|
this.flushOutputQueue();
|
|
299
277
|
}
|
|
300
278
|
}
|
|
279
|
+
// ========== Extracted helpers for executePrompt ==========
|
|
280
|
+
handleCancelledExecution(result, userPrompt, sequenceNumber, execStart) {
|
|
281
|
+
this._isExecuting = false;
|
|
282
|
+
this._executionStartTimestamp = undefined;
|
|
283
|
+
this.executionEventLog = [];
|
|
284
|
+
this.currentRunner = null;
|
|
285
|
+
const cancelledMovement = {
|
|
286
|
+
id: `prompt-${sequenceNumber}`,
|
|
287
|
+
sequenceNumber,
|
|
288
|
+
userPrompt,
|
|
289
|
+
timestamp: new Date().toISOString(),
|
|
290
|
+
tokensUsed: result ? result.totalTokens : 0,
|
|
291
|
+
summary: '',
|
|
292
|
+
filesModified: [],
|
|
293
|
+
assistantResponse: result?.assistantResponse,
|
|
294
|
+
thinkingOutput: result?.thinkingOutput,
|
|
295
|
+
toolUseHistory: result?.toolUseHistory?.map(t => ({
|
|
296
|
+
toolName: t.toolName,
|
|
297
|
+
toolId: t.toolId,
|
|
298
|
+
toolInput: t.toolInput,
|
|
299
|
+
result: t.result,
|
|
300
|
+
})),
|
|
301
|
+
errorOutput: 'Execution cancelled by user',
|
|
302
|
+
durationMs: Date.now() - execStart,
|
|
303
|
+
};
|
|
304
|
+
this.persistMovement(cancelledMovement);
|
|
305
|
+
const fallbackResult = {
|
|
306
|
+
completed: false, needsHandoff: false, totalTokens: 0, sessionId: '',
|
|
307
|
+
output: '', exitCode: 1, signalName: 'SIGTERM',
|
|
308
|
+
};
|
|
309
|
+
this.emitMovementComplete(cancelledMovement, result ?? fallbackResult, execStart, sequenceNumber);
|
|
310
|
+
return cancelledMovement;
|
|
311
|
+
}
|
|
312
|
+
async runRetryLoop(state, sequenceNumber, promptWithAttachments, imageAttachments, sandboxed, workingDirOverride) {
|
|
313
|
+
const maxRetries = 3;
|
|
314
|
+
let result;
|
|
315
|
+
// eslint-disable-next-line no-constant-condition
|
|
316
|
+
while (true) {
|
|
317
|
+
if (this._cancelled)
|
|
318
|
+
break;
|
|
319
|
+
this.resetIterationState(state);
|
|
320
|
+
const { useResume, resumeSessionId } = this.determineResumeStrategy(state);
|
|
321
|
+
const runner = this.createExecutionRunner(state, sequenceNumber, useResume, resumeSessionId, imageAttachments, sandboxed, workingDirOverride);
|
|
322
|
+
this.currentRunner = runner;
|
|
323
|
+
result = await runner.run();
|
|
324
|
+
this.currentRunner = null;
|
|
325
|
+
if (this._cancelled)
|
|
326
|
+
break;
|
|
327
|
+
this.updateBestResult(state, result);
|
|
328
|
+
const nativeTimeouts = result.nativeTimeoutCount ?? 0;
|
|
329
|
+
this.detectResumeContextLoss(result, state, useResume, maxRetries, nativeTimeouts);
|
|
330
|
+
await this.detectNativeTimeoutContextLoss(result, state, maxRetries, nativeTimeouts);
|
|
331
|
+
this.flushPostTimeoutOutput(result, state);
|
|
332
|
+
// Signal crashes checked first: they use --resume (lighter), and context loss
|
|
333
|
+
// recovery would clear the session ID, preventing future --resume attempts.
|
|
334
|
+
if (this.shouldRetrySignalCrash(result, state, maxRetries, promptWithAttachments))
|
|
335
|
+
continue;
|
|
336
|
+
if (this.shouldRetryContextLoss(result, state, useResume, nativeTimeouts, maxRetries, promptWithAttachments))
|
|
337
|
+
continue;
|
|
338
|
+
if (this.applyToolTimeoutRetry(state, maxRetries, promptWithAttachments))
|
|
339
|
+
continue;
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
return result;
|
|
343
|
+
}
|
|
344
|
+
/** Prepare prompt with attachments and limit image count */
|
|
345
|
+
preparePromptAndAttachments(userPrompt, attachments) {
|
|
346
|
+
const diskPaths = attachments ? this.persistAttachments(attachments) : [];
|
|
347
|
+
const prompt = this.buildPromptWithAttachments(userPrompt, attachments, diskPaths);
|
|
348
|
+
const MAX_IMAGE_ATTACHMENTS = 20;
|
|
349
|
+
const allImages = attachments?.filter(a => a.isImage);
|
|
350
|
+
let imageAttachments = allImages;
|
|
351
|
+
if (allImages && allImages.length > MAX_IMAGE_ATTACHMENTS) {
|
|
352
|
+
imageAttachments = allImages.slice(-MAX_IMAGE_ATTACHMENTS);
|
|
353
|
+
this.queueOutput(`\n[[MSTRO_ERROR:TOO_MANY_IMAGES]] ${allImages.length} images attached, limit is ${MAX_IMAGE_ATTACHMENTS}. Using the ${MAX_IMAGE_ATTACHMENTS} most recent.\n`);
|
|
354
|
+
this.flushOutputQueue();
|
|
355
|
+
}
|
|
356
|
+
return { prompt, imageAttachments };
|
|
357
|
+
}
|
|
358
|
+
/** Determine whether to use --resume and which session ID */
|
|
359
|
+
determineResumeStrategy(state) {
|
|
360
|
+
if (state.freshRecoveryMode) {
|
|
361
|
+
state.freshRecoveryMode = false;
|
|
362
|
+
return { useResume: false, resumeSessionId: undefined };
|
|
363
|
+
}
|
|
364
|
+
if (state.contextRecoverySessionId) {
|
|
365
|
+
const id = state.contextRecoverySessionId;
|
|
366
|
+
state.contextRecoverySessionId = undefined;
|
|
367
|
+
return { useResume: true, resumeSessionId: id };
|
|
368
|
+
}
|
|
369
|
+
if (state.retryNumber === 0) {
|
|
370
|
+
return { useResume: !this.isFirstPrompt, resumeSessionId: this.claudeSessionId };
|
|
371
|
+
}
|
|
372
|
+
if (state.lastWatchdogCheckpoint?.inProgressTools.length === 0 && state.lastWatchdogCheckpoint.claudeSessionId) {
|
|
373
|
+
return { useResume: true, resumeSessionId: state.lastWatchdogCheckpoint.claudeSessionId };
|
|
374
|
+
}
|
|
375
|
+
return { useResume: false, resumeSessionId: undefined };
|
|
376
|
+
}
|
|
377
|
+
/** Create HeadlessRunner for one retry iteration */
|
|
378
|
+
createExecutionRunner(state, sequenceNumber, useResume, resumeSessionId, imageAttachments, sandboxed, workingDirOverride) {
|
|
379
|
+
return new HeadlessRunner({
|
|
380
|
+
workingDir: workingDirOverride || this.options.workingDir,
|
|
381
|
+
tokenBudgetThreshold: this.options.tokenBudgetThreshold,
|
|
382
|
+
maxSessions: this.options.maxSessions,
|
|
383
|
+
verbose: this.options.verbose,
|
|
384
|
+
noColor: this.options.noColor,
|
|
385
|
+
model: this.options.model,
|
|
386
|
+
improvisationMode: true,
|
|
387
|
+
movementNumber: sequenceNumber,
|
|
388
|
+
continueSession: useResume,
|
|
389
|
+
claudeSessionId: resumeSessionId,
|
|
390
|
+
outputCallback: (text) => {
|
|
391
|
+
this.executionEventLog.push({ type: 'output', data: { text, timestamp: Date.now() }, timestamp: Date.now() });
|
|
392
|
+
this.queueOutput(text);
|
|
393
|
+
this.flushOutputQueue();
|
|
394
|
+
},
|
|
395
|
+
thinkingCallback: (text) => {
|
|
396
|
+
this.executionEventLog.push({ type: 'thinking', data: { text }, timestamp: Date.now() });
|
|
397
|
+
this.emit('onThinking', text);
|
|
398
|
+
this.flushOutputQueue();
|
|
399
|
+
},
|
|
400
|
+
toolUseCallback: (event) => {
|
|
401
|
+
this.executionEventLog.push({ type: 'toolUse', data: { ...event, timestamp: Date.now() }, timestamp: Date.now() });
|
|
402
|
+
this.emit('onToolUse', event);
|
|
403
|
+
this.flushOutputQueue();
|
|
404
|
+
},
|
|
405
|
+
tokenUsageCallback: (usage) => {
|
|
406
|
+
this.emit('onTokenUsage', usage);
|
|
407
|
+
},
|
|
408
|
+
directPrompt: state.currentPrompt,
|
|
409
|
+
imageAttachments,
|
|
410
|
+
promptContext: (state.retryNumber === 0 && this.isResumedSession && this.isFirstPrompt)
|
|
411
|
+
? { accumulatedKnowledge: this.buildHistoricalContext(), filesModified: [] }
|
|
412
|
+
: undefined,
|
|
413
|
+
onToolTimeout: (checkpoint) => {
|
|
414
|
+
state.checkpointRef.value = checkpoint;
|
|
415
|
+
},
|
|
416
|
+
sandboxed,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
/** Save checkpoint and reset per-iteration state before each retry loop pass. */
|
|
420
|
+
resetIterationState(state) {
|
|
421
|
+
if (state.checkpointRef.value)
|
|
422
|
+
state.lastWatchdogCheckpoint = state.checkpointRef.value;
|
|
423
|
+
state.checkpointRef.value = null;
|
|
424
|
+
state.contextLost = false;
|
|
425
|
+
}
|
|
426
|
+
/** Update best result tracking */
|
|
427
|
+
updateBestResult(state, result) {
|
|
428
|
+
if (!state.bestResult || scoreRunResult(result) > scoreRunResult(state.bestResult)) {
|
|
429
|
+
state.bestResult = result;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** Detect resume context loss (Path 1): session expired on --resume */
|
|
433
|
+
detectResumeContextLoss(result, state, useResume, maxRetries, nativeTimeouts) {
|
|
434
|
+
if (!useResume || state.checkpointRef.value || state.retryNumber >= maxRetries || nativeTimeouts > 0) {
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (!result.assistantResponse || result.assistantResponse.trim().length === 0) {
|
|
438
|
+
state.contextLost = true;
|
|
439
|
+
if (this.options.verbose)
|
|
440
|
+
console.log('[CONTEXT-RECOVERY] Resume context loss: null/empty response');
|
|
441
|
+
}
|
|
442
|
+
else if (result.resumeBufferedOutput !== undefined) {
|
|
443
|
+
state.contextLost = true;
|
|
444
|
+
if (this.options.verbose)
|
|
445
|
+
console.log('[CONTEXT-RECOVERY] Resume context loss: buffer never flushed (no thinking/tools)');
|
|
446
|
+
}
|
|
447
|
+
else if ((!result.toolUseHistory || result.toolUseHistory.length === 0) &&
|
|
448
|
+
!result.thinkingOutput &&
|
|
449
|
+
result.assistantResponse.length < 500) {
|
|
450
|
+
state.contextLost = true;
|
|
451
|
+
if (this.options.verbose)
|
|
452
|
+
console.log('[CONTEXT-RECOVERY] Resume context loss: no tools, no thinking, short response');
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/** Detect native timeout context loss (Path 2): tool timeouts caused confusion */
|
|
456
|
+
async detectNativeTimeoutContextLoss(result, state, maxRetries, nativeTimeouts) {
|
|
457
|
+
if (state.contextLost)
|
|
458
|
+
return;
|
|
459
|
+
// Deduplicate by toolId: if a toolId has at least one entry with a result,
|
|
460
|
+
// its orphaned duplicates are Claude Code internal retries, not actual timeouts.
|
|
461
|
+
const succeededIds = new Set();
|
|
462
|
+
const allIds = new Set();
|
|
463
|
+
for (const t of result.toolUseHistory ?? []) {
|
|
464
|
+
allIds.add(t.toolId);
|
|
465
|
+
if (t.result !== undefined)
|
|
466
|
+
succeededIds.add(t.toolId);
|
|
467
|
+
}
|
|
468
|
+
const toolsWithoutResult = [...allIds].filter(id => !succeededIds.has(id)).length;
|
|
469
|
+
const effectiveTimeouts = Math.max(nativeTimeouts, toolsWithoutResult);
|
|
470
|
+
if (effectiveTimeouts === 0 || !result.assistantResponse || state.checkpointRef.value || state.retryNumber >= maxRetries) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const writeToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
474
|
+
const contextLossCtx = {
|
|
475
|
+
assistantResponse: result.assistantResponse,
|
|
476
|
+
effectiveTimeouts,
|
|
477
|
+
nativeTimeoutCount: nativeTimeouts,
|
|
478
|
+
successfulToolCalls: result.toolUseHistory?.filter(t => t.result !== undefined && !t.isError).length ?? 0,
|
|
479
|
+
thinkingOutputLength: result.thinkingOutput?.length ?? 0,
|
|
480
|
+
hasSuccessfulWrite: result.toolUseHistory?.some(t => writeToolNames.has(t.toolName) && t.result !== undefined && !t.isError) ?? false,
|
|
481
|
+
};
|
|
482
|
+
const claudeCmd = process.env.CLAUDE_COMMAND || 'claude';
|
|
483
|
+
const verdict = await assessContextLoss(contextLossCtx, claudeCmd, this.options.verbose);
|
|
484
|
+
state.contextLost = verdict.contextLost;
|
|
485
|
+
if (this.options.verbose) {
|
|
486
|
+
console.log(`[CONTEXT-RECOVERY] Haiku verdict: ${state.contextLost ? 'LOST' : 'OK'} — ${verdict.reason}`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
/** Flush post-timeout output if context wasn't lost */
|
|
490
|
+
flushPostTimeoutOutput(result, state) {
|
|
491
|
+
if (!state.contextLost && result.postTimeoutOutput) {
|
|
492
|
+
this.queueOutput(result.postTimeoutOutput);
|
|
493
|
+
this.flushOutputQueue();
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
/** Check if context loss recovery should trigger a retry. Returns true if loop should continue. */
|
|
497
|
+
shouldRetryContextLoss(result, state, useResume, nativeTimeouts, maxRetries, promptWithAttachments) {
|
|
498
|
+
if (state.checkpointRef.value || state.retryNumber >= maxRetries || !state.contextLost) {
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
this.accumulateToolResults(result, state);
|
|
502
|
+
state.retryNumber++;
|
|
503
|
+
const path = (useResume && nativeTimeouts === 0) ? 'InterMovementRecovery' : 'NativeTimeoutRecovery';
|
|
504
|
+
state.retryLog.push({
|
|
505
|
+
retryNumber: state.retryNumber,
|
|
506
|
+
path,
|
|
507
|
+
reason: `Context lost (${nativeTimeouts} timeouts, ${state.accumulatedToolResults.length} tools preserved)`,
|
|
508
|
+
timestamp: Date.now(),
|
|
509
|
+
});
|
|
510
|
+
if (useResume && nativeTimeouts === 0) {
|
|
511
|
+
this.applyInterMovementRecovery(state, promptWithAttachments);
|
|
512
|
+
}
|
|
513
|
+
else {
|
|
514
|
+
this.applyNativeTimeoutRecovery(result, state, promptWithAttachments);
|
|
515
|
+
}
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
/** Accumulate completed tool results from a run into the retry state.
|
|
519
|
+
* Caps at MAX_ACCUMULATED_RESULTS to prevent recovery prompts from exceeding context limits.
|
|
520
|
+
* When the cap is reached, older results are evicted (FIFO) to make room for newer ones. */
|
|
521
|
+
static MAX_ACCUMULATED_RESULTS = 50;
|
|
522
|
+
accumulateToolResults(result, state) {
|
|
523
|
+
if (!result.toolUseHistory)
|
|
524
|
+
return;
|
|
525
|
+
for (const t of result.toolUseHistory) {
|
|
526
|
+
if (t.result !== undefined) {
|
|
527
|
+
state.accumulatedToolResults.push({
|
|
528
|
+
toolName: t.toolName,
|
|
529
|
+
toolId: t.toolId,
|
|
530
|
+
toolInput: t.toolInput,
|
|
531
|
+
result: t.result,
|
|
532
|
+
isError: t.isError,
|
|
533
|
+
duration: t.duration,
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
// Evict oldest results if over the cap
|
|
538
|
+
const cap = ImprovisationSessionManager.MAX_ACCUMULATED_RESULTS;
|
|
539
|
+
if (state.accumulatedToolResults.length > cap) {
|
|
540
|
+
state.accumulatedToolResults = state.accumulatedToolResults.slice(-cap);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/** Handle inter-movement context loss recovery (resume session expired) */
|
|
544
|
+
applyInterMovementRecovery(state, promptWithAttachments) {
|
|
545
|
+
// Preserve session ID so --resume remains available on subsequent retries.
|
|
546
|
+
// The fresh recovery prompt will be used, but if this attempt also fails,
|
|
547
|
+
// the next retry can still try --resume via shouldRetrySignalCrash.
|
|
548
|
+
const historicalResults = this.extractHistoricalToolResults();
|
|
549
|
+
const allResults = [...historicalResults, ...state.accumulatedToolResults];
|
|
550
|
+
this.emit('onAutoRetry', {
|
|
551
|
+
retryNumber: state.retryNumber,
|
|
552
|
+
maxRetries: 3,
|
|
553
|
+
toolName: 'InterMovementRecovery',
|
|
554
|
+
completedCount: allResults.length,
|
|
555
|
+
});
|
|
556
|
+
this.queueOutput(`\n[[MSTRO_CONTEXT_RECOVERY]] Session context expired — continuing with ${allResults.length} preserved results from prior work (retry ${state.retryNumber}/3).\n`);
|
|
557
|
+
this.flushOutputQueue();
|
|
558
|
+
state.freshRecoveryMode = true;
|
|
559
|
+
state.currentPrompt = this.buildInterMovementRecoveryPrompt(promptWithAttachments, allResults);
|
|
560
|
+
}
|
|
561
|
+
/** Handle native-timeout context loss recovery (tool timeouts caused confusion) */
|
|
562
|
+
applyNativeTimeoutRecovery(result, state, promptWithAttachments) {
|
|
563
|
+
const completedCount = state.accumulatedToolResults.length;
|
|
564
|
+
this.emit('onAutoRetry', {
|
|
565
|
+
retryNumber: state.retryNumber,
|
|
566
|
+
maxRetries: 3,
|
|
567
|
+
toolName: 'ContextRecovery',
|
|
568
|
+
completedCount,
|
|
569
|
+
});
|
|
570
|
+
if (result.claudeSessionId && state.retryNumber === 1) {
|
|
571
|
+
this.queueOutput(`\n[[MSTRO_CONTEXT_RECOVERY]] Context loss detected — resuming session with ${completedCount} preserved results (retry ${state.retryNumber}/3).\n`);
|
|
572
|
+
this.flushOutputQueue();
|
|
573
|
+
state.contextRecoverySessionId = result.claudeSessionId;
|
|
574
|
+
this.claudeSessionId = result.claudeSessionId;
|
|
575
|
+
state.currentPrompt = this.buildContextRecoveryPrompt(promptWithAttachments);
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
this.queueOutput(`\n[[MSTRO_CONTEXT_RECOVERY]] Continuing with fresh context — ${completedCount} preserved results injected (retry ${state.retryNumber}/3).\n`);
|
|
579
|
+
this.flushOutputQueue();
|
|
580
|
+
state.freshRecoveryMode = true;
|
|
581
|
+
state.currentPrompt = this.buildFreshRecoveryPrompt(promptWithAttachments, state.accumulatedToolResults, state.timedOutTools);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
/** Handle tool timeout checkpoint. Returns true if loop should continue. */
|
|
585
|
+
applyToolTimeoutRetry(state, maxRetries, promptWithAttachments) {
|
|
586
|
+
if (!state.checkpointRef.value || state.retryNumber >= maxRetries) {
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
const cp = state.checkpointRef.value;
|
|
590
|
+
state.retryNumber++;
|
|
591
|
+
state.timedOutTools.push({
|
|
592
|
+
toolName: cp.hungTool.toolName,
|
|
593
|
+
input: cp.hungTool.input ?? {},
|
|
594
|
+
timeoutMs: cp.hungTool.timeoutMs,
|
|
595
|
+
});
|
|
596
|
+
const canResumeSession = cp.inProgressTools.length === 0 && !!cp.claudeSessionId;
|
|
597
|
+
state.retryLog.push({
|
|
598
|
+
retryNumber: state.retryNumber,
|
|
599
|
+
path: 'ToolTimeout',
|
|
600
|
+
reason: `${cp.hungTool.toolName} timed out after ${cp.hungTool.timeoutMs}ms, ${cp.completedTools.length} tools completed, ${canResumeSession ? 'resuming' : 'fresh start'}`,
|
|
601
|
+
timestamp: Date.now(),
|
|
602
|
+
});
|
|
603
|
+
this.emit('onAutoRetry', {
|
|
604
|
+
retryNumber: state.retryNumber,
|
|
605
|
+
maxRetries,
|
|
606
|
+
toolName: cp.hungTool.toolName,
|
|
607
|
+
url: cp.hungTool.url,
|
|
608
|
+
completedCount: cp.completedTools.length,
|
|
609
|
+
});
|
|
610
|
+
trackEvent(AnalyticsEvents.IMPROVISE_AUTO_RETRY, {
|
|
611
|
+
retry_number: state.retryNumber,
|
|
612
|
+
hung_tool: cp.hungTool.toolName,
|
|
613
|
+
hung_url: cp.hungTool.url?.slice(0, 200),
|
|
614
|
+
completed_tools: cp.completedTools.length,
|
|
615
|
+
elapsed_ms: cp.elapsedMs,
|
|
616
|
+
resume_attempted: canResumeSession,
|
|
617
|
+
});
|
|
618
|
+
state.currentPrompt = canResumeSession
|
|
619
|
+
? this.buildResumeRetryPrompt(cp, state.timedOutTools)
|
|
620
|
+
: this.buildRetryPrompt(cp, promptWithAttachments, state.timedOutTools);
|
|
621
|
+
this.queueOutput(`\n[[MSTRO_AUTO_RETRY]] Auto-retry ${state.retryNumber}/${maxRetries}: ${canResumeSession ? 'Resuming session' : 'Continuing'} with ${cp.completedTools.length} successful results, skipping failed ${cp.hungTool.toolName}.\n`);
|
|
622
|
+
this.flushOutputQueue();
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Detect and retry after a signal crash (e.g., SIGTERM exit code 143).
|
|
627
|
+
* When the Claude process is killed externally (OOM, system signal, internal timeout
|
|
628
|
+
* that bypasses our watchdog), no existing recovery path catches it because contextLost
|
|
629
|
+
* is never set and no checkpoint is created. This adds a dedicated recovery path.
|
|
630
|
+
*/
|
|
631
|
+
shouldRetrySignalCrash(result, state, maxRetries, promptWithAttachments) {
|
|
632
|
+
// Only trigger for signal-killed processes (exit code 128+) that weren't already
|
|
633
|
+
// handled by context-loss or tool-timeout recovery paths.
|
|
634
|
+
// Must have an actual signal name — regular errors (e.g., auth failures, exit code 1)
|
|
635
|
+
// should NOT be retried as signal crashes.
|
|
636
|
+
const isSignalCrash = !!result.signalName;
|
|
637
|
+
const exitCodeSignal = !result.completed && !result.signalName && result.error?.match(/exited with code (1[2-9]\d|[2-9]\d{2})/);
|
|
638
|
+
if ((!isSignalCrash && !exitCodeSignal) || state.retryNumber >= maxRetries) {
|
|
639
|
+
return false;
|
|
640
|
+
}
|
|
641
|
+
// Don't re-trigger if tool timeout watchdog already handled this iteration
|
|
642
|
+
// (contextLost is NOT checked here — signal crash takes priority over context loss
|
|
643
|
+
// because it uses --resume which is lighter and avoids re-sending accumulated results)
|
|
644
|
+
if (state.checkpointRef.value) {
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
this.accumulateToolResults(result, state);
|
|
648
|
+
state.retryNumber++;
|
|
649
|
+
const completedCount = state.accumulatedToolResults.length;
|
|
650
|
+
const signalInfo = result.signalName || 'unknown signal';
|
|
651
|
+
const useResume = !!result.claudeSessionId && state.retryNumber === 1;
|
|
652
|
+
state.retryLog.push({
|
|
653
|
+
retryNumber: state.retryNumber,
|
|
654
|
+
path: 'SignalCrash',
|
|
655
|
+
reason: `Process killed (${signalInfo}), ${completedCount} tools preserved, ${useResume ? 'resuming' : 'fresh start'}`,
|
|
656
|
+
timestamp: Date.now(),
|
|
657
|
+
});
|
|
658
|
+
this.emit('onAutoRetry', {
|
|
659
|
+
retryNumber: state.retryNumber,
|
|
660
|
+
maxRetries,
|
|
661
|
+
toolName: `SignalCrash(${signalInfo})`,
|
|
662
|
+
completedCount,
|
|
663
|
+
});
|
|
664
|
+
trackEvent(AnalyticsEvents.IMPROVISE_AUTO_RETRY, {
|
|
665
|
+
retry_number: state.retryNumber,
|
|
666
|
+
hung_tool: `signal_crash:${signalInfo}`,
|
|
667
|
+
completed_tools: completedCount,
|
|
668
|
+
resume_attempted: useResume,
|
|
669
|
+
});
|
|
670
|
+
// If we have a session ID, try resuming first (preserves full context)
|
|
671
|
+
if (useResume) {
|
|
672
|
+
this.queueOutput(`\n[[MSTRO_SIGNAL_RECOVERY]] Process killed (${signalInfo}) — resuming session with ${completedCount} preserved results (retry ${state.retryNumber}/${maxRetries}).\n`);
|
|
673
|
+
this.flushOutputQueue();
|
|
674
|
+
state.contextRecoverySessionId = result.claudeSessionId;
|
|
675
|
+
this.claudeSessionId = result.claudeSessionId;
|
|
676
|
+
state.currentPrompt = this.buildSignalCrashRecoveryPrompt(promptWithAttachments, true);
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
// Fresh start with accumulated results injected
|
|
680
|
+
this.queueOutput(`\n[[MSTRO_SIGNAL_RECOVERY]] Process killed (${signalInfo}) — restarting with ${completedCount} preserved results (retry ${state.retryNumber}/${maxRetries}).\n`);
|
|
681
|
+
this.flushOutputQueue();
|
|
682
|
+
state.freshRecoveryMode = true;
|
|
683
|
+
const allResults = [...this.extractHistoricalToolResults(), ...state.accumulatedToolResults];
|
|
684
|
+
state.currentPrompt = this.buildSignalCrashRecoveryPrompt(promptWithAttachments, false, allResults);
|
|
685
|
+
}
|
|
686
|
+
return true;
|
|
687
|
+
}
|
|
688
|
+
/** Build a recovery prompt after signal crash */
|
|
689
|
+
buildSignalCrashRecoveryPrompt(originalPrompt, isResume, toolResults) {
|
|
690
|
+
const parts = [];
|
|
691
|
+
if (isResume) {
|
|
692
|
+
parts.push('Your previous execution was interrupted by a system signal (the process was killed externally).');
|
|
693
|
+
parts.push('Your full conversation history is preserved — including all successful tool results.');
|
|
694
|
+
parts.push('');
|
|
695
|
+
parts.push('Review your conversation history above and continue from where you left off.');
|
|
696
|
+
}
|
|
697
|
+
else {
|
|
698
|
+
parts.push('## AUTOMATIC RETRY — Previous Execution Interrupted');
|
|
699
|
+
parts.push('');
|
|
700
|
+
parts.push('The previous execution was interrupted by a system signal (process killed).');
|
|
701
|
+
if (toolResults && toolResults.length > 0) {
|
|
702
|
+
parts.push(`${toolResults.length} tool results were preserved from prior work.`);
|
|
703
|
+
parts.push('');
|
|
704
|
+
parts.push('### Preserved results:');
|
|
705
|
+
for (const t of toolResults.slice(-20)) {
|
|
706
|
+
const inputSummary = JSON.stringify(t.toolInput).slice(0, 120);
|
|
707
|
+
const resultPreview = (t.result ?? '').slice(0, 200);
|
|
708
|
+
parts.push(`- **${t.toolName}**(${inputSummary}): ${resultPreview}`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
parts.push('');
|
|
713
|
+
parts.push('### Original task:');
|
|
714
|
+
parts.push(originalPrompt);
|
|
715
|
+
parts.push('');
|
|
716
|
+
parts.push('INSTRUCTIONS:');
|
|
717
|
+
parts.push('1. Use the results above -- do not re-fetch content you already have');
|
|
718
|
+
parts.push('2. Continue from where you left off');
|
|
719
|
+
parts.push('3. Prefer multiple small, focused tool calls over single large ones');
|
|
720
|
+
parts.push('4. Do NOT spawn Task subagents — do work inline to avoid further interruptions');
|
|
721
|
+
return parts.join('\n');
|
|
722
|
+
}
|
|
723
|
+
/** Select the best result across retries using Haiku assessment */
|
|
724
|
+
async selectBestResult(state, result, userPrompt) {
|
|
725
|
+
if (!state.bestResult || state.bestResult === result || state.retryNumber === 0) {
|
|
726
|
+
return result;
|
|
727
|
+
}
|
|
728
|
+
const claudeCmd = process.env.CLAUDE_COMMAND || 'claude';
|
|
729
|
+
const bestToolCount = state.bestResult.toolUseHistory?.filter(t => t.result !== undefined && !t.isError).length ?? 0;
|
|
730
|
+
const currentToolCount = result.toolUseHistory?.filter(t => t.result !== undefined && !t.isError).length ?? 0;
|
|
731
|
+
try {
|
|
732
|
+
const verdict = await assessBestResult({
|
|
733
|
+
originalPrompt: userPrompt,
|
|
734
|
+
resultA: {
|
|
735
|
+
successfulToolCalls: bestToolCount,
|
|
736
|
+
responseLength: state.bestResult.assistantResponse?.length ?? 0,
|
|
737
|
+
hasThinking: !!state.bestResult.thinkingOutput,
|
|
738
|
+
responseTail: (state.bestResult.assistantResponse ?? '').slice(-500),
|
|
739
|
+
},
|
|
740
|
+
resultB: {
|
|
741
|
+
successfulToolCalls: currentToolCount,
|
|
742
|
+
responseLength: result.assistantResponse?.length ?? 0,
|
|
743
|
+
hasThinking: !!result.thinkingOutput,
|
|
744
|
+
responseTail: (result.assistantResponse ?? '').slice(-500),
|
|
745
|
+
},
|
|
746
|
+
}, claudeCmd, this.options.verbose);
|
|
747
|
+
if (verdict.winner === 'A') {
|
|
748
|
+
if (this.options.verbose)
|
|
749
|
+
console.log(`[BEST-RESULT] Haiku picked earlier attempt: ${verdict.reason}`);
|
|
750
|
+
return this.mergeResultSessionId(state.bestResult, result.claudeSessionId);
|
|
751
|
+
}
|
|
752
|
+
if (this.options.verbose)
|
|
753
|
+
console.log(`[BEST-RESULT] Haiku picked final attempt: ${verdict.reason}`);
|
|
754
|
+
return result;
|
|
755
|
+
}
|
|
756
|
+
catch {
|
|
757
|
+
return this.fallbackBestResult(state.bestResult, result);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
/** Fallback best result selection using numeric scoring */
|
|
761
|
+
fallbackBestResult(bestResult, result) {
|
|
762
|
+
if (scoreRunResult(bestResult) > scoreRunResult(result)) {
|
|
763
|
+
if (this.options.verbose) {
|
|
764
|
+
console.log(`[BEST-RESULT] Haiku unavailable, numeric fallback: earlier attempt (score ${scoreRunResult(bestResult)} vs ${scoreRunResult(result)})`);
|
|
765
|
+
}
|
|
766
|
+
return this.mergeResultSessionId(bestResult, result.claudeSessionId);
|
|
767
|
+
}
|
|
768
|
+
return result;
|
|
769
|
+
}
|
|
770
|
+
/** Replace a result's claudeSessionId with a newer one */
|
|
771
|
+
mergeResultSessionId(result, sessionId) {
|
|
772
|
+
if (sessionId)
|
|
773
|
+
return { ...result, claudeSessionId: sessionId };
|
|
774
|
+
return result;
|
|
775
|
+
}
|
|
776
|
+
/** Capture Claude session ID and surface execution failures */
|
|
777
|
+
captureSessionAndSurfaceErrors(result) {
|
|
778
|
+
if (result.claudeSessionId) {
|
|
779
|
+
this.claudeSessionId = result.claudeSessionId;
|
|
780
|
+
this.history.claudeSessionId = result.claudeSessionId;
|
|
781
|
+
}
|
|
782
|
+
if (!result.completed && result.error) {
|
|
783
|
+
this.queueOutput(`\n[[MSTRO_ERROR:EXECUTION_FAILED]] ${result.error}\n`);
|
|
784
|
+
this.flushOutputQueue();
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
/** Build a MovementRecord from execution result */
|
|
788
|
+
buildMovementRecord(result, userPrompt, sequenceNumber, execStart, retryLog) {
|
|
789
|
+
return {
|
|
790
|
+
id: `prompt-${sequenceNumber}`,
|
|
791
|
+
sequenceNumber,
|
|
792
|
+
userPrompt,
|
|
793
|
+
timestamp: new Date().toISOString(),
|
|
794
|
+
tokensUsed: result.totalTokens,
|
|
795
|
+
summary: '',
|
|
796
|
+
filesModified: [],
|
|
797
|
+
assistantResponse: result.assistantResponse,
|
|
798
|
+
thinkingOutput: result.thinkingOutput,
|
|
799
|
+
toolUseHistory: result.toolUseHistory?.map(t => ({
|
|
800
|
+
toolName: t.toolName,
|
|
801
|
+
toolId: t.toolId,
|
|
802
|
+
toolInput: t.toolInput,
|
|
803
|
+
result: t.result,
|
|
804
|
+
isError: t.isError,
|
|
805
|
+
duration: t.duration
|
|
806
|
+
})),
|
|
807
|
+
errorOutput: result.error,
|
|
808
|
+
durationMs: Date.now() - execStart,
|
|
809
|
+
retryLog: retryLog && retryLog.length > 0 ? retryLog : undefined,
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
/** Handle file conflicts from execution result */
|
|
813
|
+
handleConflicts(result) {
|
|
814
|
+
if (!result.conflicts || result.conflicts.length === 0)
|
|
815
|
+
return;
|
|
816
|
+
this.queueOutput(`\n⚠ File conflicts detected: ${result.conflicts.length}`);
|
|
817
|
+
result.conflicts.forEach(c => {
|
|
818
|
+
this.queueOutput(` - ${c.filePath} (modified by: ${c.modifiedBy.join(', ')})`);
|
|
819
|
+
if (c.backupPath) {
|
|
820
|
+
this.queueOutput(` Backup created: ${c.backupPath}`);
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
this.flushOutputQueue();
|
|
824
|
+
}
|
|
825
|
+
/** Persist movement to history */
|
|
826
|
+
persistMovement(movement) {
|
|
827
|
+
this.history.movements.push(movement);
|
|
828
|
+
this.history.totalTokens += movement.tokensUsed;
|
|
829
|
+
this.saveHistory();
|
|
830
|
+
}
|
|
831
|
+
/** Emit movement completion events and analytics */
|
|
832
|
+
emitMovementComplete(movement, result, execStart, sequenceNumber) {
|
|
833
|
+
this.emit('onMovementComplete', movement);
|
|
834
|
+
trackEvent(AnalyticsEvents.IMPROVISE_MOVEMENT_COMPLETED, {
|
|
835
|
+
tokens_used: movement.tokensUsed,
|
|
836
|
+
duration_ms: Date.now() - execStart,
|
|
837
|
+
sequence_number: sequenceNumber,
|
|
838
|
+
tool_count: result.toolUseHistory?.length || 0,
|
|
839
|
+
model: this.options.model || 'default',
|
|
840
|
+
});
|
|
841
|
+
this.emit('onSessionUpdate', this.getHistory());
|
|
842
|
+
}
|
|
301
843
|
/**
|
|
302
844
|
* Build historical context for resuming a session.
|
|
303
845
|
* This creates a summary of the previous conversation that will be injected
|
|
@@ -339,6 +881,253 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
339
881
|
contextParts.push('');
|
|
340
882
|
return contextParts.join('\n');
|
|
341
883
|
}
|
|
884
|
+
/**
|
|
885
|
+
* Build a retry prompt from a tool timeout checkpoint.
|
|
886
|
+
* Injects completed tool results and instructs Claude to skip the failed resource.
|
|
887
|
+
*/
|
|
888
|
+
buildRetryPrompt(checkpoint, originalPrompt, allTimedOut) {
|
|
889
|
+
const urlSuffix = checkpoint.hungTool.url ? ` while fetching: ${checkpoint.hungTool.url}` : '';
|
|
890
|
+
const parts = [
|
|
891
|
+
'## AUTOMATIC RETRY -- Previous Execution Interrupted',
|
|
892
|
+
'',
|
|
893
|
+
`The previous execution was interrupted because ${checkpoint.hungTool.toolName} timed out after ${Math.round(checkpoint.hungTool.timeoutMs / 1000)}s${urlSuffix}.`,
|
|
894
|
+
'',
|
|
895
|
+
];
|
|
896
|
+
if (allTimedOut && allTimedOut.length > 0) {
|
|
897
|
+
parts.push(...this.formatTimedOutTools(allTimedOut), '');
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
parts.push('This URL/resource is unreachable. DO NOT retry the same URL or query.', '');
|
|
901
|
+
}
|
|
902
|
+
if (checkpoint.completedTools.length > 0) {
|
|
903
|
+
parts.push(...this.formatCompletedTools(checkpoint.completedTools), '');
|
|
904
|
+
}
|
|
905
|
+
if (checkpoint.inProgressTools && checkpoint.inProgressTools.length > 0) {
|
|
906
|
+
parts.push(...this.formatInProgressTools(checkpoint.inProgressTools), '');
|
|
907
|
+
}
|
|
908
|
+
if (checkpoint.assistantText) {
|
|
909
|
+
const preview = checkpoint.assistantText.length > 8000
|
|
910
|
+
? `${checkpoint.assistantText.slice(0, 8000)}...\n(truncated — full response was ${checkpoint.assistantText.length} chars)`
|
|
911
|
+
: checkpoint.assistantText;
|
|
912
|
+
parts.push('### Your response before interruption:', preview, '');
|
|
913
|
+
}
|
|
914
|
+
parts.push('### Original task (continue from where you left off):');
|
|
915
|
+
parts.push(originalPrompt);
|
|
916
|
+
parts.push('');
|
|
917
|
+
parts.push('INSTRUCTIONS:');
|
|
918
|
+
parts.push('1. Use the results above -- do not re-fetch content you already have');
|
|
919
|
+
parts.push('2. Find ALTERNATIVE sources for the content that timed out (different URL, different approach)');
|
|
920
|
+
parts.push('3. Re-run any in-progress tools that were lost (listed above) if their results are needed');
|
|
921
|
+
parts.push('4. If no alternative exists, proceed with the results you have and note what was unavailable');
|
|
922
|
+
return parts.join('\n');
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Build a short retry prompt for --resume sessions.
|
|
926
|
+
* The session already has full conversation context, so we only need to
|
|
927
|
+
* explain what timed out and instruct Claude to continue.
|
|
928
|
+
*/
|
|
929
|
+
buildResumeRetryPrompt(checkpoint, allTimedOut) {
|
|
930
|
+
const parts = [];
|
|
931
|
+
parts.push(`Your previous ${checkpoint.hungTool.toolName} call timed out after ${Math.round(checkpoint.hungTool.timeoutMs / 1000)}s${checkpoint.hungTool.url ? ` fetching: ${checkpoint.hungTool.url}` : ''}.`);
|
|
932
|
+
// List all timed-out tools across retries so Claude avoids repeating them
|
|
933
|
+
if (allTimedOut && allTimedOut.length > 1) {
|
|
934
|
+
parts.push('');
|
|
935
|
+
parts.push('All timed-out tools/resources (DO NOT retry any of these):');
|
|
936
|
+
for (const t of allTimedOut) {
|
|
937
|
+
const inputSummary = this.summarizeToolInput(t.input);
|
|
938
|
+
parts.push(`- ${t.toolName}(${inputSummary})`);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
else {
|
|
942
|
+
parts.push('This URL/resource is unreachable. DO NOT retry the same URL or query.');
|
|
943
|
+
}
|
|
944
|
+
parts.push('Continue your task — find an alternative source or proceed with the results you already have.');
|
|
945
|
+
return parts.join('\n');
|
|
946
|
+
}
|
|
947
|
+
// Context loss detection is now handled by assessContextLoss() in stall-assessor.ts
|
|
948
|
+
// using Haiku assessment instead of brittle regex patterns.
|
|
949
|
+
/**
|
|
950
|
+
* Build a recovery prompt for --resume after context loss.
|
|
951
|
+
* Since we're resuming the same session, Claude has full conversation history
|
|
952
|
+
* (including all preserved tool results). We just need to redirect it back to the task.
|
|
953
|
+
*/
|
|
954
|
+
buildContextRecoveryPrompt(originalPrompt) {
|
|
955
|
+
const parts = [];
|
|
956
|
+
parts.push('Your previous response indicated you lost context due to tool timeouts, but your full conversation history is preserved — including all successful tool results.');
|
|
957
|
+
parts.push('');
|
|
958
|
+
parts.push('Review your conversation history above. You already have results from many successful tool calls. Use those results to continue the task.');
|
|
959
|
+
parts.push('');
|
|
960
|
+
parts.push('Original task:');
|
|
961
|
+
parts.push(originalPrompt);
|
|
962
|
+
parts.push('');
|
|
963
|
+
parts.push('INSTRUCTIONS:');
|
|
964
|
+
parts.push('1. Review your conversation history — all your previous tool results are still available');
|
|
965
|
+
parts.push('2. Continue from where you left off using the results you already gathered');
|
|
966
|
+
parts.push('3. If specific tool calls timed out, skip those and work with what you have');
|
|
967
|
+
parts.push('4. Do NOT start over — build on the work already done');
|
|
968
|
+
parts.push('5. Do NOT spawn Task subagents for work that previously timed out — do it inline instead');
|
|
969
|
+
parts.push('6. Prefer multiple small, focused tool calls over single large ones to avoid further timeouts');
|
|
970
|
+
return parts.join('\n');
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Build a recovery prompt for a fresh session (no --resume) after repeated context loss.
|
|
974
|
+
* Injects all accumulated tool results from previous attempts so Claude can continue
|
|
975
|
+
* the task without re-fetching data it already gathered.
|
|
976
|
+
*/
|
|
977
|
+
buildFreshRecoveryPrompt(originalPrompt, toolResults, timedOutTools) {
|
|
978
|
+
const parts = [
|
|
979
|
+
'## CONTINUING LONG-RUNNING TASK',
|
|
980
|
+
'',
|
|
981
|
+
'The previous execution encountered tool timeouts and lost context.',
|
|
982
|
+
'Below are all results gathered before the interruption. Continue the task using these results.',
|
|
983
|
+
'',
|
|
984
|
+
];
|
|
985
|
+
if (timedOutTools && timedOutTools.length > 0) {
|
|
986
|
+
parts.push(...this.formatTimedOutTools(timedOutTools), '');
|
|
987
|
+
}
|
|
988
|
+
parts.push(...this.formatToolResults(toolResults));
|
|
989
|
+
parts.push('### Original task:');
|
|
990
|
+
parts.push(originalPrompt);
|
|
991
|
+
parts.push('');
|
|
992
|
+
parts.push('INSTRUCTIONS:');
|
|
993
|
+
parts.push('1. Use the preserved results above \u2014 do NOT re-fetch data you already have');
|
|
994
|
+
parts.push('2. Continue the task from where it was interrupted');
|
|
995
|
+
parts.push('3. If you need additional data, fetch it (but try alternative sources if the original timed out)');
|
|
996
|
+
parts.push('4. Complete the original task fully');
|
|
997
|
+
parts.push('5. Do NOT spawn Task subagents for work that previously timed out \u2014 do it inline instead');
|
|
998
|
+
parts.push('6. Prefer multiple small, focused tool calls over single large ones to avoid further timeouts');
|
|
999
|
+
return parts.join('\n');
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Extract tool results from the last N movements in history.
|
|
1003
|
+
* Used for inter-movement recovery to provide context from prior work
|
|
1004
|
+
* when a resume session is corrupted/expired.
|
|
1005
|
+
*/
|
|
1006
|
+
extractHistoricalToolResults(maxMovements = 3) {
|
|
1007
|
+
const results = [];
|
|
1008
|
+
const recentMovements = this.history.movements.slice(-maxMovements);
|
|
1009
|
+
for (const movement of recentMovements) {
|
|
1010
|
+
if (!movement.toolUseHistory)
|
|
1011
|
+
continue;
|
|
1012
|
+
for (const tool of movement.toolUseHistory) {
|
|
1013
|
+
if (tool.result !== undefined && !tool.isError) {
|
|
1014
|
+
results.push({
|
|
1015
|
+
toolName: tool.toolName,
|
|
1016
|
+
toolId: tool.toolId,
|
|
1017
|
+
toolInput: tool.toolInput,
|
|
1018
|
+
result: tool.result,
|
|
1019
|
+
isError: tool.isError,
|
|
1020
|
+
duration: tool.duration,
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
return results;
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Build a recovery prompt for inter-movement context loss.
|
|
1029
|
+
* The Claude session expired between movements (not due to native timeouts).
|
|
1030
|
+
* Includes prior conversation summary + preserved tool results + anti-timeout guidance.
|
|
1031
|
+
*/
|
|
1032
|
+
buildInterMovementRecoveryPrompt(originalPrompt, toolResults) {
|
|
1033
|
+
const parts = [
|
|
1034
|
+
'## SESSION RECOVERY — Prior Session Expired',
|
|
1035
|
+
'',
|
|
1036
|
+
'Your previous session expired between prompts. Below is a summary of the conversation so far and all preserved tool results.',
|
|
1037
|
+
'',
|
|
1038
|
+
];
|
|
1039
|
+
parts.push(...this.formatConversationHistory(this.history.movements));
|
|
1040
|
+
parts.push(...this.formatToolResults(toolResults));
|
|
1041
|
+
parts.push('### Current user prompt:');
|
|
1042
|
+
parts.push(originalPrompt);
|
|
1043
|
+
parts.push('');
|
|
1044
|
+
parts.push('INSTRUCTIONS:');
|
|
1045
|
+
parts.push('1. Use the preserved results above — do NOT re-fetch data you already have');
|
|
1046
|
+
parts.push('2. Continue the conversation naturally based on the history above');
|
|
1047
|
+
parts.push('3. If you need additional data, fetch it with small focused tool calls');
|
|
1048
|
+
parts.push('4. Do NOT spawn Task subagents — do work inline to avoid further timeouts');
|
|
1049
|
+
parts.push('5. Prefer multiple small, focused tool calls over single large ones');
|
|
1050
|
+
return parts.join('\n');
|
|
1051
|
+
}
|
|
1052
|
+
/** Summarize a tool input for display in retry prompts */
|
|
1053
|
+
summarizeToolInput(input) {
|
|
1054
|
+
if (input.url)
|
|
1055
|
+
return String(input.url).slice(0, 100);
|
|
1056
|
+
if (input.query)
|
|
1057
|
+
return String(input.query).slice(0, 100);
|
|
1058
|
+
if (input.command)
|
|
1059
|
+
return String(input.command).slice(0, 100);
|
|
1060
|
+
if (input.prompt)
|
|
1061
|
+
return String(input.prompt).slice(0, 100);
|
|
1062
|
+
return JSON.stringify(input).slice(0, 100);
|
|
1063
|
+
}
|
|
1064
|
+
/** Format a list of timed-out tools for retry prompts */
|
|
1065
|
+
formatTimedOutTools(tools) {
|
|
1066
|
+
const lines = [];
|
|
1067
|
+
lines.push('### Tools/resources that have timed out (DO NOT retry these):');
|
|
1068
|
+
for (const t of tools) {
|
|
1069
|
+
const inputSummary = this.summarizeToolInput(t.input);
|
|
1070
|
+
lines.push(`- **${t.toolName}**(${inputSummary}) — timed out after ${Math.round(t.timeoutMs / 1000)}s`);
|
|
1071
|
+
}
|
|
1072
|
+
return lines;
|
|
1073
|
+
}
|
|
1074
|
+
/** Format completed checkpoint tools for retry prompts */
|
|
1075
|
+
formatCompletedTools(tools, maxLen = 2000) {
|
|
1076
|
+
const lines = [];
|
|
1077
|
+
lines.push('### Results already obtained:');
|
|
1078
|
+
for (const tool of tools) {
|
|
1079
|
+
const inputSummary = this.summarizeToolInput(tool.input);
|
|
1080
|
+
const preview = tool.result.length > maxLen ? `${tool.result.slice(0, maxLen)}...` : tool.result;
|
|
1081
|
+
lines.push(`- **${tool.toolName}**(${inputSummary}): ${preview}`);
|
|
1082
|
+
}
|
|
1083
|
+
return lines;
|
|
1084
|
+
}
|
|
1085
|
+
/** Format in-progress tools for retry prompts */
|
|
1086
|
+
formatInProgressTools(tools) {
|
|
1087
|
+
const lines = [];
|
|
1088
|
+
lines.push('### Tools that were still running (lost when process was killed):');
|
|
1089
|
+
for (const tool of tools) {
|
|
1090
|
+
const inputSummary = this.summarizeToolInput(tool.input);
|
|
1091
|
+
lines.push(`- **${tool.toolName}**(${inputSummary}) — was in progress, may need re-running`);
|
|
1092
|
+
}
|
|
1093
|
+
return lines;
|
|
1094
|
+
}
|
|
1095
|
+
/** Format tool results from ToolUseRecord[] for recovery prompts */
|
|
1096
|
+
formatToolResults(toolResults, maxLen = 3000) {
|
|
1097
|
+
const completed = toolResults.filter(t => t.result !== undefined && !t.isError);
|
|
1098
|
+
if (completed.length === 0)
|
|
1099
|
+
return [];
|
|
1100
|
+
const lines = [`### ${completed.length} preserved results from prior work:`, ''];
|
|
1101
|
+
for (const tool of completed) {
|
|
1102
|
+
const inputSummary = this.summarizeToolInput(tool.toolInput);
|
|
1103
|
+
const preview = tool.result && tool.result.length > maxLen
|
|
1104
|
+
? `${tool.result.slice(0, maxLen)}...\n(truncated, ${tool.result.length} chars total)`
|
|
1105
|
+
: tool.result || '';
|
|
1106
|
+
lines.push(`**${tool.toolName}**(${inputSummary}):`);
|
|
1107
|
+
lines.push(preview);
|
|
1108
|
+
lines.push('');
|
|
1109
|
+
}
|
|
1110
|
+
return lines;
|
|
1111
|
+
}
|
|
1112
|
+
/** Format conversation history for recovery prompts */
|
|
1113
|
+
formatConversationHistory(movements, maxMovements = 5) {
|
|
1114
|
+
const recent = movements.slice(-maxMovements);
|
|
1115
|
+
if (recent.length === 0)
|
|
1116
|
+
return [];
|
|
1117
|
+
const lines = ['### Conversation so far:'];
|
|
1118
|
+
for (const movement of recent) {
|
|
1119
|
+
const promptText = movement.userPrompt.length > 300 ? `${movement.userPrompt.slice(0, 300)}...` : movement.userPrompt;
|
|
1120
|
+
lines.push(`**User (prompt ${movement.sequenceNumber}):** ${promptText}`);
|
|
1121
|
+
if (movement.assistantResponse) {
|
|
1122
|
+
const response = movement.assistantResponse.length > 1000
|
|
1123
|
+
? `${movement.assistantResponse.slice(0, 1000)}...\n(truncated, ${movement.assistantResponse.length} chars)`
|
|
1124
|
+
: movement.assistantResponse;
|
|
1125
|
+
lines.push(`**Your response:** ${response}`);
|
|
1126
|
+
}
|
|
1127
|
+
lines.push('');
|
|
1128
|
+
}
|
|
1129
|
+
return lines;
|
|
1130
|
+
}
|
|
342
1131
|
/**
|
|
343
1132
|
* Load history from disk
|
|
344
1133
|
*/
|
|
@@ -377,6 +1166,7 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
377
1166
|
* Cancel current execution
|
|
378
1167
|
*/
|
|
379
1168
|
cancel() {
|
|
1169
|
+
this._cancelled = true;
|
|
380
1170
|
if (this.currentRunner) {
|
|
381
1171
|
this.currentRunner.cleanup();
|
|
382
1172
|
this.currentRunner = null;
|
|
@@ -404,6 +1194,7 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
404
1194
|
this.accumulatedKnowledge = '';
|
|
405
1195
|
this.isFirstPrompt = true; // Reset to start fresh Claude session
|
|
406
1196
|
this.claudeSessionId = undefined; // Clear Claude session ID to start new conversation
|
|
1197
|
+
this.cleanupAttachments();
|
|
407
1198
|
this.saveHistory();
|
|
408
1199
|
this.emit('onSessionUpdate', this.getHistory());
|
|
409
1200
|
}
|
|
@@ -445,6 +1236,12 @@ export class ImprovisationSessionManager extends EventEmitter {
|
|
|
445
1236
|
get isExecuting() {
|
|
446
1237
|
return this._isExecuting;
|
|
447
1238
|
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Timestamp when current execution started (undefined when not executing)
|
|
1241
|
+
*/
|
|
1242
|
+
get executionStartTimestamp() {
|
|
1243
|
+
return this._executionStartTimestamp;
|
|
1244
|
+
}
|
|
448
1245
|
/**
|
|
449
1246
|
* Get buffered execution events for replay on reconnect.
|
|
450
1247
|
* Only meaningful while isExecuting is true.
|