@ai-sdk/harness-claude-code 1.0.185 → 1.0.187

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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @ai-sdk/harness-claude-code
2
2
 
3
+ ## 1.0.187
4
+
5
+ ### Patch Changes
6
+
7
+ - 71bef69: feat(harness): require approval for sensitive workspace file changes in `allow-edits` permission mode
8
+ - Updated dependencies [6d50947]
9
+ - Updated dependencies [71bef69]
10
+ - @ai-sdk/provider-utils@5.0.81
11
+ - @ai-sdk/harness@1.0.183
12
+
13
+ ## 1.0.186
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [2ebc78b]
18
+ - Updated dependencies [1a94af3]
19
+ - Updated dependencies [cb4fa52]
20
+ - @ai-sdk/provider-utils@5.0.80
21
+ - @ai-sdk/harness@1.0.182
22
+ - @ai-sdk/provider@4.0.38
23
+
3
24
  ## 1.0.185
4
25
 
5
26
  ### Patch Changes
@@ -1,14 +1,14 @@
1
- import { appendFile, lstat, mkdir, realpath, writeFile } from "node:fs/promises";
1
+ import { appendFile, lstat, mkdir, readdir, realpath, writeFile } from "node:fs/promises";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { createPublicKey, randomBytes, randomUUID, verify } from "node:crypto";
4
4
  import { argv, env, pid, stdout } from "node:process";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { Buffer as Buffer$1 } from "node:buffer";
7
+ import path from "node:path";
7
8
  import * as claudeAgentSdk from "@anthropic-ai/claude-agent-sdk";
8
9
  import * as mcpServerModule from "@modelcontextprotocol/sdk/server/mcp.js";
9
10
  import { isDeepStrictEqual } from "node:util";
10
11
  import { z } from "zod/v4";
11
- import path from "node:path";
12
12
  //#region ../harness/dist/bridge/index.js
13
13
  const BRIDGE_AUTH_TIMEOUT_MS = 1e4;
14
14
  const BRIDGE_AUTH_MESSAGE_PREFIX = "ai-sdk-harness-bridge-auth-v1\0";
@@ -88,6 +88,132 @@ var HarnessBridgeCapabilityUnsupportedError = class extends Error {
88
88
  return error != null && typeof error === "object" && "name" in error && error.name === name && "message" in error && typeof error.message === "string";
89
89
  }
90
90
  };
