@ai-sdk/harness-claude-code 1.0.177 → 1.0.179

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 CHANGED
@@ -1,5 +1,44 @@
1
1
  # @ai-sdk/harness-claude-code
2
2
 
3
+ ## 1.0.179
4
+
5
+ ### Patch Changes
6
+
7
+ - ae4e236: add an additionalDirectories setting and trust those directories like the working directory in file approvals
8
+ - a54f0fd: fix(harness): abort a running turn when its host disconnects for good
9
+ - Updated dependencies [8e8033a]
10
+ - Updated dependencies [a54f0fd]
11
+ - @ai-sdk/harness@1.0.175
12
+
13
+ ## 1.0.178
14
+
15
+ ### Patch Changes
16
+
17
+ - a9a6fe7: fix(harness-claude-code): map dotted AI Gateway model IDs in the `ANTHROPIC_DEFAULT_*_MODEL` variables to the ID shapes Claude Code expects
18
+ - c7ebb56: map dotted ids in `CLAUDE_CODE_SUBAGENT_MODEL` to the ids Claude Code expects
19
+ - 3bf70f8: Recover Claude Code turn starts lost on a dropped WebSocket connection using idempotent start identifiers. Bound the wait for the first turn event with `turnStartTimeoutMs` (120 seconds by default), and fail safely when reconnecting to an older bridge that has not accepted the start.
20
+
21
+ Preserve first delivery of turns submitted during an idle reconnect, including on older bridges, without sending duplicate starts or treating an unsent start as lost.
22
+
23
+ Clean up failed initial sends without leaving a delayed unhandled rejection, and replay pending steering only after the recovered start.
24
+
25
+ `SandboxChannel.send` accepts `queueIfDisconnected: false` for callers that own reconnect replay; discarded frames do not invoke `onSent`. The default continues queueing frames.
26
+
27
+ - 5a05735: fix(harness-claude-code): isolate turn events after abort to prevent session reuse errors
28
+ - Updated dependencies [36802d4]
29
+ - Updated dependencies [e0143b0]
30
+ - Updated dependencies [934100c]
31
+ - Updated dependencies [892af4d]
32
+ - Updated dependencies [3bf70f8]
33
+ - Updated dependencies [89aff56]
34
+ - Updated dependencies [41465fd]
35
+ - Updated dependencies [9754014]
36
+ - Updated dependencies [4bb73b0]
37
+ - Updated dependencies [2e44144]
38
+ - @ai-sdk/provider@4.0.36
39
+ - @ai-sdk/harness@1.0.174
40
+ - @ai-sdk/provider-utils@5.0.75
41
+
3
42
  ## 1.0.177
4
43
 
5
44
  ### Patch Changes
@@ -201,6 +201,12 @@ const WS_OPEN = 1;
201
201
  async function runBridge(options) {
202
202
  const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;
203
203
  const teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;
204
+ const hostDisconnectTimeoutMs = options.hostDisconnectTimeoutMs != null && Number.isFinite(options.hostDisconnectTimeoutMs) && options.hostDisconnectTimeoutMs > 0 ? Math.min(options.hostDisconnectTimeoutMs, 2147483647) : void 0;
205
+ let hostDisconnectTimer;
206
+ const clearHostDisconnectTimer = () => {
207
+ clearTimeout(hostDisconnectTimer);
208
+ hostDisconnectTimer = void 0;
209
+ };
204
210
  const expectedToken = options.token ?? env.BRIDGE_CHANNEL_TOKEN ?? "";
205
211
  const bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? "0", 10);
206
212
  const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;
