owenloop 0.5.22 → 0.5.23

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.
@@ -30,7 +30,7 @@ import { classifyToolCall, 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,26 @@ 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
+ const MIN_IDLE_TIMEOUT_MS = 1_000;
73
+ const MAX_IDLE_TIMEOUT_MS = 3_600_000;
74
+ /** Parse the one adapter-owned recovery setting without silently opting out. */
75
+ export function parseClaudeIdleTimeout(value) {
76
+ if (value === undefined)
77
+ return undefined;
78
+ if (!/^[1-9][0-9]*$/u.test(value)) {
79
+ 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}`);
80
+ }
81
+ const idleTimeoutMs = Number(value);
82
+ if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < MIN_IDLE_TIMEOUT_MS || idleTimeoutMs > MAX_IDLE_TIMEOUT_MS) {
83
+ 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}`);
84
+ }
85
+ return { idleTimeoutMs };
86
+ }
87
+ export function claudeRecoveryPolicy(env = process.env) {
88
+ return parseClaudeIdleTimeout(env[CLAUDE_IDLE_TIMEOUT_VAR]);
89
+ }
70
90
  /**
71
91
  * Build the environment the harness child runs under.
72
92
  *
@@ -597,6 +617,7 @@ function mergeMcpServers(bagServers, mount) {
597
617
  */
598
618
  export function buildClaudeOptions(inputs, extra) {
599
619
  const { permissions } = inputs;
620
+ const diagnosticEvent = inputs.recoveryPolicy === undefined ? extra.onEvent : (_event) => { };
600
621
  const isolated = permissions.tools !== undefined ||
601
622
  permissions.filesystem === 'read-only' ||
602
623
  permissions.network === 'owenloop-only';
@@ -609,14 +630,20 @@ export function buildClaudeOptions(inputs, extra) {
609
630
  : mergeMcpServers(permissions.extensions['mcpServers'], inputs.owenloopMcp),
610
631
  ...(isolated ? { settingSources: [], strictMcpConfig: true, skills: [] } : {}),
611
632
  stderr: (data) => {
633
+ // Recovery control state and worker logs are deliberately payload-free.
634
+ // Legacy turns keep their established stderr telemetry verbatim.
612
635
  const line = data.trimEnd();
613
- extra.onEvent({ kind: 'progress', text: `stderr: ${line}`, failure: cap(line) });
636
+ diagnosticEvent({ kind: 'progress', text: `stderr: ${line}`, failure: cap(line) });
614
637
  },
615
638
  // Set here, before the `permissionMode` block below, because it is not
616
639
  // conditional on that block running: a step naming no mode at all is exactly
617
640
  // the case that used to reach the SDK's `default` and be denied wholesale.
618
- canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), permissions.filesystem, extra.onEvent, inputs.approvals),
641
+ canUseTool: buildCanUseTool(inputs.cwd, gatePolicyFor(permissions.permissionMode), permissions.filesystem, diagnosticEvent, inputs.approvals),
619
642
  };
643
+ // Partial messages are provider transport only: they reset liveness below but
644
+ // are never mapped into progress/evidence output.
645
+ if (inputs.recoveryPolicy !== undefined)
646
+ options.includePartialMessages = true;
620
647
  // Omit the key entirely when nothing resolves — see `resolveExecutable`.
621
648
  const executable = resolveExecutable(extra.env);
622
649
  if (executable !== undefined)
