@puku-ai/sdk 4.0.2 → 4.0.4

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.
Files changed (214) hide show
  1. package/README.md +24 -7
  2. package/dist/index.cjs +85 -0
  3. package/dist/vendor/_vendor/partial-json-parser/parser.cjs +225 -0
  4. package/dist/vendor/api-promise.cjs +18 -0
  5. package/dist/vendor/client.cjs +1013 -0
  6. package/dist/vendor/core/api-promise.cjs +80 -0
  7. package/dist/vendor/core/api.cjs +2 -0
  8. package/dist/vendor/core/credentials.cjs +313 -0
  9. package/dist/vendor/core/error.cjs +156 -0
  10. package/dist/vendor/core/middleware.cjs +173 -0
  11. package/dist/vendor/core/pagination.cjs +215 -0
  12. package/dist/vendor/core/resource.cjs +11 -0
  13. package/dist/vendor/core/streaming.cjs +346 -0
  14. package/dist/vendor/core/uploads.cjs +5 -0
  15. package/dist/vendor/error.cjs +18 -0
  16. package/dist/vendor/helpers/beta/environments.cjs +30 -0
  17. package/dist/vendor/helpers/beta/json-schema.cjs +56 -0
  18. package/dist/vendor/helpers/beta/mcp.cjs +418 -0
  19. package/dist/vendor/helpers/beta/memory.cjs +17 -0
  20. package/dist/vendor/helpers/beta/standard-schema.cjs +57 -0
  21. package/dist/vendor/helpers/beta/zod.cjs +88 -0
  22. package/dist/vendor/helpers/index.cjs +7 -0
  23. package/dist/vendor/helpers/json-schema.cjs +36 -0
  24. package/dist/vendor/helpers/zod.cjs +77 -0
  25. package/dist/vendor/index.cjs +54 -0
  26. package/dist/vendor/internal/builtin-types.cjs +3 -0
  27. package/dist/vendor/internal/constants.cjs +12 -0
  28. package/dist/vendor/internal/decoders/jsonl.cjs +40 -0
  29. package/dist/vendor/internal/decoders/line.cjs +109 -0
  30. package/dist/vendor/internal/detect-platform.cjs +159 -0
  31. package/dist/vendor/internal/errors.cjs +42 -0
  32. package/dist/vendor/internal/file-store.cjs +535 -0
  33. package/dist/vendor/internal/headers.cjs +119 -0
  34. package/dist/vendor/internal/message-stream-utils.cjs +33 -0
  35. package/dist/vendor/internal/node.browser.cjs +21 -0
  36. package/dist/vendor/internal/node.cjs +55 -0
  37. package/dist/vendor/internal/parse.cjs +65 -0
  38. package/dist/vendor/internal/qs/formats.cjs +12 -0
  39. package/dist/vendor/internal/qs/index.cjs +13 -0
  40. package/dist/vendor/internal/qs/stringify.cjs +276 -0
  41. package/dist/vendor/internal/qs/types.cjs +2 -0
  42. package/dist/vendor/internal/qs/utils.cjs +229 -0
  43. package/dist/vendor/internal/request-options.cjs +31 -0
  44. package/dist/vendor/internal/request-signal.cjs +49 -0
  45. package/dist/vendor/internal/shim-types.cjs +3 -0
  46. package/dist/vendor/internal/shims.cjs +91 -0
  47. package/dist/vendor/internal/stainless-helper-header.cjs +90 -0
  48. package/dist/vendor/internal/stream-utils.cjs +37 -0
  49. package/dist/vendor/internal/to-file.cjs +95 -0
  50. package/dist/vendor/internal/types.cjs +3 -0
  51. package/dist/vendor/internal/uploads.cjs +148 -0
  52. package/dist/vendor/internal/utils/abort.cjs +24 -0
  53. package/dist/vendor/internal/utils/async-queue.cjs +69 -0
  54. package/dist/vendor/internal/utils/backoff.cjs +43 -0
  55. package/dist/vendor/internal/utils/base64.cjs +37 -0
  56. package/dist/vendor/internal/utils/bytes.cjs +30 -0
  57. package/dist/vendor/internal/utils/env.cjs +21 -0
  58. package/dist/vendor/internal/utils/log.cjs +111 -0
  59. package/dist/vendor/internal/utils/path.cjs +78 -0
  60. package/dist/vendor/internal/utils/promise.cjs +17 -0
  61. package/dist/vendor/internal/utils/query.cjs +41 -0
  62. package/dist/vendor/internal/utils/sleep.cjs +27 -0
  63. package/dist/vendor/internal/utils/time.cjs +7 -0
  64. package/dist/vendor/internal/utils/uuid.cjs +18 -0
  65. package/dist/vendor/internal/utils/values.cjs +125 -0
  66. package/dist/vendor/internal/utils.cjs +24 -0
  67. package/dist/vendor/lib/BetaMessageStream.cjs +665 -0
  68. package/dist/vendor/lib/MessageStream.cjs +612 -0
  69. package/dist/vendor/lib/beta-parser.cjs +78 -0
  70. package/dist/vendor/lib/credentials/credential-chain.cjs +244 -0
  71. package/dist/vendor/lib/credentials/identity-token.cjs +71 -0
  72. package/dist/vendor/lib/credentials/oidc-federation.cjs +81 -0
  73. package/dist/vendor/lib/credentials/token-cache.cjs +113 -0
  74. package/dist/vendor/lib/credentials/types.cjs +267 -0
  75. package/dist/vendor/lib/credentials/user-oauth.cjs +129 -0
  76. package/dist/vendor/lib/credentials.cjs +7 -0
  77. package/dist/vendor/lib/environments/index.cjs +17 -0
  78. package/dist/vendor/lib/environments/poller.cjs +226 -0
  79. package/dist/vendor/lib/environments/worker.cjs +609 -0
  80. package/dist/vendor/lib/helper-client.cjs +57 -0
  81. package/dist/vendor/lib/middleware.cjs +779 -0
  82. package/dist/vendor/lib/parser.cjs +65 -0
  83. package/dist/vendor/lib/sessions/accumulate.cjs +44 -0
  84. package/dist/vendor/lib/standard-schema.cjs +44 -0
  85. package/dist/vendor/lib/tools/BetaRunnableTool.cjs +30 -0
  86. package/dist/vendor/lib/tools/BetaToolRunner.cjs +500 -0
  87. package/dist/vendor/lib/tools/BetaToolRunner.d.ts +1 -1
  88. package/dist/vendor/lib/tools/CompactionControl.cjs +27 -0
  89. package/dist/vendor/lib/tools/SessionToolRunner.cjs +740 -0
  90. package/dist/vendor/lib/tools/ToolError.cjs +46 -0
  91. package/dist/vendor/lib/transform-json-schema.cjs +113 -0
  92. package/dist/vendor/pagination.cjs +18 -0
  93. package/dist/vendor/resource.cjs +18 -0
  94. package/dist/vendor/resources/beta/agents/agents.cjs +159 -0
  95. package/dist/vendor/resources/beta/agents/agents.d.ts +3 -3
  96. package/dist/vendor/resources/beta/agents/agents.js +1 -1
  97. package/dist/vendor/resources/beta/agents/index.cjs +8 -0
  98. package/dist/vendor/resources/beta/agents/versions.cjs +35 -0
  99. package/dist/vendor/resources/beta/agents.cjs +18 -0
  100. package/dist/vendor/resources/beta/beta.cjs +105 -0
  101. package/dist/vendor/resources/beta/deployment-runs.cjs +54 -0
  102. package/dist/vendor/resources/beta/deployments.cjs +195 -0
  103. package/dist/vendor/resources/beta/dreams.cjs +115 -0
  104. package/dist/vendor/resources/beta/dreams.d.ts +2 -2
  105. package/dist/vendor/resources/beta/environments/environments.cjs +178 -0
  106. package/dist/vendor/resources/beta/environments/index.cjs +8 -0
  107. package/dist/vendor/resources/beta/environments/work.cjs +256 -0
  108. package/dist/vendor/resources/beta/environments.cjs +18 -0
  109. package/dist/vendor/resources/beta/files.cjs +123 -0
  110. package/dist/vendor/resources/beta/index.cjs +38 -0
  111. package/dist/vendor/resources/beta/memory-stores/index.cjs +10 -0
  112. package/dist/vendor/resources/beta/memory-stores/memories.cjs +129 -0
  113. package/dist/vendor/resources/beta/memory-stores/memory-stores.cjs +173 -0
  114. package/dist/vendor/resources/beta/memory-stores/memory-versions.cjs +80 -0
  115. package/dist/vendor/resources/beta/memory-stores.cjs +18 -0
  116. package/dist/vendor/resources/beta/messages/batches.cjs +206 -0
  117. package/dist/vendor/resources/beta/messages/batches.d.ts +3 -3
  118. package/dist/vendor/resources/beta/messages/index.cjs +11 -0
  119. package/dist/vendor/resources/beta/messages/messages.cjs +189 -0
  120. package/dist/vendor/resources/beta/messages/messages.d.ts +5 -5
  121. package/dist/vendor/resources/beta/messages/messages.js +4 -11
  122. package/dist/vendor/resources/beta/messages/messages.js.map +1 -1
  123. package/dist/vendor/resources/beta/messages.cjs +18 -0
  124. package/dist/vendor/resources/beta/models.cjs +59 -0
  125. package/dist/vendor/resources/beta/organization/api-keys.cjs +55 -0
  126. package/dist/vendor/resources/beta/organization/compliance-settings.cjs +51 -0
  127. package/dist/vendor/resources/beta/organization/external-keys.cjs +118 -0
  128. package/dist/vendor/resources/beta/organization/federation/federation.cjs +49 -0
  129. package/dist/vendor/resources/beta/organization/federation/index.cjs +10 -0
  130. package/dist/vendor/resources/beta/organization/federation/issuers.cjs +168 -0
  131. package/dist/vendor/resources/beta/organization/federation/rules/index.cjs +8 -0
  132. package/dist/vendor/resources/beta/organization/federation/rules/rules.cjs +226 -0
  133. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.cjs +113 -0
  134. package/dist/vendor/resources/beta/organization/federation/rules.cjs +18 -0
  135. package/dist/vendor/resources/beta/organization/federation.cjs +18 -0
  136. package/dist/vendor/resources/beta/organization/index.cjs +24 -0
  137. package/dist/vendor/resources/beta/organization/invites.cjs +75 -0
  138. package/dist/vendor/resources/beta/organization/organization.cjs +90 -0
  139. package/dist/vendor/resources/beta/organization/rate-limits.cjs +30 -0
  140. package/dist/vendor/resources/beta/organization/service-accounts/index.cjs +8 -0
  141. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.cjs +202 -0
  142. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.cjs +124 -0
  143. package/dist/vendor/resources/beta/organization/service-accounts.cjs +18 -0
  144. package/dist/vendor/resources/beta/organization/users.cjs +66 -0
  145. package/dist/vendor/resources/beta/organization/workspaces/index.cjs +12 -0
  146. package/dist/vendor/resources/beta/organization/workspaces/members.cjs +101 -0
  147. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.cjs +33 -0
  148. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.cjs +188 -0
  149. package/dist/vendor/resources/beta/organization/workspaces/workspaces.cjs +140 -0
  150. package/dist/vendor/resources/beta/organization/workspaces.cjs +18 -0
  151. package/dist/vendor/resources/beta/organization.cjs +18 -0
  152. package/dist/vendor/resources/beta/sessions/events.cjs +119 -0
  153. package/dist/vendor/resources/beta/sessions/index.cjs +12 -0
  154. package/dist/vendor/resources/beta/sessions/resources.cjs +131 -0
  155. package/dist/vendor/resources/beta/sessions/sessions.cjs +186 -0
  156. package/dist/vendor/resources/beta/sessions/sessions.d.ts +1 -1
  157. package/dist/vendor/resources/beta/sessions/threads/events.cjs +60 -0
  158. package/dist/vendor/resources/beta/sessions/threads/index.cjs +8 -0
  159. package/dist/vendor/resources/beta/sessions/threads/threads.cjs +116 -0
  160. package/dist/vendor/resources/beta/sessions/threads.cjs +18 -0
  161. package/dist/vendor/resources/beta/sessions.cjs +18 -0
  162. package/dist/vendor/resources/beta/skills/index.cjs +8 -0
  163. package/dist/vendor/resources/beta/skills/skills.cjs +132 -0
  164. package/dist/vendor/resources/beta/skills/versions.cjs +128 -0
  165. package/dist/vendor/resources/beta/skills.cjs +18 -0
  166. package/dist/vendor/resources/beta/tunnels/certificates.cjs +128 -0
  167. package/dist/vendor/resources/beta/tunnels/index.cjs +8 -0
  168. package/dist/vendor/resources/beta/tunnels/tunnels.cjs +209 -0
  169. package/dist/vendor/resources/beta/tunnels.cjs +18 -0
  170. package/dist/vendor/resources/beta/user-profiles.cjs +117 -0
  171. package/dist/vendor/resources/beta/vaults/credentials.cjs +176 -0
  172. package/dist/vendor/resources/beta/vaults/index.cjs +8 -0
  173. package/dist/vendor/resources/beta/vaults/vaults.cjs +177 -0
  174. package/dist/vendor/resources/beta/vaults.cjs +18 -0
  175. package/dist/vendor/resources/beta/webhooks.cjs +32 -0
  176. package/dist/vendor/resources/beta.cjs +18 -0
  177. package/dist/vendor/resources/completions.cjs +22 -0
  178. package/dist/vendor/resources/completions.d.ts +3 -3
  179. package/dist/vendor/resources/files.cjs +51 -0
  180. package/dist/vendor/resources/index.cjs +31 -0
  181. package/dist/vendor/resources/messages/batches.cjs +160 -0
  182. package/dist/vendor/resources/messages/batches.d.ts +1 -1
  183. package/dist/vendor/resources/messages/batches.js +1 -1
  184. package/dist/vendor/resources/messages/index.cjs +8 -0
  185. package/dist/vendor/resources/messages/messages.cjs +159 -0
  186. package/dist/vendor/resources/messages/messages.d.ts +7 -7
  187. package/dist/vendor/resources/messages/messages.js +6 -13
  188. package/dist/vendor/resources/messages/messages.js.map +1 -1
  189. package/dist/vendor/resources/messages.cjs +18 -0
  190. package/dist/vendor/resources/models.cjs +44 -0
  191. package/dist/vendor/resources/shared.cjs +3 -0
  192. package/dist/vendor/resources/skills/index.cjs +8 -0
  193. package/dist/vendor/resources/skills/skills.cjs +72 -0
  194. package/dist/vendor/resources/skills/versions.cjs +40 -0
  195. package/dist/vendor/resources/skills.cjs +18 -0
  196. package/dist/vendor/resources/top-level.cjs +3 -0
  197. package/dist/vendor/resources.cjs +17 -0
  198. package/dist/vendor/streaming.cjs +18 -0
  199. package/dist/vendor/tools/agent-toolset/fs-util.cjs +193 -0
  200. package/dist/vendor/tools/agent-toolset/memories.cjs +916 -0
  201. package/dist/vendor/tools/agent-toolset/node.browser.cjs +147 -0
  202. package/dist/vendor/tools/agent-toolset/node.cjs +939 -0
  203. package/dist/vendor/tools/agent-toolset/skills.cjs +325 -0
  204. package/dist/vendor/tools/agent-toolset/sync-interval.cjs +28 -0
  205. package/dist/vendor/tools/memory/node.browser.cjs +48 -0
  206. package/dist/vendor/tools/memory/node.cjs +364 -0
  207. package/dist/vendor/uploads.cjs +18 -0
  208. package/dist/vendor/version.cjs +4 -0
  209. package/package.json +12 -13
  210. package/sdk.cjs +0 -14293
  211. package/sdk.cjs.map +0 -149
  212. package/sdk.d.ts +0 -10866
  213. package/sdk.mjs +0 -68
  214. package/sdk.mjs.map +0 -149