91
+ function assertWriteProtectedPathEntries(entries) {
92
+ for (const entry of entries) if (typeof entry !== "string" || entry.length === 0 || path.posix.isAbsolute(entry) || entry.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) throw new TypeError(`Write-protected path entries must be relative paths without empty, "." or ".." segments; received ${JSON.stringify(entry)}.`);
93
+ }
94
+ function isInsideWriteProtectionPath({ parent, candidate }) {
95
+ const relative = path.posix.relative(parent, candidate);
96
+ return relative === "" || relative !== ".." && !relative.startsWith("../") && !path.posix.isAbsolute(relative);
97
+ }
98
+ function matchesWriteProtectedPath({ targets, protectedPaths, anyProtectedPathExists }) {
99
+ return targets.some((target) => protectedPaths.some((protectedPath) => isInsideWriteProtectionPath({
100
+ parent: protectedPath,
101
+ candidate: target.path
102
+ }) || isInsideWriteProtectionPath({
103
+ parent: target.path,
104
+ candidate: protectedPath
105
+ })) || anyProtectedPathExists && target.isMultiLinkFile);
106
+ }
107
+ /**
108
+ * Returns whether writing to any of `paths` touches a write-protected path and
109
+ * therefore requires the host's approval. Runs inside the sandbox, next to the
110
+ * files it checks.
111
+ *
112
+ * `writeProtectedPaths` entries are relative to `workDir` and must not contain
113
+ * empty, `.`, or `..` segments. Relative `paths` resolve against `cwd`, which
114
+ * defaults to `workDir`.
115
+ *
116
+ * A path matches when its canonical location is a protected path, lies inside
117
+ * one, or is a parent of one. Each protected entry is protected both at its
118
+ * literal location below the canonical working directory and at its canonical
119
+ * location. The literal location covers parents of a protected path that is
120
+ * itself a symlink, whose canonical location lies elsewhere.
121
+ *
122
+ * Protected paths are resolved on every call because the filesystem can change
123
+ * during a session. Symlinks inside protected directories protect their
124
+ * targets as well, so files reachable through a protected path cannot be
125
+ * written through an unprotected alias. While any protected path exists,
126
+ * writes to files with more than one link match too. Any resolution failure,
127
+ * including dangling or looping symlinks, reports the write as protected.
128
+ */
129
+ async function isWriteProtectedPath({ workDir, cwd = workDir, paths, writeProtectedPaths }) {
130
+ assertWriteProtectedPathEntries(writeProtectedPaths);
131
+ if (paths.length === 0) return true;
132
+ try {
133
+ const canonicalWorkDir = await realpath(workDir);
134
+ const protection = await collectWriteProtectedPaths({
135
+ canonicalWorkDir,
136
+ protectedRoots: await Promise.all(writeProtectedPaths.map((entry) => resolveExistingPrefix(`${workDir}/${entry}`)))
137
+ });
138
+ if (protection == null) return true;
139
+ const targets = [];
140
+ for (const filePath of paths) {
141
+ if (typeof filePath !== "string" || filePath.trim().length === 0) return true;
142
+ if (!path.posix.isAbsolute(filePath) && !path.posix.isAbsolute(cwd)) return true;
143
+ const absolutePath = path.posix.isAbsolute(filePath) ? filePath : `${cwd}/${filePath}`;
144
+ for (const candidatePath of /* @__PURE__ */ new Set([absolutePath, path.posix.normalize(absolutePath)])) {
145
+ const target = await resolveExistingPrefix(candidatePath);
146
+ const stats = protection.anyRootExists ? await lstatIfExists(target) : void 0;
147
+ targets.push({
148
+ path: target,
149
+ isMultiLinkFile: stats?.isFile() === true && stats.nlink > 1
150
+ });
151
+ }
152
+ }
153
+ return matchesWriteProtectedPath({
154
+ targets,
155
+ protectedPaths: [...writeProtectedPaths.map((entry) => path.posix.join(canonicalWorkDir, entry)), ...protection.paths],
156
+ anyProtectedPathExists: protection.anyRootExists
157
+ });
158
+ } catch {
159
+ return true;
160
+ }
161
+ }
162
+ async function collectWriteProtectedPaths({ canonicalWorkDir, protectedRoots }) {
163
+ const paths = [...protectedRoots];
164
+ const queue = [];
165
+ let anyRootExists = false;
166
+ for (const root of protectedRoots) {
167
+ const stats = await lstatIfExists(root);
168
+ if (stats == null) continue;
169
+ anyRootExists = true;
170
+ if (stats.isDirectory()) queue.push(root);
171
+ }
172
+ const scanned = /* @__PURE__ */ new Set();
173
+ let entryCount = 0;
174
+ while (queue.length > 0) {
175
+ const directory = queue.shift();
176
+ if (scanned.has(directory)) continue;
177
+ scanned.add(directory);
178
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
179
+ entryCount += 1;
180
+ if (entryCount > 2e3) return void 0;
181
+ const entryPath = path.posix.join(directory, entry.name);
182
+ if (entry.isSymbolicLink()) {
183
+ const target = await realpath(entryPath);
184
+ paths.push(target);
185
+ if (isInsideWriteProtectionPath({
186
+ parent: canonicalWorkDir,
187
+ candidate: target
188
+ }) && (await lstat(target)).isDirectory()) queue.push(target);
189
+ } else if (entry.isDirectory()) queue.push(entryPath);
190
+ }
191
+ }
192
+ return {
193
+ paths,
194
+ anyRootExists
195
+ };
196
+ }
197
+ async function resolveExistingPrefix(inputPath) {
198
+ let existingPath = inputPath;
199
+ const missingSegments = [];
200
+ while (await lstatIfExists(existingPath) == null) {
201
+ const parent = path.posix.dirname(existingPath);
202
+ const segment = path.posix.basename(existingPath);
203
+ if (parent === existingPath || segment === ".." || segment === ".") throw new Error(`Unable to resolve path ${JSON.stringify(inputPath)}.`);
204
+ missingSegments.unshift(segment);
205
+ existingPath = parent;
206
+ }
207
+ return path.posix.join(await realpath(existingPath), ...missingSegments);
208
+ }
209
+ async function lstatIfExists(entryPath) {
210
+ try {
211
+ return await lstat(entryPath);
212
+ } catch (error) {
213
+ if (error != null && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
214
+ throw error;
215
+ }
216
+ }
91
217
  function getNormalizedInlineImage(part) {
92
218
  if (part.type === "file" && part.mediaType.startsWith("image/") && part.mediaType !== "image/*" && part.data.type === "data" && typeof part.data.data === "string") return {
93
219
  data: part.data.data,
@@ -1584,6 +1710,11 @@ const NATIVE_TO_COMMON = {
1584
1710
  WebSearch: "webSearch",
1585
1711
  AskUserQuestion: "askUserQuestions"
1586
1712
  };
1713
+ const CLAUDE_CODE_WRITE_PROTECTED_PATHS = [
1714
+ ".agents/skills",
1715
+ ".claude",
1716
+ ".mcp.json"
1717
+ ];
1587
1718
  const NATIVE_TOOL_KINDS = {
1588
1719
  Read: "readonly",
1589
1720
  Glob: "readonly",
@@ -1859,13 +1990,40 @@ async function needsHostApproval(input) {
1859
1990
  }
1860
1991
  if (input.blockedPath != null) paths.push(input.blockedPath);
1861
1992
  if (!paths.every((value) => typeof value === "string")) return true;
1862
- return !await areFileToolPathsTrusted({
1993
+ if (!await areFileToolPathsTrusted({
1863
1994
  workDir: workdir,
1864
1995
  cwd: input.cwd,
1865
1996
  paths,
1866
1997
  access,
1867
1998
  readableSkillRoots: input.readableSkillRoots,
1868
1999
  additionalDirectories: input.additionalDirectories
2000
+ })) return true;
2001
+ return access === "write" && await isWriteProtectedPath({
2002
+ workDir: workdir,
2003
+ cwd: input.cwd,
2004
+ paths,
2005
+ writeProtectedPaths: CLAUDE_CODE_WRITE_PROTECTED_PATHS
2006
+ });
2007
+ }
2008
+ async function isProtectedClaudeFileWrite(input) {
2009
+ const args = input.toolInput != null && typeof input.toolInput === "object" ? input.toolInput : {};
2010
+ let target;
2011
+ switch (input.toolName) {
2012
+ case "Write":
2013
+ case "Edit":
2014
+ target = args.file_path;
2015
+ break;
2016
+ case "NotebookEdit":
2017
+ target = args.notebook_path;
2018
+ break;
2019
+ default: return false;
2020
+ }
2021
+ if (typeof target !== "string") return true;
2022
+ return isWriteProtectedPath({
2023
+ workDir: workdir,
2024
+ cwd: input.cwd,
2025
+ paths: [target],
2026
+ writeProtectedPaths: CLAUDE_CODE_WRITE_PROTECTED_PATHS
1869
2027
  });
1870
2028
  }
1871
2029
  function createApprovalPreToolUseHook(input) {
@@ -1886,7 +2044,11 @@ function createApprovalPreToolUseHook(input) {
1886
2044
  }
1887
2045
  } };
1888
2046
  }
1889
- if (!await needsHostApproval({
2047
+ if (!(input.autoMode ? await isProtectedClaudeFileWrite({
2048
+ toolName,
2049
+ toolInput: hookInput.tool_input,
2050
+ cwd: hookInput.cwd
2051
+ }) : await needsHostApproval({
1890
2052
  toolName,
1891
2053
  toolInput: hookInput.tool_input,
1892
2054
  cwd: hookInput.cwd,
@@ -1894,7 +2056,7 @@ function createApprovalPreToolUseHook(input) {
1894
2056
  additionalDirectories: input.additionalDirectories,
1895
2057
  permissionMode: input.permissionMode,
1896
2058
  inactiveNativeTools: input.inactiveNativeTools
1897
- })) return {};
2059
+ }))) return {};
1898
2060
  input.deferredToolUseIds.add(toolUseID);
1899
2061
  return { hookSpecificOutput: {
1900
2062
  hookEventName: "PreToolUse",
@@ -2056,6 +2218,7 @@ async function runTurn(start, turn) {
2056
2218
  readableSkillRoots: start.readableSkillRoots ?? [],
2057
2219
  additionalDirectories: start.additionalDirectories ?? [],
2058
2220
  permissionMode,
2221
+ autoMode: start.autoMode === true,
2059
2222
  inactiveNativeTools: new Set(inactiveNativeTools),
2060
2223
  decisions: approvalDecisions,
2061
2224
  deferredToolUseIds,
@@ -2103,7 +2266,7 @@ async function runTurn(start, turn) {
2103
2266
  } } : {},
2104
2267
  includePartialMessages: true,
2105
2268
  hooks: {
2106
- PreToolUse: [...permissionMode === "allow-all" || start.autoMode === true ? [] : [{ hooks: [approvalPreToolUseHook] }], {
2269
+ PreToolUse: [...permissionMode === "allow-all" ? [] : [{ hooks: [approvalPreToolUseHook] }], {
2107
2270
  matcher: "AskUserQuestion",
2108
2271
  hooks: [questionPreToolUseHook],
2109
2272
  ...start.questionTimeoutMs !== void 0 ? { timeout: Math.ceil(start.questionTimeoutMs / 1e3) } : {}