-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrunner.ts
More file actions
1410 lines (1355 loc) · 50.4 KB
/
Copy pathrunner.ts
File metadata and controls
1410 lines (1355 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EventEmitter } from "node:events";
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output, stderr } from "node:process";
import { join } from "node:path";
import { type Agent } from "@intx/agent";
import { getLogger } from "@intx/log";
import { type Config } from "../config/index.js";
import {
shellTimeoutFromSettings,
toolWatchdogFromSettings,
type MCPServerConfig,
} from "../config/settings.js";
import {
codexProfileFromProviderName,
isCodexProviderName,
} from "../config/codex-providers.js";
import { xaiProfileFromProviderName } from "../config/xai-providers.js";
import {
peekSourceCredentialSecret,
registerSourceCredential,
} from "../config/source-credentials.js";
import { formatDirectorSystemPrompt } from "../agent/directors/identity.js";
import { DIRECTOR_REGISTRY } from "../agent/directors/registry.js";
import type { DirectorId, DirectorPackage } from "../agent/directors/types.js";
import { submitOutputDefinition } from "../agent/director.js";
import { handleChatDirectorEvent } from "../agent/chat-event-subscribers.js";
import {
shellDefinition,
updatePlanDefinition,
} from "../agent/codex-tool-proxies.js";
import {
CodexRefreshLockError,
codexAuthFailureDiagnostic,
getValidCodexToken,
} from "../auth/codex/session.js";
import { getValidXaiToken } from "../auth/xai/session.js";
import {
type ActivatedToolTracker,
type ToolAvailability,
} from "../agent/tool-search.js";
import { detectLanguageServerAvailable } from "../agent/lsp-availability.js";
import {
resolveSessionMode,
type SessionMode,
} from "../config/session-mode.js";
import {
createSubAgentSessionStore,
type SubAgentProvider,
type SubAgentSessionStore,
} from "../subagent/index.js";
import { getProcessAdmissionQueue } from "../subagent/admission.js";
import { disposeExecRuntime, formatCaughtError } from "./dispose.js";
import {
EXEC_MCP_CONNECT_WAIT_MS,
EXEC_MCP_HANDSHAKE_TIMEOUT_MS,
armExecMcpHandshakeAbort,
awaitExecMcpThenResume,
followExecMcpHandshake,
} from "./mcp-handshake.js";
import type {
ContextStore,
InferenceSource,
InboundMessage,
} from "@intx/types/runtime";
import { OPERATOR_ORIGINATED_FLAG } from "../agent/message-provenance.js";
import { loadAgentProfiles } from "../agent/profiles.js";
import type {
ApprovalOutcome,
PermissionRequest,
} from "../permission/types.js";
import { savedSkipPermissionsWarning } from "../permission/saved-skip-warning.js";
import {
createAgentToolset,
type AgentToolset,
type OperatorResult,
} from "../agent/tools.js";
import { liveTelemetry } from "../telemetry/singleton.js";
import {
CREDENTIAL_FAILURE_USER_MESSAGE,
isResolvedProviderFailureError,
terminalProviderFailureMessage,
} from "../inference-error-message.js";
import type { InferenceErrorLike } from "../inference-gateway-error.js";
import {
collectToolPlugins,
resolveToolPlugins,
} from "../plugins/tool-plugins.js";
import {
formatExpandSkip,
type ExpandPluginPathSkip,
} from "../plugins/loader.js";
import { consumeStream } from "../session/stream-consumer.js";
import { COMPACTION_CONTINUATION_EVENT } from "../agent/compaction.js";
import {
generateSessionId,
initSessionDir,
sessionContextDir,
sessionDir,
} from "../session/index.js";
import {
setActiveRun,
syncRunStateHandle,
type RunStateHandle,
} from "../session/active-run.js";
import { startRunHeartbeat } from "../session/run-liveness.js";
import {
setActiveDisposeHost,
clearActiveDisposeHost,
} from "../session/active-host.js";
import {
finalizeRunState,
loadState,
saveState,
type ConnectedMcpServer,
} from "../session/state.js";
import { resolveExecRunStatus, type RunSink } from "../session/run-sink.js";
import { createRunSummary } from "../session/hooks.js";
import {
buildCompactionContinuationMessage,
buildShellBackgroundMessage,
buildSubAgentProvider,
createContinuationGate,
createSessionPruningCompactor,
loadSessionChatPrompt,
skillDirsFromEnabledPlugins,
} from "../session/runtime-assembly.js";
import {
createApprovalResume,
resolveParkedCallIdFromStore,
} from "../session/approval-resume.js";
import { createReactorAuthorize } from "../permission/reactor-authorize.js";
import {
assembleChatAgent,
assembleInferenceBase,
assembleSessionGate,
assembleSessionLifecycle,
assembleSessionTrust,
createAdvertisedToolset,
loadSessionLocalSettings,
resolveLiveSessionSources,
} from "../session/assemble-runtime.js";
import type { CompactionArchive } from "../session/compaction-archive.js";
import { tryReadPriorHandoffFile } from "../session/compaction-handoff.js";
import { emitPluginWarningSummary } from "../plugins/diagnostics.js";
import { createModelSummarizer } from "../session/summarizer.js";
import { ID_PREFIX, LOG_NAMESPACE_ROOT } from "../branding.js";
import {
anthropicCacheWriteAt,
resumeCacheWriteSeed,
} from "../provider/cache-ttl.js";
import type { ReactorEmittedEvent } from "@intx/inference";
import { setAgentSourceUnlessClosed } from "../tui/agent-source-sync.js";
import { ensureFreshInferenceSource } from "../subagent/refresh-inference-source.js";
import {
MAX_TOOL_APPROVAL_PAUSE_MS,
getToolApprovalBudget,
} from "../tui/tool-execution-watchdog.js";
import { createApprovalDeliverer } from "../tui/approval-delivery.js";
import { createCorrelationAcceptance } from "../tui/correlation-acceptance.js";
import { APPROVAL_TIMEOUT_RESULT_TEXT } from "../permission/decline-markers.js";
import { WorkflowHost } from "../workflows/host.js";
const logger = getLogger([LOG_NAMESPACE_ROOT, "exec"]);
const SELECTED_PROVIDER_FAILURE = "SelectedProviderFailure";
export function formatExecMcpTrustQuestion(server: MCPServerConfig): string {
return (
`Trust local MCP server "${server.name}" for this project?` +
(server.command !== undefined
? `\nCommand: ${server.command}${(server.args ?? []).length > 0 ? ` ${(server.args ?? []).join(" ")}` : ""}`
: server.url !== undefined
? `\nURL: ${server.url}`
: "")
);
}
export async function refreshSelectedProviderCredential<T>(
refresh: () => Promise<T>,
): Promise<T> {
try {
return await refresh();
} catch (cause) {
const error = new Error(formatCaughtError(cause), { cause });
error.name = SELECTED_PROVIDER_FAILURE;
throw error;
}
}
function execTerminalProviderFailureMessage(
config: Config,
diagnostic: InferenceErrorLike,
): string {
const providerId = diagnostic.providerId ?? config.providerName;
const displayLabel =
providerId === config.providerName
? config.settings?.providers[config.providerName]?.name
: undefined;
return terminalProviderFailureMessage(providerId, diagnostic, displayLabel);
}
// Unwraps a Codex refresh-lock failure whether it arrives raw or as the
// cause of a SELECTED_PROVIDER_FAILURE wrapper.
function codexRefreshLockFailure(err: unknown): CodexRefreshLockError | null {
if (err instanceof CodexRefreshLockError) return err;
if (
err instanceof Error &&
err.name === SELECTED_PROVIDER_FAILURE &&
err.cause instanceof CodexRefreshLockError
)
return err.cause;
return null;
}
export function execUserFailureMessage(
config: Config,
err: unknown,
providerFailureObserved: boolean,
providerError?: InferenceErrorLike,
): string {
// A Codex refresh blocked on the inter-process lock arrives raw (pre-send,
// no SELECTED wrapper) or as the cause of a SELECTED_PROVIDER_FAILURE (the
// first-inference refresh at exec start). Either way it keeps its own lock
// message: mapping it to the generic re-login hint would send the operator
// into a futile loop that never removes the lock file.
const lockFailure = codexRefreshLockFailure(err);
if (lockFailure !== null) return lockFailure.message;
if (err instanceof Error && err.name === SELECTED_PROVIDER_FAILURE) {
return CREDENTIAL_FAILURE_USER_MESSAGE;
}
// A pre-send Codex refresh throws the raw auth error (no SELECTED wrapper):
// a failed refresh is still a credential failure with a re-login hint.
if (codexAuthFailureDiagnostic(err) !== null) {
return CREDENTIAL_FAILURE_USER_MESSAGE;
}
if (providerError === undefined && isResolvedProviderFailureError(err))
return err.message;
if (providerFailureObserved || isResolvedProviderFailureError(err)) {
const diagnostic = providerError ?? {
category: "fatal",
message: err instanceof Error ? err.message : String(err),
};
return execTerminalProviderFailureMessage(config, diagnostic);
}
return formatCaughtError(err);
}
/**
* Exec-primary director overlay. Omit / skywalker keep the product default
* (`loadSessionChatPrompt` + advertised session tools). Any other closed-fleet
* id uses the package prompt and allowlist. Worker effort/nudge are not applied.
*/
export interface ExecDirectorOverlay {
/** Package system prompt; omitted on the skywalker default path. */
systemPrompt?: string;
/** `pkg.tools.allow` (fleet tools stripped when `maySpawn` is false). */
advertisedAllow?: readonly string[];
mountFleet: boolean;
}
export function resolveExecDirectorOverlay(
director: DirectorId | undefined,
): ExecDirectorOverlay {
if (director === undefined || director === "skywalker") {
return { mountFleet: true };
}
return resolveExecDirectorOverlayForPackage(DIRECTOR_REGISTRY[director]);
}
/**
* Single enforcement point for the exec allowlist. Everything the overlay
* permits — tool_search results, promoter activation, onToolsActivate, the
* call gate — flows through here, so a tool outside the allow can never
* become callable.
*/
export function isExecOverlayToolAllowed(
overlay: ExecDirectorOverlay,
name: string,
): boolean {
return (
overlay.advertisedAllow === undefined ||
overlay.advertisedAllow.includes(name)
);
}
export function resolveExecDirectorOverlayForPackage(
pkg: DirectorPackage,
): ExecDirectorOverlay {
const allow = pkg.tools?.allow;
const deny = pkg.tools?.deny ?? [];
if ((allow === undefined || allow.length === 0) && deny.length > 0) {
throw new Error(
`Director package "${pkg.id}" sets tools.deny without tools.allow — ` +
"exec overlays enforce a closed allow list, so a deny-only package " +
"has no list to subtract from. Add tools.allow.",
);
}
const allowed =
allow !== undefined && allow.length > 0
? allow.filter((name) => !deny.includes(name))
: undefined;
if (allowed !== undefined && allowed.length === 0) {
throw new Error(
`Director package "${pkg.id}" tools.allow minus tools.deny is empty — ` +
"exec overlays enforce a closed allow list, so no tool would be " +
"advertised. Keep an allow entry outside tools.deny.",
);
}
const advertisedAllow =
allowed !== undefined
? pkg.spawn.maySpawn
? [
...allowed,
// Exec mounts wait_agents beside the fleet verbs (mountWaitAgents),
// so it stays advertised here even though the package allow omits
// it for TUI/nested mailbox-mail collection.
...(!allowed.includes("wait_agents") ? ["wait_agents"] : []),
]
: allowed.filter(
(name) =>
![
"search_agents",
"spawn_agent",
"wait_agents",
"list_agents",
"close_agent",
"resume_agent",
"interrupt_agent",
"send_input",
"read_agent_trace",
].includes(name),
)
: undefined;
return {
systemPrompt: formatDirectorSystemPrompt(pkg),
...(advertisedAllow !== undefined ? { advertisedAllow } : {}),
mountFleet: pkg.spawn.maySpawn,
};
}
/**
* Build the inbound message for exec's one genuine operator input: the
* initial task supplied on the command line. Carries
* OPERATOR_ORIGINATED_FLAG so director.ts's loop-protection backstop can
* tell this apart from system-originated sends.
*/
function operatorTaskMessage(task: string): InboundMessage {
return {
ref: { uid: 1, mailbox: "INBOX" },
headers: {
from: "user@local",
to: ["agent@local"],
date: new Date().toISOString(),
messageId: `<${crypto.randomUUID()}@local>`,
interchangeType: "conversation.message",
},
flags: [OPERATOR_ORIGINATED_FLAG],
content: task,
signatureStatus: "missing",
};
}
export interface ExecResult {
exitCode: number;
sessionId: string;
text: string;
error?: string;
/** Run status after send/close (done | failed | cancelled). */
status?: "done" | "failed" | "cancelled";
/** Wall time from runExec start to summary (ms). */
durationMs?: number;
turnsUsed?: number;
toolCallCount?: number;
tokenUsage?: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
thinking: number;
};
/** Provider/model the config resolved for this run. */
provider?: string;
model?: string;
}
export function createExecToolCallGate(
isAdvertised: (name: string) => boolean,
options: { isCodex: boolean },
): (name: string) => boolean {
const unadvertisedCallable = new Set<string>([
submitOutputDefinition.name,
...(options.isCodex
? [shellDefinition.name, updatePlanDefinition.name]
: []),
]);
return (name) => unadvertisedCallable.has(name) || isAdvertised(name);
}
export function createExecToolPromoter(args: {
activate: (names: readonly string[]) => boolean;
isAllowed: (name: string) => boolean;
persist?: () => void;
commitWire?: () => void;
}): (names: string[]) => void {
return (names) => {
if (!args.activate(names.filter((name) => args.isAllowed(name)))) return;
args.commitWire?.();
args.persist?.();
};
}
/**
* Product non-TUI agent path (`corbits exec "prompt"`).
*
* Shares the same ChatDirector, toolset, permission gate, session mode, and
* sub-agent surface as the TUI — without Ink. Bootstrap consumes the shared
* session assembly in src/session/assemble-runtime.ts; see
* docs/ARCHITECTURE.md "Exec Runner" for the intentional deltas.
*
* Operator/permission prompts use stdin when a TTY is available; otherwise
* they deny (fail closed) unless `--dangerously-skip-permissions` / auto
* grants cover the action.
*/
export async function runExec(config: Config): Promise<ExecResult> {
const task = config.task.trim();
if (task.length === 0) {
stderr.write('Usage: corbits exec "<prompt>"\n');
return {
exitCode: 2,
sessionId: config.sessionId,
text: "",
error: "missing prompt",
status: "failed",
durationMs: 0,
turnsUsed: 0,
toolCallCount: 0,
tokenUsage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
thinking: 0,
},
provider: config.providerName,
model: config.model,
};
}
const sessionId =
config.sessionId.length > 0 ? config.sessionId : generateSessionId();
const startedAt = Date.now();
const workdir = sessionContextDir(config.cwd, sessionId);
await initSessionDir(config.cwd, sessionId);
const prior =
config.sessionId.length > 0
? await loadState(config.cwd, config.sessionId)
: undefined;
const priorState = prior?.kind === "ok" ? prior.state : undefined;
let connectedMcp: ConnectedMcpServer[] = [];
let agent: Agent | null = null;
let toolset: AgentToolset | null = null;
let subAgentSessions: SubAgentSessionStore | null = null;
let textOut = "";
let finalized = false;
let turnsUsed = 0;
let runSink: RunSink | null = null;
let providerFailureObserved = false;
let providerError: InferenceErrorLike | undefined;
let result: ExecResult | undefined;
// Assigned once the advertised toolset exists (below); persist reads it live
// so a snapshot taken before that point still writes, just without the field.
const activatedToolsRef: { current?: ActivatedToolTracker } = {};
const activeRunHandle: RunStateHandle = {
sessionId,
cwd: config.cwd,
task,
startedAt,
turnsUsed: 0,
model: `${config.providerName}:${config.model}`,
...(priorState?.lastCacheWriteAt !== undefined
? { lastCacheWriteAt: priorState.lastCacheWriteAt }
: {}),
...(priorState?.lastCacheWriteAt !== undefined &&
priorState.model !== undefined
? { cacheWriteModel: priorState.model }
: {}),
};
let stopHeartbeat: (() => void) | undefined;
const persist = async (
status: "running" | "done" | "failed" | "cancelled",
extra?: { error?: string },
): Promise<void> => {
if (finalized && status === "running") return;
if (status !== "running") {
finalized = true;
stopHeartbeat?.();
stopHeartbeat = undefined;
}
const model = `${config.providerName}:${config.model}`;
const nextTurnsUsed = runSink?.getTurnCount() ?? turnsUsed;
const activatedTools = activatedToolsRef.current?.list() ?? [];
syncRunStateHandle(activeRunHandle, {
turnsUsed: nextTurnsUsed,
task,
startedAt,
model,
activatedTools,
});
const snapshot = {
status,
turnsUsed: nextTurnsUsed,
task,
startedAt,
model,
mcpServers: connectedMcp,
...(activatedTools.length > 0 ? { activatedTools } : {}),
...(activeRunHandle.lastCacheWriteAt !== undefined
? { lastCacheWriteAt: activeRunHandle.lastCacheWriteAt }
: {}),
...(status !== "running" ? { finishedAt: Date.now() } : {}),
...(extra?.error !== undefined ? { error: extra.error } : {}),
};
const write =
status === "running"
? saveState(config.cwd, sessionId, snapshot).then(() => {
if (!finalized) {
setActiveRun(activeRunHandle);
}
})
: finalizeRunState(config.cwd, sessionId, snapshot);
await write.catch((err: unknown) => {
// Persistence failure must not fail the run, but dropping it silently
// hides disk/permission problems that leave run.json stale.
logger.warn(
"saveState failed for session {sessionId} status={status}: {error}",
{
sessionId,
status,
error: formatCaughtError(err),
},
);
});
};
await persist("running");
stopHeartbeat = startRunHeartbeat({
shouldTick: () => !finalized,
tick: () => persist("running"),
});
try {
// Pricing seed is optional for exec; continue without rates rather than fail the run.
const inferenceDeps = await assembleInferenceBase((err: unknown) => {
logger.debug("seedPricingMetadataFromCache failed: {error}", {
error: formatCaughtError(err),
});
});
// One-shot migration only when the path-trust file does not exist yet.
// Headless exec has no frame to corrupt, so a skipped marketplace member
// writes straight to stderr here — an explicit choice at this call site,
// not `expandPluginPath` falling back to it on its own.
const sessionTrust = await assembleSessionTrust({
cwd: config.cwd,
pluginPaths: config.settings?.pluginPaths,
discoverClaudePlugins: config.settings?.discoverClaudePlugins,
onExpandSkip: (skip: ExpandPluginPathSkip) => {
process.stderr.write(`plugins: ${formatExpandSkip(skip)}\n`);
},
telemetry: liveTelemetry,
});
const { projectTrust, pluginModules } = sessionTrust;
const pluginLoadDiag = sessionTrust.diagnostics;
emitPluginWarningSummary(pluginLoadDiag, (line) => logger.warn(line));
// Metadata-only (untrusted) modules stay out of executable plugins.
const executablePlugins = () =>
pluginModules.filter((m) => m.metadataOnly !== true);
const pluginConfig = config.settings?.plugins ?? {};
const toolPluginCandidates = collectToolPlugins(executablePlugins());
const extraToolPlugins = await resolveToolPlugins({
candidates: toolPluginCandidates,
pluginConfig,
});
const skillDirs = skillDirsFromEnabledPlugins(
executablePlugins(),
pluginConfig,
);
const profilesDir = join(config.cwd, ".agents", "agents");
const liveAgentProfiles = await loadAgentProfiles(profilesDir);
// loadLocalSettings maps ENOENT → null; a throw is real I/O or schema failure.
const localSettingsForMode = await loadSessionLocalSettings({
cwd: config.cwd,
globalSettingsPath: config.globalSettingsPath,
onError: (err: unknown) => {
logger.warn("Failed to load local settings: {error}", {
error: formatCaughtError(err),
});
},
});
const sessionMode: SessionMode =
resolveSessionMode(config.settings, localSettingsForMode) ??
"orchestrator";
const interactive = input.isTTY === true && output.isTTY === true;
if (config.skipPermissionsFromSettings) {
stderr.write(
`${savedSkipPermissionsWarning(config.globalSettingsPath, "exec")}\n`,
);
}
const { gate: permissionGate } = await assembleSessionGate({
cwd: config.cwd,
sessionId,
providerName: config.providerName,
model: config.model,
telemetry: liveTelemetry,
requestApproval: (request: PermissionRequest): Promise<ApprovalOutcome> =>
promptPermission(request, interactive),
getActiveProviderModel: () => `${config.providerName}:${config.model}`,
onPersistNotice: (text) => {
stderr.write(`${text}\n`);
},
onPendingProjectGrants: (text) => {
stderr.write(`${text}\n`);
},
interactive,
skipPermissions: config.dangerouslySkipPermissions,
auto: config.auto,
// Main session: gating rides the reactor's approval-suspend seam. In
// exec (headless) an ask resolves to a deny effect, so the hook blocks
// — the same policy the middleware path applied.
reactorGated: true,
});
const liveSubAgentProvider: { current: SubAgentProvider } = {
current: buildSubAgentProvider(config),
};
const fleetSessions = createSubAgentSessionStore({
admission: getProcessAdmissionQueue(),
});
subAgentSessions = fleetSessions;
const shellTimeout = shellTimeoutFromSettings(config.settings);
const toolWatchdog = toolWatchdogFromSettings(config.settings);
const toolAvailability: ToolAvailability = {
languageServerAvailable: detectLanguageServerAvailable(config.cwd),
operatorAvailable: interactive,
// Exec primary keeps wait_agents mounted: headless runs have no
// mailbox-mail flush, so wait_agents stays the collection path here.
waitAgentsMounted: true,
};
let currentAgent: Agent | null = null;
let currentStorage: ContextStore | null = null;
const evidenceArchiveHolder: { current?: CompactionArchive } = {};
const overlay = resolveExecDirectorOverlay(config.director);
const workflowHostHolder: { instance?: WorkflowHost } = {};
const subAgentSettings = config.settings;
const agentToolset = await createAgentToolset({
cwd: config.cwd,
permissionGate,
skillDirs,
telemetry: liveTelemetry,
isCodex: isCodexProviderName(config.providerName),
...(shellTimeout !== undefined ? { shellTimeout } : {}),
...(toolWatchdog !== undefined ? { toolWatchdog } : {}),
...(localSettingsForMode?.env !== undefined
? { shellEnv: localSettingsForMode.env }
: {}),
...(localSettingsForMode?.pinnedTools !== undefined
? { pinnedTools: localSettingsForMode.pinnedTools }
: {}),
getBlobWriter: () => currentStorage?.writeBlob,
getEvidenceArchive: () => evidenceArchiveHolder.current,
getContextDir: () => workdir,
// Background run_shell completions re-enter the reactor on a later turn.
onBackgroundShellExit: (exit) => {
currentAgent?.deliver(buildShellBackgroundMessage(exit));
},
getBlobReader: () => {
if (currentAgent === null) {
throw new Error("blob reader requested before agent init");
}
return currentAgent.blobReader;
},
isWorkflowActive: () => workflowHostHolder.instance?.isActive() === true,
completeWorkflowStep: (stepId) =>
workflowHostHolder.instance?.complete(stepId) ?? "not-current",
...(interactive
? {
onOperatorGate: (question: string, options: string[]) =>
promptOperator(question, options, true),
}
: {}),
sessionMode,
toolAvailability,
// Closed director overlays unmount tool_search (unless allowed) and
// filter its index, so search cannot surface outside-allow tools.
...(overlay.advertisedAllow !== undefined
? { toolSearchAllow: overlay.advertisedAllow }
: {}),
// Exec-primary keeps wait_agents mounted (with an advertised allow):
// headless runs have no mailbox-mail flush, so wait_agents stays the
// collection path here. TUI primary and nested orchestrators omit it.
mountWaitAgents: true,
...(config.mcpServers !== undefined
? { mcpServers: config.mcpServers }
: {}),
mcpServersSource: config.mcpServersSource ?? "none",
projectTrust,
requestMcpTrust: async (server) => {
if (!interactive) return false;
const result = await promptOperator(
formatExecMcpTrustQuestion(server),
["Trust and connect", "Deny"],
true,
);
return result.kind === "option" && result.index === 0;
},
...(overlay.mountFleet
? {
subAgent: {
provider: () => liveSubAgentProvider.current,
sessions: fleetSessions,
getWorkdirBase: () => sessionDir(config.cwd, sessionId),
onProgress: () => undefined,
...(subAgentSettings !== undefined
? { settings: () => subAgentSettings }
: {}),
catalog: () => config.providers,
profiles: () => liveAgentProfiles,
},
}
: {}),
...(extraToolPlugins.length > 0 ? { extraToolPlugins } : {}),
});
toolset = agentToolset;
setActiveDisposeHost(() =>
disposeExecRuntime({ agent, toolset, subAgentSessions }),
);
const systemPrompt =
overlay.systemPrompt ??
(
await loadSessionChatPrompt({
cwd: config.cwd,
skillDirs,
...(config.systemPromptExtensions !== undefined
? { systemPromptExtensions: config.systemPromptExtensions }
: {}),
...(config.promptSectionOmit !== undefined
? { promptSectionOmit: config.promptSectionOmit }
: {}),
sessionMode,
toolAvailability,
skills: agentToolset.skills,
providerName: config.providerName,
model: config.model,
})
).systemPrompt;
const initialCodexProfile = codexProfileFromProviderName(
config.providerName,
);
const initialXaiProfile = xaiProfileFromProviderName(config.providerName);
const initialBundle = resolveLiveSessionSources(config, sessionId);
const liveSources = initialBundle.sources;
const liveDefaultSource = initialBundle.defaultSource;
const selectedSource = initialBundle.selected;
let liveSource: InferenceSource = selectedSource;
// Refresh OAuth tokens before first inference when starting on codex/xai.
if (initialCodexProfile !== undefined) {
const { access } = await refreshSelectedProviderCredential(() =>
getValidCodexToken(initialCodexProfile),
);
registerSourceCredential(liveSource.credentialId, access);
liveSubAgentProvider.current = {
...liveSubAgentProvider.current,
apiKey: access,
};
}
if (initialXaiProfile !== undefined) {
const { access } = await refreshSelectedProviderCredential(() =>
getValidXaiToken(initialXaiProfile),
);
registerSourceCredential(liveSource.credentialId, access);
liveSubAgentProvider.current = {
...liveSubAgentProvider.current,
apiKey: access,
};
}
const summarizeForCompaction = createModelSummarizer({
getSource: () => liveSource,
deps: inferenceDeps,
getArchive: () => evidenceArchiveHolder.current,
timeoutMs: config.summarizerTimeoutMs,
telemetry: liveTelemetry,
// A 401 here usually means the shared OAuth file rotated under another
// process; re-read it so the retry runs on the fresh token.
refreshAuth: async () => {
const before = peekSourceCredentialSecret(liveSource.credentialId);
const fresh = await ensureFreshInferenceSource(
liveSource,
config.providers,
);
liveSource = fresh;
if (peekSourceCredentialSecret(fresh.credentialId) === before) return;
if (currentAgent !== null)
setAgentSourceUnlessClosed(currentAgent, fresh);
},
});
const {
activated: activatedToolNames,
computeAdvertised,
isAdvertised,
flushPromotions,
} = createAdvertisedToolset({
sessionMode,
toolAvailability,
getProvider: () => config,
builtInPrefix: overlay.advertisedAllow,
...(localSettingsForMode?.pinnedTools !== undefined
? { pinnedTools: localSettingsForMode.pinnedTools }
: {}),
});
activatedToolsRef.current = activatedToolNames;
// Same wire contract as the TUI: a registered tool the model was never
// shown errors toward tool_search instead of dispatching blind.
agentToolset.dynamicRunner.setCallGate(
createExecToolCallGate(isAdvertised, {
isCodex: isCodexProviderName(config.providerName),
}),
// Same promoted-but-unmounted contract as the TUI gate: an activated
// name missing from the registry errors toward retry (see run() in
// DynamicToolRunner).
{ isActivated: (name) => activatedToolNames.has(name) },
);
const { directorHolder, buildAgent } = assembleChatAgent({
toolsId: `${ID_PREFIX}/exec-tools`,
agentId: `${ID_PREFIX}/exec-agent`,
systemPrompt,
getDynamicRunner: () => agentToolset.dynamicRunner,
computeAdvertised,
inactivityTimeoutMs: config.inactivityTimeoutMs ?? 750_000,
totalTimeoutMs: config.totalTimeoutMs,
clearDenials: () => permissionGate.clearDenials(),
getProvider: () => config,
getWorkdir: () => workdir,
getSessionId: () => sessionId,
authorize: createReactorAuthorize(permissionGate),
inferenceDeps,
getSources: () => {
const sources = liveSources.length > 0 ? liveSources : [liveSource];
// OAuth refreshes land in the shared credential cell (keyed by source
// id), so every source already resolves the live secret — no per-send
// credential copy is needed.
return sources;
},
getDefaultSource: () =>
liveDefaultSource.length > 0 ? liveDefaultSource : liveSource.id,
anthropicCachePrompt: () => config.anthropicCachePrompt,
getCompactor: () =>
createSessionPruningCompactor({
summarize: summarizeForCompaction,
summaryContext: () => {
const tools = activatedToolNames.list();
return tools.length > 0 ? { activatedTools: tools } : undefined;
},
readPriorHandoff: () =>
tryReadPriorHandoffFile(
currentStorage?.readBlob.bind(currentStorage),
),
telemetry: liveTelemetry,
onFolded: () => {
// Fold restarts the cached prefix, so catch promotions still
// pending. Search already flushed names onto the next infer.
if (flushPromotions()) {
directorHolder.instance?.updateToolDefinitions(
computeAdvertised(
agentToolset.dynamicRunner.currentDefinitions(),
),
);
}
},
}),
getCacheWriteSeed: () =>
resumeCacheWriteSeed({
at: activeRunHandle.lastCacheWriteAt,
storedModel: activeRunHandle.cacheWriteModel,
liveProvider: config.providerName,
liveProtocol: liveSource.provider,
}),
onBuilt: (agent, storage) => {
currentAgent = agent;
currentStorage = storage;
},
evidenceArchiveHolder,
});
// tool_search starts as a no-op promoter; without this, the call gate
// refuses MCP/present/plugin names the result just told the model to
// invoke. Under a closed overlay the promoter only activates allowed
// names, so outside-allow tools can never become advertised or callable.
const commitPromotedWire = (): void => {
if (flushPromotions()) {
directorHolder.instance?.updateToolDefinitions(
computeAdvertised(agentToolset.dynamicRunner.currentDefinitions()),
);
}
};
const promoteAndCommitWire = createExecToolPromoter({
activate: (names) => activatedToolNames.activate(names),
isAllowed: (name) => isExecOverlayToolAllowed(overlay, name),
persist: () => {
void persist("running");
},
commitWire: commitPromotedWire,
});
agentToolset.setToolPromoter(promoteAndCommitWire);
const workflowHost = new WorkflowHost({
cwd: config.cwd,
getSessionId: () => sessionId,
getToolDefinitions: () => agentToolset.dynamicRunner.currentDefinitions(),
getDirector: () => directorHolder.instance,
});
workflowHostHolder.instance = workflowHost;
const emitter = new EventEmitter();
const {
hookManager,
runSink: liveSink,
cycleRecorder,
} = await assembleSessionLifecycle({
cwd: config.cwd,
emitter,
getTelemetry: () => liveTelemetry,
getSessionId: () => sessionId,
getSource: () => liveSource,
onTurnBoundarySnapshot: (event) => {
if (event?.type === "inference.done") {
const at = anthropicCacheWriteAt(event.data.source, Date.now());
if (at !== undefined) {
activeRunHandle.lastCacheWriteAt = at;
activeRunHandle.cacheWriteModel = `${event.data.source.provider}:${event.data.source.model}`;
}
}
void persist("running");
},
resolveContextDir: () => workdir,
});
runSink = liveSink;
currentAgent = await buildAgent();
agent = currentAgent;
// Local non-null handle after init (currentAgent stays mutable for compaction deliver).
const activeAgent = currentAgent;
const activeStorage = currentStorage;
if (activeStorage === null)
throw new Error("approval resume: no context store");
if (agentToolset.connectMCP !== undefined) {
const handshake = armExecMcpHandshakeAbort(EXEC_MCP_HANDSHAKE_TIMEOUT_MS);
const connecting = followExecMcpHandshake(
agentToolset.connectMCP(
{
interactiveAuth: false,
onStatus: (status) => {
if (status.state === "connected") {
connectedMcp = [
...connectedMcp.filter((s) => s.name !== status.name),
{ name: status.name, toolCount: status.tools.length },
];
}
},
onToolsChanged: (definitions) =>
directorHolder.instance?.updateToolDefinitions(
computeAdvertised(definitions),
),
},
handshake.signal,
),
handshake,
).catch((err: unknown) => {
logger.warn("MCP connect failed: {error}", {
error: formatCaughtError(err),
});
});