@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.
@@ -50,6 +50,7 @@ import {
50
50
  type SandboxChannelReconnectOptions,
51
51
  } from '@ai-sdk/harness/utils';
52
52
  import {
53
+ generateId,
53
54
  tool,
54
55
  type Experimental_SandboxSession as SandboxSession,
55
56
  type Experimental_SandboxProcess,
@@ -133,6 +134,11 @@ export type ClaudeCodeHarnessSettings = {
133
134
  * the query stops and the turn ends with an error. Unset means no limit.
134
135
  */
135
136
  readonly maxBudgetUsd?: number;
137
+ /**
138
+ * Absolute paths of directories Claude can access in addition to the session
139
+ * working directory.
140
+ */
141
+ readonly additionalDirectories?: ReadonlyArray<string>;
136
142
  /**
137
143
  * Only use the MCP servers configured with `mcpServers`, and ignore any other
138
144
  * MCP configuration such as a project `.mcp.json` or user settings.
@@ -188,6 +194,14 @@ export type ClaudeCodeHarnessSettings = {
188
194
  readonly portEndpoint?: HarnessV1PortEndpoint;
189
195
  /** Maximum milliseconds to wait for the bridge to advertise its port. Defaults to 120000. */
190
196
  readonly startupTimeoutMs?: number;
197
+ /** Maximum milliseconds to wait for the first turn event. Defaults to 120000. */
198
+ readonly turnStartTimeoutMs?: number;
199
+ /**
200
+ * Abort a running turn when its host disconnects and does not reconnect
201
+ * within this many milliseconds, so the turn stops spending. A suspended
202
+ * turn is exempt. Unset keeps the turn running until it finishes.
203
+ */
204
+ readonly hostDisconnectTimeoutMs?: number;
191
205
  /**
192
206
  * Configures reconnection attempts after an established bridge connection
193
207
  * drops. The reconnect window includes connection establishment and
@@ -858,6 +872,7 @@ const claudeCodeBridgeCoordsSchema = z.object({
858
872
  port: z.number(),
859
873
  token: z.string(),
860
874
  lastSeenEventId: z.number(),
875
+ startId: z.string().optional(),
861
876
  sandboxId: z.string().optional(),
862
877
  });
863
878
 
@@ -1050,7 +1065,9 @@ export function createClaudeCode(
1050
1065
  sessionId: startOpts.sessionId,
1051
1066
  });
1052
1067
  let supportsUserMessageResponses = false;
1068
+ let bridgeHello: BridgeHello | undefined;
1053
1069
  const onHello = (hello: BridgeHello) => {
1070
+ bridgeHello = hello;
1054
1071
  supportsUserMessageResponses =
1055
1072
  hello.capabilities?.experimental_userMessageResponses === true;
1056
1073
  };
@@ -1096,6 +1113,7 @@ export function createClaudeCode(
1096
1113
  return createSession({
1097
1114
  sessionId: startOpts.sessionId,
1098
1115
  channel: attachChannel,
1116
+ startId: coords.startId,
1099
1117
  finishListenerAttachment,
1100
1118
  ...(resumeSessionId ? { resumeSessionId } : {}),
1101
1119
  // The live bridge was spawned by another process; this one owns no
@@ -1105,6 +1123,7 @@ export function createClaudeCode(
1105
1123
  maxTurns: settings.maxTurns,
1106
1124
  skillOverrides: settings.skillOverrides,
1107
1125
  maxBudgetUsd: settings.maxBudgetUsd,
1126
+ additionalDirectories: settings.additionalDirectories,
1108
1127
  strictMcpConfig: settings.strictMcpConfig,
1109
1128
  questionTimeoutMs: settings.questionTimeoutMs,
1110
1129
  excludeDynamicSections: settings.excludeDynamicSections,
@@ -1128,6 +1147,8 @@ export function createClaudeCode(
1128
1147
  mcpServers: settings.mcpServers,
1129
1148
  toolHints: settings.toolHints,
1130
1149
  supportsUserMessageResponses: () => supportsUserMessageResponses,
1150
+ getBridgeHello: () => bridgeHello,
1151
+ turnStartTimeoutMs: settings.turnStartTimeoutMs ?? 120_000,
1131
1152
  });
1132
1153
  } catch {
1133
1154
  // Bridge no longer reachable — recover by respawning below.
@@ -1194,7 +1215,7 @@ export function createClaudeCode(
1194
1215
  });
1195
1216
 
1196
1217
  const proc = await toolSafeSandboxSession.spawn({
1197
- command: `node ${shellQuote(`${bootstrapDir}/bridge.mjs`)} --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)}`,
1218
+ command: `node ${shellQuote(`${bootstrapDir}/bridge.mjs`)} --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)}${settings.hostDisconnectTimeoutMs !== undefined ? ` --host-disconnect-timeout-ms ${shellQuote(String(settings.hostDisconnectTimeoutMs))}` : ''}`,
1198
1219
  env,
1199
1220
  abortSignal: startOpts.abortSignal,
1200
1221
  });
@@ -1277,10 +1298,12 @@ export function createClaudeCode(
1277
1298
  sessionId: startOpts.sessionId,
1278
1299
  channel,
1279
1300
  finishListenerAttachment,
1301
+ startId: respawnStrategy === 'replay' ? coords?.startId : undefined,
1280
1302
  proc,
1281
1303
  maxTurns: settings.maxTurns,
1282
1304
  skillOverrides: settings.skillOverrides,
1283
1305
  maxBudgetUsd: settings.maxBudgetUsd,
1306
+ additionalDirectories: settings.additionalDirectories,
1284
1307
  strictMcpConfig: settings.strictMcpConfig,
1285
1308
  questionTimeoutMs: settings.questionTimeoutMs,
1286
1309
  excludeDynamicSections: settings.excludeDynamicSections,
@@ -1314,6 +1337,8 @@ export function createClaudeCode(
1314
1337
  mcpServers: settings.mcpServers,
1315
1338
  toolHints: settings.toolHints,
1316
1339
  supportsUserMessageResponses: () => supportsUserMessageResponses,
1340
+ getBridgeHello: () => bridgeHello,
1341
+ turnStartTimeoutMs: settings.turnStartTimeoutMs ?? 120_000,
1317
1342
  });
1318
1343
  },
1319
1344
  };
@@ -1329,11 +1354,13 @@ export function createClaudeCode(
1329
1354
  function createSession({
1330
1355
  sessionId,
1331
1356
  channel,
1357
+ startId,
1332
1358
  finishListenerAttachment,
1333
1359
  proc,
1334
1360
  maxTurns,
1335
1361
  skillOverrides,
1336
1362
  maxBudgetUsd,
1363
+ additionalDirectories,
1337
1364
  strictMcpConfig,
1338
1365
  questionTimeoutMs,
1339
1366
  excludeDynamicSections,
@@ -1359,15 +1386,19 @@ function createSession({
1359
1386
  mcpServers,
1360
1387
  toolHints,
1361
1388
  supportsUserMessageResponses,
1389
+ getBridgeHello,
1390
+ turnStartTimeoutMs,
1362
1391
  }: {
1363
1392
  sessionId: string;
1364
1393
  channel: ClaudeCodeChannel;
1394
+ startId?: string;
1365
1395
  finishListenerAttachment: (() => void) | undefined;
1366
1396
  /** Undefined on `attach` — the live bridge was spawned by another process. */
1367
1397
  proc: Experimental_SandboxProcess | undefined;
1368
1398
  maxTurns: number | undefined;
1369
1399
  skillOverrides: ClaudeCodeHarnessSettings['skillOverrides'];
1370
1400
  maxBudgetUsd: number | undefined;
1401
+ additionalDirectories: ReadonlyArray<string> | undefined;
1371
1402
  strictMcpConfig: boolean | undefined;
1372
1403
  questionTimeoutMs: number | undefined;
1373
1404
  excludeDynamicSections: boolean | undefined;
@@ -1403,6 +1434,8 @@ function createSession({
1403
1434
  mcpServers: Record<string, unknown> | undefined;
1404
1435
  toolHints: ClaudeCodeHarnessSettings['toolHints'];
1405
1436
  supportsUserMessageResponses: () => boolean;
1437
+ getBridgeHello: () => BridgeHello | undefined;
1438
+ turnStartTimeoutMs: number;
1406
1439
  }): HarnessV1Session {
1407
1440
  let stopped = false;
1408
1441
  let stopPromise: Promise<void> | undefined;
@@ -1422,6 +1455,7 @@ function createSession({
1422
1455
  * stop/detach must record for exact resume.
1423
1456
  */
1424
1457
  let lastClaudeSessionId = resumeSessionId;
1458
+ let activeStartId = startId;
1425
1459
 
1426
1460
  /*
1427
1461
  * Wire the channel into one turn's worth of events and return the control
@@ -1433,31 +1467,55 @@ function createSession({
1433
1467
  const wireTurn = (turnOpts: {
1434
1468
  emit: (event: HarnessV1StreamPart) => void;
1435
1469
  abortSignal?: AbortSignal;
1436
- }): HarnessV1PromptControl => {
1470
+ startId?: string;
1471
+ }): {
1472
+ control: HarnessV1PromptControl;
1473
+ sendStart: (message: Extract<InboundMessage, { type: 'start' }>) => void;
1474
+ } => {
1475
+ activeStartId = turnOpts.startId;
1476
+ let expectedStartId = turnOpts.startId;
1477
+ let isSettled = false;
1478
+ const belongsToTurn = (event: { startId?: string }): boolean => {
1479
+ if (isSettled) return false;
1480
+ if (event.startId == null) return true;
1481
+ if (expectedStartId == null) {
1482
+ expectedStartId = event.startId;
1483
+ activeStartId = event.startId;
1484
+ }
1485
+ return event.startId === expectedStartId;
1486
+ };
1437
1487
  let pendingResolve: (() => void) | undefined;
1438
1488
  let pendingReject: ((err: unknown) => void) | undefined;
1439
1489
  const done = new Promise<void>((resolve, reject) => {
1440
1490
  pendingResolve = resolve;
1441
1491
  pendingReject = reject;
1442
1492
  });
1443
- const userMessageSubmitter = supportsUserMessageResponses()
1444
- ? experimental_createBridgeUserMessageSubmitter({
1445
- send: message => channel.send(message),
1446
- onResponse: listener => channel.on('user-message-response', listener),
1447
- onReconnect: listener => channel.onReconnect(listener),
1448
- })
1449
- : undefined;
1450
1493
  const unsubs: Array<() => void> = [];
1451
- const forward = (event: HarnessV1StreamPart) => {
1494
+ let pendingStart: Extract<InboundMessage, { type: 'start' }> | undefined;
1495
+ let awaitingStartSend = false;
1496
+ let startCursor = 0;
1497
+ let startTimer: ReturnType<typeof setTimeout> | undefined;
1498
+ const clearPendingStart = () => {
1499
+ pendingStart = undefined;
1500
+ clearTimeout(startTimer);
1501
+ };
1502
+ const forward = (event: HarnessV1StreamPart & { startId?: string }) => {
1503
+ clearPendingStart();
1504
+ /*
1505
+ * Keep the event object: the channel attaches a non-enumerable replay
1506
+ * checkpoint that must reach the consumer for step-boundary suspension.
1507
+ * Only the adapter's wire-level turn identifier is removed.
1508
+ */
1509
+ delete event.startId;
1452
1510
  try {
1453
1511
  turnOpts.emit(event);
1454
1512
  } catch {}
1455
1513
  };
1456
1514
 
1457
- let isSettled = false;
1458
1515
  const settleSuccess = () => {
1459
1516
  if (isSettled) return;
1460
1517
  isSettled = true;
1518
+ clearPendingStart();
1461
1519
  userMessageSubmitter?.close();
1462
1520
  for (const u of unsubs) u();
1463
1521
  pendingResolve!();
@@ -1465,11 +1523,68 @@ function createSession({
1465
1523
  const settleError = (err: unknown) => {
1466
1524
  if (isSettled) return;
1467
1525
  isSettled = true;
1526
+ clearPendingStart();
1468
1527
  userMessageSubmitter?.close(err);
1469
1528
  for (const u of unsubs) u();
1470
1529
  pendingReject!(err);
1471
1530
  };
1472
1531
 
1532
+ const sendPendingStart = () => {
1533
+ if (pendingStart == null) return;
1534
+ awaitingStartSend = true;
1535
+ try {
1536
+ channel.send(pendingStart, {
1537
+ onSent: () => {
1538
+ awaitingStartSend = false;
1539
+ },
1540
+ });
1541
+ } catch (error) {
1542
+ awaitingStartSend = false;
1543
+ throw error;
1544
+ }
1545
+ };
1546
+ const failStart = (error: Error) => {
1547
+ settleError(error);
1548
+ channel.beginClose();
1549
+ try {
1550
+ channel.send({ type: 'abort' });
1551
+ } catch {}
1552
+ channel.close();
1553
+ };
1554
+ unsubs.push(
1555
+ channel.onReconnect(() => {
1556
+ if (pendingStart == null || isSettled || awaitingStartSend) return;
1557
+ const hello = getBridgeHello();
1558
+ if (hello?.capabilities?.idempotentStart === true) {
1559
+ sendPendingStart();
1560
+ return;
1561
+ }
1562
+ if (
1563
+ hello?.state !== 'waiting' ||
1564
+ hello.lastSeq == null ||
1565
+ hello.lastSeq > startCursor
1566
+ ) {
1567
+ return;
1568
+ }
1569
+ failStart(
1570
+ new Error(
1571
+ 'claude-code bridge is waiting for a start after reconnect and does not support safe start retries.',
1572
+ ),
1573
+ );
1574
+ }),
1575
+ );
1576
+
1577
+ // Retry the turn start before the submitter replays pending steering.
1578
+ const userMessageSubmitter = supportsUserMessageResponses()
1579
+ ? experimental_createBridgeUserMessageSubmitter({
1580
+ // The submitter owns replay, after the turn start has been retried.
1581
+ send: message =>
1582
+ channel.send(message, { queueIfDisconnected: false }),
1583
+ onResponse: listener => channel.on('user-message-response', listener),
1584
+ onReconnect: listener => channel.onReconnect(listener),
1585
+ })
1586
+ : undefined;
1587
+
1473
1588
  const eventTypes = [
1474
1589
  'stream-start',
1475
1590
  'text-start',
@@ -1491,12 +1606,14 @@ function createSession({
1491
1606
  for (const type of eventTypes) {
1492
1607
  unsubs.push(
1493
1608
  channel.on(type, msg => {
1609
+ if (!belongsToTurn(msg)) return;
1494
1610
  forward(msg);
1495
1611
  }),
1496
1612
  );
1497
1613
  }
1498
1614
  unsubs.push(
1499
1615
  channel.on('finish', msg => {
1616
+ if (!belongsToTurn(msg)) return;
1500
1617
  const metadata = (
1501
1618
  msg as {
1502
1619
  harnessMetadata?: { 'claude-code'?: { sessionId?: unknown } };
@@ -1511,6 +1628,7 @@ function createSession({
1511
1628
  );
1512
1629
  unsubs.push(
1513
1630
  channel.on('error', msg => {
1631
+ if (!belongsToTurn(msg)) return;
1514
1632
  forward(msg);
1515
1633
  settleError(msg.error);
1516
1634
  }),
@@ -1556,7 +1674,7 @@ function createSession({
1556
1674
  }
1557
1675
  }
1558
1676
 
1559
- return {
1677
+ const control: HarnessV1PromptControl = {
1560
1678
  submitToolResult: async input => {
1561
1679
  channel.send({
1562
1680
  type: 'tool-result',
@@ -1585,6 +1703,35 @@ function createSession({
1585
1703
  }),
1586
1704
  done,
1587
1705
  };
1706
+ return {
1707
+ control,
1708
+ sendStart: message => {
1709
+ if (isSettled) return;
1710
+ startCursor = Math.max(
1711
+ channel.lastSeenEventId ?? 0,
1712
+ getBridgeHello()?.lastSeq ?? 0,
1713
+ );
1714
+ pendingStart = { ...message, startId: expectedStartId };
1715
+ startTimer = setTimeout(() => {
1716
+ if (isSettled || pendingStart == null) return;
1717
+ failStart(
1718
+ new Error(
1719
+ `claude-code bridge did not emit a turn event within ${turnStartTimeoutMs}ms.`,
1720
+ ),
1721
+ );
1722
+ }, turnStartTimeoutMs);
1723
+ startTimer.unref?.();
1724
+ try {
1725
+ sendPendingStart();
1726
+ } catch (error) {
1727
+ // The caller never receives control when the initial send throws.
1728
+ // Consume its rejection and remove the timer and turn listeners.
1729
+ void done.catch(() => {});
1730
+ settleError(error);
1731
+ throw error;
1732
+ }
1733
+ },
1734
+ };
1588
1735
  };
1589
1736
 
1590
1737
  const prepareTurn = async (turnOpts: {
@@ -1592,7 +1739,8 @@ function createSession({
1592
1739
  skills: ReadonlyArray<HarnessV1Skill>;
1593
1740
  emit: (event: HarnessV1StreamPart) => void;
1594
1741
  abortSignal?: AbortSignal;
1595
- }): Promise<HarnessV1PromptControl> => {
1742
+ startId?: string;
1743
+ }): Promise<ReturnType<typeof wireTurn>> => {
1596
1744
  if (
1597
1745
  turnOpts.responseFormat?.type === 'json' &&
1598
1746
  turnOpts.responseFormat.schema == null
@@ -1618,6 +1766,7 @@ function createSession({
1618
1766
  return wireTurn({
1619
1767
  emit: turnOpts.emit,
1620
1768
  abortSignal: turnOpts.abortSignal,
1769
+ startId: turnOpts.startId,
1621
1770
  });
1622
1771
  };
1623
1772
 
@@ -1625,7 +1774,10 @@ function createSession({
1625
1774
  sessionId,
1626
1775
  isResume,
1627
1776
  doPromptTurn: async promptOpts => {
1628
- const control = await prepareTurn(promptOpts);
1777
+ const { control, sendStart } = await prepareTurn({
1778
+ ...promptOpts,
1779
+ startId: generateId(),
1780
+ });
1629
1781
 
1630
1782
  /*
1631
1783
  * A signal that was already aborted has settled the turn inside
@@ -1657,6 +1809,9 @@ function createSession({
1657
1809
  maxTurns,
1658
1810
  ...(skillOverrides !== undefined ? { skillOverrides } : {}),
1659
1811
  ...(maxBudgetUsd !== undefined ? { maxBudgetUsd } : {}),
1812
+ ...(additionalDirectories !== undefined
1813
+ ? { additionalDirectories: [...additionalDirectories] }
1814
+ : {}),
1660
1815
  ...(strictMcpConfig !== undefined ? { strictMcpConfig } : {}),
1661
1816
  ...(questionTimeoutMs !== undefined ? { questionTimeoutMs } : {}),
1662
1817
  ...(excludeDynamicSections !== undefined
@@ -1691,12 +1846,15 @@ function createSession({
1691
1846
  pendingResumeFlag = false;
1692
1847
  // Recovery starts a native turn once. Later continuations attach to it.
1693
1848
  rerunContinue = false;
1694
- channel.send(startMessage);
1849
+ sendStart(startMessage);
1695
1850
 
1696
1851
  return control;
1697
1852
  },
1698
1853
  doContinueTurn: async continueOpts => {
1699
- const control = await prepareTurn(continueOpts);
1854
+ const { control, sendStart } = await prepareTurn({
1855
+ ...continueOpts,
1856
+ startId: rerunContinue ? generateId() : activeStartId,
1857
+ });
1700
1858
 
1701
1859
  /*
1702
1860
  * attach / replay: the still-running (or disk-replayed) turn streams into
@@ -1716,7 +1874,7 @@ function createSession({
1716
1874
  if (rerunContinue && !continueOpts.abortSignal?.aborted) {
1717
1875
  rerunContinue = false;
1718
1876
  pendingResumeFlag = false;
1719
- channel.send({
1877
+ sendStart({
1720
1878
  type: 'start' as const,
1721
1879
  /*
1722
1880
  * A continuation nudge rather than an empty prompt: `continue: true`
@@ -1741,6 +1899,9 @@ function createSession({
1741
1899
  maxTurns,
1742
1900
  ...(skillOverrides !== undefined ? { skillOverrides } : {}),
1743
1901
  ...(maxBudgetUsd !== undefined ? { maxBudgetUsd } : {}),
1902
+ ...(additionalDirectories !== undefined
1903
+ ? { additionalDirectories: [...additionalDirectories] }
1904
+ : {}),
1744
1905
  ...(strictMcpConfig !== undefined ? { strictMcpConfig } : {}),
1745
1906
  ...(questionTimeoutMs !== undefined ? { questionTimeoutMs } : {}),
1746
1907
  ...(excludeDynamicSections !== undefined
@@ -1809,6 +1970,7 @@ function createSession({
1809
1970
  port: bridgePort,
1810
1971
  token: bridgeToken,
1811
1972
  lastSeenEventId,
1973
+ ...(activeStartId == null ? {} : { startId: activeStartId }),
1812
1974
  ...(sandboxId == null ? {} : { sandboxId }),
1813
1975
  },
1814
1976
  ...(lastClaudeSessionId
@@ -1968,6 +2130,7 @@ function createSession({
1968
2130
  port: bridgePort,
1969
2131
  token: bridgeToken,
1970
2132
  lastSeenEventId,
2133
+ ...(activeStartId == null ? {} : { startId: activeStartId }),
1971
2134
  ...(sandboxId == null ? {} : { sandboxId }),
1972
2135
  },
1973
2136
  ...(lastClaudeSessionId