@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.
@@ -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
+ }
@@ -172,13 +172,31 @@ export function createOpenCodeRequestTransformations({
172
172
  environmentVariableName: 'OPENCODE_API_KEY',
173
173
  matchUrl: 'https://opencode.ai/zen/go/v1',
174
174
  });
175
- case 'gitlab':
176
- return createBearerTransformation({
177
- environment,
178
- sandboxEnvironment,
179
- environmentVariableName: 'GITLAB_TOKEN',
180
- matchUrl: environment.GITLAB_INSTANCE_URL ?? 'https://gitlab.com',
181
- });
175
+ case 'gitlab': {
176
+ const credential = environment.GITLAB_TOKEN;
177
+ const sandboxCredential = sandboxEnvironment.GITLAB_TOKEN;
178
+ if (credential == null || sandboxCredential == null) return [];
179
+
180
+ const requestUrl = new URL(
181
+ `${environment.GITLAB_INSTANCE_URL ?? 'https://gitlab.com'}/api/v4/ai/third_party_agents/direct_access`,
182
+ );
183
+ return [
184
+ {
185
+ match: {
186
+ host: requestUrl.hostname,
187
+ path: { exact: requestUrl.pathname },
188
+ method: ['POST'],
189
+ headers: [
190
+ {
191
+ key: { exact: 'Authorization' },
192
+ value: { exact: `Bearer ${sandboxCredential}` },
193
+ },
194
+ ],
195
+ },
196
+ transform: { headers: { Authorization: `Bearer ${credential}` } },
197
+ },
198
+ ];
199
+ }
182
200
  }
183
201
  }
184
202
 
@@ -33,6 +33,7 @@ export const startMessageSchema = harnessV1BridgeStartBaseSchema
33
33
  .omit({ builtinToolFiltering: true })
