arco-workbench 0.1.8 → 0.1.9
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/CONTRIBUTING.md +11 -0
- package/README.md +7 -5
- package/client/dist/assets/{PhosphorBackdrop-D7jdAV_G.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-DrDm60h8.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
- package/client/dist/assets/{XtermView-BGFujb1e.js → XtermView-Xk7_9JaH.js} +1 -1
- package/client/dist/assets/{galleryEditor-D951A2sE.js → galleryEditor-CI8ClzBa.js} +1 -1
- package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
- package/client/dist/assets/{index-CsVy3eZm.js → index-C7WzZfsr.js} +246 -244
- package/client/dist/index.html +2 -2
- package/client/src/App.tsx +2 -0
- package/client/src/components/ChatMessage.tsx +33 -8
- package/client/src/components/ChatModeView.tsx +2 -0
- package/client/src/components/ClusterRightPanel/SkillsControl.tsx +25 -8
- package/client/src/components/CodexLateCommand.tsx +34 -0
- package/client/src/components/DialogShell.tsx +2 -0
- package/client/src/components/MemberCard.tsx +4 -1
- package/client/src/components/MemberPane.tsx +3 -1
- package/client/src/components/PhoneUpload.tsx +288 -0
- package/client/src/components/PrimaryStatus.tsx +14 -6
- package/client/src/components/RuntimeStateBanner.tsx +5 -0
- package/client/src/components/SkillEditorDialog.tsx +2 -2
- package/client/src/components/SkillsSettings.tsx +17 -5
- package/client/src/components/TerminalInput.tsx +3 -1
- package/client/src/components/WorkflowView.tsx +2 -0
- package/client/src/explorer/ArtifactsLens.tsx +37 -28
- package/client/src/explorer/ExplorerApp.tsx +5 -4
- package/client/src/explorer/types.ts +8 -3
- package/client/src/help/content/cluster.tsx +11 -1
- package/client/src/help/content/composer.tsx +18 -1
- package/client/src/help/content/header.tsx +2 -1
- package/client/src/help/content/misc.tsx +1 -1
- package/client/src/help/content/settings.tsx +1 -1
- package/client/src/help/manualSections/clusters.tsx +3 -0
- package/client/src/help/manualSections/configuration.tsx +3 -1
- package/client/src/help/manualSections/gettingStarted.tsx +4 -4
- package/client/src/help/manualSections/maintenance.tsx +7 -6
- package/client/src/help/manualSections/powerFeatures.tsx +3 -2
- package/client/src/help/manualSections/workspace.tsx +30 -0
- package/client/src/stores/appStore.ts +7 -0
- package/client/src/stores/appStore.types.ts +4 -0
- package/client/src/styles/global.css +109 -0
- package/client/src/utils/phoneTheme.ts +38 -0
- package/client/src/utils/phoneUploadApi.ts +10 -0
- package/client/src/ws/handleServerMessage.ts +23 -6
- package/docs/CLIENT.md +7 -1
- package/docs/FEATURES.md +6 -3
- package/docs/GETTING_STARTED.md +8 -3
- package/docs/INDEX.md +1 -1
- package/docs/OPERATIONS.md +199 -48
- package/docs/PROTOCOL_CLUSTER.md +9 -1
- package/docs/PROVIDERS.md +34 -0
- package/docs/SETTINGS.md +5 -3
- package/native/darwin-arm64/manifest.json +1 -1
- package/native/linux-x64/manifest.json +1 -1
- package/native/win32-x64/manifest.json +1 -1
- package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -0
- package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +11 -0
- package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/server/dist/clusterDirector.js +1 -0
- package/server/dist/clusterPeerOps.js +4 -1
- package/server/dist/clusterRehydrate.js +2 -0
- package/server/dist/explorerDocs.d.ts +10 -6
- package/server/dist/explorerDocs.js +75 -34
- package/server/dist/http/attachmentUpload.d.ts +13 -0
- package/server/dist/http/attachmentUpload.js +38 -0
- package/server/dist/http/browserWorktrees.d.ts +23 -0
- package/server/dist/http/browserWorktrees.js +120 -0
- package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
- package/server/dist/http/phoneUploadDrafts.js +125 -0
- package/server/dist/http/phoneUploadListener.d.ts +17 -0
- package/server/dist/http/phoneUploadListener.js +81 -0
- package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
- package/server/dist/http/phoneUploadNetwork.js +106 -0
- package/server/dist/http/phoneUploadPage.d.ts +2 -0
- package/server/dist/http/phoneUploadPage.js +136 -0
- package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
- package/server/dist/http/phoneUploadRouteHistory.js +72 -0
- package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
- package/server/dist/http/phoneUploadRoutes.js +419 -0
- package/server/dist/http/phoneUploadTheme.d.ts +17 -0
- package/server/dist/http/phoneUploadTheme.js +96 -0
- package/server/dist/http/projectBinding.d.ts +1 -0
- package/server/dist/http/projectBinding.js +3 -2
- package/server/dist/http/readConfinement.js +5 -1
- package/server/dist/http/router.js +13 -24
- package/server/dist/http/writeConfinement.js +19 -2
- package/server/dist/primitives/seedWorker.d.ts +1 -0
- package/server/dist/primitives/seedWorker.js +2 -1
- package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
- package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
- package/server/dist/providers/codex-appserver/index.d.ts +52 -2
- package/server/dist/providers/codex-appserver/index.js +239 -21
- package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
- package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
- package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
- package/server/dist/providers/codex-appserver/worker.js +89 -20
- package/server/dist/providers/codex.js +2 -2
- package/server/dist/providers/codexCodeMode.d.ts +2 -1
- package/server/dist/providers/codexCodeMode.js +7 -3
- package/server/dist/workers/WorkerManager.d.ts +1 -0
- package/server/dist/workers/WorkerManager.js +1 -0
- package/server/dist/workers/processKill.d.ts +9 -1
- package/server/dist/workers/processKill.js +26 -10
- package/server/dist/ws/handoffHandlers.js +2 -0
- package/server/dist/ws/turnEngine.js +17 -0
- package/server/package.json +1 -1
- package/server/src/clusterDirector.ts +1 -0
- package/server/src/clusterPeerOps.ts +4 -1
- package/server/src/clusterRehydrate.ts +2 -0
- package/server/src/explorerDocs.ts +75 -34
- package/server/src/http/attachmentUpload.ts +49 -0
- package/server/src/http/browserWorktrees.ts +124 -0
- package/server/src/http/phoneUploadDrafts.ts +118 -0
- package/server/src/http/phoneUploadListener.ts +96 -0
- package/server/src/http/phoneUploadNetwork.ts +117 -0
- package/server/src/http/phoneUploadPage.ts +137 -0
- package/server/src/http/phoneUploadRouteHistory.ts +73 -0
- package/server/src/http/phoneUploadRoutes.ts +398 -0
- package/server/src/http/phoneUploadTheme.ts +97 -0
- package/server/src/http/projectBinding.ts +3 -2
- package/server/src/http/readConfinement.ts +5 -1
- package/server/src/http/router.ts +11 -25
- package/server/src/http/writeConfinement.ts +13 -2
- package/server/src/primitives/seedWorker.ts +3 -1
- package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
- package/server/src/providers/codex-appserver/index.ts +222 -20
- package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
- package/server/src/providers/codex-appserver/worker.ts +85 -21
- package/server/src/providers/codex.ts +2 -2
- package/server/src/providers/codexCodeMode.ts +8 -3
- package/server/src/workers/WorkerManager.ts +2 -0
- package/server/src/workers/processKill.ts +35 -7
- package/server/src/ws/handoffHandlers.ts +2 -0
- package/server/src/ws/turnEngine.ts +15 -0
- package/shared/dist/protocol/chat.d.ts +1 -0
- package/shared/dist/protocol/clusters.d.ts +2 -0
- package/shared/dist/protocol/serverMessages.d.ts +11 -0
- package/shared/dist/protocol/workflows.d.ts +1 -0
- package/shared/src/protocol/chat.ts +1 -0
- package/shared/src/protocol/clusters.ts +4 -5
- package/shared/src/protocol/serverMessages.ts +11 -0
- package/shared/src/protocol/workflows.ts +4 -0
|
@@ -225,6 +225,7 @@ export function runPrimaryTurn(
|
|
|
225
225
|
// ignore it; the post-turn drain still picks up anything not consumed.
|
|
226
226
|
drainSteer?: () => SteerItem[];
|
|
227
227
|
peekSteer?: () => readonly SteerItem[];
|
|
228
|
+
pendingInput?: WorkerConfig['pendingInput'];
|
|
228
229
|
// Phase 6b — paired with drainSteer for the Codex app-server worker.
|
|
229
230
|
// Symmetrical contract — same scoping (primary-turn only), same
|
|
230
231
|
// in-process callback shape. Called when a `turn/steer` round-trip
|
|
@@ -359,7 +360,7 @@ export function runPrimaryTurn(
|
|
|
359
360
|
webSearchMaxUses?: number;
|
|
360
361
|
},
|
|
361
362
|
): TurnHandle {
|
|
362
|
-
const { primary, prompt, resumeSessionId, attachments, disableRssGuard, appendSystemPrompt, systemPrompt, interactionMode, disableProviderHooks, chatWebAccess, voiceOperator, incognito, drainSteer, peekSteer, requeueSteer, onSteerDelivered, codexTransport, codexContextPolicy, providerAccountRef, codexHome, claudeTransport, ultracode, claudeNativeTaskDisabled, claudeNativeSubagent, claudeNativeCompact, claudeNativeInTurnCompactPercent, claudeNativeForceInterleavedThinkingBeta, claudeNativeThinkingDisplay, nativeSubagents, claudeNativePlanModeArmed, turnNotice, efficiencyToolFilter, efficiencyFactForce, efficiencyConfigProtection, efficiencySandbox, reviewSafeMode, outputStyle, goal, toolPosture, clusterId, clusterAccessMode, executionCwd, persistenceCwd, clusterTaskBoardAttached, clusterPlan, clusterRole, clusterEfficiencyDoctrine, clusterProgressDoctrine, clusterMcpConfigPath, codebaseMemoryAttached, codebaseMemoryIndexPath, mcpRegistryServers, mcpDisallowedTools, ollamaParams, webSearchMaxUses } = args;
|
|
363
|
+
const { primary, prompt, resumeSessionId, attachments, disableRssGuard, appendSystemPrompt, systemPrompt, interactionMode, disableProviderHooks, chatWebAccess, voiceOperator, incognito, drainSteer, peekSteer, pendingInput, requeueSteer, onSteerDelivered, codexTransport, codexContextPolicy, providerAccountRef, codexHome, claudeTransport, ultracode, claudeNativeTaskDisabled, claudeNativeSubagent, claudeNativeCompact, claudeNativeInTurnCompactPercent, claudeNativeForceInterleavedThinkingBeta, claudeNativeThinkingDisplay, nativeSubagents, claudeNativePlanModeArmed, turnNotice, efficiencyToolFilter, efficiencyFactForce, efficiencyConfigProtection, efficiencySandbox, reviewSafeMode, outputStyle, goal, toolPosture, clusterId, clusterAccessMode, executionCwd, persistenceCwd, clusterTaskBoardAttached, clusterPlan, clusterRole, clusterEfficiencyDoctrine, clusterProgressDoctrine, clusterMcpConfigPath, codebaseMemoryAttached, codebaseMemoryIndexPath, mcpRegistryServers, mcpDisallowedTools, ollamaParams, webSearchMaxUses } = args;
|
|
363
364
|
|
|
364
365
|
const workerId = `primary-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
365
366
|
|
|
@@ -403,6 +404,7 @@ export function runPrimaryTurn(
|
|
|
403
404
|
disableRssGuard,
|
|
404
405
|
drainSteer,
|
|
405
406
|
peekSteer,
|
|
407
|
+
pendingInput,
|
|
406
408
|
requeueSteer,
|
|
407
409
|
onSteerDelivered,
|
|
408
410
|
codexTransport,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// docs/PROVIDERS.md - a Codex app-server turn that ends while a command the
|
|
2
|
+
// agent started is still running is not over for Arco. These limits bound the
|
|
3
|
+
// wait and the text that carries each result back to the agent.
|
|
4
|
+
import type { HeldCommandResult } from './lateCommands.js';
|
|
5
|
+
|
|
6
|
+
export const HELD_WAIT_LIMIT_MS = 30 * 60_000;
|
|
7
|
+
export const HELD_CONTINUATION_LIMIT = 20;
|
|
8
|
+
export const HELD_OUTPUT_CHARS = 4_000;
|
|
9
|
+
// Results in one message; any further results in the same batch keep their
|
|
10
|
+
// exit code but not their output.
|
|
11
|
+
export const HELD_RESULTS_WITH_OUTPUT = 8;
|
|
12
|
+
// Ends this close together go to the agent in one continuation.
|
|
13
|
+
export const HELD_BATCH_MS = 2_000;
|
|
14
|
+
|
|
15
|
+
export function formatDuration(ms: number): string {
|
|
16
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
17
|
+
if (seconds < 60) return `${seconds}s`;
|
|
18
|
+
const minutes = Math.floor(seconds / 60);
|
|
19
|
+
if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
|
|
20
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function shortCommand(command: string, max = 160): string {
|
|
24
|
+
const flat = command.replace(/\s+/g, ' ').trim();
|
|
25
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function outcome(result: HeldCommandResult): string {
|
|
29
|
+
return typeof result.exitCode === 'number' ? `exit ${result.exitCode}` : result.failed ? 'failed' : 'ended';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The operator-visible line for one delivered result. */
|
|
33
|
+
export function heldResultNotice(result: HeldCommandResult, continues: boolean): string {
|
|
34
|
+
return `Command ended: \`${shortCommand(result.command)}\` - ${outcome(result)} after ${formatDuration(result.endedAt - result.startedAt)}.${continues ? ' Codex continues.' : ''}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The text Codex receives: each result once, output tail capped. */
|
|
38
|
+
export function heldResultsMessage(results: HeldCommandResult[], stillRunning: Array<{ command: string }>): string {
|
|
39
|
+
const parts = ['[Arco] A command you started has ended since your last reply. This is its result, observed by Arco; it is not from the operator.'];
|
|
40
|
+
results.forEach((result, index) => {
|
|
41
|
+
const lines = [
|
|
42
|
+
`Command: ${result.command}`,
|
|
43
|
+
...(result.cwd ? [`Working directory: ${result.cwd}`] : []),
|
|
44
|
+
`Result: ${outcome(result)} after ${formatDuration(result.endedAt - result.startedAt)}`,
|
|
45
|
+
];
|
|
46
|
+
if (index < HELD_RESULTS_WITH_OUTPUT) {
|
|
47
|
+
const output = result.output ?? '';
|
|
48
|
+
const tail = output.length > HELD_OUTPUT_CHARS ? output.slice(-HELD_OUTPUT_CHARS) : output;
|
|
49
|
+
lines.push(output.length > HELD_OUTPUT_CHARS
|
|
50
|
+
? `Output (last ${HELD_OUTPUT_CHARS} of ${output.length} characters):\n${tail}`
|
|
51
|
+
: `Output:\n${tail || '(none)'}`);
|
|
52
|
+
} else lines.push('Output: not included; too many results in one message.');
|
|
53
|
+
parts.push(lines.join('\n'));
|
|
54
|
+
});
|
|
55
|
+
if (stillRunning.length) parts.push(`Still running: ${stillRunning.map(item => shortCommand(item.command)).join('; ')}. Arco tells you when ${stillRunning.length === 1 ? 'it ends' : 'they end'}.`);
|
|
56
|
+
parts.push('Continue the work.');
|
|
57
|
+
return parts.join('\n\n');
|
|
58
|
+
}
|
|
@@ -12,12 +12,17 @@ import { providerSessionScope } from '../sessionScope.js';
|
|
|
12
12
|
// to tear down the long-lived child when the operator closes the tab.
|
|
13
13
|
|
|
14
14
|
import { EventEmitter } from 'events';
|
|
15
|
-
import type { WorkerConfig, WorkerStatus } from '@arco/shared';
|
|
15
|
+
import type { PrimaryToolUseMessage, WorkerConfig, WorkerStatus } from '@arco/shared';
|
|
16
16
|
import type { Provider, ProviderProcess } from '../types.js';
|
|
17
17
|
import { CodexAppServerWorker, computeMcpSignature, bootstrapSurfaceKey, type ToolUseEvent, type PrimaryArtifactEvent, type TurnSettleData } from './worker.js';
|
|
18
18
|
import { codexContextWindowOverride } from '../codexContextWindow.js';
|
|
19
19
|
import { allowVoiceTools, blockVoiceTools, observeVoiceTools } from '../../voice/operatorTools.js';
|
|
20
20
|
import { ComputerTurnWatchdog } from '../../voice/turnWatchdog.js';
|
|
21
|
+
import type { SteerItem } from '@arco/shared';
|
|
22
|
+
import {
|
|
23
|
+
HELD_BATCH_MS, HELD_CONTINUATION_LIMIT, HELD_WAIT_LIMIT_MS,
|
|
24
|
+
formatDuration, heldResultNotice, heldResultsMessage, shortCommand,
|
|
25
|
+
} from './heldCommands.js';
|
|
21
26
|
|
|
22
27
|
const workersByWorkflow = new Map<string, CodexAppServerWorker>();
|
|
23
28
|
const compactReservations = new Map<string, CodexAppServerWorker>();
|
|
@@ -70,7 +75,7 @@ function resetFailureCount(workflowId: string): void {
|
|
|
70
75
|
|
|
71
76
|
// One operator turn against the long-lived worker. ProviderProcess shape
|
|
72
77
|
// preserved so WorkerManager / seedWorker can stay unchanged.
|
|
73
|
-
class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
78
|
+
export class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
74
79
|
readonly id: string;
|
|
75
80
|
private _status: WorkerStatus = 'spawning';
|
|
76
81
|
private _output = '';
|
|
@@ -86,6 +91,24 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
86
91
|
private watchdog?: ComputerTurnWatchdog;
|
|
87
92
|
private stopToolObserver?: () => void;
|
|
88
93
|
private timeoutReason?: string;
|
|
94
|
+
// docs/PROVIDERS.md - the Arco turn stays open while a command the agent
|
|
95
|
+
// started is still running after its Codex turn completed. Each Codex turn
|
|
96
|
+
// inside it adds its cost; the result is reported once, at the end.
|
|
97
|
+
private readonly startedAt = Date.now();
|
|
98
|
+
private costUsd = 0;
|
|
99
|
+
private lastResult?: TurnSettleData;
|
|
100
|
+
private continuations = 0;
|
|
101
|
+
private waitedMs = 0;
|
|
102
|
+
private waitStartedAt = 0;
|
|
103
|
+
private waitTimer?: NodeJS.Timeout;
|
|
104
|
+
private inputTimer?: NodeJS.Timeout;
|
|
105
|
+
private batchTimer?: NodeJS.Timeout;
|
|
106
|
+
private resultSteer?: Promise<void>;
|
|
107
|
+
// STOP: nothing continues, and no later result restarts the turn.
|
|
108
|
+
private stopped = false;
|
|
109
|
+
// Interrupt & send: the wait ends, but the commands stay held so the
|
|
110
|
+
// operator's next turn receives their results.
|
|
111
|
+
private interrupting = false;
|
|
89
112
|
|
|
90
113
|
constructor(
|
|
91
114
|
id: string,
|
|
@@ -168,11 +191,17 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
168
191
|
}
|
|
169
192
|
|
|
170
193
|
async interrupt(): Promise<void> {
|
|
171
|
-
if (
|
|
194
|
+
if (this.settled) return;
|
|
195
|
+
this.interrupting = true;
|
|
196
|
+
this.stopWaitClock();
|
|
197
|
+
await this.worker.cancelCurrentTurn();
|
|
172
198
|
}
|
|
173
199
|
|
|
174
200
|
kill(): void {
|
|
175
201
|
if (this.settled) return;
|
|
202
|
+
this.stopped = true;
|
|
203
|
+
this.stopWaitClock();
|
|
204
|
+
this.worker.abandonHeldCommands();
|
|
176
205
|
// Async; the wrapper's `error` event fires when `turn_settled` lands.
|
|
177
206
|
void this.worker.cancelCurrentTurn().catch((err: unknown) => {
|
|
178
207
|
if (this.settled) return;
|
|
@@ -221,26 +250,26 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
221
250
|
this.fail('turn settled with no result');
|
|
222
251
|
return;
|
|
223
252
|
}
|
|
224
|
-
this.settled = true;
|
|
225
|
-
this._status = 'completed';
|
|
226
|
-
this.unwire();
|
|
227
253
|
// Successful turn — the spawn-failure circuit breaker resets so any
|
|
228
254
|
// earlier intermittent crashes stop counting toward the 3-strike cap.
|
|
229
255
|
resetFailureCount(this.workflowId);
|
|
230
|
-
this.
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
256
|
+
this.costUsd += r.costUsd ?? 0;
|
|
257
|
+
this.lastResult = r;
|
|
258
|
+
void this.afterCodexTurn();
|
|
259
|
+
};
|
|
260
|
+
const onHeldCommands = () => {
|
|
261
|
+
if (this.settled || this.stopped) return;
|
|
262
|
+
if (this.waitStartedAt) {
|
|
263
|
+
// Ends that arrive close together go to the agent in one turn.
|
|
264
|
+
if (!this.batchTimer) this.batchTimer = setTimeout(() => { this.batchTimer = undefined; this.reviewWait(); }, HELD_BATCH_MS);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
// A result that arrives while the final answer is being written waits
|
|
268
|
+
// for the turn to complete and continues it, so it is never lost.
|
|
269
|
+
if (this.worker.hasHeldResults() && !this.resultSteer && !this.lastResult && this.worker.acceptsResultSteer) {
|
|
270
|
+
// A Codex turn is running: the result goes into it, never a second turn.
|
|
271
|
+
this.resultSteer = this.steerResults().finally(() => { this.resultSteer = undefined; });
|
|
272
|
+
}
|
|
244
273
|
};
|
|
245
274
|
const onFatal = (reason: string) => {
|
|
246
275
|
if (this.settled) return;
|
|
@@ -258,6 +287,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
258
287
|
this.worker.on('system_notice', onSystemNotice);
|
|
259
288
|
this.worker.on('turn_settled', onSettled);
|
|
260
289
|
this.worker.on('fatal', onFatal);
|
|
290
|
+
this.worker.on('held_commands', onHeldCommands);
|
|
261
291
|
|
|
262
292
|
this.wired.push(
|
|
263
293
|
{ event: 'init', fn: onInit as (...args: unknown[]) => void },
|
|
@@ -268,6 +298,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
268
298
|
{ event: 'system_notice', fn: onSystemNotice as (...args: unknown[]) => void },
|
|
269
299
|
{ event: 'turn_settled', fn: onSettled as (...args: unknown[]) => void },
|
|
270
300
|
{ event: 'fatal', fn: onFatal as (...args: unknown[]) => void },
|
|
301
|
+
{ event: 'held_commands', fn: onHeldCommands as (...args: unknown[]) => void },
|
|
271
302
|
);
|
|
272
303
|
|
|
273
304
|
// Phase 6a unused but harmless — silences "WorkerConfig.appendSystemPrompt
|
|
@@ -277,6 +308,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
277
308
|
}
|
|
278
309
|
|
|
279
310
|
private unwire(): void {
|
|
311
|
+
this.stopWaitClock();
|
|
280
312
|
this.watchdog?.stop(); this.watchdog = undefined;
|
|
281
313
|
this.stopToolObserver?.(); this.stopToolObserver = undefined;
|
|
282
314
|
for (const { event, fn } of this.wired) {
|
|
@@ -290,8 +322,157 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
|
|
|
290
322
|
this.settled = true;
|
|
291
323
|
this._status = 'failed';
|
|
292
324
|
this.unwire();
|
|
325
|
+
// After Interrupt & send the operator's message runs next and takes the
|
|
326
|
+
// results; any other failure leaves nobody to deliver them to.
|
|
327
|
+
if (!this.interrupting) this.worker.abandonHeldCommands();
|
|
293
328
|
this.emit('error', reason);
|
|
294
329
|
}
|
|
330
|
+
|
|
331
|
+
// ── Waiting on commands the agent started ───────────────────────────
|
|
332
|
+
|
|
333
|
+
private async afterCodexTurn(): Promise<void> {
|
|
334
|
+
// A result steer still in flight either landed in the turn that just
|
|
335
|
+
// ended or comes back to the queue of results; wait to know which.
|
|
336
|
+
if (this.resultSteer) await this.resultSteer;
|
|
337
|
+
if (this.settled) return;
|
|
338
|
+
const running = this.worker.heldCommands;
|
|
339
|
+
const ready = this.worker.hasHeldResults();
|
|
340
|
+
if (this.stopped || (!ready && running.length === 0)) return this.finish();
|
|
341
|
+
if (this.continuations >= HELD_CONTINUATION_LIMIT) {
|
|
342
|
+
return this.giveUp(`Arco stopped continuing Codex after ${HELD_CONTINUATION_LIMIT} command results in this turn.`);
|
|
343
|
+
}
|
|
344
|
+
if (ready && (running.length === 0 || this.worker.hasFailedHeldResult())) return this.continueWith([]);
|
|
345
|
+
this.startWait();
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private startWait(): void {
|
|
349
|
+
const remaining = HELD_WAIT_LIMIT_MS - this.waitedMs;
|
|
350
|
+
if (remaining <= 0) return this.giveUp(`Arco stopped waiting after ${formatDuration(HELD_WAIT_LIMIT_MS)} in this turn.`);
|
|
351
|
+
this.waitStartedAt = Date.now();
|
|
352
|
+
this.worker.showHeldUntil(this.waitStartedAt + remaining);
|
|
353
|
+
this.waitTimer = setTimeout(() => {
|
|
354
|
+
this.stopWaitClock();
|
|
355
|
+
this.giveUp(`Arco stopped waiting after ${formatDuration(HELD_WAIT_LIMIT_MS)} in this turn.`);
|
|
356
|
+
}, remaining);
|
|
357
|
+
this.waitTimer.unref?.();
|
|
358
|
+
this.inputTimer = setInterval(() => this.checkInput(), 500);
|
|
359
|
+
this.inputTimer.unref?.();
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private stopWaitClock(): void {
|
|
363
|
+
if (this.waitStartedAt) {
|
|
364
|
+
this.waitedMs += Date.now() - this.waitStartedAt;
|
|
365
|
+
this.worker.releaseHeldWait();
|
|
366
|
+
}
|
|
367
|
+
this.waitStartedAt = 0;
|
|
368
|
+
clearTimeout(this.waitTimer); this.waitTimer = undefined;
|
|
369
|
+
clearInterval(this.inputTimer); this.inputTimer = undefined;
|
|
370
|
+
clearTimeout(this.batchTimer); this.batchTimer = undefined;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private reviewWait(): void {
|
|
374
|
+
if (this.settled || !this.waitStartedAt) return;
|
|
375
|
+
const running = this.worker.heldCommands;
|
|
376
|
+
const ready = this.worker.hasHeldResults();
|
|
377
|
+
if (ready && (running.length === 0 || this.worker.hasFailedHeldResult())) {
|
|
378
|
+
this.stopWaitClock();
|
|
379
|
+
this.continueWith([]);
|
|
380
|
+
} else if (!ready && running.length === 0) {
|
|
381
|
+
// Codex lost the commands (connection or thread closed); the lost
|
|
382
|
+
// line has already been shown.
|
|
383
|
+
this.stopWaitClock();
|
|
384
|
+
this.finish();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Direct operator input or an explicit nudge ends the wait. A steer goes
|
|
389
|
+
// to the agent at once; a follow-up waits for the turn to end, so the
|
|
390
|
+
// turn ends here and the follow-up turn takes over the held commands.
|
|
391
|
+
private checkInput(): void {
|
|
392
|
+
if (this.settled || !this.waitStartedAt) return;
|
|
393
|
+
const pending = this.config.pendingInput?.();
|
|
394
|
+
if (!pending) return;
|
|
395
|
+
const peeked = this.config.peekSteer?.() ?? [];
|
|
396
|
+
if (pending === 'follow-up' || peeked.some(item => item.attachments?.length)) {
|
|
397
|
+
this.stopWaitClock();
|
|
398
|
+
this.emit('system_notice', `Stopped waiting for ${this.runningLabel()}: your message is next. Arco still passes the result on when it ends.`);
|
|
399
|
+
return this.finish();
|
|
400
|
+
}
|
|
401
|
+
const items = this.config.drainSteer?.() ?? [];
|
|
402
|
+
if (!items.length) return;
|
|
403
|
+
this.stopWaitClock();
|
|
404
|
+
this.continueWith(items);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private continueWith(items: SteerItem[]): void {
|
|
408
|
+
this.continuations += 1;
|
|
409
|
+
const results = this.worker.takeHeldResults();
|
|
410
|
+
const running = this.worker.heldCommands;
|
|
411
|
+
for (const result of results) this.emit('system_notice', heldResultNotice(result, true));
|
|
412
|
+
const message = [
|
|
413
|
+
...(results.length ? [heldResultsMessage(results, running)] : []),
|
|
414
|
+
...items.map(item => item.content),
|
|
415
|
+
...(!results.length && running.length ? [`[Arco] Still running: ${running.map(item => shortCommand(item.command)).join('; ')}. Arco tells you when it ends.`] : []),
|
|
416
|
+
].join('\n\n');
|
|
417
|
+
this._output += this._output ? '\n\n' : '';
|
|
418
|
+
this.lastResult = undefined;
|
|
419
|
+
this.worker.beginTurn(message, undefined, { continuation: true })
|
|
420
|
+
.then(() => {
|
|
421
|
+
if (items.length) this.config.onSteerDelivered?.(items);
|
|
422
|
+
if (this.settled) void this.worker.cancelCurrentTurn().catch(() => {});
|
|
423
|
+
})
|
|
424
|
+
.catch((err: unknown) => {
|
|
425
|
+
if (this.settled) return;
|
|
426
|
+
this.worker.restoreHeldResults(results);
|
|
427
|
+
if (items.length) this.config.requeueSteer?.(items, 'follow-up');
|
|
428
|
+
this.fail(err instanceof Error ? err.message : String(err));
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private async steerResults(): Promise<void> {
|
|
433
|
+
const results = this.worker.takeHeldResults();
|
|
434
|
+
if (!results.length) return;
|
|
435
|
+
const delivered = await this.worker.steerText(heldResultsMessage(results, this.worker.heldCommands));
|
|
436
|
+
if (!delivered) { this.worker.restoreHeldResults(results); return; }
|
|
437
|
+
for (const result of results) this.emit('system_notice', heldResultNotice(result, false));
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
private runningLabel(): string {
|
|
441
|
+
const running = this.worker.heldCommands;
|
|
442
|
+
return running.length ? running.map(item => `\`${shortCommand(item.command)}\``).join(', ') : 'the command';
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private giveUp(line: string): void {
|
|
446
|
+
const running = this.worker.heldCommands;
|
|
447
|
+
this.worker.abandonHeldCommands();
|
|
448
|
+
this.emit('system_notice', running.length
|
|
449
|
+
? `${line} Still running: ${running.map(item => `\`${shortCommand(item.command)}\``).join(', ')}. Its row records how it ends.`
|
|
450
|
+
: line);
|
|
451
|
+
this.finish();
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
private finish(): void {
|
|
455
|
+
if (this.settled) return;
|
|
456
|
+
const r = this.lastResult;
|
|
457
|
+
if (!r) { this.fail('turn settled with no result'); return; }
|
|
458
|
+
this.settled = true;
|
|
459
|
+
this._status = 'completed';
|
|
460
|
+
this.unwire();
|
|
461
|
+
this.emit('result', {
|
|
462
|
+
text: this._output.length >= r.text.length ? this._output : r.text,
|
|
463
|
+
costUsd: this.costUsd,
|
|
464
|
+
durationMs: Math.max(r.durationMs ?? 0, Date.now() - this.startedAt),
|
|
465
|
+
...(r.usage ? { usage: r.usage } : {}),
|
|
466
|
+
...(typeof r.modelContextWindow === 'number' ? { modelContextWindow: r.modelContextWindow } : {}),
|
|
467
|
+
...(typeof r.freshContextWindow === 'number' ? { freshContextWindow: r.freshContextWindow } : {}),
|
|
468
|
+
...(typeof r.lastPromptTokens === 'number' ? { lastPromptTokens: r.lastPromptTokens } : {}),
|
|
469
|
+
// docs/PROVIDERS.md - Codex doesn't expose tool_result bytes
|
|
470
|
+
// through the app-server JSON-RPC surface. Sentinel: -1 = unknown.
|
|
471
|
+
thinkingBytes: 0,
|
|
472
|
+
toolResultBytes: -1,
|
|
473
|
+
toolResultBytesRaw: -1,
|
|
474
|
+
});
|
|
475
|
+
}
|
|
295
476
|
}
|
|
296
477
|
|
|
297
478
|
// Long-lived worker accessor. Creates lazily on first turn for a given
|
|
@@ -335,6 +516,23 @@ function acquireWorker(
|
|
|
335
516
|
}
|
|
336
517
|
const fresh = new CodexAppServerWorker(workflowId, config, resumeSessionId);
|
|
337
518
|
workersByWorkflow.set(workflowId, fresh);
|
|
519
|
+
fresh.on('late_command', (event: ToolUseEvent, lateCommand: PrimaryToolUseMessage['lateCommand']) => {
|
|
520
|
+
void import('../../server/broadcast.js').then(({ broadcastWorkflow }) => {
|
|
521
|
+
const { name: tool, ...entry } = event;
|
|
522
|
+
broadcastWorkflow(workflowId, {
|
|
523
|
+
...entry, type: 'primary_tool_use', workflowId, tool, lateCommand,
|
|
524
|
+
...(lateCommand?.state === 'finished' ? {} : { status: 'in_progress' }),
|
|
525
|
+
});
|
|
526
|
+
if (lateCommand?.state === 'lost') {
|
|
527
|
+
let command = 'A command';
|
|
528
|
+
try { command = JSON.parse(event.input).command || command; } catch { /* use the fallback */ }
|
|
529
|
+
broadcastWorkflow(workflowId, {
|
|
530
|
+
type: 'system_notice', workflowId,
|
|
531
|
+
content: `Codex lost the result for ${command.slice(0, 240)} when its connection closed.`,
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
}).catch(error => console.warn('[arco] could not record a late Codex command result', error));
|
|
535
|
+
});
|
|
338
536
|
fresh.on('fatal', (reason: string) => {
|
|
339
537
|
// Drop the cache entry so the next operator turn re-spawns. Don't
|
|
340
538
|
// dispose() — the entry is already torn down by `onChildDeath`.
|
|
@@ -350,6 +548,10 @@ function acquireWorker(
|
|
|
350
548
|
return fresh;
|
|
351
549
|
}
|
|
352
550
|
|
|
551
|
+
export function runningCodexLateCommands(workflowId: string) {
|
|
552
|
+
return workersByWorkflow.get(workflowId)?.runningLateCommands ?? [];
|
|
553
|
+
}
|
|
554
|
+
|
|
353
555
|
// Operator-triggered native compaction against the long-lived per-workflow
|
|
354
556
|
// thread (the app-server equivalent of `/compact` in Codex CLI). Out-of-band
|
|
355
557
|
// vs. the per-turn CodexAppServerTurn wrapper — it talks straight to the
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import type { CodexLateCommand, PrimaryToolUseMessage } from '@arco/shared';
|
|
2
|
+
import type { ToolUseEvent } from './worker.js';
|
|
3
|
+
|
|
4
|
+
const DISPLAY_MS = 5 * 60_000;
|
|
5
|
+
const MAX_COMMANDS = 64;
|
|
6
|
+
|
|
7
|
+
// A program meant to keep running (a server or a watcher) must never hold a
|
|
8
|
+
// turn open. Programs the shell put in the background (`&`, `nohup`) end the
|
|
9
|
+
// shell at once, so Codex completes their item inside the turn; only a known
|
|
10
|
+
// long-running program started in the foreground needs this pattern. Kept
|
|
11
|
+
// narrower than the preview detector's pattern: `vite build` or `deno run
|
|
12
|
+
// script.ts` end on their own and must still be waited on.
|
|
13
|
+
const LONG_RUNNING_RE = new RegExp([
|
|
14
|
+
String.raw`\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b`,
|
|
15
|
+
String.raw`\b(?:vite|next|astro|nuxt|remix|gatsby|docusaurus)\s+(?:dev|develop|start|serve|preview)\b`,
|
|
16
|
+
String.raw`\bvite\s*(?:$|['"]|--(?:host|port)\b)`,
|
|
17
|
+
String.raw`\bpython3?\s+-m\s+http\.server\b`,
|
|
18
|
+
String.raw`\buvicorn\b`, String.raw`\bflask\s+run\b`, String.raw`\brails\s+s(?:erver)?\b`, String.raw`\bphp\s+-S\b`,
|
|
19
|
+
String.raw`(?:^|\s)--watch\b`, String.raw`\bwatch\s+-n\b`, String.raw`\btail\s+(?:-\w+\s+)*-\w*[fF]\b`,
|
|
20
|
+
String.raw`\bsleep\s+infinity\b`,
|
|
21
|
+
String.raw`\bdocker[\s-]compose\s+(?:\S+\s+)*up\b(?![^|;&]*\s(?:-d|--detach)\b)`,
|
|
22
|
+
].join('|'));
|
|
23
|
+
|
|
24
|
+
export function isLongRunningProgram(command: string): boolean {
|
|
25
|
+
return LONG_RUNNING_RE.test(command);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface HeldCommandResult {
|
|
29
|
+
itemId: string;
|
|
30
|
+
command: string;
|
|
31
|
+
cwd?: string;
|
|
32
|
+
startedAt: number;
|
|
33
|
+
endedAt: number;
|
|
34
|
+
exitCode?: number;
|
|
35
|
+
output?: string;
|
|
36
|
+
failed: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Command {
|
|
40
|
+
turnId: string;
|
|
41
|
+
startedAt: number;
|
|
42
|
+
event: ToolUseEvent;
|
|
43
|
+
waitingUntil?: number;
|
|
44
|
+
timer?: NodeJS.Timeout;
|
|
45
|
+
// The agent waits on this command: its result is delivered to the agent
|
|
46
|
+
// once, by the wrapper of the Arco turn that holds it.
|
|
47
|
+
held?: boolean;
|
|
48
|
+
// The Arco turn is open right now only because of this command.
|
|
49
|
+
waiting?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function commandText(event: Pick<ToolUseEvent, 'input'>): { command: string; cwd?: string } {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(event.input) as { command?: unknown; cwd?: unknown };
|
|
55
|
+
return {
|
|
56
|
+
command: typeof parsed.command === 'string' ? parsed.command : 'a shell command',
|
|
57
|
+
...(typeof parsed.cwd === 'string' ? { cwd: parsed.cwd } : {}),
|
|
58
|
+
};
|
|
59
|
+
} catch { return { command: 'a shell command' }; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class CodexLateCommands {
|
|
63
|
+
private readonly commands = new Map<string, Command>();
|
|
64
|
+
// Ended held commands whose result has not yet been delivered to the agent.
|
|
65
|
+
private readonly results: HeldCommandResult[] = [];
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
private readonly publish: (event: ToolUseEvent, state: NonNullable<PrimaryToolUseMessage['lateCommand']>) => void,
|
|
69
|
+
private readonly onHeldChange: () => void = () => {},
|
|
70
|
+
) {}
|
|
71
|
+
|
|
72
|
+
start(turnId: string, event: ToolUseEvent): void {
|
|
73
|
+
if (!event.itemId || this.commands.has(event.itemId)) return;
|
|
74
|
+
if (this.commands.size >= MAX_COMMANDS) {
|
|
75
|
+
const oldest = this.commands.keys().next().value;
|
|
76
|
+
if (oldest) {
|
|
77
|
+
const previous = this.commands.get(oldest)!;
|
|
78
|
+
if (previous.waitingUntil) this.notify(previous, 'untracked');
|
|
79
|
+
clearTimeout(previous.timer);
|
|
80
|
+
this.commands.delete(oldest);
|
|
81
|
+
if (previous.held) this.onHeldChange();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
this.commands.set(event.itemId, { turnId, event, startedAt: Date.now() });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** True once the long-lived publisher owns this completion. */
|
|
88
|
+
complete(turnId: string, event: ToolUseEvent): boolean {
|
|
89
|
+
const id = event.itemId;
|
|
90
|
+
const command = id ? this.commands.get(id) : undefined;
|
|
91
|
+
if (!id || !command || command.turnId !== turnId) return false;
|
|
92
|
+
this.commands.delete(id);
|
|
93
|
+
clearTimeout(command.timer);
|
|
94
|
+
if (!command.waitingUntil) return false;
|
|
95
|
+
this.notify(command, 'finished', event);
|
|
96
|
+
if (command.held) {
|
|
97
|
+
this.results.push(this.result(command, event));
|
|
98
|
+
this.onHeldChange();
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A command that ended inside its own turn after the agent's final answer
|
|
105
|
+
* had started: the model never saw the result, so it is kept for delivery
|
|
106
|
+
* once that turn has completed. The completion is still shown in the turn.
|
|
107
|
+
* False when the command is unknown, belongs to another turn or has
|
|
108
|
+
* already outlived its turn.
|
|
109
|
+
*/
|
|
110
|
+
completeUnseen(turnId: string, event: ToolUseEvent): boolean {
|
|
111
|
+
const id = event.itemId;
|
|
112
|
+
const command = id ? this.commands.get(id) : undefined;
|
|
113
|
+
if (!id || !command || command.turnId !== turnId || command.waitingUntil) return false;
|
|
114
|
+
this.commands.delete(id);
|
|
115
|
+
clearTimeout(command.timer);
|
|
116
|
+
if (!isLongRunningProgram(commandText(command.event).command)) {
|
|
117
|
+
this.results.push(this.result(command, event));
|
|
118
|
+
this.onHeldChange();
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
settle(turnId: string): void {
|
|
124
|
+
let held = false;
|
|
125
|
+
for (const command of this.commands.values()) {
|
|
126
|
+
if (command.turnId !== turnId || command.waitingUntil) continue;
|
|
127
|
+
command.waitingUntil = Date.now() + DISPLAY_MS;
|
|
128
|
+
command.held = !isLongRunningProgram(commandText(command.event).command);
|
|
129
|
+
held ||= command.held;
|
|
130
|
+
this.notify(command, 'running');
|
|
131
|
+
command.timer = setTimeout(() => this.notify(command, 'untracked'), DISPLAY_MS);
|
|
132
|
+
command.timer.unref();
|
|
133
|
+
}
|
|
134
|
+
if (held) this.onHeldChange();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Commands the agent still waits on, oldest first. */
|
|
138
|
+
running(): Array<{ itemId: string; command: string; startedAt: number }> {
|
|
139
|
+
return [...this.commands.values()].flatMap(command => command.held && command.event.itemId
|
|
140
|
+
? [{ itemId: command.event.itemId, command: commandText(command.event).command, startedAt: command.startedAt }] : []);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
hasResults(): boolean { return this.results.length > 0; }
|
|
144
|
+
|
|
145
|
+
hasFailedResult(): boolean { return this.results.some(result => result.failed); }
|
|
146
|
+
|
|
147
|
+
/** Ended results; each is handed out exactly once. */
|
|
148
|
+
takeResults(): HeldCommandResult[] { return this.results.splice(0); }
|
|
149
|
+
|
|
150
|
+
/** Put back results whose delivery failed, ahead of any newer ones. */
|
|
151
|
+
restoreResults(results: HeldCommandResult[]): void {
|
|
152
|
+
if (results.length) this.results.unshift(...results);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The Arco turn now waits on the held commands, at most until `until`. */
|
|
156
|
+
hold(until: number): void {
|
|
157
|
+
for (const command of this.commands.values()) {
|
|
158
|
+
if (!command.held || !command.waitingUntil) continue;
|
|
159
|
+
command.waiting = true;
|
|
160
|
+
if (command.waitingUntil < until) {
|
|
161
|
+
command.waitingUntil = until;
|
|
162
|
+
clearTimeout(command.timer);
|
|
163
|
+
command.timer = setTimeout(() => this.notify(command, 'untracked'), Math.max(0, until - Date.now()));
|
|
164
|
+
command.timer.unref();
|
|
165
|
+
}
|
|
166
|
+
this.notify(command, 'running');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The turn no longer waits (it continued, ended or was stopped). */
|
|
171
|
+
release(): void {
|
|
172
|
+
for (const command of this.commands.values()) {
|
|
173
|
+
if (!command.waiting) continue;
|
|
174
|
+
command.waiting = false;
|
|
175
|
+
this.notify(command, 'running');
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Nobody waits on these commands any more (STOP, the wait limit, a failed
|
|
181
|
+
* turn). They keep running and their rows still record how they end, but
|
|
182
|
+
* no result reaches the agent.
|
|
183
|
+
*/
|
|
184
|
+
abandon(): void {
|
|
185
|
+
this.release();
|
|
186
|
+
this.results.length = 0;
|
|
187
|
+
for (const command of this.commands.values()) command.held = false;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
snapshot(): CodexLateCommand[] {
|
|
191
|
+
const now = Date.now();
|
|
192
|
+
return [...this.commands.values()].flatMap(({ event, startedAt, waitingUntil, waiting }) =>
|
|
193
|
+
event.itemId && waitingUntil && waitingUntil > now
|
|
194
|
+
? [{ itemId: event.itemId, input: event.input, startedAt, waitingUntil, ...(waiting ? { waiting } : {}) }] : []);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
disconnect(): void {
|
|
198
|
+
const held = this.results.length > 0 || [...this.commands.values()].some(command => command.held);
|
|
199
|
+
for (const command of this.commands.values()) {
|
|
200
|
+
clearTimeout(command.timer);
|
|
201
|
+
this.notify(command, 'lost');
|
|
202
|
+
}
|
|
203
|
+
this.commands.clear();
|
|
204
|
+
this.results.length = 0;
|
|
205
|
+
if (held) this.onHeldChange();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private result(command: Command, event: ToolUseEvent): HeldCommandResult {
|
|
209
|
+
const { command: text, cwd } = commandText(command.event);
|
|
210
|
+
return {
|
|
211
|
+
itemId: command.event.itemId!, command: text, ...(cwd ? { cwd } : {}),
|
|
212
|
+
startedAt: command.startedAt, endedAt: Date.now(),
|
|
213
|
+
...(typeof event.exitCode === 'number' ? { exitCode: event.exitCode } : {}),
|
|
214
|
+
...(typeof event.output === 'string' ? { output: event.output } : {}),
|
|
215
|
+
failed: event.status === 'failed' || (typeof event.exitCode === 'number' && event.exitCode !== 0),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private notify(command: Command, state: NonNullable<PrimaryToolUseMessage['lateCommand']>['state'], result?: ToolUseEvent): void {
|
|
220
|
+
this.publish(result ?? command.event, {
|
|
221
|
+
state, startedAt: command.startedAt, waitingUntil: command.waitingUntil ?? Date.now(),
|
|
222
|
+
...(command.waiting && state === 'running' ? { waiting: true } : {}),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|