owenloop 0.5.22 → 0.5.24
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/CHANGELOG.md +14 -0
- package/dist/packages/work/src/agent/brief.d.ts +16 -0
- package/dist/packages/work/src/agent/brief.js +23 -0
- package/dist/packages/work/src/agent/loop.d.ts +11 -1
- package/dist/packages/work/src/agent/loop.js +520 -8
- package/dist/packages/work/src/harness/claude.d.ts +43 -3
- package/dist/packages/work/src/harness/claude.js +520 -115
- package/dist/packages/work/src/harness/contract.d.ts +36 -1
- package/dist/packages/work/src/harness/contract.js +34 -0
- package/dist/packages/work/src/harness/gatekeeper.d.ts +21 -0
- package/dist/packages/work/src/harness/gatekeeper.js +55 -8
- package/dist/packages/work/src/harness/session-store.d.ts +18 -0
- package/dist/packages/work/src/harness/session-store.js +30 -1
- package/dist/packages/work/src/roles/agent-run.js +5 -1
- package/dist/packages/work/src/roles/sessions.d.ts +7 -0
- package/dist/packages/work/src/roles/sessions.js +56 -5
- package/docs/agent-runner.md +42 -3
- package/docs/cli.md +4 -0
- package/package.json +1 -1
- package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
- package/plugins/claude-code/plugin/.mcp.json +1 -1
- package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
- package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
import { randomUUID } from 'node:crypto';
|
|
27
27
|
import { accessSync, constants, existsSync } from 'node:fs';
|
|
28
28
|
import { delimiter, join } from 'node:path';
|
|
29
|
-
import { classifyToolCall, READ_ONLY_TOOLS } from "./gatekeeper.js";
|
|
29
|
+
import { classifyExactWorkdirPath, classifyToolCall, EXACT_WORKDIR_DENIAL_MESSAGE, PATH_BEARING_TOOL_NAMES, READ_ONLY_TOOLS, } from "./gatekeeper.js";
|
|
30
30
|
import { register } from "./registry.js";
|
|
31
31
|
import { filterOwenloopEnv } from "./child-env.js";
|
|
32
32
|
import { normalizeStepPermissions, validateHarnessOptions } from "./permissions.js";
|
|
33
|
-
import { ResumeUnavailableError, NEUTRAL_PERMISSION_MODES, isNeutralPermissionMode } from "./contract.js";
|
|
33
|
+
import { HarnessIdleTimeoutError, HarnessTurnError, ResumeUnavailableError, NEUTRAL_PERMISSION_MODES, isHarnessTurnError, isNeutralPermissionMode, } from "./contract.js";
|
|
34
34
|
/** The registry key — the id a step def names in `x.harness.id`, and the key
|
|
35
35
|
* `harness-versions.json` pins the CLI under. */
|
|
36
36
|
const HARNESS_ID = 'claude-code';
|
|
@@ -67,6 +67,39 @@ const STRIPPED_ENV_KEYS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDEC
|
|
|
67
67
|
const ALLOW_API_BILLING_VAR = 'OWENLOOP_ALLOW_API_BILLING';
|
|
68
68
|
/** Operator override for the CLI binary; see `resolveExecutable`. */
|
|
69
69
|
const BIN_OVERRIDE_VAR = 'OWENLOOP_CLAUDE_BIN';
|
|
70
|
+
/** Host-only opt-in liveness controller. Never admitted to the child env. */
|
|
71
|
+
export const CLAUDE_IDLE_TIMEOUT_VAR = 'OWENLOOP_CLAUDE_IDLE_TIMEOUT_MS';
|
|
72
|
+
/** Host-only opt-in for the exact snapshot-root Claude audit profile. */
|
|
73
|
+
export const CLAUDE_EXACT_WORKDIR_VAR = 'OWENLOOP_CLAUDE_EXACT_WORKDIR';
|
|
74
|
+
const MIN_IDLE_TIMEOUT_MS = 1_000;
|
|
75
|
+
const MAX_IDLE_TIMEOUT_MS = 3_600_000;
|
|
76
|
+
/** Parse the one adapter-owned recovery setting without silently opting out. */
|
|
77
|
+
export function parseClaudeIdleTimeout(value) {
|
|
78
|
+
if (value === undefined)
|
|
79
|
+
return undefined;
|
|
80
|
+
if (!/^[1-9][0-9]*$/u.test(value)) {
|
|
81
|
+
throw new HarnessTurnError('configuration', true, `${CLAUDE_IDLE_TIMEOUT_VAR} must be a canonical decimal integer between ${MIN_IDLE_TIMEOUT_MS} and ${MAX_IDLE_TIMEOUT_MS}`);
|
|
82
|
+
}
|
|
83
|
+
const idleTimeoutMs = Number(value);
|
|
84
|
+
if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < MIN_IDLE_TIMEOUT_MS || idleTimeoutMs > MAX_IDLE_TIMEOUT_MS) {
|
|
85
|
+
throw new HarnessTurnError('configuration', true, `${CLAUDE_IDLE_TIMEOUT_VAR} must be a canonical decimal integer between ${MIN_IDLE_TIMEOUT_MS} and ${MAX_IDLE_TIMEOUT_MS}`);
|
|
86
|
+
}
|
|
87
|
+
return { idleTimeoutMs };
|
|
88
|
+
}
|
|
89
|
+
export function claudeRecoveryPolicy(env = process.env) {
|
|
90
|
+
return parseClaudeIdleTimeout(env[CLAUDE_IDLE_TIMEOUT_VAR]);
|
|
91
|
+
}
|
|
92
|
+
/** Parse the strict profile as a boolean rather than passing its host spelling onward. */
|
|
93
|
+
export function parseClaudeExactWorkdir(value) {
|
|
94
|
+
if (value === undefined)
|
|
95
|
+
return false;
|
|
96
|
+
if (value === '1')
|
|
97
|
+
return true;
|
|
98
|
+
throw new HarnessTurnError('configuration', true, `${CLAUDE_EXACT_WORKDIR_VAR} must be exactly 1 when present`);
|
|
99
|
+
}
|
|
100
|
+
export function claudeExactWorkdir(env = process.env) {
|
|
101
|
+
return parseClaudeExactWorkdir(env[CLAUDE_EXACT_WORKDIR_VAR]);
|
|
102
|
+
}
|
|
70
103
|
/**
|
|
71
104
|
* Build the environment the harness child runs under.
|
|
72
105
|
*
|
|
@@ -383,17 +416,30 @@ function approvalTitle(toolName, input, suppliedTitle) {
|
|
|
383
416
|
* the behavior is exactly what it was before: deny, and name `ask` as the
|
|
384
417
|
* channel that does reach someone.
|
|
385
418
|
*/
|
|
386
|
-
function buildCanUseTool(cwd, policy, filesystem, onEvent, approvals) {
|
|
419
|
+
function buildCanUseTool(cwd, policy, filesystem, onEvent, approvals, exactWorkdir = false) {
|
|
387
420
|
return async (toolName, input, options) => {
|
|
388
421
|
let verdict;
|
|
389
422
|
try {
|
|
390
|
-
verdict = classifyToolCall({
|
|
423
|
+
verdict = classifyToolCall({
|
|
424
|
+
toolName,
|
|
425
|
+
input,
|
|
426
|
+
workdir: cwd,
|
|
427
|
+
blockedPath: options.blockedPath,
|
|
428
|
+
filesystem,
|
|
429
|
+
exactWorkdir,
|
|
430
|
+
}, policy);
|
|
391
431
|
}
|
|
392
432
|
catch (err) {
|
|
393
433
|
verdict = { decision: 'escalate', reason: `the gatekeeper could not judge this call (${errText(err)})` };
|
|
394
434
|
}
|
|
395
435
|
if (verdict.decision === 'allow')
|
|
396
436
|
return { behavior: 'allow' };
|
|
437
|
+
// This is a host boundary, not a legacy escalation. It never enters the
|
|
438
|
+
// approval channel and its fixed message cannot serialize a model path.
|
|
439
|
+
if (verdict.decision === 'deny') {
|
|
440
|
+
onEvent({ kind: 'progress', text: `exact work-root policy: ${toolName} denied` });
|
|
441
|
+
return { behavior: 'deny', message: verdict.reason };
|
|
442
|
+
}
|
|
397
443
|
if (approvals !== undefined) {
|
|
398
444
|
const title = approvalTitle(toolName, input, options.title);
|
|
399
445
|
onEvent({
|
|
@@ -470,6 +516,7 @@ const READ_ONLY_OWENLOOP_ONLY_NETWORK_TOOLS = [...READ_ONLY_TOOLS]
|
|
|
470
516
|
const BORN_BOUND_OWENLOOP_TOOL_NAMES = ['get_order', 'submit', 'ask'];
|
|
471
517
|
const BORN_BOUND_OWENLOOP_TOOLS = BORN_BOUND_OWENLOOP_TOOL_NAMES.map((name) => `mcp__owenloop__${name}`);
|
|
472
518
|
const RESTRICTED_OWENLOOP_DENIED_TOOLS = ['mcp__owenloop__reject'];
|
|
519
|
+
const EXACT_WORKDIR_BUILTINS = new Set(['Read', 'Glob', 'Grep']);
|
|
473
520
|
const OWENLOOP_CONTROL_TOOLS = new Set([
|
|
474
521
|
...BORN_BOUND_OWENLOOP_TOOLS,
|
|
475
522
|
'mcp__plugin_owenloop_owenloop__get_order',
|
|
@@ -483,8 +530,43 @@ const OWENLOOP_CONTROL_DENY_SPECS = new Set([
|
|
|
483
530
|
'mcp__plugin_owenloop_owenloop__*',
|
|
484
531
|
'mcp__*',
|
|
485
532
|
]);
|
|
533
|
+
function effectiveClaudeTools(permissions) {
|
|
534
|
+
if (permissions.tools !== undefined)
|
|
535
|
+
return permissions.tools;
|
|
536
|
+
if (permissions.filesystem === 'read-only') {
|
|
537
|
+
return permissions.network === 'owenloop-only'
|
|
538
|
+
? READ_ONLY_OWENLOOP_ONLY_NETWORK_TOOLS
|
|
539
|
+
: [...READ_ONLY_TOOLS];
|
|
540
|
+
}
|
|
541
|
+
if (permissions.network === 'owenloop-only')
|
|
542
|
+
return [...OWENLOOP_ONLY_NETWORK_TOOLS];
|
|
543
|
+
return undefined;
|
|
544
|
+
}
|
|
545
|
+
function strictWorkdirToolIssue(permissions) {
|
|
546
|
+
const effective = effectiveClaudeTools(permissions);
|
|
547
|
+
if (effective === undefined) {
|
|
548
|
+
return {
|
|
549
|
+
field: 'tools',
|
|
550
|
+
message: `${CLAUDE_EXACT_WORKDIR_VAR}=1 requires an explicit or derived built-in surface containing only Read, Glob, and Grep`,
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
const unsafe = effective.filter((tool) => !EXACT_WORKDIR_BUILTINS.has(tool) && !BORN_BOUND_OWENLOOP_TOOLS.includes(tool));
|
|
554
|
+
if (unsafe.length === 0)
|
|
555
|
+
return undefined;
|
|
556
|
+
return {
|
|
557
|
+
field: 'tools',
|
|
558
|
+
message: `${CLAUDE_EXACT_WORKDIR_VAR}=1 permits only Read, Glob, Grep, and born-bound Owenloop controls; remove: ${unsafe.join(', ')}`,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
486
561
|
function claudePreflight(permissions) {
|
|
487
562
|
const issues = [];
|
|
563
|
+
let exactWorkdir = false;
|
|
564
|
+
try {
|
|
565
|
+
exactWorkdir = claudeExactWorkdir(process.env);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
issues.push({ field: CLAUDE_EXACT_WORKDIR_VAR, message: errText(error) });
|
|
569
|
+
}
|
|
488
570
|
const authoredMode = permissions.permissionMode;
|
|
489
571
|
if (authoredMode !== undefined) {
|
|
490
572
|
if (!ACCEPTED_PERMISSION_MODES.includes(authoredMode)) {
|
|
@@ -548,6 +630,11 @@ function claudePreflight(permissions) {
|
|
|
548
630
|
message: `the born-bound Owenloop control plane must retain get_order/submit access; remove: ${deniedControl.join(', ')}`,
|
|
549
631
|
});
|
|
550
632
|
}
|
|
633
|
+
if (exactWorkdir) {
|
|
634
|
+
const strictIssue = strictWorkdirToolIssue(permissions);
|
|
635
|
+
if (strictIssue !== undefined)
|
|
636
|
+
issues.push(strictIssue);
|
|
637
|
+
}
|
|
551
638
|
return issues;
|
|
552
639
|
}
|
|
553
640
|
/**
|
|
@@ -561,6 +648,42 @@ const RESUME_FAILURE_RE = /no conversation found|session not found|--resume/i;
|
|
|
561
648
|
function isPlainMap(v) {
|
|
562
649
|
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
563
650
|
}
|
|
651
|
+
/** Programmatic PreToolUse guard for every path-bearing exposed built-in. */
|
|
652
|
+
export function buildExactWorkdirPreToolUse(cwd) {
|
|
653
|
+
return async (input) => {
|
|
654
|
+
const deny = {
|
|
655
|
+
continue: true,
|
|
656
|
+
hookSpecificOutput: {
|
|
657
|
+
hookEventName: 'PreToolUse',
|
|
658
|
+
permissionDecision: 'deny',
|
|
659
|
+
permissionDecisionReason: EXACT_WORKDIR_DENIAL_MESSAGE,
|
|
660
|
+
},
|
|
661
|
+
};
|
|
662
|
+
try {
|
|
663
|
+
if (input.hook_event_name !== 'PreToolUse' || !PATH_BEARING_TOOL_NAMES.has(input.tool_name))
|
|
664
|
+
return deny;
|
|
665
|
+
if (!isPlainMap(input.tool_input))
|
|
666
|
+
return deny;
|
|
667
|
+
const verdict = classifyExactWorkdirPath({
|
|
668
|
+
toolName: input.tool_name,
|
|
669
|
+
input: input.tool_input,
|
|
670
|
+
workdir: cwd,
|
|
671
|
+
});
|
|
672
|
+
if (verdict.decision === 'deny')
|
|
673
|
+
return deny;
|
|
674
|
+
return {
|
|
675
|
+
continue: true,
|
|
676
|
+
hookSpecificOutput: {
|
|
677
|
+
hookEventName: 'PreToolUse',
|
|
678
|
+
permissionDecision: 'allow',
|
|
679
|
+
},
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
catch {
|
|
683
|
+
return deny;
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
}
|
|
564
687
|
/** The mount for owenloop's own work-holder MCP surface, built from the worker's
|
|
565
688
|
* verbatim argv. `alwaysLoad` forces its tools into the turn-1 prompt instead of
|
|
566
689
|
* deferring them behind tool search — a step agent that cannot see `submit` on
|
|
@@ -568,7 +691,7 @@ function isPlainMap(v) {
|
|
|
568
691
|
function owenloopMount(mount) {
|
|
569
692
|
return { type: 'stdio', command: mount.command, args: mount.args, alwaysLoad: true };
|
|
570
693
|
}
|
|
571
|
-
/** Restricted sessions register a positive
|
|
694
|
+
/** Restricted sessions register a positive born-bound subset. The selector is
|
|
572
695
|
* derived from the same names used by `allowedTools`, so the declared exception
|
|
573
696
|
* and the MCP server's actual `tools/list` cannot drift within this adapter. */
|
|
574
697
|
function restrictedOwenloopMount(mount) {
|
|
@@ -597,7 +720,16 @@ function mergeMcpServers(bagServers, mount) {
|
|
|
597
720
|
*/
|
|
598
721
|
export function buildClaudeOptions(inputs, extra) {
|
|
599
722
|
const { permissions } = inputs;
|
|
600
|
-
const
|
|
723
|
+
const exactWorkdir = inputs.exactWorkdir === true;
|
|
724
|
+
const effectiveTools = effectiveClaudeTools(permissions);
|
|
725
|
+
if (exactWorkdir) {
|
|
726
|
+
const issue = strictWorkdirToolIssue(permissions);
|
|
727
|
+
if (issue !== undefined)
|
|
728
|
+
throw new HarnessTurnError('configuration', true, issue.message);
|
|
729
|
+
}
|
|
730
|
+
const diagnosticEvent = inputs.recoveryPolicy === undefined ? extra.onEvent : (_event) => { };
|
|
731
|
+
const isolated = exactWorkdir ||
|
|
732
|
+
permissions.tools !== undefined ||
|
|
601
733
|
permissions.filesystem === 'read-only' ||
|
|
602
734
|
permissions.network === 'owenloop-only';
|
|
603
735
|
const options = {
|
|
@@ -609,14 +741,25 @@ export function buildClaudeOptions(inputs, extra) {
|
|
|
609
741
|
: mergeMcpServers(permissions.extensions['mcpServers'], inputs.owenloopMcp),
|
|
610
742
|
...(isolated ? { settingSources: [], strictMcpConfig: true, skills: [] } : {}),
|
|
611
743
|
stderr: (data) => {
|
|
744
|
+
// Recovery control state and worker logs are deliberately payload-free.
|
|
745
|
+
// Legacy turns keep their established stderr telemetry verbatim.
|
|
612
746
|
const line = data.trimEnd();
|
|
613
|
-
|
|
747
|
+
diagnosticEvent({ kind: 'progress', text: `stderr: ${line}`, failure: cap(line) });
|
|
614
748
|
},
|
|
615
749
|
// Set here, before the `permissionMode` block below, because it is not
|
|
616
750
|
// conditional on that block running: a step naming no mode at all is exactly
|
|
617
751
|
// the case that used to reach the SDK's `default` and be denied wholesale.
|
|
618
|
-
canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), permissions.filesystem,
|
|
752
|
+
canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), permissions.filesystem, diagnosticEvent, inputs.approvals, exactWorkdir),
|
|
619
753
|
};
|
|
754
|
+
if (exactWorkdir) {
|
|
755
|
+
options.hooks = {
|
|
756
|
+
PreToolUse: [{ matcher: [...PATH_BEARING_TOOL_NAMES].join('|'), hooks: [buildExactWorkdirPreToolUse(inputs.cwd)] }],
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
// Partial messages are provider transport only: they reset liveness below but
|
|
760
|
+
// are never mapped into progress/evidence output.
|
|
761
|
+
if (inputs.recoveryPolicy !== undefined)
|
|
762
|
+
options.includePartialMessages = true;
|
|
620
763
|
// Omit the key entirely when nothing resolves — see `resolveExecutable`.
|
|
621
764
|
const executable = resolveExecutable(extra.env);
|
|
622
765
|
if (executable !== undefined)
|
|
@@ -635,7 +778,7 @@ export function buildClaudeOptions(inputs, extra) {
|
|
|
635
778
|
// Dropped rather than thrown or coerced — the same stance normalization
|
|
636
779
|
// takes for a bad `maxTurns`. The linter only checks effort is a string,
|
|
637
780
|
// so an unlintable-but-legal bag can carry an out-of-union value.
|
|
638
|
-
|
|
781
|
+
diagnosticEvent({
|
|
639
782
|
kind: 'progress',
|
|
640
783
|
text: `dropped out-of-range effort '${rawEffort}' (expected one of ${EFFORT_LEVELS.join('|')})`,
|
|
641
784
|
});
|
|
@@ -658,7 +801,7 @@ export function buildClaudeOptions(inputs, extra) {
|
|
|
658
801
|
options.allowDangerouslySkipPermissions = true;
|
|
659
802
|
}
|
|
660
803
|
else {
|
|
661
|
-
|
|
804
|
+
diagnosticEvent({
|
|
662
805
|
kind: 'progress',
|
|
663
806
|
text: `dropped unknown permissionMode '${permissions.permissionMode}' (expected one of ${ACCEPTED_PERMISSION_MODES.join('|')})`,
|
|
664
807
|
});
|
|
@@ -676,19 +819,8 @@ export function buildClaudeOptions(inputs, extra) {
|
|
|
676
819
|
// exception: the audited built-in list becomes explicit, and `allowedTools`
|
|
677
820
|
// also auto-allows the born-bound get_order/submit MCP tools so the restricted
|
|
678
821
|
// agent can inspect and finish its order without an unattended permission prompt.
|
|
679
|
-
// The restricted MCP child itself registers exactly those
|
|
822
|
+
// The restricted MCP child itself registers exactly those born-bound tools; allowedTools
|
|
680
823
|
// is permission automation, not an MCP visibility filter.
|
|
681
|
-
let effectiveTools = permissions.tools;
|
|
682
|
-
if (effectiveTools === undefined && permissions.filesystem === 'read-only') {
|
|
683
|
-
// Filesystem and network are independent. A read-only filesystem still gets
|
|
684
|
-
// audited network readers unless the step separately restricts the network.
|
|
685
|
-
effectiveTools = permissions.network === 'owenloop-only'
|
|
686
|
-
? READ_ONLY_OWENLOOP_ONLY_NETWORK_TOOLS
|
|
687
|
-
: [...READ_ONLY_TOOLS];
|
|
688
|
-
}
|
|
689
|
-
else if (effectiveTools === undefined && permissions.network === 'owenloop-only') {
|
|
690
|
-
effectiveTools = [...OWENLOOP_ONLY_NETWORK_TOOLS];
|
|
691
|
-
}
|
|
692
824
|
if (effectiveTools !== undefined) {
|
|
693
825
|
options.tools = effectiveTools.filter((tool) => !OWENLOOP_CONTROL_TOOLS.has(tool));
|
|
694
826
|
options.allowedTools = [
|
|
@@ -734,7 +866,7 @@ export function buildClaudeOptions(inputs, extra) {
|
|
|
734
866
|
// Outside isolation, `settingSources` and `strictMcpConfig` stay unset so the
|
|
735
867
|
// SDK preserves its normal settings and MCP behavior, including the full
|
|
736
868
|
// get_order/submit/reject work-holder server. Isolation sets `settingSources: []`
|
|
737
|
-
// and `strictMcpConfig: true` above, mounts the positive
|
|
869
|
+
// and `strictMcpConfig: true` above, mounts the positive born-bound work-holder
|
|
738
870
|
// subset, and removes settings, hooks, skills, or external MCP that could bypass
|
|
739
871
|
// the authored restriction.
|
|
740
872
|
// `persistSession` always stays unset: its default is `true`, and disabling it
|
|
@@ -748,6 +880,16 @@ const DEFAULT_START_DEPENDENCIES = {
|
|
|
748
880
|
return (args) => query(args);
|
|
749
881
|
},
|
|
750
882
|
};
|
|
883
|
+
const DEFAULT_DELIVER_DEPENDENCIES = {
|
|
884
|
+
loadQuery: async () => {
|
|
885
|
+
const { query } = await import('@anthropic-ai/claude-agent-sdk');
|
|
886
|
+
return (args) => query(args);
|
|
887
|
+
},
|
|
888
|
+
getSessionInfo: async (token, opts) => {
|
|
889
|
+
const { getSessionInfo } = await import('@anthropic-ai/claude-agent-sdk');
|
|
890
|
+
return getSessionInfo(token, opts);
|
|
891
|
+
},
|
|
892
|
+
};
|
|
751
893
|
/** Module-level, process-wide, keyed by session token. Only reachable from the
|
|
752
894
|
* process that started the session — which is exactly why `stop` is documented
|
|
753
895
|
* as a no-op on a token this process did not start. */
|
|
@@ -760,6 +902,11 @@ const PROGRESS_TEXT_CAP = 2_000;
|
|
|
760
902
|
function cap(text) {
|
|
761
903
|
return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
|
|
762
904
|
}
|
|
905
|
+
/** A payload-free failure line safe for recovery logs and durable telemetry. */
|
|
906
|
+
function sanitizedFailureText(error) {
|
|
907
|
+
const category = isHarnessTurnError(error) ? error.category : 'provider';
|
|
908
|
+
return `provider failure category=${category} (details redacted)`;
|
|
909
|
+
}
|
|
763
910
|
/** Mark messages produced inside a Task-tool subagent. A flat log cannot
|
|
764
911
|
* otherwise tell a subagent's work from the main agent's. */
|
|
765
912
|
function origin(parentToolUseId) {
|
|
@@ -874,68 +1021,228 @@ function emitUser(message, onEvent) {
|
|
|
874
1021
|
* what it uses is what lets a fixture drive it. A live `Query` still satisfies
|
|
875
1022
|
* the narrower type, so nothing at the call sites changes.
|
|
876
1023
|
*/
|
|
877
|
-
export async function consumeTurn(q, onEvent, onInit, expectedSessionId) {
|
|
1024
|
+
export async function consumeTurn(q, onEvent, onInit, expectedSessionId, control = {}) {
|
|
878
1025
|
let sessionId;
|
|
1026
|
+
let sawInit = false;
|
|
879
1027
|
let finalResponse;
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1028
|
+
let terminalFailure;
|
|
1029
|
+
let timer;
|
|
1030
|
+
let timeout;
|
|
1031
|
+
let idleTimeoutFailure;
|
|
1032
|
+
let timerGeneration = 0;
|
|
1033
|
+
let controlledQueryClosed = false;
|
|
1034
|
+
const recoveryEnabled = control.idleTimeoutMs !== undefined;
|
|
1035
|
+
const strictModelIdentity = control.expectedModel !== undefined;
|
|
1036
|
+
const sanitizeProviderTelemetry = control.sanitizeProviderTelemetry === true;
|
|
1037
|
+
const now = control.now ?? Date.now;
|
|
1038
|
+
const setTimer = control.setTimer ?? setTimeout;
|
|
1039
|
+
const clearTimer = control.clearTimer ?? clearTimeout;
|
|
1040
|
+
const closeControlledQuery = () => {
|
|
1041
|
+
if (controlledQueryClosed)
|
|
1042
|
+
return;
|
|
1043
|
+
controlledQueryClosed = true;
|
|
1044
|
+
try {
|
|
1045
|
+
control.close?.();
|
|
898
1046
|
}
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
onEvent({ kind: 'assistant_response', text: finalResponse });
|
|
902
|
-
if (message.subtype !== 'success') {
|
|
903
|
-
// The contract's channel for "something went wrong that is not a resume
|
|
904
|
-
// failure". Emitted BEFORE turn_ended so a caller reading events in
|
|
905
|
-
// order sees the cause before the turn closes.
|
|
906
|
-
onEvent({
|
|
907
|
-
kind: 'exited',
|
|
908
|
-
exitCode: null,
|
|
909
|
-
error: message.errors.join('; ') || message.subtype,
|
|
910
|
-
});
|
|
911
|
-
}
|
|
912
|
-
onEvent({ kind: 'turn_ended' });
|
|
913
|
-
return { sessionId, sawResult: true };
|
|
1047
|
+
catch {
|
|
1048
|
+
// Turn classification is authoritative; exact-query cleanup is best effort.
|
|
914
1049
|
}
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
1050
|
+
};
|
|
1051
|
+
const arm = () => {
|
|
1052
|
+
const idleTimeoutMs = control.idleTimeoutMs;
|
|
1053
|
+
if (idleTimeoutMs === undefined)
|
|
1054
|
+
return;
|
|
1055
|
+
if (timer !== undefined)
|
|
1056
|
+
clearTimer(timer);
|
|
1057
|
+
const generation = ++timerGeneration;
|
|
1058
|
+
idleTimeoutFailure = undefined;
|
|
1059
|
+
const at = now();
|
|
1060
|
+
const deadlineAt = at + idleTimeoutMs;
|
|
1061
|
+
control.onActivity?.({ at, deadlineAt });
|
|
1062
|
+
timeout = new Promise((_resolve, reject) => {
|
|
1063
|
+
timer = setTimer(() => {
|
|
1064
|
+
if (generation !== timerGeneration)
|
|
1065
|
+
return;
|
|
1066
|
+
timer = undefined;
|
|
1067
|
+
idleTimeoutFailure = new HarnessIdleTimeoutError(idleTimeoutMs);
|
|
1068
|
+
// Latch and reject first so an iterator read that synchronously rejects
|
|
1069
|
+
// during abort/close cannot win the race as a generic provider failure.
|
|
1070
|
+
reject(idleTimeoutFailure);
|
|
1071
|
+
try {
|
|
1072
|
+
control.abortController?.abort();
|
|
1073
|
+
}
|
|
1074
|
+
catch {
|
|
1075
|
+
// An already-aborted controller is an equivalent successful teardown.
|
|
1076
|
+
}
|
|
1077
|
+
closeControlledQuery();
|
|
1078
|
+
}, idleTimeoutMs);
|
|
1079
|
+
});
|
|
1080
|
+
};
|
|
1081
|
+
const classifyAssistantError = (error) => {
|
|
1082
|
+
if (error === undefined)
|
|
1083
|
+
return undefined;
|
|
1084
|
+
if (error === 'authentication_failed' || error === 'oauth_org_not_allowed') {
|
|
1085
|
+
return new HarnessTurnError('authentication', true, `provider authentication failure (${error})`);
|
|
918
1086
|
}
|
|
919
|
-
|
|
920
|
-
|
|
1087
|
+
if (error === 'model_not_found') {
|
|
1088
|
+
return new HarnessTurnError('model-unavailable', true, 'provider model is unavailable');
|
|
1089
|
+
}
|
|
1090
|
+
return new HarnessTurnError('provider', false, 'provider reported an unclassified assistant failure');
|
|
1091
|
+
};
|
|
1092
|
+
const classifyResult = (message) => {
|
|
1093
|
+
if (message.type !== 'result' || message.subtype === 'success')
|
|
1094
|
+
return undefined;
|
|
1095
|
+
const structured = message;
|
|
1096
|
+
if (Array.isArray(structured.permission_denials) && structured.permission_denials.length > 0) {
|
|
1097
|
+
return new HarnessTurnError('permission-policy', true, 'provider denied the configured permission policy');
|
|
921
1098
|
}
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
1099
|
+
return new HarnessTurnError('provider', false, 'provider returned an unclassified error result');
|
|
1100
|
+
};
|
|
1101
|
+
const iterator = q[Symbol.asyncIterator]();
|
|
1102
|
+
arm(); // Must cover silence before the first iterator result.
|
|
1103
|
+
try {
|
|
1104
|
+
for (;;) {
|
|
1105
|
+
const next = iterator.next();
|
|
1106
|
+
const item = timeout === undefined ? await next : await Promise.race([next, timeout]);
|
|
1107
|
+
if (item.done) {
|
|
1108
|
+
if (strictModelIdentity && !sawInit) {
|
|
1109
|
+
throw new HarnessTurnError('model-unavailable', true, 'provider did not confirm the configured literal model');
|
|
1110
|
+
}
|
|
1111
|
+
if ((recoveryEnabled || strictModelIdentity) && terminalFailure !== undefined)
|
|
1112
|
+
throw terminalFailure;
|
|
1113
|
+
return { sessionId, sawResult: false };
|
|
1114
|
+
}
|
|
1115
|
+
const message = item.value;
|
|
1116
|
+
// Reset BEFORE mapping. A partial event stays transport-only but is still
|
|
1117
|
+
// proof of provider liveness.
|
|
1118
|
+
arm();
|
|
1119
|
+
if (message.type === 'system' && message.subtype === 'init') {
|
|
1120
|
+
sawInit = true;
|
|
1121
|
+
if (expectedSessionId !== undefined && message.session_id !== expectedSessionId) {
|
|
1122
|
+
if (sanitizeProviderTelemetry) {
|
|
1123
|
+
throw new HarnessTurnError('provider', false, 'provider session identity mismatch (details redacted)');
|
|
1124
|
+
}
|
|
1125
|
+
throw new Error(`provider session id mismatch: expected ${expectedSessionId}, received ${message.session_id}`);
|
|
1126
|
+
}
|
|
1127
|
+
if (strictModelIdentity && message.model !== control.expectedModel) {
|
|
1128
|
+
throw new HarnessTurnError('model-unavailable', true, 'provider did not honor the configured literal model');
|
|
1129
|
+
}
|
|
1130
|
+
sessionId = message.session_id;
|
|
1131
|
+
// The ONLY place these are observable. The live smoke asserts on the
|
|
1132
|
+
// `apiKeySource` here (subscription OAuth vs. an API key), and a later
|
|
1133
|
+
// phase's version-mismatch warning will want `claude_code_version`.
|
|
1134
|
+
if (!sanitizeProviderTelemetry) {
|
|
1135
|
+
const servers = message.mcp_servers.map((s) => `${s.name}=${s.status}`).join(',');
|
|
1136
|
+
onEvent({
|
|
1137
|
+
kind: 'progress',
|
|
1138
|
+
text: `session ${message.session_id}: cliVersion=${message.claude_code_version} ` +
|
|
1139
|
+
`model=${message.model} apiKeySource=${message.apiKeySource} ` +
|
|
1140
|
+
`permissionMode=${message.permissionMode} cwd=${message.cwd} mcp=[${servers}]`,
|
|
1141
|
+
model: cap(message.model),
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
onInit?.(sessionId);
|
|
1145
|
+
}
|
|
1146
|
+
else if (message.type === 'system' && message.subtype === 'model_refusal_fallback' && strictModelIdentity) {
|
|
1147
|
+
throw new HarnessTurnError('model-unavailable', true, 'provider attempted a model fallback');
|
|
1148
|
+
}
|
|
1149
|
+
else if (message.type === 'result') {
|
|
1150
|
+
if (strictModelIdentity && !sawInit) {
|
|
1151
|
+
throw new HarnessTurnError('model-unavailable', true, 'provider did not confirm the configured literal model');
|
|
1152
|
+
}
|
|
1153
|
+
const classified = recoveryEnabled || strictModelIdentity ? terminalFailure ?? classifyResult(message) : undefined;
|
|
1154
|
+
if (!sanitizeProviderTelemetry && finalResponse !== undefined) {
|
|
1155
|
+
onEvent({ kind: 'assistant_response', text: finalResponse });
|
|
1156
|
+
}
|
|
1157
|
+
if (message.subtype !== 'success' || classified !== undefined) {
|
|
1158
|
+
// The contract's channel for "something went wrong that is not a resume
|
|
1159
|
+
// failure". Emitted BEFORE turn_ended so a caller reading events in
|
|
1160
|
+
// order sees the cause before the turn closes.
|
|
1161
|
+
onEvent({
|
|
1162
|
+
kind: 'exited',
|
|
1163
|
+
exitCode: null,
|
|
1164
|
+
error: sanitizeProviderTelemetry || message.subtype === 'success'
|
|
1165
|
+
? sanitizedFailureText(classified)
|
|
1166
|
+
: message.errors.join('; ') || message.subtype,
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
onEvent({ kind: 'turn_ended' });
|
|
1170
|
+
if ((recoveryEnabled || strictModelIdentity) && classified !== undefined)
|
|
1171
|
+
throw classified;
|
|
1172
|
+
return { sessionId, sawResult: true };
|
|
1173
|
+
}
|
|
1174
|
+
else if (message.type === 'assistant') {
|
|
1175
|
+
if (!sanitizeProviderTelemetry) {
|
|
1176
|
+
emitAssistant(message, onEvent);
|
|
1177
|
+
finalResponse = assistantResponse(message) ?? finalResponse;
|
|
1178
|
+
}
|
|
1179
|
+
if (recoveryEnabled || strictModelIdentity)
|
|
1180
|
+
terminalFailure ??= classifyAssistantError(message.error);
|
|
1181
|
+
}
|
|
1182
|
+
else if ((recoveryEnabled || strictModelIdentity) && message.type === 'auth_status' && message.error !== undefined) {
|
|
1183
|
+
// `error` is a structured SDK field. Its prose is deliberately neither
|
|
1184
|
+
// logged nor parsed for recovery decisions.
|
|
1185
|
+
throw new HarnessTurnError('authentication', true, 'provider authentication status failed');
|
|
1186
|
+
}
|
|
1187
|
+
else if (message.type === 'user') {
|
|
1188
|
+
if (!sanitizeProviderTelemetry)
|
|
1189
|
+
emitUser(message, onEvent);
|
|
1190
|
+
}
|
|
1191
|
+
// `needs_input` is NEVER emitted: this SDK path has no blocking-question
|
|
1192
|
+
// channel that maps to it, and the contract has no reply channel by design.
|
|
1193
|
+
// `stream_event` is deliberately NOT mapped. Recovery-enabled options opt
|
|
1194
|
+
// into partial messages only to reset liveness; their payload would merely
|
|
1195
|
+
// duplicate the eventual assistant message and must not escape telemetry.
|
|
1196
|
+
// Other unrecognized types stay silent by design: the vendor adds message
|
|
1197
|
+
// kinds between releases, and a mapping that threw on one would turn a
|
|
1198
|
+
// routine CLI upgrade into a failed order.
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
catch (error) {
|
|
1202
|
+
if (!recoveryEnabled && !strictModelIdentity)
|
|
1203
|
+
throw error;
|
|
1204
|
+
if (terminalFailure?.terminal === true)
|
|
1205
|
+
throw terminalFailure;
|
|
1206
|
+
if (idleTimeoutFailure !== undefined)
|
|
1207
|
+
throw idleTimeoutFailure;
|
|
1208
|
+
if (isHarnessTurnError(error))
|
|
1209
|
+
throw error;
|
|
1210
|
+
// This is our own session-integrity guard, not a provider failure. Preserve
|
|
1211
|
+
// its actionable detail while normalizing all actual SDK failures below.
|
|
1212
|
+
if (error instanceof Error && error.message.startsWith('provider session id mismatch:'))
|
|
1213
|
+
throw error;
|
|
1214
|
+
// `deliverClaude` has a provider-specific, secondary resume-refusal fallback
|
|
1215
|
+
// behind its deterministic session-info preflight. Keep the original refusal
|
|
1216
|
+
// text intact until that boundary can translate it to ResumeUnavailableError;
|
|
1217
|
+
// wrapping it here would make an opt-out resume race look like a generic turn
|
|
1218
|
+
// failure and suppress the established same-firing cold replay.
|
|
1219
|
+
if (RESUME_FAILURE_RE.test(errText(error)))
|
|
1220
|
+
throw error;
|
|
1221
|
+
throw new HarnessTurnError('provider', false, 'provider SDK stream failed');
|
|
1222
|
+
}
|
|
1223
|
+
finally {
|
|
1224
|
+
timerGeneration += 1;
|
|
1225
|
+
if (timer !== undefined)
|
|
1226
|
+
clearTimer(timer);
|
|
1227
|
+
// Manual iterator driving does not perform AsyncIteratorClose when the
|
|
1228
|
+
// result message returns from inside the loop. Close this exact query before
|
|
1229
|
+
// a same-token recovery turn can replace it in SESSIONS.
|
|
1230
|
+
closeControlledQuery();
|
|
931
1231
|
}
|
|
932
|
-
return { sessionId, sawResult: false };
|
|
933
1232
|
}
|
|
934
1233
|
/** The message text of an unknown thrown value, for an `exited` event. */
|
|
935
1234
|
function errText(err) {
|
|
936
1235
|
return err instanceof Error ? err.message : String(err);
|
|
937
1236
|
}
|
|
938
1237
|
export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DEPENDENCIES) {
|
|
1238
|
+
// Parse and validate host policy before even emitting a start marker: a bad
|
|
1239
|
+
// audit configuration must not construct a provider query or a resumable row.
|
|
1240
|
+
const exactWorkdir = claudeExactWorkdir(process.env);
|
|
1241
|
+
if (exactWorkdir) {
|
|
1242
|
+
const issue = strictWorkdirToolIssue(args.permissions);
|
|
1243
|
+
if (issue !== undefined)
|
|
1244
|
+
throw new HarnessTurnError('configuration', true, issue.message);
|
|
1245
|
+
}
|
|
939
1246
|
// The provider token exists before any SDK work. `started` is synchronous by
|
|
940
1247
|
// contract, so the caller's fsynced active-row append must return before the
|
|
941
1248
|
// query factory can initialize a process or receive prompt bytes.
|
|
@@ -955,7 +1262,7 @@ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DE
|
|
|
955
1262
|
}
|
|
956
1263
|
const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
|
|
957
1264
|
const abortController = new AbortController();
|
|
958
|
-
const options = buildClaudeOptions(args, { env, abortController, onEvent, sessionId });
|
|
1265
|
+
const options = buildClaudeOptions({ ...args, exactWorkdir }, { env, abortController, onEvent, sessionId });
|
|
959
1266
|
let q;
|
|
960
1267
|
try {
|
|
961
1268
|
// A plain STRING prompt, not an AsyncIterable. Query construction is the
|
|
@@ -971,52 +1278,79 @@ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DE
|
|
|
971
1278
|
catch {
|
|
972
1279
|
// An already-aborted controller is equivalent to success.
|
|
973
1280
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1281
|
+
if (args.recoveryPolicy === undefined) {
|
|
1282
|
+
onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
|
|
1283
|
+
throw err;
|
|
1284
|
+
}
|
|
1285
|
+
const failure = isHarnessTurnError(err)
|
|
1286
|
+
? err
|
|
1287
|
+
: new HarnessTurnError('provider', false, 'provider SDK query initialization failed');
|
|
1288
|
+
onEvent({
|
|
1289
|
+
kind: 'exited',
|
|
1290
|
+
exitCode: null,
|
|
1291
|
+
error: sanitizedFailureText(failure),
|
|
1292
|
+
});
|
|
1293
|
+
throw failure;
|
|
976
1294
|
}
|
|
977
1295
|
SESSIONS.set(sessionId, { query: q, abortController, options });
|
|
978
|
-
let
|
|
979
|
-
let
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
if (
|
|
1296
|
+
let exactClosed = false;
|
|
1297
|
+
let failureEventEmitted = false;
|
|
1298
|
+
const turnOnEvent = (event) => {
|
|
1299
|
+
if (event.kind === 'exited')
|
|
1300
|
+
failureEventEmitted = true;
|
|
1301
|
+
onEvent(event);
|
|
1302
|
+
};
|
|
1303
|
+
const closeExact = () => {
|
|
1304
|
+
if (exactClosed)
|
|
1305
|
+
return;
|
|
1306
|
+
exactClosed = true;
|
|
1307
|
+
if (SESSIONS.get(sessionId)?.query === q)
|
|
990
1308
|
SESSIONS.delete(sessionId);
|
|
991
1309
|
try {
|
|
992
1310
|
abortController.abort();
|
|
993
1311
|
}
|
|
994
1312
|
catch {
|
|
995
|
-
//
|
|
1313
|
+
// Best-effort, idempotent teardown.
|
|
996
1314
|
}
|
|
997
1315
|
try {
|
|
998
1316
|
q.close();
|
|
999
1317
|
}
|
|
1000
1318
|
catch {
|
|
1001
|
-
//
|
|
1319
|
+
// The timeout/failure remains authoritative.
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
let initVerified = false;
|
|
1323
|
+
let outcome;
|
|
1324
|
+
try {
|
|
1325
|
+
outcome = await consumeTurn(q, turnOnEvent, () => {
|
|
1326
|
+
initVerified = true;
|
|
1327
|
+
}, sessionId, {
|
|
1328
|
+
...(args.recoveryPolicy !== undefined ? { idleTimeoutMs: args.recoveryPolicy.idleTimeoutMs } : {}),
|
|
1329
|
+
sanitizeProviderTelemetry: args.recoveryPolicy !== undefined,
|
|
1330
|
+
abortController,
|
|
1331
|
+
close: closeExact,
|
|
1332
|
+
...(exactWorkdir && options.model !== undefined ? { expectedModel: options.model } : {}),
|
|
1333
|
+
onActivity: (activity) => onEvent({ kind: 'activity', ...activity }),
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
catch (err) {
|
|
1337
|
+
// An init mismatch or pre-init failure must not leave the preselected token
|
|
1338
|
+
// registered. `consumeTurn` closes every settled exact query; this explicit
|
|
1339
|
+
// delete preserves the cold-start gate even if that cleanup seam changes.
|
|
1340
|
+
if (!initVerified)
|
|
1341
|
+
SESSIONS.delete(sessionId);
|
|
1342
|
+
closeExact();
|
|
1343
|
+
if (!failureEventEmitted) {
|
|
1344
|
+
onEvent({
|
|
1345
|
+
kind: 'exited',
|
|
1346
|
+
exitCode: null,
|
|
1347
|
+
error: args.recoveryPolicy !== undefined ? sanitizedFailureText(err) : errText(err),
|
|
1348
|
+
});
|
|
1002
1349
|
}
|
|
1003
|
-
onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
|
|
1004
1350
|
throw err;
|
|
1005
1351
|
}
|
|
1006
1352
|
if (outcome.sessionId === undefined) {
|
|
1007
|
-
|
|
1008
|
-
try {
|
|
1009
|
-
abortController.abort();
|
|
1010
|
-
}
|
|
1011
|
-
catch {
|
|
1012
|
-
// An already-aborted controller is equivalent to success.
|
|
1013
|
-
}
|
|
1014
|
-
try {
|
|
1015
|
-
q.close();
|
|
1016
|
-
}
|
|
1017
|
-
catch {
|
|
1018
|
-
// The missing-init error below is authoritative.
|
|
1019
|
-
}
|
|
1353
|
+
closeExact();
|
|
1020
1354
|
const why = outcome.sawResult
|
|
1021
1355
|
? 'the turn ended without confirming the supplied session id'
|
|
1022
1356
|
: 'the stream ended before confirming the supplied session id';
|
|
@@ -1025,12 +1359,22 @@ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DE
|
|
|
1025
1359
|
}
|
|
1026
1360
|
return ref;
|
|
1027
1361
|
}
|
|
1028
|
-
async function
|
|
1362
|
+
export async function deliverClaude(ref, message, args, onEvent, dependencies = DEFAULT_DELIVER_DEPENDENCIES) {
|
|
1363
|
+
// This must precede the session-info preflight too: an incompatible strict
|
|
1364
|
+
// profile is a configuration error, not a reason to ask the provider first.
|
|
1365
|
+
const exactWorkdir = claudeExactWorkdir(process.env);
|
|
1366
|
+
if (exactWorkdir) {
|
|
1367
|
+
const issue = strictWorkdirToolIssue(args.permissions);
|
|
1368
|
+
if (issue !== undefined)
|
|
1369
|
+
throw new HarnessTurnError('configuration', true, issue.message);
|
|
1370
|
+
}
|
|
1029
1371
|
// Session lookup is scoped to the PROJECT DIRECTORY, so a deleted worktree can
|
|
1030
1372
|
// never resume no matter how good the token is. Distinct message on purpose —
|
|
1031
1373
|
// the caller reads these to tell the two failures apart.
|
|
1032
1374
|
if (!existsSync(args.cwd)) {
|
|
1033
|
-
throw new ResumeUnavailableError(
|
|
1375
|
+
throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
|
|
1376
|
+
? 'recovery resume cwd is unavailable (details redacted)'
|
|
1377
|
+
: `resume cwd no longer exists: ${args.cwd}`);
|
|
1034
1378
|
}
|
|
1035
1379
|
// Deterministic pre-check, rather than parsing a failed query's error text
|
|
1036
1380
|
// (that string is unverified and can change between releases).
|
|
@@ -1041,14 +1385,15 @@ async function deliver(ref, message, args, onEvent) {
|
|
|
1041
1385
|
// hang and never a wrong-session resume — so it is the safe way to be wrong.
|
|
1042
1386
|
let known = false;
|
|
1043
1387
|
try {
|
|
1044
|
-
|
|
1045
|
-
known = (await getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
|
|
1388
|
+
known = (await dependencies.getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
|
|
1046
1389
|
}
|
|
1047
1390
|
catch {
|
|
1048
1391
|
known = false;
|
|
1049
1392
|
}
|
|
1050
1393
|
if (!known) {
|
|
1051
|
-
throw new ResumeUnavailableError(
|
|
1394
|
+
throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
|
|
1395
|
+
? 'provider no longer knows the recovery session (details redacted)'
|
|
1396
|
+
: `provider no longer knows session ${ref.token}`);
|
|
1052
1397
|
}
|
|
1053
1398
|
const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
|
|
1054
1399
|
const abortController = new AbortController();
|
|
@@ -1067,7 +1412,7 @@ async function deliver(ref, message, args, onEvent) {
|
|
|
1067
1412
|
// A resumed turn does not inherit permission mode / tool lists / model from the
|
|
1068
1413
|
// session — they are per-invocation flags — which is exactly why they must be
|
|
1069
1414
|
// re-mapped here.
|
|
1070
|
-
const options = buildClaudeOptions(args, {
|
|
1415
|
+
const options = buildClaudeOptions({ ...args, exactWorkdir }, {
|
|
1071
1416
|
env,
|
|
1072
1417
|
abortController,
|
|
1073
1418
|
onEvent,
|
|
@@ -1075,20 +1420,79 @@ async function deliver(ref, message, args, onEvent) {
|
|
|
1075
1420
|
});
|
|
1076
1421
|
// `forkSession` is deliberately NOT set: a fork would mint a new session id the
|
|
1077
1422
|
// caller does not know about, and resume must continue the SAME session.
|
|
1078
|
-
|
|
1079
|
-
|
|
1423
|
+
let q;
|
|
1424
|
+
try {
|
|
1425
|
+
const query = await dependencies.loadQuery();
|
|
1426
|
+
q = query({ prompt: message, options });
|
|
1427
|
+
}
|
|
1428
|
+
catch (err) {
|
|
1429
|
+
if (args.recoveryPolicy === undefined) {
|
|
1430
|
+
onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
|
|
1431
|
+
throw err;
|
|
1432
|
+
}
|
|
1433
|
+
const failure = isHarnessTurnError(err)
|
|
1434
|
+
? err
|
|
1435
|
+
: new HarnessTurnError('provider', false, 'provider SDK query initialization failed');
|
|
1436
|
+
onEvent({
|
|
1437
|
+
kind: 'exited',
|
|
1438
|
+
exitCode: null,
|
|
1439
|
+
error: sanitizedFailureText(failure),
|
|
1440
|
+
});
|
|
1441
|
+
throw failure;
|
|
1442
|
+
}
|
|
1080
1443
|
SESSIONS.set(ref.token, { query: q, abortController, options });
|
|
1444
|
+
let exactClosed = false;
|
|
1445
|
+
let failureEventEmitted = false;
|
|
1446
|
+
const turnOnEvent = (event) => {
|
|
1447
|
+
if (event.kind === 'exited')
|
|
1448
|
+
failureEventEmitted = true;
|
|
1449
|
+
onEvent(event);
|
|
1450
|
+
};
|
|
1451
|
+
const closeExact = () => {
|
|
1452
|
+
if (exactClosed)
|
|
1453
|
+
return;
|
|
1454
|
+
exactClosed = true;
|
|
1455
|
+
if (SESSIONS.get(ref.token)?.query === q)
|
|
1456
|
+
SESSIONS.delete(ref.token);
|
|
1457
|
+
try {
|
|
1458
|
+
abortController.abort();
|
|
1459
|
+
}
|
|
1460
|
+
catch {
|
|
1461
|
+
// Best-effort, idempotent teardown.
|
|
1462
|
+
}
|
|
1463
|
+
try {
|
|
1464
|
+
q.close();
|
|
1465
|
+
}
|
|
1466
|
+
catch {
|
|
1467
|
+
// The timeout/failure remains authoritative.
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1081
1470
|
try {
|
|
1082
1471
|
// Never emits `started` — the contract forbids re-emitting it on a resume.
|
|
1083
|
-
await consumeTurn(q,
|
|
1472
|
+
await consumeTurn(q, turnOnEvent, undefined, undefined, {
|
|
1473
|
+
...(args.recoveryPolicy !== undefined ? { idleTimeoutMs: args.recoveryPolicy.idleTimeoutMs } : {}),
|
|
1474
|
+
sanitizeProviderTelemetry: args.recoveryPolicy !== undefined,
|
|
1475
|
+
abortController,
|
|
1476
|
+
close: closeExact,
|
|
1477
|
+
...(exactWorkdir && options.model !== undefined ? { expectedModel: options.model } : {}),
|
|
1478
|
+
onActivity: (activity) => onEvent({ kind: 'activity', ...activity }),
|
|
1479
|
+
});
|
|
1084
1480
|
}
|
|
1085
1481
|
catch (err) {
|
|
1086
1482
|
const text = errText(err);
|
|
1087
1483
|
// Belt and braces behind the `getSessionInfo` pre-check.
|
|
1088
1484
|
if (RESUME_FAILURE_RE.test(text)) {
|
|
1089
|
-
throw new ResumeUnavailableError(
|
|
1485
|
+
throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
|
|
1486
|
+
? 'provider refused recovery resume (details redacted)'
|
|
1487
|
+
: `provider refused resume of session ${ref.token}: ${text}`);
|
|
1488
|
+
}
|
|
1489
|
+
if (!failureEventEmitted) {
|
|
1490
|
+
onEvent({
|
|
1491
|
+
kind: 'exited',
|
|
1492
|
+
exitCode: null,
|
|
1493
|
+
error: args.recoveryPolicy !== undefined ? sanitizedFailureText(err) : text,
|
|
1494
|
+
});
|
|
1090
1495
|
}
|
|
1091
|
-
onEvent({ kind: 'exited', exitCode: null, error: text });
|
|
1092
1496
|
throw err;
|
|
1093
1497
|
}
|
|
1094
1498
|
}
|
|
@@ -1234,9 +1638,10 @@ export const claudeAdapter = {
|
|
|
1234
1638
|
// The provider stores the session and resumes it from the opaque token this
|
|
1235
1639
|
// adapter puts in `HarnessSessionRef.token`.
|
|
1236
1640
|
resumeTier: 'native-token',
|
|
1641
|
+
recoveryPolicy: () => claudeRecoveryPolicy(),
|
|
1237
1642
|
preflight: claudePreflight,
|
|
1238
1643
|
start: startClaude,
|
|
1239
|
-
deliver,
|
|
1644
|
+
deliver: deliverClaude,
|
|
1240
1645
|
stop,
|
|
1241
1646
|
lintStep,
|
|
1242
1647
|
resumeCommand,
|