@@ -0,0 +1,939 @@
1
+ "use strict";
2
+ /**
3
+ * Node implementation of the `agent_toolset_20260401` tools — `bash`, `read`,
4
+ * `write`, `edit`, `glob`, `grep` — plus the workdir/skills
5
+ * {@link AgentToolContext}.
6
+ *
7
+ * This mirrors `@puku-ai/sdk/tools/memory/node`: it is the explicit,
8
+ * Node-only entry point for these implementations. Importing it pulls in
9
+ * `node:child_process`, `node:fs`, etc., so it is kept separate from the rest of
10
+ * the SDK — depending on it is an opt-in.
11
+ *
12
+ * **Node 22+ is required** for this module: the `glob` tool uses the native
13
+ * `fs.glob`, added in Node 22. The rest of the SDK still supports Node 18+; only
14
+ * the agent toolset has this requirement.
15
+ *
16
+ * The result of {@link betaAgentToolset20260401} is a plain `BetaRunnableTool[]`;
17
+ * hand it to any tool runner — `client.beta.messages.toolRunner({ …, tools })`
18
+ * for the Messages API, or `client.beta.sessions.events.toolRunner({ …, tools })`
19
+ * for a managed-agents session:
20
+ *
21
+ * ```ts
22
+ * import { betaAgentToolset20260401 } from '@puku-ai/sdk/tools/agent-toolset/node';
23
+ *
24
+ * const tools = betaAgentToolset20260401({ workdir: '/work' });
25
+ * const tools2 = betaAgentToolset20260401({ workdir: '/work' }).filter((t) => t.name !== 'bash');
26
+ * ```
27
+ *
28
+ * Trust model: the file tools confine to `workdir` plus any `allowedRoots`
29
+ * (symlink-aware) and are safe without a sandbox; `bash` is unrestricted and
30
+ * should run inside one. See {@link AgentToolContext}.
31
+ */
32
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k;
34
+ var desc = Object.getOwnPropertyDescriptor(m, k);
35
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
36
+ desc = { enumerable: true, get: function() { return m[k]; } };
37
+ }
38
+ Object.defineProperty(o, k2, desc);
39
+ }) : (function(o, m, k, k2) {
40
+ if (k2 === undefined) k2 = k;
41
+ o[k2] = m[k];
42
+ }));
43
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
44
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
45
+ }) : function(o, v) {
46
+ o["default"] = v;
47
+ });
48
+ var __importStar = (this && this.__importStar) || (function () {
49
+ var ownKeys = function(o) {
50
+ ownKeys = Object.getOwnPropertyNames || function (o) {
51
+ var ar = [];
52
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
53
+ return ar;
54
+ };
55
+ return ownKeys(o);
56
+ };
57
+ return function (mod) {
58
+ if (mod && mod.__esModule) return mod;
59
+ var result = {};
60
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
61
+ __setModuleDefault(result, mod);
62
+ return result;
63
+ };
64
+ })();
65
+ Object.defineProperty(exports, "__esModule", { value: true });
66
+ exports.BashSession = exports.BashTimeoutError = exports.MARKER_PATH = exports.MEMORY_FLUSH_TIMEOUT_MS = exports.MIN_MEMORY_SYNC_INTERVAL_MS = exports.DEFAULT_MEMORY_SYNC_INTERVAL_MS = exports.SessionMemoryError = exports.SessionMemoryStores = exports.extractSkillArchive = exports.setupSkills = void 0;
67
+ exports.betaAgentToolset20260401 = betaAgentToolset20260401;
68
+ exports.resolvePath = resolvePath;
69
+ exports.betaBashTool = betaBashTool;
70
+ exports.betaReadTool = betaReadTool;
71
+ exports.betaWriteTool = betaWriteTool;
72
+ exports.betaEditTool = betaEditTool;
73
+ exports.betaGlobTool = betaGlobTool;
74
+ exports.betaGrepTool = betaGrepTool;
75
+ const fs = __importStar(require("node:fs/promises"));
76
+ const fssync = __importStar(require("node:fs"));
77
+ const path = __importStar(require("node:path"));
78
+ const cp = __importStar(require("node:child_process"));
79
+ const crypto = __importStar(require("node:crypto"));
80
+ const readline = __importStar(require("node:readline"));
81
+ const error_1 = require("../../core/error");
82
+ const ToolError_1 = require("../../lib/tools/ToolError");
83
+ const json_schema_1 = require("../../helpers/beta/json-schema");
84
+ const promise_1 = require("../../internal/utils/promise");
85
+ const fs_util_1 = require("./fs-util");
86
+ var skills_1 = require("./skills");
87
+ Object.defineProperty(exports, "setupSkills", { enumerable: true, get: function () { return skills_1.setupSkills; } });
88
+ Object.defineProperty(exports, "extractSkillArchive", { enumerable: true, get: function () { return skills_1.extractSkillArchive; } });
89
+ var memories_1 = require("./memories");
90
+ Object.defineProperty(exports, "SessionMemoryStores", { enumerable: true, get: function () { return memories_1.SessionMemoryStores; } });
91
+ Object.defineProperty(exports, "SessionMemoryError", { enumerable: true, get: function () { return memories_1.SessionMemoryError; } });
92
+ Object.defineProperty(exports, "DEFAULT_MEMORY_SYNC_INTERVAL_MS", { enumerable: true, get: function () { return memories_1.DEFAULT_MEMORY_SYNC_INTERVAL_MS; } });
93
+ Object.defineProperty(exports, "MIN_MEMORY_SYNC_INTERVAL_MS", { enumerable: true, get: function () { return memories_1.MIN_MEMORY_SYNC_INTERVAL_MS; } });
94
+ Object.defineProperty(exports, "MEMORY_FLUSH_TIMEOUT_MS", { enumerable: true, get: function () { return memories_1.MEMORY_FLUSH_TIMEOUT_MS; } });
95
+ Object.defineProperty(exports, "MARKER_PATH", { enumerable: true, get: function () { return memories_1.MARKER_PATH; } });
96
+ const BASH_OUTPUT_LIMIT = 100 * 1024;
97
+ const BASH_DEFAULT_TIMEOUT_MS = 120_000;
98
+ // Default size cap for the read/edit tools (both load the whole file into
99
+ // memory) when AgentToolContext.maxFileBytes is unset. The reject-vs-truncate
100
+ // behaviour remains a separate question pending CMA validation.
101
+ const DEFAULT_MAX_FILE_BYTES = 256 * 1024;
102
+ const READ_STREAM_CHUNK_BYTES = 64 * 1024;
103
+ const NEWLINE = Buffer.from('\n');
104
+ const GREP_OUTPUT_LIMIT = 100 * 1024;
105
+ const GREP_MAX_LINE_LENGTH = 2000;
106
+ const GLOB_RESULT_LIMIT = 200;
107
+ /**
108
+ * A bash command exceeded its `timeoutMs`. Carries the timeout so a caller can
109
+ * tell it apart from an abort without matching on the message text.
110
+ */
111
+ class BashTimeoutError extends error_1.PukuError {
112
+ timeoutMs;
113
+ constructor(timeoutMs) {
114
+ super(`bash command timed out after ${timeoutMs}ms`);
115
+ this.name = 'BashTimeoutError';
116
+ this.timeoutMs = timeoutMs;
117
+ }
118
+ }
119
+ exports.BashTimeoutError = BashTimeoutError;
120
+ const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
121
+ const fsGlob = fs.glob;
122
+ function resolveMaxBytes(configured) {
123
+ return configured === undefined ? DEFAULT_MAX_FILE_BYTES : configured;
124
+ }
125
+ /**
126
+ * Throw when the deprecated {@link AgentToolContext.unrestrictedPaths} was
127
+ * passed at all. Nothing else reads that property.
128
+ */
129
+ function rejectUnrestrictedPaths(value) {
130
+ if (value === undefined)
131
+ return;
132
+ throw new error_1.PukuError('The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer ' +
133
+ "supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to " +
134
+ 'the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` ' +
135
+ 'from your context; to let the file tools reach any other directory, add it to `allowedRoots`.');
136
+ }
137
+ /**
138
+ * Returns the `agent_toolset_20260401` implementations bound to `ctx`. The
139
+ * result is a plain array of `BetaRunnableTool`; filter or extend it before
140
+ * handing it to a tool runner:
141
+ *
142
+ * ```ts
143
+ * const tools = [...betaAgentToolset20260401(ctx), myCustomTool];
144
+ * const tools = betaAgentToolset20260401(ctx).filter((t) => t.name !== 'grep');
145
+ * ```
146
+ *
147
+ * Concurrency note: `client.beta.sessions.events.toolRunner` dispatches a
148
+ * session's tool calls serially (the sessions API delivers one `agent.tool_use`
149
+ * at a time). `client.beta.messages.toolRunner` runs a turn's `tool.run` calls
150
+ * via `Promise.all`. The toolset below is safe under either model —
151
+ * {@link betaBashTool} serializes its persistent shell internally and the FS
152
+ * tools are independent per call — but {@link betaEditTool}/{@link betaWriteTool}
153
+ * cannot synchronize concurrent writes to the *same* file across processes, so a
154
+ * multi-edit turn touching one path is still subject to inherent FS lost-update
155
+ * races. Custom tools that close over mutable state should do their own queueing.
156
+ */
157
+ function betaAgentToolset20260401(ctx) {
158
+ return [
159
+ betaBashTool(ctx),
160
+ betaReadTool(ctx),
161
+ betaWriteTool(ctx),
162
+ betaEditTool(ctx),
163
+ betaGlobTool(ctx),
164
+ betaGrepTool(ctx),
165
+ ];
166
+ }
167
+ /**
168
+ * Resolve `p` against `ctx.workdir`; reject results outside `ctx.workdir` and
169
+ * `ctx.allowedRoots`. Absolute and relative inputs go through the same
170
+ * canonicalise-then-contain check — an absolute path that lands inside a
171
+ * permitted root is accepted, only paths that resolve *outside* all of them
172
+ * are rejected. Every symlink in `p` (including the leaf, even a dangling one)
173
+ * is resolved before the check, and the resolved path is what the tool then
174
+ * operates on, so a symlink inside the workdir that points outside it can
175
+ * neither pass the check nor be followed afterwards. See the trust model on
176
+ * {@link AgentToolContext}.
177
+ *
178
+ * Residual TOCTOU: a component could still be swapped for a symlink between this
179
+ * call and the eventual `fs` operation. Closing that fully needs per-component
180
+ * `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; the same
181
+ * residual exposure exists in `tools/memory/node` and is why a sandbox is still
182
+ * recommended for the toolset as a whole.
183
+ */
184
+ async function resolvePath(ctx, p) {
185
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
186
+ return (0, fs_util_1.confineToRoot)(ctx.workdir, p, { allowedRoots: ctx.allowedRoots ?? [] });
187
+ }
188
+ /**
189
+ * The read-only root `target` falls under, or `undefined`. `target` arrives
190
+ * fully canonicalized (from {@link resolvePath}), so each root is
191
+ * canonicalized too — a root recorded through a symlinked workdir must still
192
+ * match the resolved write target.
193
+ */
194
+ function readOnlyRootFor(ctx, target) {
195
+ return (0, fs_util_1.containingRoot)(ctx.readOnlyRoots ?? [], target);
196
+ }
197
+ // ---- bash ----------------------------------------------------------------
198
+ /**
199
+ * Build the environment for the spawned bash shell. The runner process holds
200
+ * PukuAI credentials in `PUKU_*` env vars — the API key, the auth token,
201
+ * and the per-work session token among them. `bash` runs an unrestricted shell,
202
+ * so any command the agent runs could read those straight out of `process.env`;
203
+ * strip the whole `PUKU_*` namespace from the child's environment.
204
+ * Everything else (PATH, HOME, locale, …) is passed through unchanged.
205
+ *
206
+ * Passing an explicit `env` to {@link AgentToolContext} does NOT add to this
207
+ * default — it FULLY REPLACES it. The provided mapping becomes the entire bash
208
+ * environment verbatim; nothing here is merged in, so callers who want the
209
+ * scrubbed process environment plus extras must build that mapping themselves.
210
+ */
211
+ function scrubbedShellEnv() {
212
+ const env = {};
213
+ for (const [key, value] of Object.entries(process.env)) {
214
+ if (key.startsWith('PUKU_'))
215
+ continue;
216
+ env[key] = value;
217
+ }
218
+ return env;
219
+ }
220
+ /**
221
+ * A persistent /bin/bash process. State (cwd, env, background jobs) survives
222
+ * across exec() calls. Uses pipes rather than a PTY so input is never echoed.
223
+ */
224
+ class BashSession {
225
+ #proc;
226
+ #buf = '';
227
+ #truncated = false;
228
+ #closed = false;
229
+ // While a command is in flight, the resolver to fire once its sentinel lands
230
+ // in `#buf` (or once the shell dies). Event-driven: no polling loop.
231
+ #waiting = null;
232
+ constructor(dir, env = scrubbedShellEnv()) {
233
+ this.#proc = cp.spawn('/bin/bash', ['--noprofile', '--norc'], {
234
+ cwd: dir,
235
+ // `env` is the full base environment (the scrubbed process env by
236
+ // default, or the verbatim replacement from `AgentToolContext.env`).
237
+ // PS1/PS2/TERM are shell-control settings BashSession always applies so
238
+ // the pipe-based sentinel exec parsing works — not part of the
239
+ // user-facing environment.
240
+ env: { ...env, PS1: '', PS2: '', TERM: 'dumb' },
241
+ stdio: ['pipe', 'pipe', 'pipe'],
242
+ detached: true,
243
+ });
244
+ this.#proc.stdout.setEncoding('utf8');
245
+ this.#proc.stderr.setEncoding('utf8');
246
+ this.#proc.stdout.on('data', (d) => this.#append(d));
247
+ this.#proc.stderr.on('data', (d) => this.#append(d));
248
+ this.#proc.once('close', () => {
249
+ this.#closed = true;
250
+ // Wake any in-flight exec so it fails fast instead of waiting for its deadline.
251
+ const w = this.#waiting;
252
+ this.#waiting = null;
253
+ w?.resolve();
254
+ });
255
+ }
256
+ /** Whether the underlying shell process has exited. */
257
+ get closed() {
258
+ return this.#closed;
259
+ }
260
+ // Cap the buffer during accumulation so a command that streams unboundedly
261
+ // can't OOM the runner. Keeps the tail so the sentinel stays detectable.
262
+ // Also resolves the in-flight exec the instant its sentinel is buffered.
263
+ #append(d) {
264
+ this.#buf += d;
265
+ if (this.#buf.length > BASH_OUTPUT_LIMIT) {
266
+ this.#buf = this.#buf.slice(this.#buf.length - BASH_OUTPUT_LIMIT);
267
+ this.#truncated = true;
268
+ }
269
+ if (this.#waiting && this.#buf.indexOf(this.#waiting.sentinel) >= 0) {
270
+ const w = this.#waiting;
271
+ this.#waiting = null;
272
+ w.resolve();
273
+ }
274
+ }
275
+ async exec(command, opts = {}) {
276
+ if (this.#closed) {
277
+ throw new error_1.PukuError('bash session terminated');
278
+ }
279
+ const timeoutMs = opts.timeoutMs ?? BASH_DEFAULT_TIMEOUT_MS;
280
+ const signal = opts.signal;
281
+ // Reject with the signal's own reason, so a caller telling a user cancel
282
+ // apart from an `AbortSignal.timeout()` sees the platform's name intact.
283
+ signal?.throwIfAborted();
284
+ this.#buf = '';
285
+ this.#truncated = false;
286
+ // Per-call nonce so a command that prints a fixed marker can't spoof the
287
+ // exit-code framing. The `''` split keeps the literal out of what we write
288
+ // to stdin — only the shell's printf reassembles it.
289
+ const sentinel = `__ANT_CMD_${crypto.randomUUID()}_DONE__`;
290
+ const sentinelSplit = `${sentinel.slice(0, 8)}''${sentinel.slice(8)}`;
291
+ // </dev/null: a stdin-reading command (`cat`, `read`) gets EOF instead of
292
+ // blocking on the shared pipe until the timeout.
293
+ const wrapped = `{ ${command}\n} </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?\n`;
294
+ this.#proc.stdin.write(wrapped);
295
+ if (this.#buf.indexOf(sentinel) < 0) {
296
+ // Park until the sentinel lands, the deadline passes, the caller aborts,
297
+ // or the shell dies — whichever comes first. `#append` (and the `close`
298
+ // handler) resolve `sentinelSeen`; the deadline / abort reject.
299
+ const { promise: sentinelSeen, resolve } = (0, promise_1.promiseWithResolvers)();
300
+ this.#waiting = { sentinel, resolve };
301
+ let timer;
302
+ let onAbort;
303
+ try {
304
+ await Promise.race([
305
+ sentinelSeen,
306
+ new Promise((_, reject) => {
307
+ timer = setTimeout(() => reject(new BashTimeoutError(timeoutMs)), timeoutMs);
308
+ }),
309
+ new Promise((_, reject) => {
310
+ if (!signal)
311
+ return;
312
+ onAbort = () => reject(signal.reason);
313
+ signal.addEventListener('abort', onAbort, { once: true });
314
+ }),
315
+ ]);
316
+ }
317
+ finally {
318
+ if (timer)
319
+ clearTimeout(timer);
320
+ if (onAbort && signal)
321
+ signal.removeEventListener('abort', onAbort);
322
+ this.#waiting = null;
323
+ }
324
+ }
325
+ const idx = this.#buf.indexOf(sentinel);
326
+ if (idx < 0) {
327
+ // The shell closed (or was killed) before emitting the sentinel.
328
+ throw new error_1.PukuError('bash session terminated');
329
+ }
330
+ const tail = this.#buf.slice(idx + sentinel.length);
331
+ const m = tail.match(/^(-?\d+)/);
332
+ const exitCode = m ? parseInt(m[1], 10) : -1;
333
+ let out = this.#buf.slice(0, idx).replace(ANSI_RE, '').replace(/\n+$/, '');
334
+ if (this.#truncated) {
335
+ out = `[output truncated]\n${out}`;
336
+ }
337
+ return { output: out, exitCode };
338
+ }
339
+ close() {
340
+ if (this.#closed)
341
+ return;
342
+ this.#closed = true;
343
+ const w = this.#waiting;
344
+ this.#waiting = null;
345
+ w?.resolve();
346
+ this.#proc.stdout.destroy();
347
+ this.#proc.stderr.destroy();
348
+ this.#proc.stdin.destroy();
349
+ try {
350
+ // Negative PID targets the process group so foreground jobs (e.g. a
351
+ // hung sleep) die with the shell.
352
+ process.kill(-this.#proc.pid, 'SIGKILL');
353
+ }
354
+ catch {
355
+ this.#proc.kill('SIGKILL');
356
+ }
357
+ this.#proc.unref();
358
+ }
359
+ }
360
+ exports.BashSession = BashSession;
361
+ function betaBashTool(ctx) {
362
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
363
+ let session;
364
+ // Concurrent run() callers chain onto this promise so writes to the shared
365
+ // shell's stdin can't interleave (which would corrupt the sentinel-match
366
+ // exit-code parsing in BashSession.exec). Each call replaces `tail` with a
367
+ // promise that resolves only after its own exec settles.
368
+ let tail = Promise.resolve();
369
+ return (0, json_schema_1.betaTool)({
370
+ name: 'bash',
371
+ description: 'Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.',
372
+ inputSchema: {
373
+ type: 'object',
374
+ properties: {
375
+ command: { type: 'string', description: 'The command to run' },
376
+ restart: { type: 'boolean', description: 'Restart the persistent shell before running' },
377
+ timeout_ms: { type: 'integer', description: 'Per-call timeout in milliseconds' },
378
+ },
379
+ },
380
+ run: async ({ command, restart, timeout_ms }, context) => {
381
+ const prev = tail;
382
+ const gate = (0, promise_1.promiseWithResolvers)();
383
+ tail = gate.promise;
384
+ // Swallow prior rejections — earlier callers got their own error path;
385
+ // we just need to wait for the shell to be free.
386
+ try {
387
+ await prev;
388
+ }
389
+ catch {
390
+ // ignore
391
+ }
392
+ try {
393
+ if (restart) {
394
+ session?.close();
395
+ session = undefined;
396
+ }
397
+ if (!command) {
398
+ if (restart)
399
+ return 'bash session restarted';
400
+ throw new ToolError_1.ToolError('bash: command is required');
401
+ }
402
+ session ??= new BashSession(ctx.workdir, ctx.env);
403
+ try {
404
+ const { output, exitCode } = await session.exec(command, {
405
+ timeoutMs: timeout_ms ?? BASH_DEFAULT_TIMEOUT_MS,
406
+ signal: context?.signal,
407
+ });
408
+ if (exitCode !== 0)
409
+ throw new ToolError_1.ToolError(output || `exit ${exitCode}`);
410
+ return output;
411
+ }
412
+ catch (e) {
413
+ if (e instanceof ToolError_1.ToolError)
414
+ throw e;
415
+ // Timeout, abort, or terminated: the still-running command will emit
416
+ // a stale sentinel, so discard this session and let the next call
417
+ // start fresh.
418
+ session.close();
419
+ session = undefined;
420
+ throw new ToolError_1.ToolError(`bash: ${e instanceof Error ? e.message : String(e)}`);
421
+ }
422
+ }
423
+ finally {
424
+ gate.resolve();
425
+ }
426
+ },
427
+ close: () => {
428
+ session?.close();
429
+ session = undefined;
430
+ },
431
+ });
432
+ }
433
+ // ---- fs ------------------------------------------------------------------
434
+ function betaReadTool(ctx) {
435
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
436
+ return (0, json_schema_1.betaTool)({
437
+ name: 'read',
438
+ description: 'Read a UTF-8 text file relative to the workdir.',
439
+ inputSchema: {
440
+ type: 'object',
441
+ properties: {
442
+ file_path: { type: 'string' },
443
+ view_range: {
444
+ type: 'array',
445
+ items: { type: 'integer' },
446
+ description: '[start_line, end_line] 1-indexed inclusive',
447
+ },
448
+ },
449
+ required: ['file_path'],
450
+ },
451
+ run: async ({ file_path, view_range }) => {
452
+ if (!file_path)
453
+ throw new ToolError_1.ToolError('read: file_path is required');
454
+ const abs = await resolvePath(ctx, file_path);
455
+ if (view_range?.length && view_range.length !== 2) {
456
+ throw new ToolError_1.ToolError('read: view_range must be [start_line, end_line]');
457
+ }
458
+ let data;
459
+ try {
460
+ // stat() before any open(): the size cap stops a multi-GB file from
461
+ // OOM'ing the runner, and isFile() rejects FIFOs/devices/dirs without
462
+ // opening them (open() on an unconnected FIFO blocks indefinitely).
463
+ const st = await fs.stat(abs);
464
+ if (!st.isFile()) {
465
+ throw new ToolError_1.ToolError(`read: ${file_path} is not a regular file`);
466
+ }
467
+ const limit = resolveMaxBytes(ctx.maxFileBytes);
468
+ if (limit !== null && st.size > limit) {
469
+ if (!view_range?.length) {
470
+ throw new ToolError_1.ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. ` +
471
+ 'Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].');
472
+ }
473
+ const [startLine, endLine] = view_range;
474
+ return await readRangeStreaming(abs, file_path, startLine, endLine, limit);
475
+ }
476
+ data = await fs.readFile(abs, 'utf8');
477
+ }
478
+ catch (e) {
479
+ if (e instanceof ToolError_1.ToolError)
480
+ throw e;
481
+ throw new ToolError_1.ToolError(`read: ${(0, fs_util_1.fsErrorMessage)(e, file_path)}`);
482
+ }
483
+ if (!view_range?.length)
484
+ return data;
485
+ const [startLine, endLine] = view_range;
486
+ const lines = data.split('\n');
487
+ const start = Math.max(0, startLine - 1);
488
+ const end = endLine > 0 ? endLine : lines.length;
489
+ return lines.slice(start, end).join('\n');
490
+ },
491
+ });
492
+ }
493
+ /** Returns lines `[startLine, endLine]` of the file at `abs`, capping the selected bytes at `limit`. */
494
+ async function readRangeStreaming(abs, filePath, startLine, endLine, limit) {
495
+ const lines = new LineRangeCollector(filePath, startLine, endLine, limit);
496
+ if (lines.rangeIsEmpty())
497
+ return '';
498
+ // Byte chunks rather than readline: a single huge line must never be buffered
499
+ // whole, so memory stays bounded by `limit` plus one chunk.
500
+ const stream = fssync.createReadStream(abs, { highWaterMark: READ_STREAM_CHUNK_BYTES });
501
+ try {
502
+ for await (const chunk of stream) {
503
+ lines.collectFrom(chunk);
504
+ if (lines.rangeIsCollected())
505
+ break;
506
+ }
507
+ }
508
+ finally {
509
+ stream.destroy();
510
+ }
511
+ return lines.text();
512
+ }
513
+ /** Collects the bytes of lines `[startLine, endLine]` from consecutive file chunks, capped at `limit`. */
514
+ class LineRangeCollector {
515
+ #filePath;
516
+ #startLine;
517
+ #endLine;
518
+ #start;
519
+ #end;
520
+ #limit;
521
+ #line = 0;
522
+ #collected = [];
523
+ #collectedBytes = 0;
524
+ constructor(filePath, startLine, endLine, limit) {
525
+ this.#filePath = filePath;
526
+ this.#startLine = startLine;
527
+ this.#endLine = endLine;
528
+ this.#start = Math.max(0, startLine - 1);
529
+ this.#end = endLine > 0 ? endLine : Infinity;
530
+ this.#limit = limit;
531
+ }
532
+ rangeIsEmpty() {
533
+ return this.#end <= this.#start;
534
+ }
535
+ rangeIsCollected() {
536
+ return this.#line >= this.#end;
537
+ }
538
+ collectFrom(chunk) {
539
+ let lineStart = 0;
540
+ while (lineStart < chunk.length && !this.rangeIsCollected()) {
541
+ const newline = chunk.indexOf(0x0a, lineStart);
542
+ const lineEnd = newline < 0 ? chunk.length : newline;
543
+ if (this.#line >= this.#start) {
544
+ this.#collect(chunk.subarray(lineStart, lineEnd), newline >= 0);
545
+ }
546
+ if (newline < 0)
547
+ break;
548
+ this.#line++;
549
+ lineStart = newline + 1;
550
+ }
551
+ }
552
+ #collect(lineBytes, newlineTerminated) {
553
+ this.#collected.push(lineBytes);
554
+ this.#collectedBytes += lineBytes.length;
555
+ if (newlineTerminated && this.#line + 1 < this.#end) {
556
+ this.#collected.push(NEWLINE);
557
+ this.#collectedBytes += NEWLINE.length;
558
+ }
559
+ if (this.#collectedBytes > this.#limit)
560
+ throw this.#overLimitError();
561
+ }
562
+ #overLimitError() {
563
+ if (this.#end - this.#start === 1) {
564
+ return new ToolError_1.ToolError(`read: line ${this.#start + 1} of ${this.#filePath} alone exceeds ${this.#limit}-byte limit. ` +
565
+ 'The read tool cannot return part of a line, so view_range cannot narrow this further.');
566
+ }
567
+ return new ToolError_1.ToolError(`read: view_range [${this.#startLine}, ${this.#endLine}] of ${this.#filePath} exceeds ${this.#limit}-byte limit. ` +
568
+ 'Narrow the view_range to read a smaller portion.');
569
+ }
570
+ text() {
571
+ return Buffer.concat(this.#collected, this.#collectedBytes).toString('utf8');
572
+ }
573
+ }
574
+ function betaWriteTool(ctx) {
575
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
576
+ return (0, json_schema_1.betaTool)({
577
+ name: 'write',
578
+ description: 'Write a UTF-8 text file relative to the workdir, creating parent directories as needed.',
579
+ inputSchema: {
580
+ type: 'object',
581
+ properties: { file_path: { type: 'string' }, content: { type: 'string' } },
582
+ required: ['file_path', 'content'],
583
+ },
584
+ run: async ({ file_path, content }) => {
585
+ if (!file_path)
586
+ throw new ToolError_1.ToolError('write: file_path is required');
587
+ const abs = await resolvePath(ctx, file_path);
588
+ const ro = await readOnlyRootFor(ctx, abs);
589
+ if (ro !== undefined) {
590
+ throw new ToolError_1.ToolError(`write: ${file_path} is inside read-only directory ${ro}`);
591
+ }
592
+ try {
593
+ await fs.mkdir(path.dirname(abs), { recursive: true, mode: fs_util_1.DIR_CREATE_MODE });
594
+ await (0, fs_util_1.atomicWriteFile)(abs, content ?? '');
595
+ }
596
+ catch (e) {
597
+ throw new ToolError_1.ToolError(`write: ${(0, fs_util_1.fsErrorMessage)(e, file_path)}`);
598
+ }
599
+ return `wrote ${Buffer.byteLength(content ?? '')} bytes to ${file_path}`;
600
+ },
601
+ });
602
+ }
603
+ function betaEditTool(ctx) {
604
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
605
+ return (0, json_schema_1.betaTool)({
606
+ name: 'edit',
607
+ description: 'Replace old_string with new_string in a file. old_string must be unique unless replace_all.',
608
+ inputSchema: {
609
+ type: 'object',
610
+ properties: {
611
+ file_path: { type: 'string' },
612
+ old_string: { type: 'string' },
613
+ new_string: { type: 'string' },
614
+ replace_all: { type: 'boolean' },
615
+ },
616
+ required: ['file_path', 'old_string', 'new_string'],
617
+ },
618
+ run: async ({ file_path, old_string, new_string, replace_all }) => {
619
+ if (!file_path)
620
+ throw new ToolError_1.ToolError('edit: file_path is required');
621
+ if (!old_string)
622
+ throw new ToolError_1.ToolError('edit: old_string is required');
623
+ const abs = await resolvePath(ctx, file_path);
624
+ const ro = await readOnlyRootFor(ctx, abs);
625
+ if (ro !== undefined) {
626
+ throw new ToolError_1.ToolError(`edit: ${file_path} is inside read-only directory ${ro}`);
627
+ }
628
+ let data;
629
+ try {
630
+ // stat() before any open() — same guard as `read`: the size cap stops a
631
+ // multi-GB file from OOM'ing the runner, and isFile() rejects
632
+ // FIFOs/devices/dirs without opening them (open() on an unconnected FIFO
633
+ // blocks indefinitely). The edit path is model-controlled, so it needs
634
+ // the same bound `read` already has.
635
+ const st = await fs.stat(abs);
636
+ if (!st.isFile()) {
637
+ throw new ToolError_1.ToolError(`edit: ${file_path} is not a regular file`);
638
+ }
639
+ const limit = resolveMaxBytes(ctx.maxFileBytes);
640
+ if (limit !== null && st.size > limit) {
641
+ throw new ToolError_1.ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. ` +
642
+ 'The edit tool loads the whole file and cannot modify a file this large.');
643
+ }
644
+ data = await fs.readFile(abs, 'utf8');
645
+ }
646
+ catch (e) {
647
+ if (e instanceof ToolError_1.ToolError)
648
+ throw e;
649
+ throw new ToolError_1.ToolError(`edit: ${(0, fs_util_1.fsErrorMessage)(e, file_path)}`);
650
+ }
651
+ const count = data.split(old_string).length - 1;
652
+ if (count === 0)
653
+ throw new ToolError_1.ToolError(`edit: old_string not found in ${file_path}`);
654
+ let updated;
655
+ if (replace_all) {
656
+ updated = data.split(old_string).join(new_string);
657
+ }
658
+ else {
659
+ if (count > 1)
660
+ throw new ToolError_1.ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);
661
+ // Callback form so `$&`/`$1`/`` $` `` in new_string are inserted
662
+ // literally instead of expanded as replacement patterns.
663
+ updated = data.replace(old_string, () => new_string);
664
+ }
665
+ try {
666
+ await (0, fs_util_1.atomicWriteFile)(abs, updated);
667
+ }
668
+ catch (e) {
669
+ throw new ToolError_1.ToolError(`edit: write: ${(0, fs_util_1.fsErrorMessage)(e, file_path)}`);
670
+ }
671
+ return `edited ${file_path} (${replace_all ? count : 1} replacement(s))`;
672
+ },
673
+ });
674
+ }
675
+ // ---- search --------------------------------------------------------------
676
+ /**
677
+ * Best-effort: stops `fs.glob` from walking out of the root via a literal or
678
+ * brace-expanded `..`. The realpath post-filter in {@link betaGlobTool} is the
679
+ * boundary; this only avoids the walk.
680
+ */
681
+ function patternCanAscend(pattern) {
682
+ return pattern.split(/[\\/{},]/).includes('..');
683
+ }
684
+ function betaGlobTool(ctx) {
685
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
686
+ return (0, json_schema_1.betaTool)({
687
+ name: 'glob',
688
+ description: 'Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.',
689
+ inputSchema: {
690
+ type: 'object',
691
+ properties: {
692
+ pattern: { type: 'string' },
693
+ path: { type: 'string', description: 'Directory to search in. Defaults to the workdir.' },
694
+ },
695
+ required: ['pattern'],
696
+ },
697
+ run: async ({ pattern, path: searchPath }) => {
698
+ if (!pattern)
699
+ throw new ToolError_1.ToolError('glob: pattern is required');
700
+ if (path.isAbsolute(pattern)) {
701
+ throw new ToolError_1.ToolError('glob: absolute pattern not permitted; pass a relative pattern (and optionally path)');
702
+ }
703
+ if (patternCanAscend(pattern)) {
704
+ throw new ToolError_1.ToolError('glob: ".." is not permitted in the pattern');
705
+ }
706
+ const root = searchPath ? await resolvePath(ctx, searchPath) : path.resolve(ctx.workdir);
707
+ // Compare canonical against canonical: a workdir that is itself a
708
+ // symlink would otherwise falsely reject every realpath'd match below.
709
+ const realRoot = searchPath ? root : await (0, fs_util_1.canonicalize)(root);
710
+ const matches = [];
711
+ // Bounds the walk for patterns that match, or brace-expand into,
712
+ // enormous trees.
713
+ let remaining = WALK_MAX_ENTRIES;
714
+ try {
715
+ // Native `fs.glob` (Node 22+). `exclude` prunes the noisy dirs the
716
+ // legacy walker skipped; only regular files are collected.
717
+ for await (const entry of fsGlob(pattern, {
718
+ cwd: root,
719
+ withFileTypes: true,
720
+ exclude: (d) => d.name === '.git' || d.name === 'node_modules',
721
+ })) {
722
+ if (remaining-- <= 0)
723
+ break;
724
+ if (!entry.isFile())
725
+ continue;
726
+ const full = path.join(entry.parentPath, entry.name);
727
+ // Drop any match that resolves outside the search root. A pattern
728
+ // that *names* a symlinked directory (the model controls the
729
+ // pattern, and the bash tool in the same session can plant the
730
+ // link) makes `fs.glob` descend through it and report entries with
731
+ // the raw parent path, so a lexical check on `full` alone would
732
+ // pass `root/link_out/secret` even though it lives outside the
733
+ // jail. Resolve-failure (ELOOP, EACCES, a racing unlink) is a deny.
734
+ let real;
735
+ try {
736
+ real = await fs.realpath(full);
737
+ }
738
+ catch {
739
+ continue;
740
+ }
741
+ if (!(0, fs_util_1.isWithin)(realRoot, real))
742
+ continue;
743
+ let mtime = 0;
744
+ try {
745
+ mtime = (await fs.stat(full)).mtimeMs;
746
+ }
747
+ catch {
748
+ // unreadable — keep it in the list with mtime 0
749
+ }
750
+ matches.push({ path: full, mtime });
751
+ }
752
+ }
753
+ catch (e) {
754
+ throw new ToolError_1.ToolError(`glob: ${e instanceof Error ? e.message : String(e)}`);
755
+ }
756
+ if (matches.length === 0)
757
+ return 'no matches';
758
+ matches.sort((a, b) => b.mtime - a.mtime);
759
+ return matches
760
+ .slice(0, GLOB_RESULT_LIMIT)
761
+ .map((m) => m.path)
762
+ .join('\n');
763
+ },
764
+ });
765
+ }
766
+ function betaGrepTool(ctx) {
767
+ rejectUnrestrictedPaths(ctx.unrestrictedPaths);
768
+ return (0, json_schema_1.betaTool)({
769
+ name: 'grep',
770
+ description: 'Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.',
771
+ inputSchema: {
772
+ type: 'object',
773
+ properties: { pattern: { type: 'string' }, path: { type: 'string' } },
774
+ required: ['pattern'],
775
+ },
776
+ run: async ({ pattern, path: p }, context) => {
777
+ if (!pattern)
778
+ throw new ToolError_1.ToolError('grep: pattern is required');
779
+ let searchPath = path.resolve(ctx.workdir);
780
+ if (p)
781
+ searchPath = await resolvePath(ctx, p);
782
+ const rg = await findRg();
783
+ return rg ?
784
+ runRipgrep(rg, pattern, searchPath, context?.signal)
785
+ : runWalkGrep(pattern, searchPath, context?.signal);
786
+ },
787
+ });
788
+ }
789
+ function runRipgrep(rg, pattern, searchPath, signal) {
790
+ return new Promise((resolve, reject) => {
791
+ const proc = cp.spawn(rg, ['-n', '--no-heading', '-e', pattern, '--', searchPath], {
792
+ ...(signal ? { signal } : {}),
793
+ });
794
+ let out = '';
795
+ let errOut = '';
796
+ let truncated = false;
797
+ proc.stdout.on('data', (d) => {
798
+ if (truncated)
799
+ return;
800
+ out += d;
801
+ if (out.length > GREP_OUTPUT_LIMIT) {
802
+ truncated = true;
803
+ out = out.slice(0, GREP_OUTPUT_LIMIT);
804
+ proc.kill('SIGKILL');
805
+ }
806
+ });
807
+ proc.stderr.on('data', (d) => (errOut += d));
808
+ proc.on('close', (code) => {
809
+ if (signal?.aborted)
810
+ return reject(new ToolError_1.ToolError('grep: aborted'));
811
+ if (truncated)
812
+ return resolve(out + `\n[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
813
+ if (code === 0)
814
+ return resolve(out);
815
+ if (code === 1)
816
+ return resolve('no matches');
817
+ reject(new ToolError_1.ToolError(`grep: rg failed: ${errOut || `exit ${code}`}`));
818
+ });
819
+ proc.on('error', (e) => {
820
+ if (signal?.aborted)
821
+ return reject(new ToolError_1.ToolError('grep: aborted'));
822
+ reject(new ToolError_1.ToolError(`grep: rg failed: ${e.message}`));
823
+ });
824
+ });
825
+ }
826
+ async function runWalkGrep(pattern, root, signal) {
827
+ let re;
828
+ try {
829
+ re = new RegExp(pattern);
830
+ }
831
+ catch (e) {
832
+ throw new ToolError_1.ToolError(`grep: invalid regex: ${e instanceof Error ? e.message : String(e)}`);
833
+ }
834
+ const hits = [];
835
+ let budget = GREP_OUTPUT_LIMIT;
836
+ const push = (line) => {
837
+ budget -= line.length + 1;
838
+ if (budget < 0) {
839
+ hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
840
+ return false;
841
+ }
842
+ hits.push(line);
843
+ return true;
844
+ };
845
+ const stat = await fs.stat(root).catch(() => null);
846
+ if (stat?.isFile()) {
847
+ await grepFile(root, re, push);
848
+ }
849
+ else {
850
+ await walk(root, '', (rel) => grepFile(path.join(root, rel), re, push), signal);
851
+ }
852
+ if (signal?.aborted)
853
+ throw new ToolError_1.ToolError('grep: aborted');
854
+ if (hits.length === 0)
855
+ return 'no matches';
856
+ return hits.join('\n');
857
+ }
858
+ async function grepFile(file, re, push) {
859
+ const stream = fssync.createReadStream(file, { encoding: 'utf8' });
860
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
861
+ let i = 0;
862
+ try {
863
+ for await (const line of rl) {
864
+ i++;
865
+ // Cap line length: `pattern` is model-supplied and JS regexes backtrack,
866
+ // so a pathological pattern against a very long line is a ReDoS.
867
+ if (line.length > GREP_MAX_LINE_LENGTH)
868
+ continue;
869
+ if (re.test(line) && !push(`${file}:${i}:${line}`))
870
+ return false;
871
+ }
872
+ }
873
+ catch {
874
+ // unreadable / binary
875
+ }
876
+ finally {
877
+ stream.destroy();
878
+ }
879
+ return true;
880
+ }
881
+ // ---- utils ---------------------------------------------------------------
882
+ const WALK_MAX_DEPTH = 40;
883
+ const WALK_MAX_ENTRIES = 50_000;
884
+ /**
885
+ * Bounded recursive walk. `fn` may return `false` to abort. Only real
886
+ * directories are descended into and only real files are handed to `fn` —
887
+ * symlinks (and devices/fifos/sockets) are skipped entirely so a symlink inside
888
+ * the root cannot be followed out of it.
889
+ */
890
+ async function walk(root, rel, fn, signal) {
891
+ let remaining = WALK_MAX_ENTRIES;
892
+ async function inner(rel, depth) {
893
+ if (depth > WALK_MAX_DEPTH)
894
+ return true;
895
+ if (signal?.aborted)
896
+ return false;
897
+ let entries;
898
+ try {
899
+ entries = await fs.readdir(path.join(root, rel), { withFileTypes: true });
900
+ }
901
+ catch {
902
+ return true;
903
+ }
904
+ for (const e of entries) {
905
+ if (e.name === '.git' || e.name === 'node_modules')
906
+ continue;
907
+ if (remaining-- <= 0)
908
+ return false;
909
+ if (signal?.aborted)
910
+ return false;
911
+ const childRel = rel ? path.join(rel, e.name) : e.name;
912
+ if (e.isDirectory()) {
913
+ if (!(await inner(childRel, depth + 1)))
914
+ return false;
915
+ }
916
+ else if (e.isFile()) {
917
+ if ((await fn(childRel)) === false)
918
+ return false;
919
+ }
920
+ // Symlinks, devices, fifos and sockets are intentionally skipped.
921
+ }
922
+ return true;
923
+ }
924
+ await inner(rel, 0);
925
+ }
926
+ async function findRg() {
927
+ const dirs = (process.env['PATH'] ?? '').split(path.delimiter);
928
+ for (const d of dirs) {
929
+ const candidate = path.join(d, 'rg');
930
+ try {
931
+ await fs.access(candidate, fssync.constants.X_OK);
932
+ return candidate;
933
+ }
934
+ catch {
935
+ // not here
936
+ }
937
+ }
938
+ return null;
939
+ }