@@ -635,7 +662,7 @@ export function buildClaudeOptions(inputs, extra) {
635
662
  // Dropped rather than thrown or coerced — the same stance normalization
636
663
  // takes for a bad `maxTurns`. The linter only checks effort is a string,
637
664
  // so an unlintable-but-legal bag can carry an out-of-union value.
638
- extra.onEvent({
665
+ diagnosticEvent({
639
666
  kind: 'progress',
640
667
  text: `dropped out-of-range effort '${rawEffort}' (expected one of ${EFFORT_LEVELS.join('|')})`,
641
668
  });
@@ -658,7 +685,7 @@ export function buildClaudeOptions(inputs, extra) {
658
685
  options.allowDangerouslySkipPermissions = true;
659
686
  }
660
687
  else {
661
- extra.onEvent({
688
+ diagnosticEvent({
662
689
  kind: 'progress',
663
690
  text: `dropped unknown permissionMode '${permissions.permissionMode}' (expected one of ${ACCEPTED_PERMISSION_MODES.join('|')})`,
664
691
  });
@@ -748,6 +775,16 @@ const DEFAULT_START_DEPENDENCIES = {
748
775
  return (args) => query(args);
749
776
  },
750
777
  };
778
+ const DEFAULT_DELIVER_DEPENDENCIES = {
779
+ loadQuery: async () => {
780
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
781
+ return (args) => query(args);
782
+ },
783
+ getSessionInfo: async (token, opts) => {
784
+ const { getSessionInfo } = await import('@anthropic-ai/claude-agent-sdk');
785
+ return getSessionInfo(token, opts);
786
+ },
787
+ };
751
788
  /** Module-level, process-wide, keyed by session token. Only reachable from the
752
789
  * process that started the session — which is exactly why `stop` is documented
753
790
  * as a no-op on a token this process did not start. */
@@ -760,6 +797,11 @@ const PROGRESS_TEXT_CAP = 2_000;
760
797
  function cap(text) {
761
798
  return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
762
799
  }
800
+ /** A payload-free failure line safe for recovery logs and durable telemetry. */
801
+ function sanitizedFailureText(error) {
802
+ const category = isHarnessTurnError(error) ? error.category : 'provider';
803
+ return `provider failure category=${category} (details redacted)`;
804
+ }
763
805
  /** Mark messages produced inside a Task-tool subagent. A flat log cannot
764
806
  * otherwise tell a subagent's work from the main agent's. */
765
807
  function origin(parentToolUseId) {
@@ -874,62 +916,199 @@ function emitUser(message, onEvent) {
874
916
  * what it uses is what lets a fixture drive it. A live `Query` still satisfies
875
917
  * the narrower type, so nothing at the call sites changes.
876
918
  */
877
- export async function consumeTurn(q, onEvent, onInit, expectedSessionId) {
919
+ export async function consumeTurn(q, onEvent, onInit, expectedSessionId, control = {}) {
878
920
  let sessionId;
879
921
  let finalResponse;
880
- for await (const message of q) {
881
- if (message.type === 'system' && message.subtype === 'init') {
882
- if (expectedSessionId !== undefined && message.session_id !== expectedSessionId) {
883
- throw new Error(`provider session id mismatch: expected ${expectedSessionId}, received ${message.session_id}`);
884
- }
885
- sessionId = message.session_id;
886
- // The ONLY place these are observable. The live smoke asserts on the
887
- // `apiKeySource` here (subscription OAuth vs. an API key), and a later
888
- // phase's version-mismatch warning will want `claude_code_version`.
889
- const servers = message.mcp_servers.map((s) => `${s.name}=${s.status}`).join(',');
890
- onEvent({
891
- kind: 'progress',
892
- text: `session ${message.session_id}: cliVersion=${message.claude_code_version} ` +
893
- `model=${message.model} apiKeySource=${message.apiKeySource} ` +
894
- `permissionMode=${message.permissionMode} cwd=${message.cwd} mcp=[${servers}]`,
895
- model: cap(message.model),
896
- });
897
- onInit?.(sessionId);
922
+ let terminalFailure;
923
+ let timer;
924
+ let timeout;
925
+ let idleTimeoutFailure;
926
+ let timerGeneration = 0;
927
+ let controlledQueryClosed = false;
928
+ const recoveryEnabled = control.idleTimeoutMs !== undefined;
929
+ const sanitizeProviderTelemetry = control.sanitizeProviderTelemetry === true;
930
+ const now = control.now ?? Date.now;
931
+ const setTimer = control.setTimer ?? setTimeout;
932
+ const clearTimer = control.clearTimer ?? clearTimeout;
933
+ const closeControlledQuery = () => {
934
+ if (controlledQueryClosed)
935
+ return;
936
+ controlledQueryClosed = true;
937
+ try {
938
+ control.close?.();
898
939
  }
899
- else if (message.type === 'result') {
900
- if (finalResponse !== undefined)
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 };
940
+ catch {
941
+ // Turn classification is authoritative; exact-query cleanup is best effort.
942
+ }
943
+ };
944
+ const arm = () => {
945
+ const idleTimeoutMs = control.idleTimeoutMs;
946
+ if (idleTimeoutMs === undefined)
947
+ return;
948
+ if (timer !== undefined)
949
+ clearTimer(timer);
950
+ const generation = ++timerGeneration;
951
+ idleTimeoutFailure = undefined;
952
+ const at = now();
953
+ const deadlineAt = at + idleTimeoutMs;
954
+ control.onActivity?.({ at, deadlineAt });
955
+ timeout = new Promise((_resolve, reject) => {
956
+ timer = setTimer(() => {
957
+ if (generation !== timerGeneration)
958
+ return;
959
+ timer = undefined;
960
+ idleTimeoutFailure = new HarnessIdleTimeoutError(idleTimeoutMs);
961
+ // Latch and reject first so an iterator read that synchronously rejects
962
+ // during abort/close cannot win the race as a generic provider failure.
963
+ reject(idleTimeoutFailure);
964
+ try {
965
+ control.abortController?.abort();
966
+ }
967
+ catch {
968
+ // An already-aborted controller is an equivalent successful teardown.
969
+ }
970
+ closeControlledQuery();
971
+ }, idleTimeoutMs);
972
+ });
973
+ };
974
+ const classifyAssistantError = (error) => {
975
+ if (error === undefined)
976
+ return undefined;
977
+ if (error === 'authentication_failed' || error === 'oauth_org_not_allowed') {
978
+ return new HarnessTurnError('authentication', true, `provider authentication failure (${error})`);
914
979
  }
915
- else if (message.type === 'assistant') {
916
- emitAssistant(message, onEvent);
917
- finalResponse = assistantResponse(message) ?? finalResponse;
980
+ if (error === 'model_not_found') {
981
+ return new HarnessTurnError('model-unavailable', true, 'provider model is unavailable');
918
982
  }
919
- else if (message.type === 'user') {
920
- emitUser(message, onEvent);
983
+ return new HarnessTurnError('provider', false, 'provider reported an unclassified assistant failure');
984
+ };
985
+ const classifyResult = (message) => {
986
+ if (message.type !== 'result' || message.subtype === 'success')
987
+ return undefined;
988
+ const structured = message;
989
+ if (Array.isArray(structured.permission_denials) && structured.permission_denials.length > 0) {
990
+ return new HarnessTurnError('permission-policy', true, 'provider denied the configured permission policy');
921
991
  }
922
- // `needs_input` is NEVER emitted: this SDK path has no blocking-question
923
- // channel that maps to it, and the contract has no reply channel by design.
924
- // `stream_event` is deliberately NOT mapped. The SDK only emits it when
925
- // `Options.includePartialMessages` is set, and `buildClaudeOptions` never
926
- // sets it — so the branch would be unreachable today, and if it ever
927
- // became reachable it would duplicate the text the `assistant` message
928
- // already carries. Unrecognized types stay silent by design: the vendor
929
- // adds message kinds between releases, and a mapping that threw on one
930
- // would turn a routine CLI upgrade into a failed order.
992
+ return new HarnessTurnError('provider', false, 'provider returned an unclassified error result');
993
+ };
994
+ const iterator = q[Symbol.asyncIterator]();
995
+ arm(); // Must cover silence before the first iterator result.
996
+ try {
997
+ for (;;) {
998
+ const next = iterator.next();
999
+ const item = timeout === undefined ? await next : await Promise.race([next, timeout]);
1000
+ if (item.done) {
1001
+ if (recoveryEnabled && terminalFailure !== undefined)
1002
+ throw terminalFailure;
1003
+ return { sessionId, sawResult: false };
1004
+ }
1005
+ const message = item.value;
1006
+ // Reset BEFORE mapping. A partial event stays transport-only but is still
1007
+ // proof of provider liveness.
1008
+ arm();
1009
+ if (message.type === 'system' && message.subtype === 'init') {
1010
+ if (expectedSessionId !== undefined && message.session_id !== expectedSessionId) {
1011
+ if (sanitizeProviderTelemetry) {
1012
+ throw new HarnessTurnError('provider', false, 'provider session identity mismatch (details redacted)');
1013
+ }
1014
+ throw new Error(`provider session id mismatch: expected ${expectedSessionId}, received ${message.session_id}`);
1015
+ }
1016
+ sessionId = message.session_id;
1017
+ // The ONLY place these are observable. The live smoke asserts on the
1018
+ // `apiKeySource` here (subscription OAuth vs. an API key), and a later
1019
+ // phase's version-mismatch warning will want `claude_code_version`.
1020
+ if (!sanitizeProviderTelemetry) {
1021
+ const servers = message.mcp_servers.map((s) => `${s.name}=${s.status}`).join(',');
1022
+ onEvent({
1023
+ kind: 'progress',
1024
+ text: `session ${message.session_id}: cliVersion=${message.claude_code_version} ` +
1025
+ `model=${message.model} apiKeySource=${message.apiKeySource} ` +
1026
+ `permissionMode=${message.permissionMode} cwd=${message.cwd} mcp=[${servers}]`,
1027
+ model: cap(message.model),
1028
+ });
1029
+ }
1030
+ onInit?.(sessionId);
1031
+ }
1032
+ else if (message.type === 'result') {
1033
+ const classified = recoveryEnabled ? terminalFailure ?? classifyResult(message) : undefined;
1034
+ if (!sanitizeProviderTelemetry && finalResponse !== undefined) {
1035
+ onEvent({ kind: 'assistant_response', text: finalResponse });
1036
+ }
1037
+ if (message.subtype !== 'success' || classified !== undefined) {
1038
+ // The contract's channel for "something went wrong that is not a resume
1039
+ // failure". Emitted BEFORE turn_ended so a caller reading events in
1040
+ // order sees the cause before the turn closes.
1041
+ onEvent({
1042
+ kind: 'exited',
1043
+ exitCode: null,
1044
+ error: sanitizeProviderTelemetry || message.subtype === 'success'
1045
+ ? sanitizedFailureText(classified)
1046
+ : message.errors.join('; ') || message.subtype,
1047
+ });
1048
+ }
1049
+ onEvent({ kind: 'turn_ended' });
1050
+ if (recoveryEnabled && classified !== undefined)
1051
+ throw classified;
1052
+ return { sessionId, sawResult: true };
1053
+ }
1054
+ else if (message.type === 'assistant') {
1055
+ if (!sanitizeProviderTelemetry) {
1056
+ emitAssistant(message, onEvent);
1057
+ finalResponse = assistantResponse(message) ?? finalResponse;
1058
+ }
1059
+ if (recoveryEnabled)
1060
+ terminalFailure ??= classifyAssistantError(message.error);
1061
+ }
1062
+ else if (recoveryEnabled && message.type === 'auth_status' && message.error !== undefined) {
1063
+ // `error` is a structured SDK field. Its prose is deliberately neither
1064
+ // logged nor parsed for recovery decisions.
1065
+ throw new HarnessTurnError('authentication', true, 'provider authentication status failed');
1066
+ }
1067
+ else if (message.type === 'user') {
1068
+ if (!sanitizeProviderTelemetry)
1069
+ emitUser(message, onEvent);
1070
+ }
1071
+ // `needs_input` is NEVER emitted: this SDK path has no blocking-question
1072
+ // channel that maps to it, and the contract has no reply channel by design.
1073
+ // `stream_event` is deliberately NOT mapped. Recovery-enabled options opt
1074
+ // into partial messages only to reset liveness; their payload would merely
1075
+ // duplicate the eventual assistant message and must not escape telemetry.
1076
+ // Other unrecognized types stay silent by design: the vendor adds message
1077
+ // kinds between releases, and a mapping that threw on one would turn a
1078
+ // routine CLI upgrade into a failed order.
1079
+ }
1080
+ }
1081
+ catch (error) {
1082
+ if (!recoveryEnabled)
1083
+ throw error;
1084
+ if (terminalFailure?.terminal === true)
1085
+ throw terminalFailure;
1086
+ if (idleTimeoutFailure !== undefined)
1087
+ throw idleTimeoutFailure;
1088
+ if (isHarnessTurnError(error))
1089
+ throw error;
1090
+ // This is our own session-integrity guard, not a provider failure. Preserve
1091
+ // its actionable detail while normalizing all actual SDK failures below.
1092
+ if (error instanceof Error && error.message.startsWith('provider session id mismatch:'))
1093
+ throw error;
1094
+ // `deliverClaude` has a provider-specific, secondary resume-refusal fallback
1095
+ // behind its deterministic session-info preflight. Keep the original refusal
1096
+ // text intact until that boundary can translate it to ResumeUnavailableError;
1097
+ // wrapping it here would make an opt-out resume race look like a generic turn
1098
+ // failure and suppress the established same-firing cold replay.
1099
+ if (RESUME_FAILURE_RE.test(errText(error)))
1100
+ throw error;
1101
+ throw new HarnessTurnError('provider', false, 'provider SDK stream failed');
1102
+ }
1103
+ finally {
1104
+ timerGeneration += 1;
1105
+ if (timer !== undefined)
1106
+ clearTimer(timer);
1107
+ // Manual iterator driving does not perform AsyncIteratorClose when the
1108
+ // result message returns from inside the loop. Close this exact query before
1109
+ // a same-token recovery turn can replace it in SESSIONS.
1110
+ closeControlledQuery();
931
1111
  }
932
- return { sessionId, sawResult: false };
933
1112
  }
934
1113
  /** The message text of an unknown thrown value, for an `exited` event. */
935
1114
  function errText(err) {
@@ -971,52 +1150,78 @@ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DE
971
1150
  catch {
972
1151
  // An already-aborted controller is equivalent to success.
973
1152
  }
974
- onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
975
- throw err;
1153
+ if (args.recoveryPolicy === undefined) {
1154
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
1155
+ throw err;
1156
+ }
1157
+ const failure = isHarnessTurnError(err)
1158
+ ? err
1159
+ : new HarnessTurnError('provider', false, 'provider SDK query initialization failed');
1160
+ onEvent({
1161
+ kind: 'exited',
1162
+ exitCode: null,
1163
+ error: sanitizedFailureText(failure),
1164
+ });
1165
+ throw failure;
976
1166
  }
977
1167
  SESSIONS.set(sessionId, { query: q, abortController, options });
978
- let initVerified = false;
979
- let outcome;
980
- try {
981
- outcome = await consumeTurn(q, onEvent, () => {
982
- initVerified = true;
983
- }, sessionId);
984
- }
985
- catch (err) {
986
- // An init mismatch or pre-init failure must not leave the preselected token
987
- // resumable. A post-init provider failure keeps the same registry behavior as
988
- // before; `stop()` can still find and idempotently close that verified session.
989
- if (!initVerified)
1168
+ let exactClosed = false;
1169
+ let failureEventEmitted = false;
1170
+ const turnOnEvent = (event) => {
1171
+ if (event.kind === 'exited')
1172
+ failureEventEmitted = true;
1173
+ onEvent(event);
1174
+ };
1175
+ const closeExact = () => {
1176
+ if (exactClosed)
1177
+ return;
1178
+ exactClosed = true;
1179
+ if (SESSIONS.get(sessionId)?.query === q)
990
1180
  SESSIONS.delete(sessionId);
991
1181
  try {
992
1182
  abortController.abort();
993
1183
  }
994
1184
  catch {
995
- // An already-aborted controller is equivalent to success.
1185
+ // Best-effort, idempotent teardown.
996
1186
  }
997
1187
  try {
998
1188
  q.close();
999
1189
  }
1000
1190
  catch {
1001
- // Preserve the provider or session-integrity error that caused the abort.
1191
+ // The timeout/failure remains authoritative.
1192
+ }
1193
+ };
1194
+ let initVerified = false;
1195
+ let outcome;
1196
+ try {
1197
+ outcome = await consumeTurn(q, turnOnEvent, () => {
1198
+ initVerified = true;
1199
+ }, sessionId, {
1200
+ ...(args.recoveryPolicy !== undefined ? { idleTimeoutMs: args.recoveryPolicy.idleTimeoutMs } : {}),
1201
+ sanitizeProviderTelemetry: args.recoveryPolicy !== undefined,
1202
+ abortController,
1203
+ close: closeExact,
1204
+ onActivity: (activity) => onEvent({ kind: 'activity', ...activity }),
1205
+ });
1206
+ }
1207
+ catch (err) {
1208
+ // An init mismatch or pre-init failure must not leave the preselected token
1209
+ // registered. `consumeTurn` closes every settled exact query; this explicit
1210
+ // delete preserves the cold-start gate even if that cleanup seam changes.
1211
+ if (!initVerified)
1212
+ SESSIONS.delete(sessionId);
1213
+ closeExact();
1214
+ if (!failureEventEmitted) {
1215
+ onEvent({
1216
+ kind: 'exited',
1217
+ exitCode: null,
1218
+ error: args.recoveryPolicy !== undefined ? sanitizedFailureText(err) : errText(err),
1219
+ });
1002
1220
  }
1003
- onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
1004
1221
  throw err;
1005
1222
  }
1006
1223
  if (outcome.sessionId === undefined) {
1007
- SESSIONS.delete(sessionId);
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
- }
1224
+ closeExact();
1020
1225
  const why = outcome.sawResult
1021
1226
  ? 'the turn ended without confirming the supplied session id'
1022
1227
  : 'the stream ended before confirming the supplied session id';
@@ -1025,12 +1230,14 @@ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DE
1025
1230
  }
1026
1231
  return ref;
1027
1232
  }
1028
- async function deliver(ref, message, args, onEvent) {
1233
+ export async function deliverClaude(ref, message, args, onEvent, dependencies = DEFAULT_DELIVER_DEPENDENCIES) {
1029
1234
  // Session lookup is scoped to the PROJECT DIRECTORY, so a deleted worktree can
1030
1235
  // never resume no matter how good the token is. Distinct message on purpose —
1031
1236
  // the caller reads these to tell the two failures apart.
1032
1237
  if (!existsSync(args.cwd)) {
1033
- throw new ResumeUnavailableError(`resume cwd no longer exists: ${args.cwd}`);
1238
+ throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
1239
+ ? 'recovery resume cwd is unavailable (details redacted)'
1240
+ : `resume cwd no longer exists: ${args.cwd}`);
1034
1241
  }
1035
1242
  // Deterministic pre-check, rather than parsing a failed query's error text
1036
1243
  // (that string is unverified and can change between releases).
@@ -1041,14 +1248,15 @@ async function deliver(ref, message, args, onEvent) {
1041
1248
  // hang and never a wrong-session resume — so it is the safe way to be wrong.
1042
1249
  let known = false;
1043
1250
  try {
1044
- const { getSessionInfo } = await import('@anthropic-ai/claude-agent-sdk');
1045
- known = (await getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
1251
+ known = (await dependencies.getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
1046
1252
  }
1047
1253
  catch {
1048
1254
  known = false;
1049
1255
  }
1050
1256
  if (!known) {
1051
- throw new ResumeUnavailableError(`provider no longer knows session ${ref.token}`);
1257
+ throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
1258
+ ? 'provider no longer knows the recovery session (details redacted)'
1259
+ : `provider no longer knows session ${ref.token}`);
1052
1260
  }
1053
1261
  const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
1054
1262
  const abortController = new AbortController();
@@ -1075,20 +1283,78 @@ async function deliver(ref, message, args, onEvent) {
1075
1283
  });
1076
1284
  // `forkSession` is deliberately NOT set: a fork would mint a new session id the
1077
1285
  // caller does not know about, and resume must continue the SAME session.
1078
- const { query } = await import('@anthropic-ai/claude-agent-sdk');
1079
- const q = query({ prompt: message, options });
1286
+ let q;
1287
+ try {
1288
+ const query = await dependencies.loadQuery();
1289
+ q = query({ prompt: message, options });
1290
+ }
1291
+ catch (err) {
1292
+ if (args.recoveryPolicy === undefined) {
1293
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
1294
+ throw err;
1295
+ }
1296
+ const failure = isHarnessTurnError(err)
1297
+ ? err
1298
+ : new HarnessTurnError('provider', false, 'provider SDK query initialization failed');
1299
+ onEvent({
1300
+ kind: 'exited',
1301
+ exitCode: null,
1302
+ error: sanitizedFailureText(failure),
1303
+ });
1304
+ throw failure;
1305
+ }
1080
1306
  SESSIONS.set(ref.token, { query: q, abortController, options });
1307
+ let exactClosed = false;
1308
+ let failureEventEmitted = false;
1309
+ const turnOnEvent = (event) => {
1310
+ if (event.kind === 'exited')
1311
+ failureEventEmitted = true;
1312
+ onEvent(event);
1313
+ };
1314
+ const closeExact = () => {
1315
+ if (exactClosed)
1316
+ return;
1317
+ exactClosed = true;
1318
+ if (SESSIONS.get(ref.token)?.query === q)
1319
+ SESSIONS.delete(ref.token);
1320
+ try {
1321
+ abortController.abort();
1322
+ }
1323
+ catch {
1324
+ // Best-effort, idempotent teardown.
1325
+ }
1326
+ try {
1327
+ q.close();
1328
+ }
1329
+ catch {
1330
+ // The timeout/failure remains authoritative.
1331
+ }
1332
+ };
1081
1333
  try {
1082
1334
  // Never emits `started` — the contract forbids re-emitting it on a resume.
1083
- await consumeTurn(q, onEvent);
1335
+ await consumeTurn(q, turnOnEvent, undefined, undefined, {
1336
+ ...(args.recoveryPolicy !== undefined ? { idleTimeoutMs: args.recoveryPolicy.idleTimeoutMs } : {}),
1337
+ sanitizeProviderTelemetry: args.recoveryPolicy !== undefined,
1338
+ abortController,
1339
+ close: closeExact,
1340
+ onActivity: (activity) => onEvent({ kind: 'activity', ...activity }),
1341
+ });
1084
1342
  }
1085
1343
  catch (err) {
1086
1344
  const text = errText(err);
1087
1345
  // Belt and braces behind the `getSessionInfo` pre-check.
1088
1346
  if (RESUME_FAILURE_RE.test(text)) {
1089
- throw new ResumeUnavailableError(`provider refused resume of session ${ref.token}: ${text}`);
1347
+ throw new ResumeUnavailableError(args.recoveryPolicy !== undefined
1348
+ ? 'provider refused recovery resume (details redacted)'
1349
+ : `provider refused resume of session ${ref.token}: ${text}`);
1350
+ }
1351
+ if (!failureEventEmitted) {
1352
+ onEvent({
1353
+ kind: 'exited',
1354
+ exitCode: null,
1355
+ error: args.recoveryPolicy !== undefined ? sanitizedFailureText(err) : text,
1356
+ });
1090
1357
  }
1091
- onEvent({ kind: 'exited', exitCode: null, error: text });
1092
1358
  throw err;
1093
1359
  }
1094
1360
  }
@@ -1234,9 +1500,10 @@ export const claudeAdapter = {
1234
1500
  // The provider stores the session and resumes it from the opaque token this
1235
1501
  // adapter puts in `HarnessSessionRef.token`.
1236
1502
  resumeTier: 'native-token',
1503
+ recoveryPolicy: () => claudeRecoveryPolicy(),
1237
1504
  preflight: claudePreflight,
1238
1505
  start: startClaude,
1239
- deliver,
1506
+ deliver: deliverClaude,
1240
1507
  stop,
1241
1508
  lintStep,
1242
1509
  resumeCommand,