@@ -222,6 +228,7 @@ async function runBridge(options) {
222
228
  * between turns. A new `start` fences on this so turns never overlap.
223
229
  */
224
230
  let activeTurn;
231
+ let lastStartId;
225
232
  let debugConfig;
226
233
  let consoleCaptureInstalled = false;
227
234
  const envDebugEnabled = ENV_TRUTHY.has((env.HARNESS_DEBUG ?? "").toLowerCase());
@@ -365,6 +372,11 @@ async function runBridge(options) {
365
372
  const handleInbound = async (msg, ws) => {
366
373
  switch (msg.type) {
367
374
  case "start": {
375
+ const startId = msg.startId;
376
+ if (startId != null) {
377
+ if (startId === lastStartId) return;
378
+ lastStartId = startId;
379
+ }
368
380
  for (;;) {
369
381
  const pendingTurn = activeTurn;
370
382
  if (pendingTurn == null) break;
@@ -382,6 +394,7 @@ async function runBridge(options) {
382
394
  const thisTurn = new Promise((resolve) => turnFinished = resolve);
383
395
  activeTurn = thisTurn;
384
396
  activeSocket = ws;
397
+ clearHostDisconnectTimer();
385
398
  const firstTurn = isFirstTurn;
386
399
  isFirstTurn = false;
387
400
  eventLog = [];
@@ -448,6 +461,7 @@ async function runBridge(options) {
448
461
  activeTurn = void 0;
449
462
  currentTurnState = "waiting";
450
463
  writeBridgeMeta("waiting");
464
+ clearHostDisconnectTimer();
451
465
  }
452
466
  turnFinished();
453
467
  }
@@ -514,6 +528,7 @@ async function runBridge(options) {
514
528
  return;
515
529
  case "resume":
516
530
  activeSocket = ws;
531
+ clearHostDisconnectTimer();
517
532
  replay(ws, msg.lastSeenEventId);
518
533
  return;
519
534
  case "destroy":
@@ -582,7 +597,10 @@ async function runBridge(options) {
582
597
  type: "bridge-hello",
583
598
  state: currentTurnState,
584
599
  lastSeq: seqCounter,
585
- capabilities: { experimental_userMessageResponses: true }
600
+ capabilities: {
601
+ idempotentStart: true,
602
+ experimental_userMessageResponses: true
603
+ }
586
604
  });
587
605
  ws.on("message", (raw) => {
588
606
  let parsed;
@@ -598,8 +616,18 @@ async function runBridge(options) {
598
616
  }
599
617
  handleInbound(parsed, ws);
600
618
  });
601
- ws.on("close", () => {
602
- if (activeSocket === ws) activeSocket = void 0;
619
+ ws.on("close", (_code, reason) => {
620
+ if (activeSocket === ws) {
621
+ activeSocket = void 0;
622
+ if (hostDisconnectTimeoutMs != null && activeTurn != null && reason.toString() !== "suspended") {
623
+ clearHostDisconnectTimer();
624
+ hostDisconnectTimer = setTimeout(() => {
625
+ hostDisconnectTimer = void 0;
626
+ if (activeSocket == null) turnAbort?.abort();
627
+ }, hostDisconnectTimeoutMs);
628
+ hostDisconnectTimer.unref?.();
629
+ }
630
+ }
603
631
  });
604
632
  ws.on("error", () => {});
605
633
  });
@@ -1321,7 +1349,8 @@ async function areFileToolPathsTrusted(options) {
1321
1349
  if (options.paths.length === 0) return false;
1322
1350
  try {
1323
1351
  const roots = [await realpath(options.workDir)];
1324
- if (options.access === "read") for (const root of options.readableSkillRoots) try {
1352
+ const trustedRoots = [...(options.additionalDirectories ?? []).filter((root) => path.posix.isAbsolute(root)), ...options.access === "read" ? options.readableSkillRoots : []];
1353
+ for (const root of trustedRoots) try {
1325
1354
  roots.push(await realpath(root));
1326
1355
  } catch {
1327
1356
  continue;
@@ -1529,7 +1558,40 @@ let lastClaudeSessionId;
1529
1558
  await runBridge({
1530
1559
  bridgeType: "claude-code",
1531
1560
  bridgeStateDir,
1532
- onStart: runTurn,
1561
+ ...args.hostDisconnectTimeoutMs !== void 0 ? { hostDisconnectTimeoutMs: args.hostDisconnectTimeoutMs } : {},
1562
+ onStart: async (start, turn) => {
1563
+ const emit = (event) => {
1564
+ if (turn.abortSignal.aborted) return;
1565
+ turn.emit({
1566
+ ...event,
1567
+ ...start.startId == null ? {} : { startId: start.startId }
1568
+ });
1569
+ };
1570
+ const emitError = ({ error, message }) => {
1571
+ if (turn.abortSignal.aborted) return;
1572
+ console.error(`[harness:claude-code:error] ${message ?? "bridge error"}:`, error);
1573
+ emit({
1574
+ type: "error",
1575
+ error: error instanceof Error ? {
1576
+ name: error.name,
1577
+ message: error.message,
1578
+ stack: error.stack
1579
+ } : error
1580
+ });
1581
+ };
1582
+ try {
1583
+ await runTurn(start, {
1584
+ ...turn,
1585
+ emit,
1586
+ emitError
1587
+ });
1588
+ } catch (error) {
1589
+ emitError({
1590
+ error,
1591
+ message: "claude-code turn failed"
1592
+ });
1593
+ }
1594
+ },
1533
1595
  onStop: () => lastClaudeSessionId == null ? {} : { claudeSessionId: lastClaudeSessionId }
1534
1596
  });
1535
1597
  function createPermissionOptions(input) {
@@ -1558,6 +1620,7 @@ function createPermissionOptions(input) {
1558
1620
  inactiveNativeTools,
1559
1621
  cwd: input.toolCwds.get(options.toolUseID) ?? "",
1560
1622
  readableSkillRoots: input.start.readableSkillRoots ?? [],
1623
+ additionalDirectories: input.start.additionalDirectories ?? [],
1561
1624
  blockedPath: options.blockedPath
1562
1625
  })) return {
1563
1626
  behavior: "allow",
@@ -1662,11 +1725,27 @@ function createPermissionSettings(input) {
1662
1725
  * the id Claude Code expects (`claude-opus-5-5`) to the gateway id, which
1663
1726
  * stays the id sent to the gateway.
1664
1727
  */
1665
- function createGatewayModelOverrides(model) {
1728
+ function toGatewayModelOverride(model) {
1666
1729
  if (!model?.startsWith("anthropic/")) return void 0;
1667
1730
  const id = model.slice(10).replace(/\[[^\]]*\]$/, "");
1668
1731
  return id.includes(".") ? { [id.replace(/\./g, "-")]: model } : void 0;
1669
1732
  }
1733
+ /**
1734
+ * The `ANTHROPIC_DEFAULT_*_MODEL` variables point Claude Code's model aliases
1735
+ * at other ids and `CLAUDE_CODE_SUBAGENT_MODEL` sets the model of subagents,
1736
+ * which it misreads the same way. `model` comes last so that its entry wins a
1737
+ * key it shares with one of them.
1738
+ */
1739
+ function createGatewayModelOverrides(model, env) {
1740
+ const overrides = {
1741
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_OPUS_MODEL),
1742
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_SONNET_MODEL),
1743
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_HAIKU_MODEL),
1744
+ ...toGatewayModelOverride(env.CLAUDE_CODE_SUBAGENT_MODEL),
1745
+ ...toGatewayModelOverride(model)
1746
+ };
1747
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
1748
+ }
1670
1749
  async function needsHostApproval(input) {
1671
1750
  if (input.toolName.startsWith("mcp__harness-tools__")) return false;
1672
1751
  if (input.inactiveNativeTools.has(input.toolName) || nativeToolRequiresApproval({
@@ -1708,7 +1787,8 @@ async function needsHostApproval(input) {
1708
1787
  cwd: input.cwd,
1709
1788
  paths,
1710
1789
  access,
1711
- readableSkillRoots: input.readableSkillRoots
1790
+ readableSkillRoots: input.readableSkillRoots,
1791
+ additionalDirectories: input.additionalDirectories
1712
1792
  });
1713
1793
  }
1714
1794
  function createApprovalPreToolUseHook(input) {
@@ -1734,6 +1814,7 @@ function createApprovalPreToolUseHook(input) {
1734
1814
  toolInput: hookInput.tool_input,
1735
1815
  cwd: hookInput.cwd,
1736
1816
  readableSkillRoots: input.readableSkillRoots,
1817
+ additionalDirectories: input.additionalDirectories,
1737
1818
  permissionMode: input.permissionMode,
1738
1819
  inactiveNativeTools: input.inactiveNativeTools
1739
1820
  })) return {};
@@ -1753,7 +1834,9 @@ function nativeToolRequiresApproval(input) {
1753
1834
  return kind === "edit" || kind === "bash";
1754
1835
  }
1755
1836
  async function runTurn(start, turn) {
1756
- const emit = (msg) => turn.emit(msg);
1837
+ const emit = (msg) => {
1838
+ if (!turn.abortSignal.aborted) turn.emit(msg);
1839
+ };
1757
1840
  const abortCtl = new AbortController();
1758
1841
  let gracefulAbort;
1759
1842
  let hardAbortTimer;
@@ -1885,11 +1968,16 @@ async function runTurn(start, turn) {
1885
1968
  approvalRequestedToolUseIds: streamEventState.approvalRequestedToolUseIds,
1886
1969
  emittedToolCallIds: streamEventState.emittedToolCallIds
1887
1970
  });
1888
- const modelOverrides = createGatewayModelOverrides(start.model);
1971
+ const sdkEnv = {
1972
+ ...env,
1973
+ ...start.env
1974
+ };
1975
+ const modelOverrides = createGatewayModelOverrides(start.model, sdkEnv);
1889
1976
  const deferredToolUseIds = /* @__PURE__ */ new Set();
1890
1977
  const approvalPreToolUseHook = createApprovalPreToolUseHook({
1891
1978
  toolCwds,
1892
1979
  readableSkillRoots: start.readableSkillRoots ?? [],
1980
+ additionalDirectories: start.additionalDirectories ?? [],
1893
1981
  permissionMode,
1894
1982
  inactiveNativeTools: new Set(inactiveNativeTools),
1895
1983
  decisions: approvalDecisions,
@@ -1921,13 +2009,11 @@ async function runTurn(start, turn) {
1921
2009
  ...start.model ? { model: start.model } : {},
1922
2010
  ...start.maxTurns !== void 0 ? { maxTurns: start.maxTurns } : {},
1923
2011
  ...start.maxBudgetUsd !== void 0 ? { maxBudgetUsd: start.maxBudgetUsd } : {},
2012
+ ...start.additionalDirectories !== void 0 ? { additionalDirectories: start.additionalDirectories } : {},
1924
2013
  ...start.strictMcpConfig !== void 0 ? { strictMcpConfig: start.strictMcpConfig } : {},
1925
2014
  ...start.agentProgressSummaries !== void 0 ? { agentProgressSummaries: start.agentProgressSummaries } : {},
1926
2015
  ...start.forwardSubagentText !== void 0 ? { forwardSubagentText: start.forwardSubagentText } : {},
1927
- ...start.env !== void 0 ? { env: {
1928
- ...env,
1929
- ...start.env
1930
- } } : {},
2016
+ ...start.env !== void 0 ? { env: sdkEnv } : {},
1931
2017
  ...skillsOption ? { skills: skillsOption } : {},
1932
2018
  ...nativeTools !== void 0 ? { tools: nativeTools } : {},
1933
2019
  ...inactiveNativeTools.length > 0 ? { disallowedTools: inactiveNativeTools } : {},
@@ -2323,6 +2409,7 @@ function parseArgs(args) {
2323
2409
  const out = {};
2324
2410
  for (let i = 0; i < args.length; i++) if (args[i] === "--workdir" && i + 1 < args.length) out.workdir = args[++i];
2325
2411
  else if (args[i] === "--bridge-state-dir" && i + 1 < args.length) out.bridgeStateDir = args[++i];
2412
+ else if (args[i] === "--host-disconnect-timeout-ms" && i + 1 < args.length) out.hostDisconnectTimeoutMs = Number(args[++i]);
2326
2413
  return out;
2327
2414
  }
2328
2415
  function emitFatal(message) {