@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/harness-opencode",
3
- "version": "1.0.176",
3
+ "version": "1.0.178",
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": {
@@ -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,10 +184,21 @@ 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',
184
198
  bridgeStateDir,
199
+ ...(args.hostDisconnectTimeoutMs !== undefined
200
+ ? { hostDisconnectTimeoutMs: args.hostDisconnectTimeoutMs }
201
+ : {}),
185
202
  onStart: runTurn,
186
203
  onStop: () =>
187
204
  runtime.sessionId ? { openCodeSessionId: runtime.sessionId } : {},
@@ -257,6 +274,27 @@ async function ensureRuntime({
257
274
  closeRuntime();
258
275
 
259
276
  try {
277
+ /*
278
+ * OpenCode always loads configuration, instructions, and skills from the
279
+ * home directory and its global config directory, even with project
280
+ * configuration disabled. A working directory that is or contains either
281
+ * location would let repository content act as trusted global
282
+ * configuration.
283
+ */
284
+ const homeDirectory = homedir();
285
+ for (const protectedPath of [
286
+ homeDirectory,
287
+ path.join(
288
+ procEnv.XDG_CONFIG_HOME || path.join(homeDirectory, '.config'),
289
+ 'opencode',
290
+ ),
291
+ ]) {
292
+ if (isPathInsideOrEqual(protectedPath, workdir)) {
293
+ throw new Error(
294
+ `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.`,
295
+ );
296
+ }
297
+ }
260
298
  if (start.tools && start.tools.length > 0) {
261
299
  runtime.toolNames = new Set(start.tools.map(tool => tool.name));
262
300
  runtime.relay = await startToolRelay({
@@ -332,10 +370,22 @@ function buildOpenCodeConfig({
332
370
  share: 'disabled',
333
371
  autoupdate: false,
334
372
  permission: {
335
- read: 'allow',
336
- glob: 'allow',
337
- grep: 'allow',
338
- list: 'allow',
373
+ read:
374
+ start.permissionMode && start.permissionMode !== 'allow-all'
375
+ ? 'ask'
376
+ : 'allow',
377
+ glob:
378
+ start.permissionMode && start.permissionMode !== 'allow-all'
379
+ ? 'ask'
380
+ : 'allow',
381
+ grep:
382
+ start.permissionMode && start.permissionMode !== 'allow-all'
383
+ ? 'ask'
384
+ : 'allow',
385
+ list:
386
+ start.permissionMode && start.permissionMode !== 'allow-all'
387
+ ? 'ask'
388
+ : 'allow',
339
389
  edit: 'ask',
340
390
  bash: 'ask',
341
391
  external_directory: 'ask',
@@ -345,6 +395,11 @@ function buildOpenCodeConfig({
345
395
  question: 'allow',
346
396
  },
347
397
  };
398
+ const instructions = resolveOpenCodeInstructions({
399
+ workdir,
400
+ hostInstructions: start.openCodeConfig?.instructions,
401
+ });
402
+ if (instructions) config.instructions = instructions;
348
403
  if (start.model) config.model = start.model;
349
404
  if (skillsDir) config.skills = { paths: [skillsDir] };
350
405
  const permission = config.permission as Record<string, unknown>;
@@ -422,6 +477,9 @@ function buildProviderConfig(
422
477
  if (procEnv.AI_GATEWAY_API_KEY && procEnv.AI_GATEWAY_BASE_URL) {
423
478
  return {
424
479
  [providerID]: {
480
+ ...(providerID === 'google' || providerID === 'mistral'
481
+ ? { npm: '@ai-sdk/openai-compatible' }
482
+ : {}),
425
483
  options: {
426
484
  apiKey: procEnv.AI_GATEWAY_API_KEY,
427
485
  baseURL: toOpenCodeGatewayBaseUrl(procEnv.AI_GATEWAY_BASE_URL),
@@ -765,6 +823,7 @@ async function runPrompt({
765
823
  const eventLoop = consumeEvents({
766
824
  client,
767
825
  sessionId,
826
+ readableSkillRoots: start.readableSkillRoots,
768
827
  permissionMode: start.permissionMode,
769
828
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
770
829
  turn,
@@ -996,6 +1055,7 @@ async function runCompaction({
996
1055
  const eventLoop = consumeEvents({
997
1056
  client,
998
1057
  sessionId,
1058
+ readableSkillRoots: start.readableSkillRoots,
999
1059
  permissionMode: start.permissionMode,
1000
1060
  inactiveBuiltinToolNames: start.inactiveBuiltinToolNames,
1001
1061
  turn,
@@ -1061,6 +1121,7 @@ async function consumeEvents({
1061
1121
  client,
1062
1122
  sessionId,
1063
1123
  permissionMode,
1124
+ readableSkillRoots = [],
1064
1125
  inactiveBuiltinToolNames,
1065
1126
  turn,
1066
1127
  state,
@@ -1073,6 +1134,7 @@ async function consumeEvents({
1073
1134
  client: OpenCodeClient;
1074
1135
  sessionId: string;
1075
1136
  permissionMode: StartMessage['permissionMode'];
1137
+ readableSkillRoots?: readonly string[];
1076
1138
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1077
1139
  turn: BridgeTurn;
1078
1140
  state: TranslationState;
@@ -1086,6 +1148,59 @@ async function consumeEvents({
1086
1148
  onSubscribed?.();
1087
1149
  if (!stream) return;
1088
1150
  const taskSessionIds = new Set([sessionId]);
1151
+ const observedCalls = new Map<string, PermissionToolCall>();
1152
+ const permissionContext: PermissionContext = {
1153
+ readableSkillRoots,
1154
+ decisions: new Map(),
1155
+ getToolCall: async ({ event, sessionId: sourceSessionId }) => {
1156
+ const props = event.properties ?? {};
1157
+ const source =
1158
+ asOpenCodeObject(props.tool) ?? asOpenCodeObject(props.source);
1159
+ const callID = stringValue(source?.callID);
1160
+ if (!callID) return undefined;
1161
+ const key = JSON.stringify([sourceSessionId, callID]);
1162
+ const observed = observedCalls.get(key);
1163
+ if (observed) return observed;
1164
+ const messageID = stringValue(source?.messageID);
1165
+ if (messageID && typeof client.session.message === 'function') {
1166
+ try {
1167
+ const response = await client.session.message({
1168
+ sessionID: sourceSessionId,
1169
+ messageID,
1170
+ directory: workdir,
1171
+ });
1172
+ const parts = asOpenCodeObject(response.data)?.parts;
1173
+ if (Array.isArray(parts)) {
1174
+ const part = parts
1175
+ .map(asOpenCodeObject)
1176
+ .find(value => value?.callID === callID);
1177
+ const snapshot = permissionToolCallFromPart(part);
1178
+ if (snapshot) {
1179
+ observedCalls.set(key, snapshot);
1180
+ return snapshot;
1181
+ }
1182
+ }
1183
+ } catch {
1184
+ return observedCalls.get(key);
1185
+ }
1186
+ }
1187
+ return observedCalls.get(key);
1188
+ },
1189
+ emitToolCall: ({ toolCallId, toolCall }) => {
1190
+ if (!toolCall || sentToolCallIds.has(toolCallId)) return;
1191
+ const nativeName = toolCall.nativeName;
1192
+ const toolName = toWireToolName(nativeName);
1193
+ state.toolCallsEmitted.add(toolCallId);
1194
+ emitToHost({
1195
+ type: 'tool-call',
1196
+ toolCallId,
1197
+ toolName,
1198
+ input: JSON.stringify(toolCall.input),
1199
+ providerExecuted: true,
1200
+ ...nativeNameField({ nativeName, toolName }),
1201
+ });
1202
+ },
1203
+ };
1089
1204
  const registerSubagentSession = (sourceSessionId: string) =>
1090
1205
  function register({
1091
1206
  parentSessionId,
@@ -1280,6 +1395,26 @@ async function consumeEvents({
1280
1395
  : undefined;
1281
1396
  if (!scopedSessionId) return false;
1282
1397
  const isDescendant = scopedSessionId !== sessionId;
1398
+ const part = asOpenCodeObject(event.properties?.part);
1399
+ const snapshot = permissionToolCallFromPart(part);
1400
+ if (snapshot && typeof part?.callID === 'string') {
1401
+ observedCalls.set(
1402
+ JSON.stringify([scopedSessionId, part.callID]),
1403
+ snapshot,
1404
+ );
1405
+ }
1406
+ if (event.type === 'session.next.tool.started') {
1407
+ const props = event.properties ?? {};
1408
+ const input = asOpenCodeObject(props.input);
1409
+ const nativeName = stringValue(props.toolName ?? props.tool);
1410
+ const callID = stringValue(props.callID);
1411
+ if (input && nativeName && callID) {
1412
+ observedCalls.set(JSON.stringify([scopedSessionId, callID]), {
1413
+ nativeName,
1414
+ input,
1415
+ });
1416
+ }
1417
+ }
1283
1418
  const waitFor = ({
1284
1419
  toolCallId,
1285
1420
  settlesToolCall,
@@ -1309,6 +1444,7 @@ async function consumeEvents({
1309
1444
  handlePermissionV2({
1310
1445
  client,
1311
1446
  sessionId: scopedSessionId,
1447
+ context: permissionContext,
1312
1448
  permissionMode,
1313
1449
  inactiveBuiltinToolNames,
1314
1450
  turn,
@@ -1322,6 +1458,7 @@ async function consumeEvents({
1322
1458
  handlePermission({
1323
1459
  client,
1324
1460
  sessionId: scopedSessionId,
1461
+ context: permissionContext,
1325
1462
  permissionMode,
1326
1463
  inactiveBuiltinToolNames,
1327
1464
  turn,
@@ -1446,6 +1583,7 @@ function sanitizeMcpToolName(value: string): string {
1446
1583
  async function handlePermissionV2({
1447
1584
  client,
1448
1585
  sessionId,
1586
+ context,
1449
1587
  permissionMode,
1450
1588
  inactiveBuiltinToolNames,
1451
1589
  turn,
@@ -1455,6 +1593,7 @@ async function handlePermissionV2({
1455
1593
  }: {
1456
1594
  client: OpenCodeClient;
1457
1595
  sessionId: string;
1596
+ context: PermissionContext;
1458
1597
  permissionMode: StartMessage['permissionMode'];
1459
1598
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1460
1599
  turn: BridgeTurn;
@@ -1466,6 +1605,10 @@ async function handlePermissionV2({
1466
1605
  const requestID = String(props.id ?? '');
1467
1606
  if (!requestID) return;
1468
1607
  const reply = await selectPermissionReply({
1608
+ context,
1609
+ sessionId,
1610
+ toolCall: await context.getToolCall({ event, sessionId }),
1611
+ metadata: asOpenCodeObject(props.metadata),
1469
1612
  action: String(props.action ?? ''),
1470
1613
  resources: Array.isArray(props.resources)
1471
1614
  ? props.resources.map(String)
@@ -1489,6 +1632,7 @@ async function handlePermissionV2({
1489
1632
  async function handlePermission({
1490
1633
  client,
1491
1634
  sessionId,
1635
+ context,
1492
1636
  permissionMode,
1493
1637
  inactiveBuiltinToolNames,
1494
1638
  turn,
@@ -1498,6 +1642,7 @@ async function handlePermission({
1498
1642
  }: {
1499
1643
  client: OpenCodeClient;
1500
1644
  sessionId: string;
1645
+ context: PermissionContext;
1501
1646
  permissionMode: StartMessage['permissionMode'];
1502
1647
  inactiveBuiltinToolNames: StartMessage['inactiveBuiltinToolNames'];
1503
1648
  turn: BridgeTurn;
@@ -1510,6 +1655,10 @@ async function handlePermission({
1510
1655
  if (!requestID) return;
1511
1656
  const tool = asOpenCodeObject(props.tool);
1512
1657
  const reply = await selectPermissionReply({
1658
+ context,
1659
+ sessionId,
1660
+ toolCall: await context.getToolCall({ event, sessionId }),
1661
+ metadata: asOpenCodeObject(props.metadata),
1513
1662
  action: String(props.permission ?? ''),
1514
1663
  resources: Array.isArray(props.patterns) ? props.patterns.map(String) : [],
1515
1664
  requestID,
@@ -1530,6 +1679,10 @@ async function handlePermission({
1530
1679
  }
1531
1680
 
1532
1681
  async function selectPermissionReply({
1682
+ context,
1683
+ sessionId,
1684
+ toolCall,
1685
+ metadata,
1533
1686
  action,
1534
1687
  resources,
1535
1688
  requestID,
@@ -1540,6 +1693,10 @@ async function selectPermissionReply({
1540
1693
  emit,
1541
1694
  waitFor,
1542
1695
  }: {
1696
+ context: PermissionContext;
1697
+ sessionId: string;
1698
+ toolCall: PermissionToolCall | undefined;
1699
+ metadata: OpenCodeObject | undefined;
1543
1700
  action: string;
1544
1701
  resources: string[];
1545
1702
  requestID: string;
@@ -1550,20 +1707,33 @@ async function selectPermissionReply({
1550
1707
  emit: EmitApprovalRequest;
1551
1708
  waitFor?: WaitForHostInput;
1552
1709
  }): 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());
1710
+ const requestApproval = () => {
1711
+ const key = toolCall
1712
+ ? JSON.stringify([sessionId, toolCallId, toolCall])
1713
+ : undefined;
1714
+ const existing = key ? context.decisions.get(key) : undefined;
1715
+ if (existing) return existing;
1716
+ const decision = (async () => {
1717
+ context.emitToolCall({
1718
+ toolCallId,
1719
+ toolCall,
1720
+ });
1721
+ await emit({
1722
+ type: 'tool-approval-request',
1723
+ approvalId: requestID,
1724
+ toolCallId,
1725
+ });
1726
+ const wait = waitFor?.({ toolCallId, settlesToolCall: false });
1727
+ wait?.markWaiting();
1728
+ return turn
1729
+ .requestToolApproval(requestID)
1730
+ .finally(() => wait?.clearWaiting());
1731
+ })();
1732
+ if (key) context.decisions.set(key, decision);
1733
+ return decision;
1559
1734
  };
1560
1735
  const toolName = toPermissionToolName(action);
1561
1736
  if (isBuiltinToolInactive({ toolName, inactiveBuiltinToolNames })) {
1562
- await emit({
1563
- type: 'tool-approval-request',
1564
- approvalId: requestID,
1565
- toolCallId,
1566
- });
1567
1737
  const decision = await requestApproval();
1568
1738
  return decision.approved
1569
1739
  ? { reply: 'once' }
@@ -1575,21 +1745,34 @@ async function selectPermissionReply({
1575
1745
  if (!permissionMode || permissionMode === 'allow-all') {
1576
1746
  return { reply: 'always' };
1577
1747
  }
1578
- if (resources.some(resource => isExternalPath(resource))) {
1579
- return { reply: 'reject', message: 'External directory access rejected.' };
1580
- }
1581
- const kind = TOOL_KIND[toolName] ?? 'bash';
1748
+ const nativeName = toolCall?.nativeName;
1749
+ const filePermission =
1750
+ action === 'external_directory' ||
1751
+ ['read', 'write', 'edit', 'glob', 'grep', 'ls'].includes(toolName);
1752
+ const kind =
1753
+ action === 'external_directory' && nativeName
1754
+ ? nativeName === 'apply_patch'
1755
+ ? 'edit'
1756
+ : (TOOL_KIND[toWireToolName(nativeName)] ?? 'bash')
1757
+ : (TOOL_KIND[toolName] ?? 'bash');
1582
1758
  const allowed =
1583
1759
  permissionMode === 'allow-edits'
1584
1760
  ? kind === 'readonly' || kind === 'edit'
1585
1761
  : kind === 'readonly';
1586
- if (allowed) return { reply: 'always' };
1762
+ if (
1763
+ allowed &&
1764
+ (!filePermission ||
1765
+ (await areOpenCodePermissionPathsTrusted({
1766
+ action,
1767
+ resources,
1768
+ metadata,
1769
+ toolCall,
1770
+ workDir: workdir,
1771
+ readableSkillRoots: context.readableSkillRoots,
1772
+ })))
1773
+ )
1774
+ return { reply: 'once' };
1587
1775
 
1588
- await emit({
1589
- type: 'tool-approval-request',
1590
- approvalId: requestID,
1591
- toolCallId,
1592
- });
1593
1776
  const decision = await requestApproval();
1594
1777
  return decision.approved
1595
1778
  ? { reply: 'once' }
@@ -1626,14 +1809,6 @@ function isBuiltinToolInactive(input: {
1626
1809
  );
1627
1810
  }
1628
1811
 
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
1812
  function isPathInsideOrEqual(file: string, root: string): boolean {
1638
1813
  const relative = path.relative(
1639
1814
  canonicalizeForContainment(root),
@@ -1662,6 +1837,35 @@ function canonicalizeForContainment(inputPath: string): string {
1662
1837
  }
1663
1838
  }
1664
1839
 
1840
+ type PermissionContext = {
1841
+ readableSkillRoots: readonly string[];
1842
+ decisions: Map<string, Promise<{ approved: boolean; reason?: string }>>;
1843
+ getToolCall(options: {
1844
+ event: OpenCodeEvent;
1845
+ sessionId: string;
1846
+ }): Promise<PermissionToolCall | undefined>;
1847
+ emitToolCall(options: {
1848
+ toolCallId: string;
1849
+ toolCall: PermissionToolCall | undefined;
1850
+ }): void;
1851
+ };
1852
+
1853
+ function permissionToolCallFromPart(
1854
+ value: unknown,
1855
+ ): PermissionToolCall | undefined {
1856
+ const part = asOpenCodeObject(value);
1857
+ const state = asOpenCodeObject(part?.state);
1858
+ const input = asOpenCodeObject(state?.input);
1859
+ if (
1860
+ part?.type !== 'tool' ||
1861
+ typeof part.tool !== 'string' ||
1862
+ !input ||
1863
+ !['running', 'completed', 'error'].includes(String(state?.status))
1864
+ )
1865
+ return undefined;
1866
+ return { nativeName: part.tool, input };
1867
+ }
1868
+
1665
1869
  function toWireToolName(nativeName: string): string {
1666
1870
  return (
1667
1871
  NATIVE_TO_COMMON[nativeName] ?? OPENCODE_TO_WIRE[nativeName] ?? nativeName
@@ -2023,18 +2227,25 @@ function parseArgs(args: string[]): {
2023
2227
  bridgeStateDir?: string;
2024
2228
  bootstrapDir?: string;
2025
2229
  skillsDir?: string;
2230
+ hostDisconnectTimeoutMs?: number;
2026
2231
  } {
2027
2232
  const out: {
2028
2233
  workdir?: string;
2029
2234
  bridgeStateDir?: string;
2030
2235
  bootstrapDir?: string;
2031
2236
  skillsDir?: string;
2237
+ hostDisconnectTimeoutMs?: number;
2032
2238
  } = {};
2033
2239
  for (let i = 0; i < args.length; i++) {
2034
2240
  if (args[i] === '--workdir' && i + 1 < args.length) {
2035
2241
  out.workdir = args[++i];
2036
2242
  } else if (args[i] === '--bridge-state-dir' && i + 1 < args.length) {
2037
2243
  out.bridgeStateDir = args[++i];
2244
+ } else if (
2245
+ args[i] === '--host-disconnect-timeout-ms' &&
2246
+ i + 1 < args.length
2247
+ ) {
2248
+ out.hostDisconnectTimeoutMs = Number(args[++i]);
2038
2249
  } else if (args[i] === '--bootstrap-dir' && i + 1 < args.length) {
2039
2250
  out.bootstrapDir = args[++i];
2040
2251
  } else if (args[i] === '--skills-dir' && i + 1 < args.length) {
@@ -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
+ }