34
34
  .extend({
35
35
  prompt: harnessPromptContentSchema,
36
+ readableSkillRoots: z.array(z.string()).optional(),
36
37
  operation: z.enum(['prompt', 'compact']).optional(),
37
38
  provider: z.string().optional(),
38
39
  variant: z.string().optional(),
@@ -125,6 +125,12 @@ export type OpenCodeHarnessSettings = {
125
125
  */
126
126
  readonly portEndpoint?: HarnessV1PortEndpoint;
127
127
  readonly startupTimeoutMs?: number;
128
+ /**
129
+ * Abort a running turn when its host disconnects and does not reconnect
130
+ * within this many milliseconds, so the turn stops spending. A suspended
131
+ * turn is exempt. Unset keeps the turn running until it finishes.
132
+ */
133
+ readonly hostDisconnectTimeoutMs?: number;
128
134
  /**
129
135
  * Configures reconnection attempts after an established bridge connection
130
136
  * drops. The reconnect window includes connection establishment and
@@ -579,7 +585,7 @@ export function createOpenCode(
579
585
  });
580
586
 
581
587
  const proc = await toolSafeSandboxSession.spawn({
582
- command: `node ${shellQuote(`${bootstrapDir}/bridge.mjs`)} --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)} --bootstrap-dir ${shellQuote(bootstrapDir)} --skills-dir ${shellQuote(skillsDir)}`,
588
+ command: `node ${shellQuote(`${bootstrapDir}/bridge.mjs`)} --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)} --bootstrap-dir ${shellQuote(bootstrapDir)} --skills-dir ${shellQuote(skillsDir)}${settings.hostDisconnectTimeoutMs !== undefined ? ` --host-disconnect-timeout-ms ${shellQuote(String(settings.hostDisconnectTimeoutMs))}` : ''}`,
583
589
  env,
584
590
  abortSignal: startOpts.abortSignal,
585
591
  });
@@ -1026,6 +1032,9 @@ function createSession({
1026
1032
  ? { instructions: promptOpts.instructions }
1027
1033
  : {}),
1028
1034
  skillsChanged: skillWriteResult.changed,
1035
+ readableSkillRoots: promptOpts.skills.map(
1036
+ skill => `${sandboxHomeDir}/.agents/skills/${skill.name}`,
1037
+ ),
1029
1038
  ...startBase(turnModel),
1030
1039
  });
1031
1040
  pendingResumeSessionId = undefined;
@@ -1055,6 +1064,9 @@ function createSession({
1055
1064
  ? { instructions: continueOpts.instructions }
1056
1065
  : {}),
1057
1066
  skillsChanged: skillWriteResult.changed,
1067
+ readableSkillRoots: continueOpts.skills.map(
1068
+ skill => `${sandboxHomeDir}/.agents/skills/${skill.name}`,
1069
+ ),
1058
1070
  ...startBase(turnModel),
1059
1071
  });
1060
1072
  pendingResumeSessionId = undefined;
@@ -255,7 +255,7 @@ export async function readOpenCodeSubscription({
255
255
  fetch?: typeof globalThis.fetch;
256
256
  }): Promise<OpenCodeSubscription | undefined> {
257
257
  if (!isSubscriptionProvider(providerId)) return undefined;
258
- const stored = await readStore({ env, homeDirectory, platform });
258
+ const stored = await readStore({ providerId, env, homeDirectory, platform });
259
259
  if (stored == null) return undefined;
260
260
  const candidate = stored.value[providerId];
261
261
  if (!isRecord(candidate)) return undefined;
@@ -661,10 +661,12 @@ async function extractOpenAIAccountId(
661
661
  }
662
662
 
663
663
  async function readStore({
664
+ providerId,
664
665
  env,
665
666
  homeDirectory,
666
667
  platform,
667
668
  }: {
669
+ providerId: string;
668
670
  env: Readonly<Record<string, string | undefined>>;
669
671
  homeDirectory: string;
670
672
  platform: NodeJS.Platform;
@@ -681,20 +683,30 @@ async function readStore({
681
683
  ? { value: parsed.value }
682
684
  : undefined;
683
685
  }
684
- const authPath =
686
+ // OpenCode keeps auth.json in its XDG data directory on every platform,
687
+ // including Windows. The GitLab auth plugin (before v3) writes to
688
+ // `~/.opencode` on Windows instead, so that store is checked as a fallback.
689
+ const authPaths =
685
690
  env.XDG_DATA_HOME != null
686
- ? join(env.XDG_DATA_HOME, 'opencode', 'auth.json')
687
- : isWindows(platform)
688
- ? join(homeDirectory, '.opencode', 'auth.json')
689
- : join(homeDirectory, '.local', 'share', 'opencode', 'auth.json');
690
- const text = await readFile(authPath, 'utf8').catch(() => undefined);
691
- if (text == null) return undefined;
692
- const parsed = await safeParseJSON({ text });
693
- if (!parsed.success || !isRecord(parsed.value)) return undefined;
694
- return {
695
- value: parsed.value,
696
- write: value => writeStore({ authPath, value }),
697
- };
691
+ ? [join(env.XDG_DATA_HOME, 'opencode', 'auth.json')]
692
+ : [
693
+ join(homeDirectory, '.local', 'share', 'opencode', 'auth.json'),
694
+ ...(isWindows(platform)
695
+ ? [join(homeDirectory, '.opencode', 'auth.json')]
696
+ : []),
697
+ ];
698
+ for (const authPath of authPaths) {
699
+ const text = await readFile(authPath, 'utf8').catch(() => undefined);
700
+ if (text == null) continue;
701
+ const parsed = await safeParseJSON({ text });
702
+ if (!parsed.success || !isRecord(parsed.value)) continue;
703
+ if (!isRecord(parsed.value[providerId])) continue;
704
+ return {
705
+ value: parsed.value,
706
+ write: value => writeStore({ authPath, value }),
707
+ };
708
+ }
709
+ return undefined;
698
710
  }
699
711
 
700
712
  async function writeStore({