@ai-sdk/harness-opencode 1.0.176 → 1.0.178

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.
@@ -1,8 +1,9 @@
1
- import { appendFile, mkdir, writeFile } from "node:fs/promises";
2
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
1
+ import { appendFile, lstat, mkdir, realpath, writeFile } from "node:fs/promises";
2
+ import { existsSync, globSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
3
  import { randomBytes, randomUUID } from "node:crypto";
4
4
  import { argv, env, pid, stdout } from "node:process";
5
5
  import { WebSocketServer } from "ws";
6
+ import { homedir } from "node:os";
6
7
  import path from "node:path";
7
8
  import { isDeepStrictEqual } from "node:util";
8
9
  import { createOpencodeClient, createOpencodeServer } from "@opencode-ai/sdk/v2";
@@ -136,6 +137,12 @@ const WS_OPEN = 1;
136
137
  async function runBridge(options) {
137
138
  const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;
138
139
  const teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;
140
+ const hostDisconnectTimeoutMs = options.hostDisconnectTimeoutMs != null && Number.isFinite(options.hostDisconnectTimeoutMs) && options.hostDisconnectTimeoutMs > 0 ? Math.min(options.hostDisconnectTimeoutMs, 2147483647) : void 0;
141
+ let hostDisconnectTimer;
142
+ const clearHostDisconnectTimer = () => {
143
+ clearTimeout(hostDisconnectTimer);
144
+ hostDisconnectTimer = void 0;
145
+ };
139
146
  const expectedToken = options.token ?? env.BRIDGE_CHANNEL_TOKEN ?? "";
140
147
  const bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? "0", 10);
141
148
  const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;
@@ -157,6 +164,7 @@ async function runBridge(options) {
157
164
  * between turns. A new `start` fences on this so turns never overlap.
158
165
  */
159
166
  let activeTurn;
167
+ let lastStartId;
160
168
  let debugConfig;
161
169
  let consoleCaptureInstalled = false;
162
170
  const envDebugEnabled = ENV_TRUTHY.has((env.HARNESS_DEBUG ?? "").toLowerCase());
@@ -300,6 +308,11 @@ async function runBridge(options) {
300
308
  const handleInbound = async (msg, ws) => {
301
309
  switch (msg.type) {
302
310
  case "start": {
311
+ const startId = msg.startId;
312
+ if (startId != null) {
313
+ if (startId === lastStartId) return;
314
+ lastStartId = startId;
315
+ }
303
316
  for (;;) {
304
317
  const pendingTurn = activeTurn;
305
318
  if (pendingTurn == null) break;
@@ -317,6 +330,7 @@ async function runBridge(options) {
317
330
  const thisTurn = new Promise((resolve) => turnFinished = resolve);
318
331
  activeTurn = thisTurn;
319
332
  activeSocket = ws;
333
+ clearHostDisconnectTimer();
320
334
  const firstTurn = isFirstTurn;
321
335
  isFirstTurn = false;
322
336
  eventLog = [];
@@ -383,6 +397,7 @@ async function runBridge(options) {
383
397
  activeTurn = void 0;
384
398
  currentTurnState = "waiting";
385
399
  writeBridgeMeta("waiting");
400
+ clearHostDisconnectTimer();
386
401
  }
387
402
  turnFinished();
388
403
  }
@@ -449,6 +464,7 @@ async function runBridge(options) {
449
464
  return;
450
465
  case "resume":
451
466
  activeSocket = ws;
467
+ clearHostDisconnectTimer();
452
468
  replay(ws, msg.lastSeenEventId);
453
469
  return;
454
470
  case "destroy":
@@ -517,7 +533,10 @@ async function runBridge(options) {
517
533
  type: "bridge-hello",
518
534
  state: currentTurnState,
519
535
  lastSeq: seqCounter,
520
- capabilities: { experimental_userMessageResponses: true }
536
+ capabilities: {
537
+ idempotentStart: true,
538
+ experimental_userMessageResponses: true
539
+ }
521
540
  });
522
541
  ws.on("message", (raw) => {
523
542
  let parsed;
@@ -533,8 +552,18 @@ async function runBridge(options) {
533
552
  }
534
553
  handleInbound(parsed, ws);
535
554
  });
536
- ws.on("close", () => {
537
- if (activeSocket === ws) activeSocket = void 0;
555
+ ws.on("close", (_code, reason) => {
556
+ if (activeSocket === ws) {
557
+ activeSocket = void 0;
558
+ if (hostDisconnectTimeoutMs != null && activeTurn != null && reason.toString() !== "suspended") {
559
+ clearHostDisconnectTimer();
560
+ hostDisconnectTimer = setTimeout(() => {
561
+ hostDisconnectTimer = void 0;
562
+ if (activeSocket == null) turnAbort?.abort();
563
+ }, hostDisconnectTimeoutMs);
564
+ hostDisconnectTimer.unref?.();
565
+ }
566
+ }
538
567
  });
539
568
  ws.on("error", () => {});
540
569
  });
@@ -1573,6 +1602,30 @@ function configureOpenCodePath({ bootstrapDir, env }) {
1573
1602
  ].join(path.delimiter);
1574
1603
  }
1575
1604
  //#endregion
1605
+ //#region src/bridge/opencode-project-isolation.ts
1606
+ const GLOB_CHARACTERS = /[*?[\]{}]/;
1607
+ function resolveOpenCodeInstructions({ workdir, hostInstructions }) {
1608
+ if (hostInstructions !== void 0 && !(Array.isArray(hostInstructions) && hostInstructions.every((entry) => typeof entry === "string"))) return;
1609
+ const directory = resolveRealPath(workdir);
1610
+ return [path.join(directory, "AGENTS.md"), ...(hostInstructions ?? []).flatMap((entry) => {
1611
+ if (entry.startsWith("http://") || entry.startsWith("https://") || entry.startsWith("~/") || path.isAbsolute(entry)) return [entry];
1612
+ if (!GLOB_CHARACTERS.test(path.dirname(entry))) return [path.join(directory, entry)];
1613
+ return globSync(entry, {
1614
+ cwd: directory,
1615
+ withFileTypes: true
1616
+ }).filter((match) => match.isFile()).map((match) => path.join(match.parentPath, match.name)).sort();
1617
+ })];
1618
+ }
1619
+ function resolveRealPath(file) {
1620
+ const resolved = path.resolve(file);
1621
+ try {
1622
+ return realpathSync(resolved);
1623
+ } catch (error) {
1624
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return resolved;
1625
+ throw error;
1626
+ }
1627
+ }
1628
+ //#endregion
1576
1629
  //#region src/bridge/opencode-server-auth.ts
1577
1630
  function configureOpenCodeServerAuth({ env }) {
1578
1631
  const username = env.OPENCODE_SERVER_USERNAME ?? "opencode";
@@ -1799,6 +1852,94 @@ function toOpenCodePromptParts(prompt) {
1799
1852
  });
1800
1853
  }
1801
1854
  //#endregion
1855
+ //#region src/bridge/permission-paths.ts
1856
+ async function areOpenCodePermissionPathsTrusted(options) {
1857
+ const args = options.toolCall?.input;
1858
+ const nativeName = options.toolCall?.nativeName;
1859
+ const access = ["edit", "write"].includes(options.action) || [
1860
+ "write",
1861
+ "edit",
1862
+ "apply_patch"
1863
+ ].includes(nativeName ?? "") ? "write" : "read";
1864
+ let targets;
1865
+ if (Array.isArray(options.metadata?.files)) {
1866
+ if (options.metadata.files.length === 0) return false;
1867
+ targets = options.metadata.files.flatMap((value) => {
1868
+ if (value == null || typeof value !== "object") return [void 0];
1869
+ const file = value;
1870
+ return file.type === "move" || file.movePath != null ? [file.filePath, file.movePath] : [file.filePath];
1871
+ });
1872
+ } else if (args && [
1873
+ "read",
1874
+ "view",
1875
+ "write",
1876
+ "edit"
1877
+ ].includes(nativeName ?? "")) targets = [args.filePath];
1878
+ else if (args && [
1879
+ "glob",
1880
+ "grep",
1881
+ "list",
1882
+ "ls"
1883
+ ].includes(nativeName ?? "")) targets = [args.path ?? options.workDir];
1884
+ else if (typeof options.metadata?.filepath === "string" && options.action !== "edit") targets = [options.metadata.filepath];
1885
+ else if (options.action === "edit" && typeof options.metadata?.filepath === "string" && path.posix.isAbsolute(options.metadata.filepath)) targets = [options.metadata.filepath];
1886
+ else if (options.action === "read" && options.resources.length > 0 && options.resources.every((value) => path.posix.isAbsolute(value))) targets = options.resources;
1887
+ else return false;
1888
+ if (!targets.every((value) => typeof value === "string")) return false;
1889
+ return areFileToolPathsTrusted({
1890
+ workDir: options.workDir,
1891
+ cwd: options.workDir,
1892
+ paths: targets,
1893
+ access,
1894
+ readableSkillRoots: options.readableSkillRoots
1895
+ });
1896
+ }
1897
+ async function areFileToolPathsTrusted(options) {
1898
+ if (options.paths.length === 0) return false;
1899
+ try {
1900
+ const roots = [await realpath(options.workDir)];
1901
+ if (options.access === "read") for (const root of options.readableSkillRoots) try {
1902
+ roots.push(await realpath(root));
1903
+ } catch {
1904
+ continue;
1905
+ }
1906
+ for (const filePath of options.paths) {
1907
+ if (typeof filePath !== "string" || filePath.trim().length === 0) return false;
1908
+ if (!path.posix.isAbsolute(filePath) && !path.posix.isAbsolute(options.cwd)) return false;
1909
+ const absolutePath = path.posix.isAbsolute(filePath) ? filePath : `${options.cwd}/${filePath}`;
1910
+ for (const candidatePath of [absolutePath, path.posix.normalize(absolutePath)]) {
1911
+ const candidate = await resolvePermissionPath({ filePath: candidatePath });
1912
+ if (!roots.some((root) => {
1913
+ const relative = path.posix.relative(root, candidate);
1914
+ return relative === "" || relative !== ".." && !relative.startsWith("../") && !path.posix.isAbsolute(relative);
1915
+ })) return false;
1916
+ }
1917
+ }
1918
+ return true;
1919
+ } catch {
1920
+ return false;
1921
+ }
1922
+ }
1923
+ async function resolvePermissionPath(options) {
1924
+ let existingPath = options.filePath;
1925
+ const missing = [];
1926
+ for (;;) {
1927
+ let exists = true;
1928
+ try {
1929
+ await lstat(existingPath);
1930
+ } catch (error) {
1931
+ if (error == null || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error;
1932
+ exists = false;
1933
+ }
1934
+ if (exists) return path.posix.join(await realpath(existingPath), ...missing);
1935
+ const parent = path.posix.dirname(existingPath);
1936
+ const segment = path.posix.basename(existingPath);
1937
+ if (parent === existingPath || segment === "." || segment === "..") throw new Error("Unable to resolve permission path.");
1938
+ missing.unshift(segment);
1939
+ existingPath = parent;
1940
+ }
1941
+ }
1942
+ //#endregion
1802
1943
  //#region src/bridge/index.ts
1803
1944
  const NATIVE_TO_COMMON = {
1804
1945
  view: "read",
@@ -1863,9 +2004,11 @@ configureOpenCodePath({
1863
2004
  bootstrapDir,
1864
2005
  env
1865
2006
  });
2007
+ env.OPENCODE_DISABLE_PROJECT_CONFIG = "1";
1866
2008
  await runBridge({
1867
2009
  bridgeType: "opencode",
1868
2010
  bridgeStateDir,
2011
+ ...args.hostDisconnectTimeoutMs !== void 0 ? { hostDisconnectTimeoutMs: args.hostDisconnectTimeoutMs } : {},
1869
2012
  onStart: runTurn,
1870
2013
  onStop: () => runtime.sessionId ? { openCodeSessionId: runtime.sessionId } : {}
1871
2014
  });
@@ -1934,6 +2077,8 @@ async function ensureRuntime({ start }) {
1934
2077
  if (runtime.client && isDeepStrictEqual(runtime.openCodeConfig, start.openCodeConfig) && isDeepStrictEqual(runtime.inactiveBuiltinToolNames, start.inactiveBuiltinToolNames)) return;
1935
2078
  closeRuntime();
1936
2079
  try {
2080
+ const homeDirectory = homedir();
2081
+ for (const protectedPath of [homeDirectory, path.join(env.XDG_CONFIG_HOME || path.join(homeDirectory, ".config"), "opencode")]) if (isPathInsideOrEqual(protectedPath, workdir)) throw new Error(`OpenCode session working directory "${workdir}" must not be or contain the sandbox home directory or OpenCode's global config directory, because OpenCode always loads configuration from those locations.`);
1937
2082
  if (start.tools && start.tools.length > 0) {
1938
2083
  runtime.toolNames = new Set(start.tools.map((tool) => tool.name));
1939
2084
  runtime.relay = await startToolRelay({ tools: start.tools });
@@ -1982,10 +2127,10 @@ function buildOpenCodeConfig({ start, relayPort, toolSchemasPath }) {
1982
2127
  share: "disabled",
1983
2128
  autoupdate: false,
1984
2129
  permission: {
1985
- read: "allow",
1986
- glob: "allow",
1987
- grep: "allow",
1988
- list: "allow",
2130
+ read: start.permissionMode && start.permissionMode !== "allow-all" ? "ask" : "allow",
2131
+ glob: start.permissionMode && start.permissionMode !== "allow-all" ? "ask" : "allow",
2132
+ grep: start.permissionMode && start.permissionMode !== "allow-all" ? "ask" : "allow",
2133
+ list: start.permissionMode && start.permissionMode !== "allow-all" ? "ask" : "allow",
1989
2134
  edit: "ask",
1990
2135
  bash: "ask",
1991
2136
  external_directory: "ask",
@@ -1995,6 +2140,11 @@ function buildOpenCodeConfig({ start, relayPort, toolSchemasPath }) {
1995
2140
  question: "allow"
1996
2141
  }
1997
2142
  };
2143
+ const instructions = resolveOpenCodeInstructions({
2144
+ workdir,
2145
+ hostInstructions: start.openCodeConfig?.instructions
2146
+ });
2147
+ if (instructions) config.instructions = instructions;
1998
2148
  if (start.model) config.model = start.model;
1999
2149
  if (skillsDir) config.skills = { paths: [skillsDir] };
2000
2150
  const permission = config.permission;
@@ -2045,6 +2195,7 @@ function buildProviderConfig(start) {
2045
2195
  const providerID = model.providerID ?? start.provider ?? env.OPENAI_NAME ?? "anthropic";
2046
2196
  const modelID = model.modelID;
2047
2197
  if (env.AI_GATEWAY_API_KEY && env.AI_GATEWAY_BASE_URL) return { [providerID]: {
2198
+ ...providerID === "google" || providerID === "mistral" ? { npm: "@ai-sdk/openai-compatible" } : {},
2048
2199
  options: {
2049
2200
  apiKey: env.AI_GATEWAY_API_KEY,
2050
2201
  baseURL: toOpenCodeGatewayBaseUrl(env.AI_GATEWAY_BASE_URL),
@@ -2236,6 +2387,7 @@ async function runPrompt({ client, sessionId, start, turn, emit }) {
2236
2387
  const eventLoop = consumeEvents({
2237
2388
  client,
2238
2389
  sessionId,
2390
+ readableSkillRoots: start.readableSkillRoots,
2239
2391
  permissionMode: start.permissionMode,
2240
2392
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
2241
2393
  turn,
@@ -2420,6 +2572,7 @@ async function runCompaction({ client, sessionId, start, turn, emit }) {
2420
2572
  const eventLoop = consumeEvents({
2421
2573
  client,
2422
2574
  sessionId,
2575
+ readableSkillRoots: start.readableSkillRoots,
2423
2576
  permissionMode: start.permissionMode,
2424
2577
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
2425
2578
  turn,
@@ -2470,7 +2623,7 @@ async function runCompaction({ client, sessionId, start, turn, emit }) {
2470
2623
  harnessMetadata: { opencode: { missingSummary: true } }
2471
2624
  });
2472
2625
  }
2473
- async function consumeEvents({ client, sessionId, permissionMode, inactiveBuiltinToolNames, turn, state, hostInputTracker, emit, signal, onSubscribed, onEvent }) {
2626
+ async function consumeEvents({ client, sessionId, permissionMode, readableSkillRoots = [], inactiveBuiltinToolNames, turn, state, hostInputTracker, emit, signal, onSubscribed, onEvent }) {
2474
2627
  const stream = await subscribeLegacyEvents({
2475
2628
  client,
2476
2629
  signal
@@ -2478,6 +2631,55 @@ async function consumeEvents({ client, sessionId, permissionMode, inactiveBuilti
2478
2631
  onSubscribed?.();
2479
2632
  if (!stream) return;
2480
2633
  const taskSessionIds = /* @__PURE__ */ new Set([sessionId]);
2634
+ const observedCalls = /* @__PURE__ */ new Map();
2635
+ const permissionContext = {
2636
+ readableSkillRoots,
2637
+ decisions: /* @__PURE__ */ new Map(),
2638
+ getToolCall: async ({ event, sessionId: sourceSessionId }) => {
2639
+ const props = event.properties ?? {};
2640
+ const source = asOpenCodeObject(props.tool) ?? asOpenCodeObject(props.source);
2641
+ const callID = stringValue(source?.callID);
2642
+ if (!callID) return void 0;
2643
+ const key = JSON.stringify([sourceSessionId, callID]);
2644
+ const observed = observedCalls.get(key);
2645
+ if (observed) return observed;
2646
+ const messageID = stringValue(source?.messageID);
2647
+ if (messageID && typeof client.session.message === "function") try {
2648
+ const parts = asOpenCodeObject((await client.session.message({
2649
+ sessionID: sourceSessionId,
2650
+ messageID,
2651
+ directory: workdir
2652
+ })).data)?.parts;
2653
+ if (Array.isArray(parts)) {
2654
+ const snapshot = permissionToolCallFromPart(parts.map(asOpenCodeObject).find((value) => value?.callID === callID));
2655
+ if (snapshot) {
2656
+ observedCalls.set(key, snapshot);
2657
+ return snapshot;
2658
+ }
2659
+ }
2660
+ } catch {
2661
+ return observedCalls.get(key);
2662
+ }
2663
+ return observedCalls.get(key);
2664
+ },
2665
+ emitToolCall: ({ toolCallId, toolCall }) => {
2666
+ if (!toolCall || sentToolCallIds.has(toolCallId)) return;
2667
+ const nativeName = toolCall.nativeName;
2668
+ const toolName = toWireToolName(nativeName);
2669
+ state.toolCallsEmitted.add(toolCallId);
2670
+ emitToHost({
2671
+ type: "tool-call",
2672
+ toolCallId,
2673
+ toolName,
2674
+ input: JSON.stringify(toolCall.input),
2675
+ providerExecuted: true,
2676
+ ...nativeNameField({
2677
+ nativeName,
2678
+ toolName
2679
+ })
2680
+ });
2681
+ }
2682
+ };
2481
2683
  const registerSubagentSession = (sourceSessionId) => function register({ parentSessionId, sessionId: subagentSessionId }) {
2482
2684
  if (parentSessionId === sourceSessionId && taskSessionIds.has(sourceSessionId)) taskSessionIds.add(subagentSessionId);
2483
2685
  };
@@ -2630,6 +2832,19 @@ async function consumeEvents({ client, sessionId, permissionMode, inactiveBuilti
2630
2832
  const scopedSessionId = !eventSessionId || eventSessionId === sessionId ? sessionId : taskSessionIds.has(eventSessionId) ? eventSessionId : void 0;
2631
2833
  if (!scopedSessionId) return false;
2632
2834
  const isDescendant = scopedSessionId !== sessionId;
2835
+ const part = asOpenCodeObject(event.properties?.part);
2836
+ const snapshot = permissionToolCallFromPart(part);
2837
+ if (snapshot && typeof part?.callID === "string") observedCalls.set(JSON.stringify([scopedSessionId, part.callID]), snapshot);
2838
+ if (event.type === "session.next.tool.started") {
2839
+ const props = event.properties ?? {};
2840
+ const input = asOpenCodeObject(props.input);
2841
+ const nativeName = stringValue(props.toolName ?? props.tool);
2842
+ const callID = stringValue(props.callID);
2843
+ if (input && nativeName && callID) observedCalls.set(JSON.stringify([scopedSessionId, callID]), {
2844
+ nativeName,
2845
+ input
2846
+ });
2847
+ }
2633
2848
  const waitFor = ({ toolCallId, settlesToolCall }) => hostInputWait({
2634
2849
  toolCallId: isDescendant ? `${scopedSessionId}:${toolCallId}` : toolCallId,
2635
2850
  isDescendant,
@@ -2645,6 +2860,7 @@ async function consumeEvents({ client, sessionId, permissionMode, inactiveBuilti
2645
2860
  else if (event.type === "permission.v2.asked") runHandler(handlePermissionV2({
2646
2861
  client,
2647
2862
  sessionId: scopedSessionId,
2863
+ context: permissionContext,
2648
2864
  permissionMode,
2649
2865
  inactiveBuiltinToolNames,
2650
2866
  turn,
@@ -2655,6 +2871,7 @@ async function consumeEvents({ client, sessionId, permissionMode, inactiveBuilti
2655
2871
  else if (event.type === "permission.asked") runHandler(handlePermission({
2656
2872
  client,
2657
2873
  sessionId: scopedSessionId,
2874
+ context: permissionContext,
2658
2875
  permissionMode,
2659
2876
  inactiveBuiltinToolNames,
2660
2877
  turn,
@@ -2719,11 +2936,18 @@ async function handleQuestion({ client, turn, emit, event, waitFor }) {
2719
2936
  function sanitizeMcpToolName(value) {
2720
2937
  return value.replace(/[^a-zA-Z0-9_-]/g, "_");
2721
2938
  }
2722
- async function handlePermissionV2({ client, sessionId, permissionMode, inactiveBuiltinToolNames, turn, emit, event, waitFor }) {
2939
+ async function handlePermissionV2({ client, sessionId, context, permissionMode, inactiveBuiltinToolNames, turn, emit, event, waitFor }) {
2723
2940
  const props = event.properties ?? {};
2724
2941
  const requestID = String(props.id ?? "");
2725
2942
  if (!requestID) return;
2726
2943
  const reply = await selectPermissionReply({
2944
+ context,
2945
+ sessionId,
2946
+ toolCall: await context.getToolCall({
2947
+ event,
2948
+ sessionId
2949
+ }),
2950
+ metadata: asOpenCodeObject(props.metadata),
2727
2951
  action: String(props.action ?? ""),
2728
2952
  resources: Array.isArray(props.resources) ? props.resources.map(String) : [],
2729
2953
  requestID,
@@ -2741,12 +2965,19 @@ async function handlePermissionV2({ client, sessionId, permissionMode, inactiveB
2741
2965
  ...reply.message ? { message: reply.message } : {}
2742
2966
  });
2743
2967
  }
2744
- async function handlePermission({ client, sessionId, permissionMode, inactiveBuiltinToolNames, turn, emit, event, waitFor }) {
2968
+ async function handlePermission({ client, sessionId, context, permissionMode, inactiveBuiltinToolNames, turn, emit, event, waitFor }) {
2745
2969
  const props = event.properties ?? {};
2746
2970
  const requestID = String(props.id ?? "");
2747
2971
  if (!requestID) return;
2748
2972
  const tool = asOpenCodeObject(props.tool);
2749
2973
  const reply = await selectPermissionReply({
2974
+ context,
2975
+ sessionId,
2976
+ toolCall: await context.getToolCall({
2977
+ event,
2978
+ sessionId
2979
+ }),
2980
+ metadata: asOpenCodeObject(props.metadata),
2750
2981
  action: String(props.permission ?? ""),
2751
2982
  resources: Array.isArray(props.patterns) ? props.patterns.map(String) : [],
2752
2983
  requestID,
@@ -2764,25 +2995,40 @@ async function handlePermission({ client, sessionId, permissionMode, inactiveBui
2764
2995
  ...reply.message ? { message: reply.message } : {}
2765
2996
  });
2766
2997
  }
2767
- async function selectPermissionReply({ action, resources, requestID, toolCallId, permissionMode, inactiveBuiltinToolNames, turn, emit, waitFor }) {
2768
- const requestApproval = async () => {
2769
- const wait = waitFor?.({
2998
+ async function selectPermissionReply({ context, sessionId, toolCall, metadata, action, resources, requestID, toolCallId, permissionMode, inactiveBuiltinToolNames, turn, emit, waitFor }) {
2999
+ const requestApproval = () => {
3000
+ const key = toolCall ? JSON.stringify([
3001
+ sessionId,
2770
3002
  toolCallId,
2771
- settlesToolCall: false
2772
- });
2773
- wait?.markWaiting();
2774
- return turn.requestToolApproval(requestID).finally(() => wait?.clearWaiting());
3003
+ toolCall
3004
+ ]) : void 0;
3005
+ const existing = key ? context.decisions.get(key) : void 0;
3006
+ if (existing) return existing;
3007
+ const decision = (async () => {
3008
+ context.emitToolCall({
3009
+ toolCallId,
3010
+ toolCall
3011
+ });
3012
+ await emit({
3013
+ type: "tool-approval-request",
3014
+ approvalId: requestID,
3015
+ toolCallId
3016
+ });
3017
+ const wait = waitFor?.({
3018
+ toolCallId,
3019
+ settlesToolCall: false
3020
+ });
3021
+ wait?.markWaiting();
3022
+ return turn.requestToolApproval(requestID).finally(() => wait?.clearWaiting());
3023
+ })();
3024
+ if (key) context.decisions.set(key, decision);
3025
+ return decision;
2775
3026
  };
2776
3027
  const toolName = toPermissionToolName(action);
2777
3028
  if (isBuiltinToolInactive({
2778
3029
  toolName,
2779
3030
  inactiveBuiltinToolNames
2780
3031
  })) {
2781
- await emit({
2782
- type: "tool-approval-request",
2783
- approvalId: requestID,
2784
- toolCallId
2785
- });
2786
3032
  const decision = await requestApproval();
2787
3033
  return decision.approved ? { reply: "once" } : {
2788
3034
  reply: "reject",
@@ -2790,17 +3036,24 @@ async function selectPermissionReply({ action, resources, requestID, toolCallId,
2790
3036
  };
2791
3037
  }
2792
3038
  if (!permissionMode || permissionMode === "allow-all") return { reply: "always" };
2793
- if (resources.some((resource) => isExternalPath(resource))) return {
2794
- reply: "reject",
2795
- message: "External directory access rejected."
2796
- };
2797
- const kind = TOOL_KIND[toolName] ?? "bash";
2798
- if (permissionMode === "allow-edits" ? kind === "readonly" || kind === "edit" : kind === "readonly") return { reply: "always" };
2799
- await emit({
2800
- type: "tool-approval-request",
2801
- approvalId: requestID,
2802
- toolCallId
2803
- });
3039
+ const nativeName = toolCall?.nativeName;
3040
+ const filePermission = action === "external_directory" || [
3041
+ "read",
3042
+ "write",
3043
+ "edit",
3044
+ "glob",
3045
+ "grep",
3046
+ "ls"
3047
+ ].includes(toolName);
3048
+ const kind = action === "external_directory" && nativeName ? nativeName === "apply_patch" ? "edit" : TOOL_KIND[toWireToolName(nativeName)] ?? "bash" : TOOL_KIND[toolName] ?? "bash";
3049
+ if ((permissionMode === "allow-edits" ? kind === "readonly" || kind === "edit" : kind === "readonly") && (!filePermission || await areOpenCodePermissionPathsTrusted({
3050
+ action,
3051
+ resources,
3052
+ metadata,
3053
+ toolCall,
3054
+ workDir: workdir,
3055
+ readableSkillRoots: context.readableSkillRoots
3056
+ }))) return { reply: "once" };
2804
3057
  const decision = await requestApproval();
2805
3058
  return decision.approved ? { reply: "once" } : {
2806
3059
  reply: "reject",
@@ -2823,10 +3076,6 @@ function toPermissionToolName(action) {
2823
3076
  function isBuiltinToolInactive(input) {
2824
3077
  return input.inactiveBuiltinToolNames?.some((toolName) => toolName === input.toolName) ?? false;
2825
3078
  }
2826
- function isExternalPath(resource) {
2827
- if (!path.isAbsolute(resource)) return false;
2828
- return !isPathInsideOrEqual(resource, workdir) && (!skillsDir || !isPathInsideOrEqual(resource, skillsDir));
2829
- }
2830
3079
  function isPathInsideOrEqual(file, root) {
2831
3080
  const relative = path.relative(canonicalizeForContainment(root), canonicalizeForContainment(file));
2832
3081
  return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
@@ -2840,6 +3089,20 @@ function canonicalizeForContainment(inputPath) {
2840
3089
  return parent === normalized ? normalized : path.join(canonicalizeForContainment(parent), path.basename(normalized));
2841
3090
  }
2842
3091
  }
3092
+ function permissionToolCallFromPart(value) {
3093
+ const part = asOpenCodeObject(value);
3094
+ const state = asOpenCodeObject(part?.state);
3095
+ const input = asOpenCodeObject(state?.input);
3096
+ if (part?.type !== "tool" || typeof part.tool !== "string" || !input || ![
3097
+ "running",
3098
+ "completed",
3099
+ "error"
3100
+ ].includes(String(state?.status))) return void 0;
3101
+ return {
3102
+ nativeName: part.tool,
3103
+ input
3104
+ };
3105
+ }
2843
3106
  function toWireToolName(nativeName) {
2844
3107
  return NATIVE_TO_COMMON[nativeName] ?? OPENCODE_TO_WIRE[nativeName] ?? nativeName;
2845
3108
  }
@@ -3075,6 +3338,7 @@ function parseArgs(args) {
3075
3338
  const out = {};
3076
3339
  for (let i = 0; i < args.length; i++) if (args[i] === "--workdir" && i + 1 < args.length) out.workdir = args[++i];
3077
3340
  else if (args[i] === "--bridge-state-dir" && i + 1 < args.length) out.bridgeStateDir = args[++i];
3341
+ else if (args[i] === "--host-disconnect-timeout-ms" && i + 1 < args.length) out.hostDisconnectTimeoutMs = Number(args[++i]);
3078
3342
  else if (args[i] === "--bootstrap-dir" && i + 1 < args.length) out.bootstrapDir = args[++i];
3079
3343
  else if (args[i] === "--skills-dir" && i + 1 < args.length) out.skillsDir = args[++i];
3080
3344
  return out;