@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/harness-claude-code",
3
- "version": "1.0.177",
3
+ "version": "1.0.179",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -26,9 +26,9 @@
26
26
  }
27
27
  },
28
28
  "dependencies": {
29
- "@ai-sdk/harness": "1.0.173",
30
- "@ai-sdk/provider": "4.0.35",
31
- "@ai-sdk/provider-utils": "5.0.74",
29
+ "@ai-sdk/harness": "1.0.175",
30
+ "@ai-sdk/provider": "4.0.36",
31
+ "@ai-sdk/provider-utils": "5.0.75",
32
32
  "ws": "^8.21.0"
33
33
  },
34
34
  "peerDependencies": {
@@ -153,7 +153,44 @@ let lastClaudeSessionId: string | undefined;
153
153
  await runBridge<StartMessage>({
154
154
  bridgeType: 'claude-code',
155
155
  bridgeStateDir,
156
- onStart: runTurn,
156
+ ...(args.hostDisconnectTimeoutMs !== undefined
157
+ ? { hostDisconnectTimeoutMs: args.hostDisconnectTimeoutMs }
158
+ : {}),
159
+ onStart: async (start, turn) => {
160
+ const emit: BridgeTurn['emit'] = event => {
161
+ if (turn.abortSignal.aborted) return;
162
+ turn.emit({
163
+ ...event,
164
+ ...(start.startId == null ? {} : { startId: start.startId }),
165
+ });
166
+ };
167
+ /*
168
+ * The shared emitError closes over its own emitter, so wrapping turn.emit
169
+ * cannot attach startId to errors or suppress them after abort. Duplicating
170
+ * its stderr logging and error serialization here is an adapter-local
171
+ * workaround to keep errors scoped to their turn without changing the
172
+ * shared bridge. Keep this duplication aligned with shared error handling.
173
+ */
174
+ const emitError: BridgeTurn['emitError'] = ({ error, message }) => {
175
+ if (turn.abortSignal.aborted) return;
176
+ console.error(
177
+ `[harness:claude-code:error] ${message ?? 'bridge error'}:`,
178
+ error,
179
+ );
180
+ emit({
181
+ type: 'error',
182
+ error:
183
+ error instanceof Error
184
+ ? { name: error.name, message: error.message, stack: error.stack }
185
+ : error,
186
+ });
187
+ };
188
+ try {
189
+ await runTurn(start, { ...turn, emit, emitError });
190
+ } catch (error) {
191
+ emitError({ error, message: 'claude-code turn failed' });
192
+ }
193
+ },
157
194
  // Claude Code's conversation state lives in the runtime's own store, keyed
158
195
  // by working directory. The resume payload names the exact conversation so a
159
196
  // later resume does not have to fall back to "most recent in this workdir".
@@ -222,6 +259,7 @@ function createPermissionOptions(input: {
222
259
  inactiveNativeTools,
223
260
  cwd: input.toolCwds.get(options.toolUseID) ?? '',
224
261
  readableSkillRoots: input.start.readableSkillRoots ?? [],
262
+ additionalDirectories: input.start.additionalDirectories ?? [],
225
263
  blockedPath: options.blockedPath,
226
264
  }))
227
265
  ) {
@@ -390,7 +428,7 @@ function createPermissionSettings(input: {
390
428
  * the id Claude Code expects (`claude-opus-5-5`) to the gateway id, which
391
429
  * stays the id sent to the gateway.
392
430
  */
393
- function createGatewayModelOverrides(
431
+ function toGatewayModelOverride(
394
432
  model: string | undefined,
395
433
  ): Record<string, string> | undefined {
396
434
  if (!model?.startsWith('anthropic/')) return undefined;
@@ -400,11 +438,32 @@ function createGatewayModelOverrides(
400
438
  return id.includes('.') ? { [id.replace(/\./g, '-')]: model } : undefined;
401
439
  }
402
440
 
441
+ /**
442
+ * The `ANTHROPIC_DEFAULT_*_MODEL` variables point Claude Code's model aliases
443
+ * at other ids and `CLAUDE_CODE_SUBAGENT_MODEL` sets the model of subagents,
444
+ * which it misreads the same way. `model` comes last so that its entry wins a
445
+ * key it shares with one of them.
446
+ */
447
+ function createGatewayModelOverrides(
448
+ model: string | undefined,
449
+ env: Record<string, string | undefined>,
450
+ ): Record<string, string> | undefined {
451
+ const overrides = {
452
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_OPUS_MODEL),
453
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_SONNET_MODEL),
454
+ ...toGatewayModelOverride(env.ANTHROPIC_DEFAULT_HAIKU_MODEL),
455
+ ...toGatewayModelOverride(env.CLAUDE_CODE_SUBAGENT_MODEL),
456
+ ...toGatewayModelOverride(model),
457
+ };
458
+ return Object.keys(overrides).length > 0 ? overrides : undefined;
459
+ }
460
+
403
461
  async function needsHostApproval(input: {
404
462
  toolName: string;
405
463
  toolInput: unknown;
406
464
  cwd: string;
407
465
  readableSkillRoots: readonly string[];
466
+ additionalDirectories: readonly string[];
408
467
  blockedPath?: string;
409
468
  permissionMode: 'allow-reads' | 'allow-edits' | 'allow-all';
410
469
  inactiveNativeTools: ReadonlySet<string>;
@@ -465,6 +524,7 @@ async function needsHostApproval(input: {
465
524
  paths,
466
525
  access,
467
526
  readableSkillRoots: input.readableSkillRoots,
527
+ additionalDirectories: input.additionalDirectories,
468
528
  }));
469
529
  }
470
530
 
@@ -482,6 +542,7 @@ function createApprovalPreToolUseHook(input: {
482
542
  deferredToolUseIds: Set<string>;
483
543
  nativeToolCallNames: Map<string, string>;
484
544
  readableSkillRoots: readonly string[];
545
+ additionalDirectories: readonly string[];
485
546
  toolCwds: Map<string, string>;
486
547
  }): HookCallback {
487
548
  return async (hookInput, toolUseID): Promise<HookJSONOutput> => {
@@ -519,6 +580,7 @@ function createApprovalPreToolUseHook(input: {
519
580
  toolInput: hookInput.tool_input,
520
581
  cwd: hookInput.cwd,
521
582
  readableSkillRoots: input.readableSkillRoots,
583
+ additionalDirectories: input.additionalDirectories,
522
584
  permissionMode: input.permissionMode,
523
585
  inactiveNativeTools: input.inactiveNativeTools,
524
586
  }))
@@ -552,7 +614,16 @@ function nativeToolRequiresApproval(input: {
552
614
  }
553
615
 
554
616
  async function runTurn(start: StartMessage, turn: BridgeTurn): Promise<void> {
555
- const emit: Emit = msg => turn.emit(msg as BridgeEvent);
617
+ /*
618
+ * The host settles an aborted turn before its query finishes interrupting.
619
+ * Keep draining the query for graceful shutdown, but do not send its remaining
620
+ * events to listeners that may already belong to the next turn.
621
+ */
622
+ const emit: Emit = msg => {
623
+ if (!turn.abortSignal.aborted) {
624
+ turn.emit(msg as BridgeEvent);
625
+ }
626
+ };
556
627
 
557
628
  // Local controller for the Claude query. Aborted either by the host (via the
558
629
  // shared runtime's `turn.abortSignal`) or by us on a terminal error.
@@ -745,11 +816,13 @@ async function runTurn(start: StartMessage, turn: BridgeTurn): Promise<void> {
745
816
  approvalRequestedToolUseIds: streamEventState.approvalRequestedToolUseIds,
746
817
  emittedToolCallIds: streamEventState.emittedToolCallIds,
747
818
  });
748
- const modelOverrides = createGatewayModelOverrides(start.model);
819
+ const sdkEnv = { ...procEnv, ...start.env };
820
+ const modelOverrides = createGatewayModelOverrides(start.model, sdkEnv);
749
821
  const deferredToolUseIds = new Set<string>();
750
822
  const approvalPreToolUseHook = createApprovalPreToolUseHook({
751
823
  toolCwds,
752
824
  readableSkillRoots: start.readableSkillRoots ?? [],
825
+ additionalDirectories: start.additionalDirectories ?? [],
753
826
  permissionMode,
754
827
  inactiveNativeTools: new Set(inactiveNativeTools),
755
828
  decisions: approvalDecisions,
@@ -781,6 +854,9 @@ async function runTurn(start: StartMessage, turn: BridgeTurn): Promise<void> {
781
854
  ...(start.maxBudgetUsd !== undefined
782
855
  ? { maxBudgetUsd: start.maxBudgetUsd }
783
856
  : {}),
857
+ ...(start.additionalDirectories !== undefined
858
+ ? { additionalDirectories: start.additionalDirectories }
859
+ : {}),
784
860
  ...(start.strictMcpConfig !== undefined
785
861
  ? { strictMcpConfig: start.strictMcpConfig }
786
862
  : {}),
@@ -790,7 +866,7 @@ async function runTurn(start: StartMessage, turn: BridgeTurn): Promise<void> {
790
866
  ...(start.forwardSubagentText !== undefined
791
867
  ? { forwardSubagentText: start.forwardSubagentText }
792
868
  : {}),
793
- ...(start.env !== undefined ? { env: { ...procEnv, ...start.env } } : {}),
869
+ ...(start.env !== undefined ? { env: sdkEnv } : {}),
794
870
  ...(skillsOption ? { skills: skillsOption } : {}),
795
871
  ...(nativeTools !== undefined ? { tools: nativeTools } : {}),
796
872
  ...(inactiveNativeTools.length > 0
@@ -1451,13 +1527,23 @@ function addUsage(
1451
1527
  function parseArgs(args: string[]): {
1452
1528
  workdir?: string;
1453
1529
  bridgeStateDir?: string;
1530
+ hostDisconnectTimeoutMs?: number;
1454
1531
  } {
1455
- const out: { workdir?: string; bridgeStateDir?: string } = {};
1532
+ const out: {
1533
+ workdir?: string;
1534
+ bridgeStateDir?: string;
1535
+ hostDisconnectTimeoutMs?: number;
1536
+ } = {};
1456
1537
  for (let i = 0; i < args.length; i++) {
1457
1538
  if (args[i] === '--workdir' && i + 1 < args.length) {
1458
1539
  out.workdir = args[++i];
1459
1540
  } else if (args[i] === '--bridge-state-dir' && i + 1 < args.length) {
1460
1541
  out.bridgeStateDir = args[++i];
1542
+ } else if (
1543
+ args[i] === '--host-disconnect-timeout-ms' &&
1544
+ i + 1 < args.length
1545
+ ) {
1546
+ out.hostDisconnectTimeoutMs = Number(args[++i]);
1461
1547
  }
1462
1548
  }
1463
1549
  return out;
@@ -7,17 +7,27 @@ export async function areFileToolPathsTrusted(options: {
7
7
  paths: readonly string[];
8
8
  access: 'read' | 'write';
9
9
  readableSkillRoots: readonly string[];
10
+ additionalDirectories?: readonly string[];
10
11
  }): Promise<boolean> {
11
12
  if (options.paths.length === 0) return false;
12
13
  try {
13
14
  const roots = [await realpath(options.workDir)];
14
- if (options.access === 'read') {
15
- for (const root of options.readableSkillRoots) {
16
- try {
17
- roots.push(await realpath(root));
18
- } catch {
19
- continue;
20
- }
15
+ /*
16
+ * Additional directories are granted to Claude Code for reading and
17
+ * writing, like the working directory. Only absolute paths are trusted so
18
+ * a relative entry cannot widen trust relative to an unknown directory.
19
+ */
20
+ const trustedRoots = [
21
+ ...(options.additionalDirectories ?? []).filter(root =>
22
+ path.posix.isAbsolute(root),
23
+ ),
24
+ ...(options.access === 'read' ? options.readableSkillRoots : []),
25
+ ];
26
+ for (const root of trustedRoots) {
27
+ try {
28
+ roots.push(await realpath(root));
29
+ } catch {
30
+ continue;
21
31
  }
22
32
  }
23
33
  for (const filePath of options.paths) {
@@ -14,7 +14,10 @@ import { z } from 'zod/v4';
14
14
  * payload, which carries Claude SDK configuration.
15
15
  */
16
16
 
17
- export const outboundMessageSchema = harnessV1BridgeOutboundMessageSchema;
17
+ export const outboundMessageSchema = z.intersection(
18
+ harnessV1BridgeOutboundMessageSchema,
19
+ z.object({ startId: z.string().optional() }),
20
+ );
18
21
  export type OutboundMessage = z.infer<typeof outboundMessageSchema>;
19
22
 
20
23
  const thinkingDisplaySchema = z.enum(['summarized', 'omitted']).optional();
@@ -45,6 +48,7 @@ export const startMessageSchema = harnessV1BridgeStartBaseSchema.extend({
45
48
  maxTurns: z.number().optional(),
46
49
  skillOverrides: skillOverridesSchema.optional(),
47
50
  maxBudgetUsd: z.number().optional(),
51
+ additionalDirectories: z.array(z.string()).optional(),
48
52
  strictMcpConfig: z.boolean().optional(),
49
53
  questionTimeoutMs: z.number().optional(),
50
54
  excludeDynamicSections: z.boolean().optional(),