@ai-sdk/harness-opencode 1.0.175 → 1.0.177

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.
@@ -5,6 +5,7 @@ import {
5
5
  } from '@ai-sdk/harness/bridge';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
8
9
  import path from 'node:path';
9
10
  import { argv, env as procEnv } from 'node:process';
10
11
  import { isDeepStrictEqual } from 'node:util';
@@ -37,6 +38,7 @@ import {
37
38
  import { createEmitStreamEvent, stringValue } from './create-emit-stream-event';
38
39
  import { mapOpenCodeFinishReason } from './opencode-finish-step';
39
40
  import { configureOpenCodePath } from './opencode-path';
41
+ import { resolveOpenCodeInstructions } from './opencode-project-isolation';
40
42
  import { configureOpenCodeServerAuth } from './opencode-server-auth';
41
43
  import {
42
44
  addUsage,
@@ -60,6 +62,10 @@ import {
60
62
  type OpenCodeQuestionRequest,
61
63
  } from './question-tool';
62
64
  import { toOpenCodePromptParts } from './opencode-prompt';
65
+ import {
66
+ areOpenCodePermissionPathsTrusted,
67
+ type PermissionToolCall,
68
+ } from './permission-paths';
63
69
 
64
70
  type Emit = (msg: Record<string, unknown>) => void;
65
71
  /* Resolves once the approval request has been sent to the host. */
@@ -178,6 +184,14 @@ const runtime: RuntimeState = {
178
184
  let currentHostInputTracker: OpenCodeHostInputTracker | undefined;
179
185
  let currentTurn: BridgeTurn | undefined;
180
186
  configureOpenCodePath({ bootstrapDir, env: procEnv });
187
+ /*
188
+ * OpenCode loads `opencode.json[c]` and `.opencode/` configuration from the
189
+ * session working directory and its parents. That configuration can define
190
+ * agent-local permissions, plugins, and MCP servers, so repository content
191
+ * could override harness permissions and built-in tool filtering. Disabling
192
+ * project configuration keeps the bridge-provided configuration authoritative.
193
+ */
194
+ procEnv.OPENCODE_DISABLE_PROJECT_CONFIG = '1';
181
195
 
182
196
  await runBridge<StartMessage>({
183
197
  bridgeType: 'opencode',
@@ -257,6 +271,27 @@ async function ensureRuntime({
257
271
  closeRuntime();
258
272
 
259
273
  try {
274
+ /*
275
+ * OpenCode always loads configuration, instructions, and skills from the
276
+ * home directory and its global config directory, even with project
277
+ * configuration disabled. A working directory that is or contains either
278
+ * location would let repository content act as trusted global
279
+ * configuration.
280
+ */
281
+ const homeDirectory = homedir();
282
+ for (const protectedPath of [
283
+ homeDirectory,
284
+ path.join(
285
+ procEnv.XDG_CONFIG_HOME || path.join(homeDirectory, '.config'),
286
+ 'opencode',
287
+ ),
288
+ ]) {
289
+ if (isPathInsideOrEqual(protectedPath, workdir)) {
290
+ throw new Error(
291
+ `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.`,
292
+ );
293
+ }
294
+ }
260
295
  if (start.tools && start.tools.length > 0) {
261
296
  runtime.toolNames = new Set(start.tools.map(tool => tool.name));
262
297
  runtime.relay = await startToolRelay({
@@ -332,10 +367,22 @@ function buildOpenCodeConfig({
332
367
  share: 'disabled',
333
368
  autoupdate: false,
334
369
  permission: {
335
- read: 'allow',
336
- glob: 'allow',
337
- grep: 'allow',
338
- list: 'allow',
370
+ read:
371
+ start.permissionMode && start.permissionMode !== 'allow-all'
372
+ ? 'ask'
373
+ : 'allow',
374
+ glob:
375
+ start.permissionMode && start.permissionMode !== 'allow-all'
376
+ ? 'ask'
377
+ : 'allow',
378
+ grep:
379
+ start.permissionMode && start.permissionMode !== 'allow-all'
380
+ ? 'ask'
381
+ : 'allow',
382
+ list:
383
+ start.permissionMode && start.permissionMode !== 'allow-all'
384
+ ? 'ask'
385
+ : 'allow',
339
386
  edit: 'ask',
340
387
  bash: 'ask',
341
388
  external_directory: 'ask',
@@ -345,6 +392,11 @@ function buildOpenCodeConfig({
345
392
  question: 'allow',
346
393
  },
347
394
  };
395
+ const instructions = resolveOpenCodeInstructions({
396
+ workdir,
397
+ hostInstructions: start.openCodeConfig?.instructions,
398
+ });
399
+ if (instructions) config.instructions = instructions;
348
400
  if (start.model) config.model = start.model;
349
401
  if (skillsDir) config.skills = { paths: [skillsDir] };
350
402
  const permission = config.permission as Record<string, unknown>;
@@ -765,6 +817,7 @@ async function runPrompt({
765
817
  const eventLoop = consumeEvents({
766
818
  client,
767
819
  sessionId,
820
+ readableSkillRoots: start.readableSkillRoots,
768
821
  permissionMode: start.permissionMode,
769
822
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
770
823
  turn,
@@ -996,6 +1049,7 @@ async function runCompaction({
996
1049
  const eventLoop = consumeEvents({
997
1050
  client,
998
1051
  sessionId,
1052
+ readableSkillRoots: start.readableSkillRoots,
999
1053
  permissionMode: start.permissionMode,
1000
1054
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
1001
1055
  turn,
@@ -1061,6 +1115,7 @@ async function consumeEvents({
1061
1115
  client,
1062
1116
  sessionId,
1063
1117
  permissionMode,
1118
+ readableSkillRoots = [],
1064
1119
  inactiveBuiltinToolNames,
1065
1120
  turn,
1066
1121
  state,
@@ -1073,6 +1128,7 @@ async function consumeEvents({
1073
1128
  client: OpenCodeClient;
1074
1129
  sessionId: string;
1075
1130
  permissionMode: StartMessage['permissionMode'];
1131
+ readableSkillRoots?: readonly string[];
1076
1132
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1077
1133
  turn: BridgeTurn;
1078
1134
  state: TranslationState;
@@ -1086,6 +1142,59 @@ async function consumeEvents({
1086
1142
  onSubscribed?.();
1087
1143
  if (!stream) return;
1088
1144
  const taskSessionIds = new Set([sessionId]);
1145
+ const observedCalls = new Map<string, PermissionToolCall>();
1146
+ const permissionContext: PermissionContext = {
1147
+ readableSkillRoots,
1148
+ decisions: new Map(),
1149
+ getToolCall: async ({ event, sessionId: sourceSessionId }) => {
1150
+ const props = event.properties ?? {};
1151
+ const source =
1152
+ asOpenCodeObject(props.tool) ?? asOpenCodeObject(props.source);
1153
+ const callID = stringValue(source?.callID);
1154
+ if (!callID) return undefined;
1155
+ const key = JSON.stringify([sourceSessionId, callID]);
1156
+ const observed = observedCalls.get(key);
1157
+ if (observed) return observed;
1158
+ const messageID = stringValue(source?.messageID);
1159
+ if (messageID && typeof client.session.message === 'function') {
1160
+ try {
1161
+ const response = await client.session.message({
1162
+ sessionID: sourceSessionId,
1163
+ messageID,
1164
+ directory: workdir,
1165
+ });
1166
+ const parts = asOpenCodeObject(response.data)?.parts;
1167
+ if (Array.isArray(parts)) {
1168
+ const part = parts
1169
+ .map(asOpenCodeObject)
1170
+ .find(value => value?.callID === callID);
1171
+ const snapshot = permissionToolCallFromPart(part);
1172
+ if (snapshot) {
1173
+ observedCalls.set(key, snapshot);
1174
+ return snapshot;
1175
+ }
1176
+ }
1177
+ } catch {
1178
+ return observedCalls.get(key);
1179
+ }
1180
+ }
1181
+ return observedCalls.get(key);
1182
+ },
1183
+ emitToolCall: ({ toolCallId, toolCall }) => {
1184
+ if (!toolCall || sentToolCallIds.has(toolCallId)) return;
1185
+ const nativeName = toolCall.nativeName;
1186
+ const toolName = toWireToolName(nativeName);
1187
+ state.toolCallsEmitted.add(toolCallId);
1188
+ emitToHost({
1189
+ type: 'tool-call',
1190
+ toolCallId,
1191
+ toolName,
1192
+ input: JSON.stringify(toolCall.input),
1193
+ providerExecuted: true,
1194
+ ...nativeNameField({ nativeName, toolName }),
1195
+ });
1196
+ },
1197
+ };
1089
1198
  const registerSubagentSession = (sourceSessionId: string) =>
1090
1199
  function register({
1091
1200
  parentSessionId,
@@ -1280,6 +1389,26 @@ async function consumeEvents({
1280
1389
  : undefined;
1281
1390
  if (!scopedSessionId) return false;
1282
1391
  const isDescendant = scopedSessionId !== sessionId;
1392
+ const part = asOpenCodeObject(event.properties?.part);
1393
+ const snapshot = permissionToolCallFromPart(part);
1394
+ if (snapshot && typeof part?.callID === 'string') {
1395
+ observedCalls.set(
1396
+ JSON.stringify([scopedSessionId, part.callID]),
1397
+ snapshot,
1398
+ );
1399
+ }
1400
+ if (event.type === 'session.next.tool.started') {
1401
+ const props = event.properties ?? {};
1402
+ const input = asOpenCodeObject(props.input);
1403
+ const nativeName = stringValue(props.toolName ?? props.tool);
1404
+ const callID = stringValue(props.callID);
1405
+ if (input && nativeName && callID) {
1406
+ observedCalls.set(JSON.stringify([scopedSessionId, callID]), {
1407
+ nativeName,
1408
+ input,
1409
+ });
1410
+ }
1411
+ }
1283
1412
  const waitFor = ({
1284
1413
  toolCallId,
1285
1414
  settlesToolCall,
@@ -1309,6 +1438,7 @@ async function consumeEvents({
1309
1438
  handlePermissionV2({
1310
1439
  client,
1311
1440
  sessionId: scopedSessionId,
1441
+ context: permissionContext,
1312
1442
  permissionMode,
1313
1443
  inactiveBuiltinToolNames,
1314
1444
  turn,
@@ -1322,6 +1452,7 @@ async function consumeEvents({
1322
1452
  handlePermission({
1323
1453
  client,
1324
1454
  sessionId: scopedSessionId,
1455
+ context: permissionContext,
1325
1456
  permissionMode,
1326
1457
  inactiveBuiltinToolNames,
1327
1458
  turn,
@@ -1446,6 +1577,7 @@ function sanitizeMcpToolName(value: string): string {
1446
1577
  async function handlePermissionV2({
1447
1578
  client,
1448
1579
  sessionId,
1580
+ context,
1449
1581
  permissionMode,
1450
1582
  inactiveBuiltinToolNames,
1451
1583
  turn,
@@ -1455,6 +1587,7 @@ async function handlePermissionV2({
1455
1587
  }: {
1456
1588
  client: OpenCodeClient;
1457
1589
  sessionId: string;
1590
+ context: PermissionContext;
1458
1591
  permissionMode: StartMessage['permissionMode'];
1459
1592
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1460
1593
  turn: BridgeTurn;
@@ -1466,6 +1599,10 @@ async function handlePermissionV2({
1466
1599
  const requestID = String(props.id ?? '');
1467
1600
  if (!requestID) return;
1468
1601
  const reply = await selectPermissionReply({
1602
+ context,
1603
+ sessionId,
1604
+ toolCall: await context.getToolCall({ event, sessionId }),
1605
+ metadata: asOpenCodeObject(props.metadata),
1469
1606
  action: String(props.action ?? ''),
1470
1607
  resources: Array.isArray(props.resources)
1471
1608
  ? props.resources.map(String)
@@ -1489,6 +1626,7 @@ async function handlePermissionV2({
1489
1626
  async function handlePermission({
1490
1627
  client,
1491
1628
  sessionId,
1629
+ context,
1492
1630
  permissionMode,
1493
1631
  inactiveBuiltinToolNames,
1494
1632
  turn,
@@ -1498,6 +1636,7 @@ async function handlePermission({
1498
1636
  }: {
1499
1637
  client: OpenCodeClient;
1500
1638
  sessionId: string;
1639
+ context: PermissionContext;
1501
1640
  permissionMode: StartMessage['permissionMode'];
1502
1641
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1503
1642
  turn: BridgeTurn;
@@ -1510,6 +1649,10 @@ async function handlePermission({
1510
1649
  if (!requestID) return;
1511
1650
  const tool = asOpenCodeObject(props.tool);
1512
1651
  const reply = await selectPermissionReply({
1652
+ context,
1653
+ sessionId,
1654
+ toolCall: await context.getToolCall({ event, sessionId }),
1655
+ metadata: asOpenCodeObject(props.metadata),
1513
1656
  action: String(props.permission ?? ''),
1514
1657
  resources: Array.isArray(props.patterns) ? props.patterns.map(String) : [],
1515
1658
  requestID,
@@ -1530,6 +1673,10 @@ async function handlePermission({
1530
1673
  }
1531
1674
 
1532
1675
  async function selectPermissionReply({
1676
+ context,
1677
+ sessionId,
1678
+ toolCall,
1679
+ metadata,
1533
1680
  action,
1534
1681
  resources,
1535
1682
  requestID,
@@ -1540,6 +1687,10 @@ async function selectPermissionReply({
1540
1687
  emit,
1541
1688
  waitFor,
1542
1689
  }: {
1690
+ context: PermissionContext;
1691
+ sessionId: string;
1692
+ toolCall: PermissionToolCall | undefined;
1693
+ metadata: OpenCodeObject | undefined;
1543
1694
  action: string;
1544
1695
  resources: string[];
1545
1696
  requestID: string;
@@ -1550,20 +1701,33 @@ async function selectPermissionReply({
1550
1701
  emit: EmitApprovalRequest;
1551
1702
  waitFor?: WaitForHostInput;
1552
1703
  }): Promise<{ reply: 'once' | 'always' | 'reject'; message?: string }> {
1553
- const requestApproval = async () => {
1554
- const wait = waitFor?.({ toolCallId, settlesToolCall: false });
1555
- wait?.markWaiting();
1556
- return turn
1557
- .requestToolApproval(requestID)
1558
- .finally(() => wait?.clearWaiting());
1704
+ const requestApproval = () => {
1705
+ const key = toolCall
1706
+ ? JSON.stringify([sessionId, toolCallId, toolCall])
1707
+ : undefined;
1708
+ const existing = key ? context.decisions.get(key) : undefined;
1709
+ if (existing) return existing;
1710
+ const decision = (async () => {
1711
+ context.emitToolCall({
1712
+ toolCallId,
1713
+ toolCall,
1714
+ });
1715
+ await emit({
1716
+ type: 'tool-approval-request',
1717
+ approvalId: requestID,
1718
+ toolCallId,
1719
+ });
1720
+ const wait = waitFor?.({ toolCallId, settlesToolCall: false });
1721
+ wait?.markWaiting();
1722
+ return turn
1723
+ .requestToolApproval(requestID)
1724
+ .finally(() => wait?.clearWaiting());
1725
+ })();
1726
+ if (key) context.decisions.set(key, decision);
1727
+ return decision;
1559
1728
  };
1560
1729
  const toolName = toPermissionToolName(action);
1561
1730
  if (isBuiltinToolInactive({ toolName, inactiveBuiltinToolNames })) {
1562
- await emit({
1563
- type: 'tool-approval-request',
1564
- approvalId: requestID,
1565
- toolCallId,
1566
- });
1567
1731
  const decision = await requestApproval();
1568
1732
  return decision.approved
1569
1733
  ? { reply: 'once' }
@@ -1575,21 +1739,34 @@ async function selectPermissionReply({
1575
1739
  if (!permissionMode || permissionMode === 'allow-all') {
1576
1740
  return { reply: 'always' };
1577
1741
  }
1578
- if (resources.some(resource => isExternalPath(resource))) {
1579
- return { reply: 'reject', message: 'External directory access rejected.' };
1580
- }
1581
- const kind = TOOL_KIND[toolName] ?? 'bash';
1742
+ const nativeName = toolCall?.nativeName;
1743
+ const filePermission =
1744
+ action === 'external_directory' ||
1745
+ ['read', 'write', 'edit', 'glob', 'grep', 'ls'].includes(toolName);
1746
+ const kind =
1747
+ action === 'external_directory' && nativeName
1748
+ ? nativeName === 'apply_patch'
1749
+ ? 'edit'
1750
+ : (TOOL_KIND[toWireToolName(nativeName)] ?? 'bash')
1751
+ : (TOOL_KIND[toolName] ?? 'bash');
1582
1752
  const allowed =
1583
1753
  permissionMode === 'allow-edits'
1584
1754
  ? kind === 'readonly' || kind === 'edit'
1585
1755
  : kind === 'readonly';
1586
- if (allowed) return { reply: 'always' };
1756
+ if (
1757
+ allowed &&
1758
+ (!filePermission ||
1759
+ (await areOpenCodePermissionPathsTrusted({
1760
+ action,
1761
+ resources,
1762
+ metadata,
1763
+ toolCall,
1764
+ workDir: workdir,
1765
+ readableSkillRoots: context.readableSkillRoots,
1766
+ })))
1767
+ )
1768
+ return { reply: 'once' };
1587
1769
 
1588
- await emit({
1589
- type: 'tool-approval-request',
1590
- approvalId: requestID,
1591
- toolCallId,
1592
- });
1593
1770
  const decision = await requestApproval();
1594
1771
  return decision.approved
1595
1772
  ? { reply: 'once' }
@@ -1626,14 +1803,6 @@ function isBuiltinToolInactive(input: {
1626
1803
  );
1627
1804
  }
1628
1805
 
1629
- function isExternalPath(resource: string): boolean {
1630
- if (!path.isAbsolute(resource)) return false;
1631
- return (
1632
- !isPathInsideOrEqual(resource, workdir) &&
1633
- (!skillsDir || !isPathInsideOrEqual(resource, skillsDir))
1634
- );
1635
- }
1636
-
1637
1806
  function isPathInsideOrEqual(file: string, root: string): boolean {
1638
1807
  const relative = path.relative(
1639
1808
  canonicalizeForContainment(root),
@@ -1662,6 +1831,35 @@ function canonicalizeForContainment(inputPath: string): string {
1662
1831
  }
1663
1832
  }
1664
1833
 
1834
+ type PermissionContext = {
1835
+ readableSkillRoots: readonly string[];
1836
+ decisions: Map<string, Promise<{ approved: boolean; reason?: string }>>;
1837
+ getToolCall(options: {
1838
+ event: OpenCodeEvent;
1839
+ sessionId: string;
1840
+ }): Promise<PermissionToolCall | undefined>;
1841
+ emitToolCall(options: {
1842
+ toolCallId: string;
1843
+ toolCall: PermissionToolCall | undefined;
1844
+ }): void;
1845
+ };
1846
+
1847
+ function permissionToolCallFromPart(
1848
+ value: unknown,
1849
+ ): PermissionToolCall | undefined {
1850
+ const part = asOpenCodeObject(value);
1851
+ const state = asOpenCodeObject(part?.state);
1852
+ const input = asOpenCodeObject(state?.input);
1853
+ if (
1854
+ part?.type !== 'tool' ||
1855
+ typeof part.tool !== 'string' ||
1856
+ !input ||
1857
+ !['running', 'completed', 'error'].includes(String(state?.status))
1858
+ )
1859
+ return undefined;
1860
+ return { nativeName: part.tool, input };
1861
+ }
1862
+
1665
1863
  function toWireToolName(nativeName: string): string {
1666
1864
  return (
1667
1865
  NATIVE_TO_COMMON[nativeName] ?? OPENCODE_TO_WIRE[nativeName] ?? nativeName
@@ -0,0 +1,71 @@
1
+ import { globSync, realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const GLOB_CHARACTERS = /[*?[\]{}]/;
5
+
6
+ /*
7
+ * With project configuration disabled, OpenCode no longer discovers the
8
+ * working directory's `AGENTS.md`, and resolves relative `instructions`
9
+ * entries against its global config directory. Absolute entries still load,
10
+ * render the same `Instructions from: <path>` block, and are re-read on every
11
+ * model step, with missing files skipped. Returns `undefined` when the host
12
+ * value is not a string array, so OpenCode reports its own validation error.
13
+ * The working directory is resolved the same way OpenCode resolves its
14
+ * instance directory, so the paths match the `Instructions from: <path>`
15
+ * headers OpenCode renders for natively discovered files.
16
+ *
17
+ * OpenCode only treats the last segment of an absolute entry as a glob
18
+ * pattern and uses the rest as a literal directory. Relative entries with
19
+ * glob characters in a directory segment, such as a `**` segment, are
20
+ * therefore expanded here into the matching files.
21
+ */
22
+ export function resolveOpenCodeInstructions({
23
+ workdir,
24
+ hostInstructions,
25
+ }: {
26
+ workdir: string;
27
+ hostInstructions: unknown;
28
+ }): string[] | undefined {
29
+ if (
30
+ hostInstructions !== undefined &&
31
+ !(
32
+ Array.isArray(hostInstructions) &&
33
+ hostInstructions.every(entry => typeof entry === 'string')
34
+ )
35
+ ) {
36
+ return undefined;
37
+ }
38
+ const directory = resolveRealPath(workdir);
39
+ return [
40
+ path.join(directory, 'AGENTS.md'),
41
+ ...((hostInstructions as string[] | undefined) ?? []).flatMap(entry => {
42
+ if (
43
+ entry.startsWith('http://') ||
44
+ entry.startsWith('https://') ||
45
+ entry.startsWith('~/') ||
46
+ path.isAbsolute(entry)
47
+ ) {
48
+ return [entry];
49
+ }
50
+ if (!GLOB_CHARACTERS.test(path.dirname(entry))) {
51
+ return [path.join(directory, entry)];
52
+ }
53
+ return globSync(entry, { cwd: directory, withFileTypes: true })
54
+ .filter(match => match.isFile())
55
+ .map(match => path.join(match.parentPath, match.name))
56
+ .sort();
57
+ }),
58
+ ];
59
+ }
60
+
61
+ function resolveRealPath(file: string): string {
62
+ const resolved = path.resolve(file);
63
+ try {
64
+ return realpathSync(resolved);
65
+ } catch (error) {
66
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
67
+ return resolved;
68
+ }
69
+ throw error;
70
+ }
71
+ }
@@ -0,0 +1,168 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ export type PermissionToolCall = {
5
+ nativeName: string;
6
+ input: Record<string, unknown>;
7
+ };
8
+
9
+ export async function areOpenCodePermissionPathsTrusted(options: {
10
+ action: string;
11
+ resources: string[];
12
+ metadata: Record<string, unknown> | undefined;
13
+ toolCall: PermissionToolCall | undefined;
14
+ workDir: string;
15
+ readableSkillRoots: readonly string[];
16
+ }): Promise<boolean> {
17
+ const args = options.toolCall?.input;
18
+ const nativeName = options.toolCall?.nativeName;
19
+ const access =
20
+ ['edit', 'write'].includes(options.action) ||
21
+ ['write', 'edit', 'apply_patch'].includes(nativeName ?? '')
22
+ ? 'write'
23
+ : 'read';
24
+ let targets: unknown[];
25
+ if (Array.isArray(options.metadata?.files)) {
26
+ if (options.metadata.files.length === 0) return false;
27
+ targets = options.metadata.files.flatMap(value => {
28
+ if (value == null || typeof value !== 'object') return [undefined];
29
+ const file = value as Record<string, unknown>;
30
+ return file.type === 'move' || file.movePath != null
31
+ ? [file.filePath, file.movePath]
32
+ : [file.filePath];
33
+ });
34
+ } else if (
35
+ args &&
36
+ ['read', 'view', 'write', 'edit'].includes(nativeName ?? '')
37
+ ) {
38
+ targets = [args.filePath];
39
+ } else if (
40
+ args &&
41
+ ['glob', 'grep', 'list', 'ls'].includes(nativeName ?? '')
42
+ ) {
43
+ targets = [args.path ?? options.workDir];
44
+ } else if (
45
+ typeof options.metadata?.filepath === 'string' &&
46
+ options.action !== 'edit'
47
+ ) {
48
+ targets = [options.metadata.filepath];
49
+ } else if (
50
+ options.action === 'edit' &&
51
+ typeof options.metadata?.filepath === 'string' &&
52
+ path.posix.isAbsolute(options.metadata.filepath)
53
+ ) {
54
+ targets = [options.metadata.filepath];
55
+ } else if (
56
+ options.action === 'read' &&
57
+ options.resources.length > 0 &&
58
+ options.resources.every(value => path.posix.isAbsolute(value))
59
+ ) {
60
+ targets = options.resources;
61
+ } else {
62
+ return false;
63
+ }
64
+ if (!targets.every((value): value is string => typeof value === 'string'))
65
+ return false;
66
+ return areFileToolPathsTrusted({
67
+ workDir: options.workDir,
68
+ cwd: options.workDir,
69
+ paths: targets,
70
+ access,
71
+ readableSkillRoots: options.readableSkillRoots,
72
+ });
73
+ }
74
+
75
+ export async function areFileToolPathsTrusted(options: {
76
+ workDir: string;
77
+ cwd: string;
78
+ paths: readonly string[];
79
+ access: 'read' | 'write';
80
+ readableSkillRoots: readonly string[];
81
+ }): Promise<boolean> {
82
+ if (options.paths.length === 0) return false;
83
+ try {
84
+ const roots = [await realpath(options.workDir)];
85
+ if (options.access === 'read') {
86
+ for (const root of options.readableSkillRoots) {
87
+ try {
88
+ roots.push(await realpath(root));
89
+ } catch {
90
+ continue;
91
+ }
92
+ }
93
+ }
94
+ for (const filePath of options.paths) {
95
+ if (typeof filePath !== 'string' || filePath.trim().length === 0) {
96
+ return false;
97
+ }
98
+ if (
99
+ !path.posix.isAbsolute(filePath) &&
100
+ !path.posix.isAbsolute(options.cwd)
101
+ ) {
102
+ return false;
103
+ }
104
+ const absolutePath = path.posix.isAbsolute(filePath)
105
+ ? filePath
106
+ : `${options.cwd}/${filePath}`;
107
+ /*
108
+ * Native runtimes differ in whether they normalize parent components
109
+ * before filesystem access. Both interpretations must stay within a
110
+ * trusted root, including when a symlink precedes a parent component.
111
+ */
112
+ for (const candidatePath of [
113
+ absolutePath,
114
+ path.posix.normalize(absolutePath),
115
+ ]) {
116
+ const candidate = await resolvePermissionPath({
117
+ filePath: candidatePath,
118
+ });
119
+ if (
120
+ !roots.some(root => {
121
+ const relative = path.posix.relative(root, candidate);
122
+ return (
123
+ relative === '' ||
124
+ (relative !== '..' &&
125
+ !relative.startsWith('../') &&
126
+ !path.posix.isAbsolute(relative))
127
+ );
128
+ })
129
+ )
130
+ return false;
131
+ }
132
+ }
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ async function resolvePermissionPath(options: {
140
+ filePath: string;
141
+ }): Promise<string> {
142
+ let existingPath = options.filePath;
143
+ const missing: string[] = [];
144
+ for (;;) {
145
+ let exists = true;
146
+ try {
147
+ await lstat(existingPath);
148
+ } catch (error) {
149
+ if (
150
+ error == null ||
151
+ typeof error !== 'object' ||
152
+ !('code' in error) ||
153
+ error.code !== 'ENOENT'
154
+ )
155
+ throw error;
156
+ exists = false;
157
+ }
158
+ if (exists)
159
+ return path.posix.join(await realpath(existingPath), ...missing);
160
+ const parent = path.posix.dirname(existingPath);
161
+ const segment = path.posix.basename(existingPath);
162
+ if (parent === existingPath || segment === '.' || segment === '..') {
163
+ throw new Error('Unable to resolve permission path.');
164
+ }
165
+ missing.unshift(segment);
166
+ existingPath = parent;
167
+ }
168
+ }