@theokit/sdk-tools 0.26.2 → 0.26.3

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/v4a-patch.ts","../src/apply-patch.ts","../src/artifact-store.ts","../src/current-time.ts","../src/internal/context-match.ts","../src/edit-file.ts","../src/formatter.ts","../src/subprocess.ts","../src/internal/git-exec.ts","../src/path-scope.ts","../src/git-diff.ts","../src/git-status.ts","../src/glob-files.ts","../src/interactive-shell.ts","../src/internal/shell-guard.ts","../src/internal/command-policy.ts","../src/internal/network-guard.ts","../src/internal/repo-map.ts","../src/internal/tool-aci.ts","../src/internal/tool-guidance.ts","../src/list-dir.ts","../src/plan-mode.ts","../src/question.ts","../src/read-file.ts","../src/read-tracker.ts","../src/reasoning-tools.ts","../src/run-vitest.ts","../src/search-text.ts","../src/shell-exec.ts","../src/todo-plan-nodes.ts","../src/todolist.ts","../src/truncation.ts","../src/update-plan.ts","../src/web-fetch.ts","../src/web-search.ts","../src/web-search-brave.ts","../src/web-search-http.ts","../src/write-file.ts"],"names":["safePathJoin","mkdir","readFile","stat","Tool","z","matchesAt","writeFile","existsSync","join","resolveSandbox","resolveFilesystem","relative","readdir","ConfigurationError","lookup","dnsLookup","walkDir","FileNotFoundError","isAbsolute","FilesystemSecurityError","DEFAULT_TIMEOUT_MS","DEFAULT_MAX_STDOUT_BYTES","spawn","BINARY_PROBE_BYTES","MAX_BACKEND_WALK_DEPTH","relativePath","dirname","fsStat","open"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,KAAA,GAAQ,iBAAA;AACd,IAAM,GAAA,GAAM,eAAA;AACZ,IAAM,GAAA,GAAM,gBAAA;AACZ,IAAM,MAAA,GAAS,mBAAA;AACf,IAAM,MAAA,GAAS,mBAAA;AACf,IAAM,IAAA,GAAO,eAAA;AACb,IAAM,QAAA,GAAW,iBAAA;AACjB,IAAM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A,eAAe,aAAa,YAAA,EAAwC;AAClE,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,MAAMS,IAAAA,CAAK,YAAA,EAAc,GAAG,CAAA;AAAA,EACvC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IAAI;AACF,IAAA,MAAM1B,KAAAA,GAAO,MAAM,MAAA,CAAO,IAAA,EAAK;AAC/B,IAAA,MAAM,WAAW,IAAA,CAAK,GAAA,CAAIqB,qBAAoB,MAAA,CAAOrB,KAAAA,CAAK,IAAI,CAAC,CAAA;AAC/D,IAAA,IAAI,QAAA,IAAY,GAAG,OAAO,KAAA;AAC1B,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,QAAQ,CAAA;AACnC,IAAA,MAAM,EAAE,WAAU,GAAI,MAAM,OAAO,IAAA,CAAK,KAAA,EAAO,CAAA,EAAG,QAAA,EAAU,CAAC,CAAA;AAC7D,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,SAAA,EAAW,KAAK,CAAA,EAAG;AACrC,MAAA,IAAI,KAAA,CAAM,CAAC,CAAA,KAAM,CAAA,EAAG,OAAO,IAAA;AAAA,IAC7B;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,SAAE;AACA,IAAA,MAAM,OAAO,KAAA,EAAM;AAAA,EACrB;AACF","file":"index.js","sourcesContent":["/**\n * V4A patch format — Codex's `apply_patch` grammar (`*** Begin Patch` … `*** End Patch`).\n *\n * A faithful TypeScript reimplementation of the Codex `apply-patch` crate (parser + seek_sequence matcher\n * + apply), with ONE deliberate hardening: the apply is STRICT — the whole plan (every new file content +\n * path check) is computed first, and only if all succeed is anything written. A mismatch/error anywhere\n * ⇒ typed error, zero writes (Codex writes file-by-file and can leave partial writes on an IO error).\n *\n * Grammar:\n * *** Begin Patch / *** End Patch envelope (markers matched after trim; CRLF stripped)\n * *** Add File: <path> then `+`lines create (strip one `+`; always trailing newline)\n * *** Delete File: <path> delete\n * *** Update File: <path> (*** Move to: <path>)? update (+ optional rename)\n * change chunks: `@@` | `@@ <ctx>` then lines:\n * ` `=context (old+new) `+`=add (new) `-`=remove (old) optional `*** End of File`\n */\n\nconst BEGIN = \"*** Begin Patch\";\nconst END = \"*** End Patch\";\nconst ADD = \"*** Add File: \";\nconst DELETE = \"*** Delete File: \";\nconst UPDATE = \"*** Update File: \";\nconst MOVE = \"*** Move to: \";\nconst EOF_MARK = \"*** End of File\";\nconst CTX = \"@@ \";\nconst CTX_EMPTY = \"@@\";\n\nexport type V4AHunk =\n | { kind: \"add\"; path: string; content: string }\n | { kind: \"delete\"; path: string }\n | { kind: \"update\"; path: string; movePath: string | null; chunks: V4AChunk[] };\n\nexport interface V4AChunk {\n context: string | null;\n oldLines: string[];\n newLines: string[];\n eof: boolean;\n}\n\nexport class V4APatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"V4APatchError\";\n }\n}\n\n/** Parse a V4A patch string into hunks. Throws {@link V4APatchError} on any structural problem. */\nexport function parseV4A(patch: string): V4AHunk[] {\n const lines = patch.split(\"\\n\").map((l) => (l.endsWith(\"\\r\") ? l.slice(0, -1) : l));\n let i = 0;\n while (i < lines.length && lines[i]!.trim() !== BEGIN) i++;\n if (i >= lines.length) throw new V4APatchError(\"Invalid patch: missing '*** Begin Patch'\");\n i++; // consume Begin Patch\n\n const hunks: V4AHunk[] = [];\n while (i < lines.length) {\n if (lines[i]!.trim() === END) return hunks;\n const step = parseNextHunk(lines, i);\n if (step.hunk) hunks.push(step.hunk);\n i = step.next;\n }\n throw new V4APatchError(\"Invalid patch: missing '*** End Patch'\");\n}\n\n/** Dispatch on the hunk-header at `i`. Returns the parsed hunk (or none, for a blank line) + next index. */\nfunction parseNextHunk(lines: string[], i: number): { hunk?: V4AHunk; next: number } {\n const line = lines[i]!;\n if (line.startsWith(ADD)) {\n const [hunk, next] = parseAdd(lines, i);\n return { hunk, next };\n }\n if (line.startsWith(DELETE)) {\n return { hunk: { kind: \"delete\", path: line.slice(DELETE.length).trim() }, next: i + 1 };\n }\n if (line.startsWith(UPDATE)) {\n const [hunk, next] = parseUpdate(lines, i);\n return { hunk, next };\n }\n if (line.trim() === \"\") return { next: i + 1 }; // tolerate blank lines between hunks\n throw new V4APatchError(`Invalid patch hunk on line ${i + 1}: unexpected '${line}'`);\n}\n\nfunction parseAdd(lines: string[], start: number): [V4AHunk, number] {\n const path = lines[start]!.slice(ADD.length).trim();\n let i = start + 1;\n const body: string[] = [];\n while (i < lines.length && lines[i]!.startsWith(\"+\")) {\n body.push(lines[i]!.slice(1));\n i++;\n }\n // Every added line (incl. the last) is followed by a newline ⇒ file always ends with a trailing newline.\n const content = body.length > 0 ? `${body.join(\"\\n\")}\\n` : \"\";\n return [{ kind: \"add\", path, content }, i];\n}\n\nfunction parseUpdate(lines: string[], start: number): [V4AHunk, number] {\n const path = lines[start]!.slice(UPDATE.length).trim();\n let i = start + 1;\n let movePath: string | null = null;\n if (i < lines.length && lines[i]!.startsWith(MOVE)) {\n movePath = lines[i]!.slice(MOVE.length).trim();\n i++;\n }\n const chunks: V4AChunk[] = [];\n let cur: V4AChunk | null = null;\n for (; i < lines.length; i++) {\n const line = lines[i]!;\n if (isHunkBoundary(line)) break;\n cur = feedLine(chunks, cur, line, path, i + 1);\n }\n pushChunk(chunks, cur, path);\n if (chunks.length === 0) throw new V4APatchError(`Update file hunk for '${path}' is empty`);\n return [{ kind: \"update\", path, movePath, chunks }, i];\n}\n\nfunction isHunkBoundary(line: string): boolean {\n return (\n line.trim() === END ||\n line.startsWith(ADD) ||\n line.startsWith(DELETE) ||\n line.startsWith(UPDATE)\n );\n}\n\nfunction emptyChunk(): V4AChunk {\n return { context: null, oldLines: [], newLines: [], eof: false };\n}\n\n/** Push a completed chunk (rejecting an empty change block), or no-op when there is no current chunk. */\nfunction pushChunk(chunks: V4AChunk[], cur: V4AChunk | null, path: string): void {\n if (!cur) return;\n if (cur.oldLines.length === 0 && cur.newLines.length === 0) {\n throw new V4APatchError(`Update hunk for '${path}' has an empty change block`);\n }\n chunks.push(cur);\n}\n\n/** Route one line inside an Update hunk: a `@@` marker starts a chunk, `*** End of File` flags eof,\n * everything else is a change line. Returns the current chunk. */\nfunction feedLine(\n chunks: V4AChunk[],\n cur: V4AChunk | null,\n line: string,\n path: string,\n lineNum: number,\n): V4AChunk {\n if (line === CTX_EMPTY || line.startsWith(CTX)) {\n pushChunk(chunks, cur, path);\n return {\n context: line === CTX_EMPTY ? null : line.slice(CTX.length),\n oldLines: [],\n newLines: [],\n eof: false,\n };\n }\n if (line.trim() === EOF_MARK) {\n if (!cur) throw new V4APatchError(`'*** End of File' before any change in '${path}'`);\n cur.eof = true;\n return cur;\n }\n return appendChangeLine(cur, line, path, lineNum);\n}\n\n/** Classify a `+`add / `-`remove / ` `|empty context line into the chunk. */\nfunction appendChangeLine(\n cur: V4AChunk | null,\n line: string,\n path: string,\n lineNum: number,\n): V4AChunk {\n const c = cur ?? emptyChunk();\n if (line.startsWith(\"+\")) {\n c.newLines.push(line.slice(1));\n return c;\n }\n if (line.startsWith(\"-\")) {\n c.oldLines.push(line.slice(1));\n return c;\n }\n if (line === \"\" || line.startsWith(\" \")) {\n const content = line === \"\" ? \"\" : line.slice(1); // bare empty line = empty context line\n c.oldLines.push(content);\n c.newLines.push(content);\n return c;\n }\n throw new V4APatchError(\n `Unexpected line in update hunk for '${path}' (line ${lineNum}): every line must start with ' ', '+', or '-': '${line}'`,\n );\n}\n\n// --- Matching: the seek_sequence ladder (exact → rstrip → trim → unicode) ---\n\nconst UNICODE_MAP: Record<string, string> = {\n \"‐\": \"-\",\n \"‑\": \"-\",\n \"‒\": \"-\",\n \"–\": \"-\",\n \"—\": \"-\",\n \"―\": \"-\",\n \"‘\": \"'\",\n \"’\": \"'\",\n \"“\": '\"',\n \"”\": '\"',\n \" \": \" \",\n \" \": \" \",\n \" \": \" \",\n};\nfunction normalise(s: string): string {\n let out = \"\";\n for (const ch of s) out += UNICODE_MAP[ch] ?? ch;\n return out.trim();\n}\n\nconst LADDER: Array<(a: string, b: string) => boolean> = [\n (a, b) => a === b,\n (a, b) => a.replace(/\\s+$/, \"\") === b.replace(/\\s+$/, \"\"),\n (a, b) => a.trim() === b.trim(),\n (a, b) => normalise(a) === normalise(b),\n];\n\nfunction matchesAt(\n lines: string[],\n pattern: string[],\n at: number,\n eq: (a: string, b: string) => boolean,\n): boolean {\n for (let k = 0; k < pattern.length; k++) {\n if (!eq(lines[at + k]!, pattern[k]!)) return false;\n }\n return true;\n}\n\n/** First index ≥ searchStart where `pattern` matches `lines` under increasing leniency; null if none.\n * `eof` forces the search to start at the tail. Mirrors Codex `seek_sequence`. */\nexport function seekSequence(\n lines: string[],\n pattern: string[],\n searchStart: number,\n eof: boolean,\n): number | null {\n if (pattern.length === 0) return searchStart;\n if (pattern.length > lines.length) return null;\n // `eof` is a HINT: prefer a match anchored at the tail, but fall back to a general forward search —\n // otherwise a last-line edit fails, because `\"a\\nb\\n\".split(\"\\n\")` has a phantom trailing \"\" that\n // pushes the tail anchor one past the real last line.\n const starts = eof\n ? [Math.max(searchStart, lines.length - pattern.length), searchStart]\n : [searchStart];\n for (const start of starts) {\n const hit = searchFrom(lines, pattern, start);\n if (hit !== null) return hit;\n }\n return null;\n}\n\n/** Scan `lines` from `start` under the leniency ladder; the first matching index, or null. */\nfunction searchFrom(lines: string[], pattern: string[], start: number): number | null {\n for (const eq of LADDER) {\n for (let i = start; i <= lines.length - pattern.length; i++) {\n if (matchesAt(lines, pattern, i, eq)) return i;\n }\n }\n return null;\n}\n\n/** Apply an update hunk's chunks to file content (forward cursor, sequential). Throws on a context/region miss. */\nexport function applyUpdateChunks(content: string, path: string, chunks: V4AChunk[]): string {\n const lines = content.split(\"\\n\");\n // Collect (start, oldLen, newLines) forward-only, then splice descending so indices stay valid.\n const edits: Array<{ start: number; oldLen: number; newLines: string[] }> = [];\n let cursor = 0;\n for (const chunk of chunks) {\n if (chunk.context !== null) {\n const ctxAt = seekSequence(lines, [chunk.context], cursor, false);\n if (ctxAt === null) {\n throw new V4APatchError(`Failed to find context '${chunk.context}' in ${path}`);\n }\n cursor = ctxAt + 1;\n }\n const at = seekSequence(lines, chunk.oldLines, cursor, chunk.eof);\n if (at === null) {\n throw new V4APatchError(\n `Failed to find expected lines in ${path}:\\n${chunk.oldLines.join(\"\\n\")}`,\n );\n }\n edits.push({ start: at, oldLen: chunk.oldLines.length, newLines: chunk.newLines });\n cursor = at + chunk.oldLines.length;\n }\n edits.sort((a, b) => b.start - a.start);\n for (const e of edits) {\n lines.splice(e.start, e.oldLen, ...e.newLines);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * `apply_patch` — built-in tool for coding agents.\n *\n * Codex's V4A patch grammar (`*** Begin Patch` … `*** End Patch`): `*** Add/Update/Delete File:`, an\n * optional `*** Move to:`, and `@@`-anchored `+`/`-`/context hunks matched with a context-tolerant ladder\n * (exact → rstrip → trim → unicode). See `internal/v4a-patch.ts` for the parser + matcher.\n *\n * Applied STRICTLY atomically: the whole patch is planned (every file read + new content computed + path\n * security-checked) before ANY write. A parse error, context mismatch, or path violation anywhere ⇒ typed\n * error and ZERO writes (stronger than Codex, which writes file-by-file and can leave partial writes).\n *\n * Return shape (always a JSON string — never throws on a bad patch):\n * - `{ ok: true, files_patched: string[] }`\n * - `{ ok: false, error: 'parse_error' | 'path_traversal' | 'forbidden_path' | 'not_found' |\n * 'patch_failed' | 'duplicate_target' | 'file_exists' | 'io_error' }`\n *\n * Security/robustness (M18 review): forbidden secrets (`.env`/`.git`/`node_modules`/`.theo`) are blocked\n * at ANY path depth and against absolute-path spelling; a file touched by two hunks is rejected\n * (`duplicate_target`); Add over an existing file is rejected (`file_exists`); Delete of a missing file\n * is `not_found`; any unexpected fs error maps to `io_error` (the handler never throws).\n */\n\nimport { mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { applyUpdateChunks, parseV4A, type V4AHunk, V4APatchError } from \"./internal/v4a-patch.js\";\n\nexport interface CreateApplyPatchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every hunk path is gated against this boundary. */\n projectRoot: string;\n}\n\nexport function createApplyPatchTool(opts: CreateApplyPatchToolOptions): CustomTool {\n const { projectRoot } = opts;\n\n return Tool.create({\n name: opts.name ?? \"apply_patch\",\n description:\n opts.description ??\n \"Apply a Codex-style V4A patch. The patch is `*** Begin Patch` … `*** End Patch` wrapping one or \" +\n \"more hunks: `*** Add File: <path>` (then `+`lines), `*** Delete File: <path>`, or `*** Update \" +\n \"File: <path>` (optional `*** Move to: <path>`) with `@@`-anchored `+` (add) / `-` (remove) / ` ` \" +\n \"(context) lines. Read a file first so your context/removed lines match. Applied atomically — a \" +\n \"mismatch anywhere aborts the whole patch with zero writes; each path is security-checked. Returns \" +\n \"{ ok, files_patched } or { ok: false, error }.\",\n inputSchema: z.object({\n patch: z.string().min(1).describe(\"V4A patch: *** Begin Patch … *** End Patch.\"),\n }),\n handler: async ({ patch }) => applyV4APatch(projectRoot, patch),\n });\n}\n\n/** A single filesystem mutation in the apply plan. A `move` is expressed as a write + an rm. */\ntype FsOp = { write: { abs: string; content: string } } | { rm: string };\n\ntype PlanResult = { ops: FsOp[]; patched: string[] } | { error: string };\n\nasync function applyV4APatch(projectRoot: string, patch: string): Promise<string> {\n let hunks: V4AHunk[];\n try {\n hunks = parseV4A(patch);\n } catch (err) {\n const detail = err instanceof V4APatchError ? err.message : String(err);\n return JSON.stringify({ ok: false, error: \"parse_error\", detail });\n }\n // Plan (verify) the WHOLE patch before any write; then execute. First failure ⇒ zero writes. An\n // unexpected fs error during execute maps to a typed `io_error` (honors the always-JSON contract).\n try {\n const plan = await buildPlan(projectRoot, hunks);\n if (\"error\" in plan) return plan.error;\n await executePlan(plan.ops);\n return JSON.stringify({ ok: true, files_patched: plan.patched });\n } catch (err) {\n return JSON.stringify({\n ok: false,\n error: \"io_error\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n}\n\n/** The file paths a hunk mutates (a move touches both its source and destination). */\nfunction hunkTargets(hunk: V4AHunk): string[] {\n if (hunk.kind === \"update\" && hunk.movePath) return [hunk.path, hunk.movePath];\n return [hunk.path];\n}\n\n/** Read + compute + path-check every hunk into a write plan (no writes). First failure aborts. A file\n * touched by two hunks is rejected (Codex forbids editing the same file twice — otherwise the second\n * read sees the original and the first edit is silently lost). */\nasync function buildPlan(projectRoot: string, hunks: V4AHunk[]): Promise<PlanResult> {\n const dup = firstDuplicateTarget(hunks);\n if (dup !== null) {\n return { error: JSON.stringify({ ok: false, error: \"duplicate_target\", path: dup }) };\n }\n const ops: FsOp[] = [];\n const patched: string[] = [];\n for (const hunk of hunks) {\n const planned = await planHunk(projectRoot, hunk);\n if (\"error\" in planned) return planned;\n ops.push(...planned.ops);\n patched.push(hunk.kind === \"update\" ? (hunk.movePath ?? hunk.path) : hunk.path);\n }\n return { ops, patched };\n}\n\n/** The first path touched by two hunks (Codex forbids editing the same file twice), or null. */\nfunction firstDuplicateTarget(hunks: V4AHunk[]): string | null {\n const seen = new Set<string>();\n for (const hunk of hunks) {\n for (const t of hunkTargets(hunk)) {\n if (seen.has(t)) return t;\n seen.add(t);\n }\n }\n return null;\n}\n\n/** Execute the write plan (all reads/computes/checks already passed). */\nasync function executePlan(ops: FsOp[]): Promise<void> {\n for (const op of ops) {\n if (\"rm\" in op) {\n await rm(op.rm, { force: true });\n } else {\n await mkdir(dirname(op.write.abs), { recursive: true });\n await writeFile(op.write.abs, op.write.content, \"utf-8\");\n }\n }\n}\n\n/** Does a path exist (any type)? */\nasync function pathExists(abs: string): Promise<boolean> {\n try {\n await stat(abs);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Plan one hunk (Codex Hunk-kind dispatch) into filesystem ops, or an error JSON string. */\nasync function planHunk(\n projectRoot: string,\n hunk: V4AHunk,\n): Promise<{ ops: FsOp[] } | { error: string }> {\n const scope = v4aScope(projectRoot, hunk.path);\n if (\"error\" in scope) return scope;\n if (hunk.kind === \"add\") {\n // Codex rejects Add over an existing file — never silently clobber.\n if (await pathExists(scope.abs)) {\n return { error: JSON.stringify({ ok: false, error: \"file_exists\", path: hunk.path }) };\n }\n return { ops: [{ write: { abs: scope.abs, content: hunk.content } }] };\n }\n if (hunk.kind === \"delete\") {\n if (!(await pathExists(scope.abs))) {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: hunk.path }) };\n }\n return { ops: [{ rm: scope.abs }] };\n }\n return planUpdate(projectRoot, hunk, scope.abs);\n}\n\n/** Plan an Update hunk: read the OLD file, compute the new content, then write-in-place or move. */\nasync function planUpdate(\n projectRoot: string,\n hunk: Extract<V4AHunk, { kind: \"update\" }>,\n abs: string,\n): Promise<{ ops: FsOp[] } | { error: string }> {\n let content: string;\n try {\n content = await readFile(abs, \"utf-8\");\n } catch (err) {\n if ((err as { code?: string }).code === \"ENOENT\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: hunk.path }) };\n }\n throw err;\n }\n let updated: string;\n try {\n updated = applyUpdateChunks(content, hunk.path, hunk.chunks);\n } catch (err) {\n if (err instanceof V4APatchError) {\n return {\n error: JSON.stringify({\n ok: false,\n error: \"patch_failed\",\n path: hunk.path,\n detail: err.message,\n }),\n };\n }\n throw err;\n }\n if (!hunk.movePath) return { ops: [{ write: { abs, content: updated } }] };\n const dest = v4aScope(projectRoot, hunk.movePath);\n if (\"error\" in dest) return dest;\n // transform-then-rename: write the new content to the destination, remove the original.\n return { ops: [{ write: { abs: dest.abs, content: updated } }, { rm: abs }] };\n}\n\n/** Sensitive path segments — secret-bearing dirs/files that must never be written at ANY depth. */\nconst FORBIDDEN_SEGMENTS = new Set([\".env\", \".git\", \"node_modules\", \".theo\"]);\n\n/** Any-segment forbidden check on a PROJECT-RELATIVE path. `isForbiddenPath` only inspects the first\n * segment (so a nested `sub/.git/hooks/…` or an absolute `<root>/.env` slips past); a writing tool must\n * block a sensitive segment at any depth. */\nfunction isForbiddenRel(rel: string): boolean {\n return rel\n .split(/[/\\\\]/)\n .filter(Boolean)\n .some((s) => s !== \".env.example\" && (FORBIDDEN_SEGMENTS.has(s) || /^\\.env\\./.test(s)));\n}\n\n/** Security-check a hunk path against the project root; returns the resolved abs path or an error JSON\n * string. Resolves FIRST (rejecting traversal/symlink/absolute escape), then checks the resulting\n * project-relative path for a forbidden segment at any depth (closes the nested/absolute `.env` hole). */\nfunction v4aScope(projectRoot: string, file: string): { abs: string } | { error: string } {\n let abs: string;\n try {\n abs = safePathJoin(projectRoot, file);\n assertNoSymlinkEscape(abs, projectRoot);\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path: file }) };\n }\n throw err;\n }\n if (isForbiddenPath(file) || isForbiddenRel(relative(projectRoot, abs))) {\n return { error: JSON.stringify({ ok: false, error: \"forbidden_path\", path: file }) };\n }\n return { abs };\n}\n","import { mkdir, readdir, readFile, stat } from \"node:fs/promises\";\nimport { safeFilenameForId, safePathJoin } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/**\n * Options for {@link createSessionArtifactStore}.\n *\n * @public\n */\nexport interface SessionArtifactStoreOptions {\n /** Directory holding one file per artifact (`<dir>/<idStrategy(id)><extension>`). */\n dir: string;\n /**\n * Map an opaque artifact id to a filesystem-safe filename stem.\n * Default: `safeFilenameForId` (accepts ANY id; deterministically hashes\n * non-conforming input). The result is additionally passed through\n * `safePathJoin`, so a traversal id can never escape `dir`.\n *\n * NOTE — the default `safeFilenameForId` is CASE-FOLDING: ids differing only\n * in case (`\"Run-1\"` vs `\"run-1\"`) map to the SAME file. If your ids are\n * case-sensitive (e.g. base64), supply a case-preserving `idStrategy`.\n */\n idStrategy?: (id: string) => string;\n /** File extension (with leading dot). Default `\".md\"`. */\n extension?: string;\n}\n\n/**\n * A generic, id-keyed, atomic artifact store. Generalizes the per-run\n * session-summary writer pattern: persist an opaque text artifact under a\n * stable id, read it back, and enumerate what's stored.\n *\n * @public\n */\nexport interface SessionArtifactStore {\n /**\n * Write (overwrite) the artifact atomically; returns the resolved path.\n * Content is persisted byte-for-byte. The id is mapped via `idStrategy`\n * (default case-folding — see {@link SessionArtifactStoreOptions.idStrategy}).\n */\n write(id: string, content: string): Promise<string>;\n /** Read the artifact, or `undefined` if absent/unreadable (never throws). */\n read(id: string): Promise<string | undefined>;\n /** Whether an artifact exists for `id` (never throws). */\n has(id: string): Promise<boolean>;\n /** The filename stems of all stored artifacts (never throws; `[]` if dir absent). */\n list(): Promise<string[]>;\n /** The resolved, traversal-safe path for `id`. */\n path(id: string): string;\n}\n\n/**\n * Create a generic artifact store rooted at `dir`. Composes the shipped\n * `safeFilenameForId`/`safePathJoin` path guard + the atomic `replaceFileAtomic`\n * writer — zero new dependencies. Reads never throw; writes fail loud.\n *\n * @public\n */\nexport function createSessionArtifactStore(\n options: SessionArtifactStoreOptions,\n): SessionArtifactStore {\n const { dir } = options;\n const idStrategy = options.idStrategy ?? ((id: string) => safeFilenameForId(id));\n const extension = options.extension ?? \".md\";\n\n function path(id: string): string {\n return safePathJoin(dir, `${idStrategy(id)}${extension}`);\n }\n\n async function write(id: string, content: string): Promise<string> {\n const target = path(id);\n await mkdir(dir, { recursive: true });\n await replaceFileAtomic(target, content);\n return target;\n }\n\n async function read(id: string): Promise<string | undefined> {\n try {\n return await readFile(path(id), \"utf8\");\n } catch {\n return undefined;\n }\n }\n\n async function has(id: string): Promise<boolean> {\n // stat (not read) — O(1) existence check, no full-file load. Never throws.\n try {\n await stat(path(id));\n return true;\n } catch {\n return false;\n }\n }\n\n async function list(): Promise<string[]> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(extension))\n .map((name) => name.slice(0, name.length - extension.length));\n }\n\n return { write, read, has, list, path };\n}\n","/**\n * `current_time` — built-in tool for coding agents.\n *\n * Returns the current date-time. Codex-faithful at the core (its `clock`/`curr_time` tool returns UTC\n * as `YYYY-MM-DD HH:MM:SS UTC`); this built-in keeps that default and adds an optional IANA `timezone`\n * (additive superset — omitted ⇒ UTC, exactly Codex's behavior) plus an unambiguous `iso` instant.\n *\n * The clock is injectable so the tool is deterministic under test (testing.md §6: never read the real\n * wall clock in a unit test).\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, current_time: \"YYYY-MM-DD HH:MM:SS <tz>\", iso: string, timezone: string }`\n * - `{ ok: false, error: \"invalid_timezone\", timezone }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nexport interface CreateCurrentTimeToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Injectable clock — defaults to `() => new Date()`. Pass a fixed clock for deterministic tests. */\n clock?: () => Date;\n}\n\n/** Format `now` as `YYYY-MM-DD HH:MM:SS <tz>` in the given IANA timezone. Throws RangeError on a bad tz\n * (Intl validates the zone); assembled from `formatToParts` so the layout is ICU-locale-independent. */\nfunction formatInTimezone(now: Date, tz: string): string {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n }).formatToParts(now);\n const p: Record<string, string> = {};\n for (const { type, value } of parts) p[type] = value;\n // ICU can emit \"24\" for midnight under hour12:false — normalize to \"00\".\n const hour = p.hour === \"24\" ? \"00\" : p.hour;\n return `${p.year}-${p.month}-${p.day} ${hour}:${p.minute}:${p.second} ${tz}`;\n}\n\nexport function createCurrentTimeTool(opts: CreateCurrentTimeToolOptions = {}): CustomTool {\n const clock = opts.clock ?? (() => new Date());\n\n return Tool.create({\n name: opts.name ?? \"current_time\",\n description:\n opts.description ??\n \"Get the current date and time. Returns { current_time, iso, timezone } as a JSON string, where \" +\n \"current_time is 'YYYY-MM-DD HH:MM:SS <timezone>' and iso is the ISO-8601 instant. Pass an optional \" +\n \"IANA timezone (e.g. 'America/Sao_Paulo', 'Europe/Lisbon'); defaults to UTC. Never state the date \" +\n \"or time from memory — always call this. Returns { ok: false, error: 'invalid_timezone' } for an \" +\n \"unknown timezone.\",\n inputSchema: z.object({\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone, e.g. 'America/Sao_Paulo' or 'Europe/Lisbon'. Defaults to UTC.\"),\n }),\n handler: ({ timezone }) => {\n const tz = timezone ?? \"UTC\";\n const now = clock();\n try {\n return JSON.stringify({\n ok: true,\n current_time: formatInTimezone(now, tz),\n iso: now.toISOString(),\n timezone: tz,\n });\n } catch {\n // Fail-clear with a typed error shape (Rule 8) instead of a cryptic RangeError.\n return JSON.stringify({ ok: false, error: \"invalid_timezone\", timezone: tz });\n }\n },\n });\n}\n","/**\n * Context-tolerant single-occurrence text matching (`seek_sequence` parity, ported\n * from the AgentBuilder Codex clone, M10/M13). Where a naive `edit_file` matches\n * `old_string` byte-for-byte (or with a single whitespace-normalized fallback),\n * this matcher is safe AND forgiving:\n *\n * Stage 1 — exact byte substring, with an **ambiguity guard**: if the target\n * appears more than once it throws instead of silently editing the first hit\n * (a too-short `old_string` editing the wrong location is the classic footgun).\n * Stage 2 — line-based match down a **strictness ladder** (exact → rstrip → trim\n * → unicode-normalize), stopping at the first rung that yields exactly ONE\n * match; a rung matching 2+ positions throws (ambiguous), never picks one.\n *\n * Pure. Preserves the file's CRLF/LF style on the replaced region. Throws typed\n * {@link ContextMatchError} (`empty | ambiguous | not_found`) so the caller maps to\n * its own `{ ok: false, error }` shape.\n */\n\nexport type ContextMatchReason = \"empty\" | \"ambiguous\" | \"not_found\";\n\nexport class ContextMatchError extends Error {\n readonly reason: ContextMatchReason;\n constructor(reason: ContextMatchReason, message: string) {\n super(message);\n this.name = \"ContextMatchError\";\n this.reason = reason;\n }\n}\n\n/** Normalize common Unicode punctuation to ASCII (dashes/quotes/odd-spaces) — the loosest ladder rung,\n * mirroring `git apply`'s fuzz so an ASCII-authored edit still matches typographic source. */\nfunction normalizeUnicode(s: string): string {\n return s\n .replace(/[‐-―−]/g, \"-\")\n .replace(/[‘-‛]/g, \"'\")\n .replace(/[“-‟]/g, '\"')\n .replace(/[ -    ]/g, \" \");\n}\n\n/** The strictness ladder: each rung normalizes a line before comparison. */\nconst LINE_MATCH_LADDER: ReadonlyArray<(s: string) => string> = [\n (s) => s, // exact\n (s) => s.replace(/\\s+$/, \"\"), // rstrip (ignore trailing whitespace)\n (s) => s.trim(), // trim (ignore leading + trailing)\n (s) => normalizeUnicode(s).trim(), // unicode + trim (loosest)\n];\n\n/** Whether `pattern` matches `lines` starting at index `i`, comparing each line under `norm`. */\nfunction matchesAt(\n lines: string[],\n pattern: string[],\n i: number,\n norm: (s: string) => string,\n): boolean {\n for (let p = 0; p < pattern.length; p++) {\n const lineAt = lines[i + p];\n const patAt = pattern[p];\n if (lineAt === undefined || patAt === undefined || norm(lineAt) !== norm(patAt)) return false;\n }\n return true;\n}\n\n/** Every start index where `pattern` matches `lines` under `norm`. */\nfunction findHits(lines: string[], pattern: string[], norm: (s: string) => string): number[] {\n const hits: number[] = [];\n for (let i = 0; i + pattern.length <= lines.length; i++) {\n if (matchesAt(lines, pattern, i, norm)) hits.push(i);\n }\n return hits;\n}\n\n/**\n * Find the UNIQUE start line index where `pattern` matches `lines`, trying the ladder top-down.\n * Returns the index at the FIRST rung yielding exactly one match; `null` if none; throws (ambiguous)\n * if a rung matches 2+ positions. Empty or too-long pattern → null.\n */\nfunction seekUniqueLineMatch(lines: string[], pattern: string[], find: string): number | null {\n if (pattern.length === 0 || pattern.length > lines.length) return null;\n for (const norm of LINE_MATCH_LADDER) {\n const hits = findHits(lines, pattern, norm);\n if (hits.length === 1) return hits[0] ?? null;\n if (hits.length > 1) {\n throw new ContextMatchError(\n \"ambiguous\",\n `target text is ambiguous (multiple matches); include more context:\\n${find}`,\n );\n }\n }\n return null;\n}\n\n/**\n * Return `content` with the single occurrence of `find` replaced by `replace`, using the two-stage\n * context-tolerant matcher. Throws {@link ContextMatchError} on empty/ambiguous/not-found.\n */\nexport function replaceUnique(content: string, find: string, replace: string): string {\n if (find === \"\") {\n throw new ContextMatchError(\n \"empty\",\n \"empty find is not a valid target; provide the text to replace\",\n );\n }\n // Stage 1 — exact byte substring (fast path + uniqueness). The ambiguity re-scan starts at\n // `first + 1` (NOT `first + find.length`) so a self-OVERLAPPING find is still caught as ambiguous.\n const first = content.indexOf(find);\n if (first !== -1) {\n if (content.indexOf(find, first + 1) !== -1) {\n throw new ContextMatchError(\n \"ambiguous\",\n `target text is ambiguous (multiple matches); include more context:\\n${find}`,\n );\n }\n return content.slice(0, first) + replace + content.slice(first + find.length);\n }\n // Stage 2 — line-based tolerant match (seek_sequence ladder).\n const lines = content.split(\"\\n\");\n const at = seekUniqueLineMatch(lines, find.split(\"\\n\"), find);\n if (at === null) {\n throw new ContextMatchError(\"not_found\", `target text not found:\\n${find}`);\n }\n const patternLen = find.split(\"\\n\").length;\n // Preserve the file's line-ending style: a CRLF file split on '\\n' keeps a trailing '\\r' per line.\n // If the MATCHED region is CRLF, re-attach '\\r' to the (LF-authored) replace lines so the edit never\n // leaves mixed CRLF/LF endings behind.\n const matchedCrlf =\n patternLen > 0 && lines.slice(at, at + patternLen).every((l) => l.endsWith(\"\\r\"));\n const replaceLines = matchedCrlf\n ? replace.split(\"\\n\").map((l) => (l.endsWith(\"\\r\") ? l : `${l}\\r`))\n : replace.split(\"\\n\");\n return [...lines.slice(0, at), ...replaceLines, ...lines.slice(at + patternLen)].join(\"\\n\");\n}\n","/**\n * `edit_file` — built-in tool for coding agents.\n *\n * Replaces a string in a project-relative file. Tries exact match first,\n * then whitespace-normalized match. Creates a `.bak` backup before editing.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, replacements: 1 }` on success\n * - `{ ok: false, error: 'no_match' | 'not_found' | 'path_traversal' |\n * 'forbidden_path' }` on refusal\n */\n\nimport { copyFile, readFile, writeFile } from \"node:fs/promises\";\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport { ContextMatchError, replaceUnique } from \"./internal/context-match.js\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nexport interface CreateEditFileToolOptions {\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ o literal de hoje (aditivo).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every edit is gated against this boundary. */\n projectRoot: string;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the read + `.bak` backup +\n * write go through the backend (surface-agnostic); omitted ⇒ the local `fs` path (byte-identical). */\n filesystem?: FilesystemProvider;\n}\n\ntype EditOutcome = { ok: true; result: string } | { ok: false; error: \"no_match\" };\n\n/** Pure string-replacement core shared by the local and backend paths (no I/O): exact → whitespace-\n * normalized → context-tolerant ladder. Extracting it keeps the matching algorithm single-sourced (DRY)\n * while both fs paths do their own read/backup/write. */\nfunction computeEdit(content: string, old_string: string, new_string: string): EditOutcome {\n const exactIdx = content.indexOf(old_string);\n if (exactIdx !== -1) {\n return {\n ok: true,\n result: content.slice(0, exactIdx) + new_string + content.slice(exactIdx + old_string.length),\n };\n }\n const normalizedContent = normalizeWhitespace(content);\n const normalizedOld = normalizeWhitespace(old_string);\n const normalizedIdx = normalizedContent.indexOf(normalizedOld);\n if (normalizedIdx !== -1) {\n const span = findOriginalSpan(content, normalizedContent, normalizedIdx, normalizedOld.length);\n return {\n ok: true,\n result: content.slice(0, span.start) + new_string + content.slice(span.end),\n };\n }\n try {\n return { ok: true, result: replaceUnique(content, old_string, new_string) };\n } catch (err) {\n if (err instanceof ContextMatchError) return { ok: false, error: \"no_match\" };\n throw err;\n }\n}\n\n/** Apply an edit through an injected FilesystemBackend (project-relative path space, like read_file):\n * read → write a `.bak` backup → write the result. The path-scope guards run in the caller. */\nasync function editViaBackend(\n filesystem: FilesystemProvider,\n ctx: unknown,\n path: string,\n old_string: string,\n new_string: string,\n): Promise<string> {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n let content: string;\n try {\n content = await backend.readFile(path);\n } catch (err) {\n // Mirror the local path: only a missing file maps to `not_found`; every other read failure\n // (a directory, a permission error, a security rejection) propagates — fail-loud, never swallowed.\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n throw err;\n }\n const outcome = computeEdit(content, old_string, new_string);\n if (!outcome.ok) return JSON.stringify({ ok: false, error: \"no_match\", path });\n await backend.writeFile(`${path}.bak`, content);\n await backend.writeFile(path, outcome.result);\n return JSON.stringify({ ok: true, replacements: 1 });\n}\n\n/** Apply an edit through the local `fs` (byte-identical to before): read → computeEdit → `.bak` → write. */\nasync function editViaLocal(\n projectRoot: string,\n path: string,\n old_string: string,\n new_string: string,\n): Promise<string> {\n const absolutePath = safePathJoin(projectRoot, path);\n let content: string;\n try {\n content = await readFile(absolutePath, \"utf-8\");\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\") {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n throw err;\n }\n const outcome = computeEdit(content, old_string, new_string);\n if (!outcome.ok) return JSON.stringify({ ok: false, error: \"no_match\", path });\n await copyFile(absolutePath, `${absolutePath}.bak`);\n await writeFile(absolutePath, outcome.result, \"utf-8\");\n return JSON.stringify({ ok: true, replacements: 1 });\n}\n\n/** Shared path-scope guard for both fs paths — returns an error JSON string, or null when the path is safe. */\nfunction editScopeError(path: string, projectRoot: string): string | null {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, path), projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\nexport function createEditFileTool(opts: CreateEditFileToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"edit_file\",\n description:\n opts.description ??\n \"Make an exact string replacement in a project-relative file. Replaces the FIRST occurrence \" +\n \"of old_string with new_string (a whitespace-normalized fallback is attempted if the exact \" +\n \"match fails) and writes a .bak backup first. Read the file first so old_string matches the \" +\n \"on-disk text exactly; include enough surrounding context to make it unique — only the first \" +\n \"match is replaced, so a too-short old_string can edit the wrong location. old_string must be \" +\n \"non-empty and differ from new_string; to change every occurrence, call edit_file repeatedly. \" +\n \"Returns { ok, replacements } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative file path.\"),\n old_string: z.string().min(1).describe(\"String to find in the file.\"),\n new_string: z.string().describe(\"Replacement string.\"),\n }),\n handler: async ({ path, old_string, new_string }, ctx) => {\n // A no-op edit (old === new) cannot change the file; refuse early so the description's\n // \"old_string must differ from new_string\" precondition is enforced, not just documented.\n if (old_string === new_string) {\n return JSON.stringify({ ok: false, error: \"no_change\", path });\n }\n\n // Path-scope guard (pure security) applies to both fs paths.\n const scopeErr = editScopeError(path, projectRoot);\n if (scopeErr !== null) return scopeErr;\n\n // Injected filesystem (surface-agnostic) ⇒ read/backup/write via the backend; absent ⇒ local `fs`.\n return filesystem !== undefined\n ? editViaBackend(filesystem, ctx, path, old_string, new_string)\n : editViaLocal(projectRoot, path, old_string, new_string);\n },\n });\n}\n\n/** Collapse runs of whitespace into a single space. */\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Map a position range in the whitespace-normalized string back to the\n * original string. Walks both strings in lockstep.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: parser logic\nfunction findOriginalSpan(\n original: string,\n _normalized: string,\n normStart: number,\n normLen: number,\n): { start: number; end: number } {\n let origIdx = 0;\n let normIdx = 0;\n\n // Skip leading whitespace that was trimmed\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n\n // Walk to normStart\n while (normIdx < normStart && origIdx < original.length) {\n if (/\\s/.test(original[origIdx]!)) {\n // skip entire whitespace run in original, counts as one in normalized\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n normIdx++; // the collapsed space\n } else {\n origIdx++;\n normIdx++;\n }\n }\n\n const start = origIdx;\n\n // Walk normLen characters\n let walked = 0;\n while (walked < normLen && origIdx < original.length) {\n if (/\\s/.test(original[origIdx]!)) {\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n walked++; // the collapsed space\n } else {\n origIdx++;\n walked++;\n }\n }\n\n return { start, end: origIdx };\n}\n","/**\n * `formatter` — output formatting utilities for tool results.\n *\n * Wraps code, diffs, file lists, errors, and truncated output references.\n */\n\n/**\n * Wrap code in a fenced code block with language tag.\n */\nexport function formatCode(language: string, code: string): string {\n return `\\`\\`\\`${language}\\n${code}\\n\\`\\`\\``;\n}\n\n/**\n * Format a unified diff with +/- prefixes preserved.\n */\nexport function formatDiff(diff: string): string {\n return `\\`\\`\\`diff\\n${diff}\\n\\`\\`\\``;\n}\n\n/**\n * Format a list of file paths as a bulleted markdown list.\n */\nexport function formatFileList(files: string[]): string {\n if (files.length === 0) return \"(no files)\";\n return files.map((f) => `- ${f}`).join(\"\\n\");\n}\n\n/**\n * Format an error message as a markdown block.\n */\nexport function formatError(message: string, code?: string): string {\n const prefix = code ? `[${code}] ` : \"\";\n return `> **Error:** ${prefix}${message}`;\n}\n\n/**\n * Format a truncated output reference.\n */\nexport function formatTruncated(overflowPath: string): string {\n return `...full output at: ${overflowPath}`;\n}\n","/**\n * Shared subprocess-watch helpers for built-in coding tools (git-diff,\n * run-vitest). Wires the on(close)/on(error) settle pattern in a single\n * place to eliminate the cross-file clone flagged by jscpd.\n *\n * @internal\n */\n\nimport type { ChildProcess } from \"node:child_process\";\n\n/**\n * Settle gate — guarantees the supplied callback fires exactly once across\n * the close/error/timeout race. Clears the timer on settle.\n */\ninterface SettleGate {\n /** True after first settle; subsequent calls are no-ops. */\n settled: () => boolean;\n /** Settle the gate, clear the timer, and call `onSettle()`. */\n fire: (onSettle: () => void) => void;\n}\n\nfunction createSettleGate(timer: NodeJS.Timeout): SettleGate {\n let done = false;\n return {\n settled: () => done,\n fire: (onSettle) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n onSettle();\n },\n };\n}\n\n/**\n * Wire SIGKILL-on-timeout for a detached process group. Returns the settle\n * gate so caller listeners can short-circuit when the timeout already fired.\n */\nexport function armTimeoutKill<T>(\n child: ChildProcess,\n timeoutMs: number,\n onTimeout: () => T,\n resolve: (value: T) => void,\n): SettleGate {\n const timer = setTimeout(() => {\n gate.fire(() => {\n try {\n process.kill(-(child.pid ?? 0), \"SIGKILL\");\n } catch {\n /* already dead */\n }\n resolve(onTimeout());\n });\n }, timeoutMs);\n const gate = createSettleGate(timer);\n return gate;\n}\n\n/**\n * Attach a close+error pair of listeners that resolve via the supplied\n * callbacks. Honors the gate so timeout-vs-close races settle exactly once.\n */\nexport function attachChildSettlers<T>(\n child: ChildProcess,\n gate: SettleGate,\n onClose: (code: number | null) => T,\n onError: (err: Error) => T,\n resolve: (value: T) => void,\n): void {\n child.on(\"close\", (code) => {\n gate.fire(() => resolve(onClose(code)));\n });\n child.on(\"error\", (err) => {\n gate.fire(() => resolve(onError(err)));\n });\n}\n","/**\n * `git` execution for tools — the engine shared by `git_diff` and `git_status`.\n *\n * M76 — promoted from `git-diff.ts`, where it was private. Duplicating it in `git-status` would duplicate\n * KNOWLEDGE: the stdout ceiling, the process-group kill on timeout and the mapping to a typed\n * typed error are the SAME rule for any git subcommand. Two copies would diverge at the first\n * fix, and the symptom would be one tool with a timeout and another that hangs the turn.\n */\nimport { spawn } from \"node:child_process\";\n\nimport { armTimeoutKill, attachChildSettlers } from \"../subprocess.js\";\n\n/** POSIX quoting for the command crossing the sandbox shell. Shared by git_diff and git_status. */\nexport function shq(arg: string): string {\n return `'${arg.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nexport function formatGitResult(result: GitProcessResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n }\n if (result.kind === \"error\") {\n return JSON.stringify({ ok: false, error: \"git_failed\", stderr: result.stderr });\n }\n return JSON.stringify({ ok: true, diff: result.stdout, truncated: result.truncated });\n}\n\ntype GitProcessResult =\n | { kind: \"ok\"; stdout: string; truncated: boolean }\n | { kind: \"error\"; stderr: string }\n | { kind: \"timeout\" };\n\nexport function runGitProcess(\n cwd: string,\n args: string[],\n timeoutMs: number,\n maxStdoutBytes: number,\n): Promise<GitProcessResult> {\n return new Promise((resolve) => {\n // Detached process group so we can kill the whole tree on timeout (EC-7).\n const child = spawn(\"git\", args, { cwd, detached: true, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n let truncated = false;\n\n const gate = armTimeoutKill<GitProcessResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n resolve,\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stdoutBytes >= maxStdoutBytes) {\n truncated = true;\n return;\n }\n const remaining = maxStdoutBytes - stdoutBytes;\n if (chunk.length > remaining) {\n stdoutChunks.push(chunk.subarray(0, remaining));\n stdoutBytes = maxStdoutBytes;\n truncated = true;\n } else {\n stdoutChunks.push(chunk);\n stdoutBytes += chunk.length;\n }\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk);\n });\n\n attachChildSettlers<GitProcessResult>(\n child,\n gate,\n (code) => {\n const stdout = Buffer.concat(stdoutChunks).toString(\"utf-8\");\n const stderr = Buffer.concat(stderrChunks).toString(\"utf-8\");\n return code === 0 ? { kind: \"ok\", stdout, truncated } : { kind: \"error\", stderr };\n },\n (err) => ({ kind: \"error\", stderr: err.message }),\n resolve,\n );\n });\n}\n","/**\n * Shared `safePathJoin + assertNoSymlinkEscape` helper for built-in coding\n * tools (git-diff, run-vitest, list-dir, read-file, search-text). Returns a\n * pre-formatted `path_traversal` JSON string on failure or `null` on pass.\n *\n * @internal\n */\n\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nexport function checkPathScope(path: string | undefined, projectRoot: string): string | null {\n if (path === undefined || path === \"\") return null;\n try {\n const abs = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(abs, projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\n/**\n * Segments that may never appear in a path honored by `allowAbsolute`.\n *\n * M76 — promoted from `read-file.ts`, where it was private. Duplicating it in `list-dir` would duplicate\n * security KNOWLEDGE: the copies would have to agree on what counts as a secret, and one fixed\n * sem a outra reabre o buraco na tool esquecida.\n */\nconst SEGMENTOS_SENSIVEIS = new Set([\".env\", \".git\", \"node_modules\", \".theo\"]);\n\n/**\n * ANY-segment secret guard — the half of `allowAbsolute` that cannot be separated.\n *\n * `isForbiddenPath` only blocks the sensitive item when it is the FIRST segment (relative to the\n * project). An absolute path (`/home/u/proj/.env/sub`) puts it deeper, and it would pass. This one\n * checks every segment, closing the \"reads-anywhere\" exfiltration.\n */\nexport function ehProibidoEmQualquerProfundidade(path: string): boolean {\n const segs = path.replace(/\\\\/g, \"/\").split(\"/\").filter(Boolean);\n return segs.some((s) => {\n if (s === \".env.example\") return false; // template — seguro\n return SEGMENTOS_SENSIVEIS.has(s) || /^\\.env\\./.test(s);\n });\n}\n","/**\n * `git_diff` — built-in tool for coding agents.\n *\n * Returns the unified diff of the working tree (or staged changes when\n * `cached=true`). Implemented as a thin `git diff` subprocess wrapper\n * with a couple of hard limits:\n *\n * - 30s wall clock timeout (kills the process group on expiry)\n * - 5 MB stdout cap (truncate + flag `truncated=true`)\n * - Path scope validated through `safePathJoin` + `assertNoSymlinkEscape`\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, diff: string, truncated?: boolean }`\n * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' }`\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { resolveSandbox, type SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { formatGitResult, runGitProcess, shq } from \"./internal/git-exec.js\";\nimport { checkPathScope } from \"./path-scope.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_STDOUT_BYTES = 5 * 1024 * 1024;\n\nexport interface CreateGitDiffToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n timeoutMs?: number;\n maxStdoutBytes?: number;\n /** Optional injected execution backend (`@theokit/sdk/sandbox`) — when provided, `git diff` runs via\n * `SandboxBackend.execute` (surface-agnostic); omitted ⇒ the local `git` child process (unchanged). */\n sandbox?: SandboxProvider;\n}\n\n/** POSIX single-quote a `git diff` argument for the backend command string (safe against metacharacters). */\n\n/** Run `git diff` through an injected SandboxBackend, mapping its result to git_diff's JSON shape. The\n * scope check (pure security) still applies; the local `.git` existsSync check does not (the repo is in\n * the backend — a non-repo surfaces as git's own \"not a git repository\"). */\nasync function diffViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n cached: boolean | undefined,\n path: string | undefined,\n projectRoot: string,\n timeoutMs: number,\n): Promise<string> {\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n const command = [\"git\", ...buildDiffArgs(cached, path)].map(shq).join(\" \");\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n if (r.timedOut) return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n if (r.exitCode !== 0) {\n return /not a git repository/i.test(r.stderr)\n ? JSON.stringify({ ok: false, error: \"not_a_repo\" })\n : JSON.stringify({ ok: false, error: \"git_failed\", stderr: r.stderr });\n }\n return JSON.stringify({ ok: true, diff: r.stdout, truncated: false });\n}\n\nexport function createGitDiffTool(opts: CreateGitDiffToolOptions): CustomTool {\n const {\n projectRoot,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES,\n sandbox,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"git_diff\",\n description:\n opts.description ??\n \"Return the unified diff of the project's working tree (or staged \" +\n \"changes when cached=true). Scoped to a single file when 'path' is \" +\n \"provided. Requires the project to be a git repository. Returns \" +\n \"{ ok, diff, truncated? } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().optional().describe(\"Optional project-relative file or dir scope.\"),\n cached: z\n .boolean()\n .optional()\n .describe(\"If true, show staged changes (git diff --cached). Default false.\"),\n }),\n handler: async ({ path, cached }, ctx) => {\n // Injected backend (surface-agnostic) ⇒ run in the sandbox; absent ⇒ the local `git` (unchanged).\n if (sandbox !== undefined) {\n return diffViaSandbox(sandbox, ctx, cached, path, projectRoot, timeoutMs);\n }\n\n // Local path — UNCHANGED (byte-identical to before).\n if (!existsSync(join(projectRoot, \".git\"))) {\n return JSON.stringify({ ok: false, error: \"not_a_repo\" });\n }\n\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n\n const args = buildDiffArgs(cached, path);\n const result = await runGitProcess(projectRoot, args, timeoutMs, maxStdoutBytes);\n return formatGitResult(result, timeoutMs);\n },\n });\n}\n\nfunction buildDiffArgs(cached: boolean | undefined, path: string | undefined): string[] {\n const args = [\"diff\", \"--no-color\"];\n if (cached === true) args.push(\"--cached\");\n if (path !== undefined && path !== \"\") args.push(\"--\", path);\n return args;\n}\n","/**\n * `git_status` — built-in tool for coding agents.\n *\n * Returns the working-tree status in porcelain v1 format (`git status --porcelain`), which is the\n * stable machine-readable form — the human format is explicitly not guaranteed across git versions.\n *\n * M76 — born alongside `git_diff` and sharing the execution engine (`internal/git-exec.ts`): the stdout\n * ceiling, process-group kill on timeout and mapping to a typed error are the SAME rule\n * for any git subcommand. The consumer (agent-builder) had this locally in 62 LoC; nothing there\n * was specific to it.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, diff: string, truncated?: boolean }` — `diff` carries the porcelain output\n * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' | 'git_failed' }`\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport type { SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { resolveSandbox } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { formatGitResult, runGitProcess, shq } from \"./internal/git-exec.js\";\n\nimport { checkPathScope } from \"./path-scope.js\";\n\nexport interface CreateGitStatusToolOptions {\n /** Absolute path to the project root. Every invocation is gated against this boundary. */\n projectRoot: string;\n /** Wall-clock cap; the process group is killed on expiry. Default 30_000. */\n timeoutMs?: number;\n /** Cap on captured stdout; excess sets `truncated: true`. Default 5 MB. */\n maxStdoutBytes?: number;\n /**\n * Injected execution backend (`@theokit/sdk/sandbox`) — when present, `git status` runs via\n * `SandboxBackend.execute`; omitido ⇒ o `git` local (inalterado).\n *\n * Symmetry with `createGitDiffTool`, flagged by the M76 review: without it `git_diff` would run\n * confined and `git_status` not, in the same session — and the asymmetry would be invisible until someone\n * perceber que uma das duas escapa do sandbox.\n */\n sandbox?: SandboxProvider;\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ `\"git_status\"` (aditivo).\n *\n * The name is a contract: the approval key, what the model sees and what telemetry records.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => the literal below (additive). */\n description?: string;\n /**\n * Include the branch line (`-b`) at the start of the output. Default `true`.\n *\n * Without it the agent sees what changed but not WHERE — and \"am I on the right branch?\" is the question that\n * precedes any commit. The consumer (agent-builder) already depended on it; omitting it would make the\n * migration lose behavior silently, which is what deleting local code must not cost.\n */\n includeBranch?: boolean;\n}\n\nexport function createGitStatusTool(opts: CreateGitStatusToolOptions): CustomTool {\n const { projectRoot, timeoutMs = 30_000, maxStdoutBytes = 5 * 1024 * 1024 } = opts;\n\n return Tool.create({\n name: opts.name ?? \"git_status\",\n description:\n opts.description ??\n \"Show the working-tree status in porcelain format: staged, unstaged and untracked paths, one \" +\n \"per line with a two-character status code. Use before committing, or to see what changed \" +\n \"without reading the full diff. Optional 'path' scopes the report to a subdirectory.\",\n inputSchema: z.object({\n path: z\n .string()\n .optional()\n .describe(\"Optional project-relative path to scope the status report.\"),\n }),\n handler: async ({ path }, ctx) => {\n // Outside a repository, `git status` writes to stderr and exits non-zero. Returning an empty string\n // here would be worse than an error: the model would read it as \"no changes\" — indistinguishable from\n // the happy path, and false. `error-handling.md` § 2 requires a typed error.\n if (!existsSync(join(projectRoot, \".git\"))) {\n return JSON.stringify({ ok: false, error: \"not_a_repo\" });\n }\n\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n\n const args = buildArgs(path, opts.includeBranch !== false);\n\n if (opts.sandbox !== undefined) {\n return statusViaSandbox(opts.sandbox, ctx, args, timeoutMs);\n }\n const result = await runGitProcess(projectRoot, args, timeoutMs, maxStdoutBytes);\n return formatGitResult(result, timeoutMs);\n },\n });\n}\n\n/**\n * Os argumentos do `git status`.\n *\n * `--porcelain=v1` is deliberate: it is the stable contract for machine reading. The human format\n * changes across git versions and would break the consumer's parsing without warning.\n */\nfunction buildArgs(path: string | undefined, withBranch: boolean): string[] {\n const args = [\"status\", \"--porcelain=v1\"];\n if (withBranch) args.push(\"-b\");\n if (path !== undefined && path !== \"\") args.push(\"--\", path);\n return args;\n}\n\n/**\n * `git status` via `SandboxBackend` — the surface-agnostic path, mirroring `diffViaSandbox`.\n *\n * It exists for symmetry with `git_diff`: without it, in a confined session the diff would run inside the\n * sandbox and the status outside — and the asymmetry would be invisible until someone noticed one of the two escapes.\n */\nasync function statusViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n args: string[],\n timeoutMs: number,\n): Promise<string> {\n const command = [\"git\", ...args].map(shq).join(\" \");\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n if (r.timedOut) return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n if (r.exitCode !== 0) {\n return /not a git repository/i.test(r.stderr)\n ? JSON.stringify({ ok: false, error: \"not_a_repo\" })\n : JSON.stringify({ ok: false, error: \"git_failed\", stderr: r.stderr });\n }\n return JSON.stringify({ ok: true, diff: r.stdout, truncated: false });\n}\n","/**\n * `glob_files` — built-in tool for coding agents.\n *\n * Lists project files matching a glob pattern. Excludes node_modules,\n * .git, and dist by default. Returns relative paths.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, files: string[], count }` (an empty match is `ok: true` with `files: []`)\n * - `{ ok: false, error: 'path_traversal' }`\n */\n\nimport { readdir } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type FilesystemBackend,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\n/** Directories excluded from traversal by default. */\nconst DEFAULT_EXCLUDES = new Set([\"node_modules\", \".git\", \"dist\", \".theo\"]);\n\n/**\n * Depth cap for the BACKEND walk only. The local `readdir(withFileTypes)` walk skips symlinks (a\n * symlink entry is neither `isDirectory()` nor `isFile()`), so it can never loop. The backend walk\n * decides type via `stat`, which follows symlinks, so an in-boundary symlink cycle (e.g. `a → .`)\n * would recurse until the path exceeds PATH_MAX. This bound stops that pathological case; real project\n * trees never approach it.\n */\nconst MAX_BACKEND_WALK_DEPTH = 64;\n\nexport interface CreateGlobToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. */\n projectRoot: string;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the walk reads through the\n * backend (Local/remote), so the tool is surface-agnostic; omitted ⇒ the local `readdir` (unchanged). */\n filesystem?: FilesystemProvider;\n}\n\nexport function createGlobTool(opts: CreateGlobToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"glob_files\",\n description:\n opts.description ??\n \"Find files by glob pattern across the project — fast at any repo size. Use glob_files when \" +\n \"you know the filename SHAPE; use search_text when you know the file CONTENT; use read_file \" +\n \"when you know the exact path. The pattern supports * and ** wildcards (e.g. '**/*.ts', \" +\n \"'src/**/*.json'); node_modules/.git/dist/.theo are excluded and results are relative paths. \" +\n \"Returns { ok, files } or { ok: false, error }.\",\n inputSchema: z.object({\n pattern: z.string().min(1).describe(\"Glob pattern (e.g. '**/*.ts', 'src/**/*.json').\"),\n cwd: z.string().optional().describe(\"Project-relative subdirectory to search from.\"),\n }),\n handler: async ({ pattern, cwd }, ctx) => {\n // Path-scope guard (pure security) applies to both fs paths.\n const scopeErr = globScopeError(cwd, projectRoot);\n if (scopeErr !== null) return scopeErr;\n const regex = globToRegex(pattern);\n\n // Injected filesystem (surface-agnostic): walk via the backend in PROJECT-RELATIVE path space\n // (like read_file); absent ⇒ the local `readdir` walk (byte-identical to before).\n if (filesystem !== undefined) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n const searchRel = cwd ?? \"\";\n const found: string[] = [];\n await walkDirBackend(backend, searchRel, searchRel, regex, found, 0);\n return JSON.stringify({ ok: true, files: found.sort(), count: found.length });\n }\n\n const searchRoot = cwd ? safePathJoin(projectRoot, cwd) : projectRoot;\n const files: string[] = [];\n await walkDir(searchRoot, searchRoot, regex, files);\n const relativePaths = files.map((f) => relative(projectRoot, f)).sort();\n return JSON.stringify({ ok: true, files: relativePaths, count: relativePaths.length });\n },\n });\n}\n\n/** Shared cwd path-scope guard — returns an error JSON string, or null when the scope is safe. */\nfunction globScopeError(cwd: string | undefined, projectRoot: string): string | null {\n if (!cwd) return null;\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, cwd), projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path: cwd });\n }\n throw err;\n }\n}\n\nasync function walkDir(\n base: string,\n dir: string,\n pattern: RegExp,\n results: string[],\n): Promise<void> {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return; // directory doesn't exist or unreadable\n }\n\n for (const entry of entries) {\n if (DEFAULT_EXCLUDES.has(entry.name)) continue;\n\n const fullPath = join(dir, entry.name);\n const relPath = relative(base, fullPath);\n\n if (entry.isDirectory()) {\n await walkDir(base, fullPath, pattern, results);\n } else if (entry.isFile() && pattern.test(relPath)) {\n results.push(fullPath);\n }\n }\n}\n\n/** Backend walk (surface-agnostic): mirrors {@link walkDir} in PROJECT-RELATIVE path space via\n * `backend.list` + `backend.stat` (the FilesystemBackend interface returns untyped names, so a\n * `stat` per entry supplies isDirectory/isFile). Collects project-relative paths. */\nasync function walkDirBackend(\n backend: FilesystemBackend,\n base: string,\n dir: string,\n pattern: RegExp,\n results: string[],\n depth: number,\n): Promise<void> {\n if (depth > MAX_BACKEND_WALK_DEPTH) return; // symlink-cycle guard (see MAX_BACKEND_WALK_DEPTH)\n let names: string[];\n try {\n names = await backend.list(dir);\n } catch {\n return; // directory doesn't exist or unreadable\n }\n for (const name of names) {\n await walkBackendEntry(backend, base, dir, name, pattern, results, depth);\n }\n}\n\n/** Handle one backend directory entry: stat it, recurse on dirs, collect matching files. */\nasync function walkBackendEntry(\n backend: FilesystemBackend,\n base: string,\n dir: string,\n name: string,\n pattern: RegExp,\n results: string[],\n depth: number,\n): Promise<void> {\n if (DEFAULT_EXCLUDES.has(name)) return;\n const fullRel = dir === \"\" ? name : `${dir}/${name}`;\n const relPath = base === \"\" ? fullRel : relative(base, fullRel);\n let st: { isDirectory: boolean; isFile: boolean };\n try {\n st = await backend.stat(fullRel);\n } catch {\n return;\n }\n if (st.isDirectory) {\n await walkDirBackend(backend, base, fullRel, pattern, results, depth + 1);\n } else if (st.isFile && pattern.test(relPath)) {\n results.push(fullRel);\n }\n}\n\n/** Convert a simple glob pattern to a RegExp. Supports * and ** wildcards. */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: parser logic\nfunction globToRegex(pattern: string): RegExp {\n let regexStr = \"\";\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i]!;\n if (ch === \"*\" && pattern[i + 1] === \"*\") {\n // ** matches any path segment(s)\n regexStr += \".*\";\n i += 2;\n if (pattern[i] === \"/\") i++; // skip trailing slash after **\n } else if (ch === \"*\") {\n // * matches anything except /\n regexStr += \"[^/]*\";\n i++;\n } else if (ch === \"?\") {\n regexStr += \"[^/]\";\n i++;\n // biome-ignore lint/suspicious/noTemplateCurlyInString: regex escape chars, not template\n } else if (\".+^${}()|[]\\\\\".includes(ch)) {\n regexStr += `\\\\${ch}`;\n i++;\n } else {\n regexStr += ch;\n i++;\n }\n }\n return new RegExp(`^${regexStr}$`);\n}\n","/**\n * `interactive_shell` + `write_stdin` — built-in tools for driving an interactive\n * session (a REPL, `git rebase -i`, any command that PROMPTS for stdin).\n *\n * Surface-agnostic by construction: both tools depend on an INJECTED\n * `InteractiveProvider` (`@theokit/sdk/interactive`) exactly as `read_file`\n * depends on `FilesystemProvider`. The HOST supplies the backend — a local\n * `@theokit/sdk-pty` (terminal), a container/E2B backend (cluster/web), or a\n * Tauri backend (desktop) — so the SAME tool runs on every theokit surface with\n * NO native dependency here. When no backend is injected (or it cannot allocate\n * a session) the tool returns `{ ok: false, error: 'interactive_unavailable' }`\n * and the agent falls back to non-interactive exec.\n *\n * Return shapes (always a JSON string):\n * interactive_shell → `{ ok: true, session_id, output }` | `{ ok: false, error }`\n * write_stdin → `{ ok: true, output, alive }` | `{ ok: false, error }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type InteractiveProvider,\n InteractiveUnavailableError,\n NoSuchSessionError,\n resolveInteractive,\n} from \"@theokit/sdk/interactive\";\nimport { z } from \"zod\";\n\nexport interface CreateInteractiveShellToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** The interactive backend, or a per-request resolver of one (injected — never a direct native dep). */\n interactive: InteractiveProvider<unknown>;\n}\n\n/** Map the SDK's typed interactive errors to the tool's `{ ok: false, error }` JSON. Re-throws anything\n * else (a real bug), per the sdk-tools \"JSON on user mistakes, throw on SDK bugs\" contract. */\n/**\n * U-2 — a session cap carries `max` and `liveSessionIds`, and those are the only fields the model\n * can act on: without them \"interactive_unavailable\" cannot be told apart from a missing backend,\n * and the obvious remedy (reuse one of the open sessions) is invisible.\n *\n * Checked STRUCTURALLY rather than with `instanceof`. The class that raises it lives in\n * `@theokit/sdk-pty`, which this package does not depend on and should not — and the tool accepts an\n * INJECTED backend, so any provider reporting the same two fields deserves the same treatment.\n */\nfunction capFields(err: object): { max: number; liveSessionIds: readonly string[] } | undefined {\n const e = err as { max?: unknown; liveSessionIds?: unknown };\n if (typeof e.max !== \"number\") return undefined;\n if (!Array.isArray(e.liveSessionIds)) return undefined;\n if (!e.liveSessionIds.every((id) => typeof id === \"string\")) return undefined;\n return { max: e.max, liveSessionIds: e.liveSessionIds as readonly string[] };\n}\n\nfunction toErrorJson(err: unknown): string {\n // Before the superclass branch: `MaxSessionsError extends InteractiveUnavailableError`, so\n // matching the parent first flattened the subclass and dropped what made it actionable.\n if (typeof err === \"object\" && err !== null) {\n const cap = capFields(err);\n if (cap !== undefined) {\n return JSON.stringify({\n ok: false,\n error: \"interactive_session_limit\",\n max: cap.max,\n live_session_ids: [...cap.liveSessionIds],\n message: (err as { message?: unknown }).message,\n });\n }\n }\n if (err instanceof InteractiveUnavailableError) {\n return JSON.stringify({ ok: false, error: \"interactive_unavailable\" });\n }\n if (err instanceof NoSuchSessionError) {\n return JSON.stringify({ ok: false, error: \"no_such_session\" });\n }\n throw err;\n}\n\n/** Start an interactive session; returns a `session_id` to drive with `write_stdin`. */\nexport function createInteractiveShellTool(opts: CreateInteractiveShellToolOptions): CustomTool {\n const { interactive } = opts;\n return Tool.create({\n name: opts.name ?? \"interactive_shell\",\n description:\n opts.description ??\n \"Start an interactive shell session for a command that PROMPTS for input or is a REPL \" +\n \"(python, node, `git rebase -i`, a `read` prompt) — NOT for one-shot commands (use shell_exec). \" +\n \"Returns a session_id; drive it with write_stdin, reading the incremental output each step. \" +\n \"Returns { ok, session_id, output } or { ok: false, error }.\",\n inputSchema: z.object({\n command: z\n .string()\n .min(1)\n .describe(\"Command to run interactively, e.g. 'python3' or 'bash -i'.\"),\n yield_time_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"How long to wait for startup output before returning (clamped by the backend).\"),\n }),\n handler: async ({ command, yield_time_ms }, ctx) => {\n try {\n const backend = await resolveInteractive(interactive, ctx ?? {});\n const { sessionId, output } = await backend.startInteractive(command, {\n yieldMs: yield_time_ms,\n });\n return JSON.stringify({ ok: true, session_id: sessionId, output });\n } catch (err) {\n return toErrorJson(err);\n }\n },\n });\n}\n\n/** Write to a live interactive session's stdin and read the output it produces. */\nexport function createWriteStdinTool(opts: CreateInteractiveShellToolOptions): CustomTool {\n const { interactive } = opts;\n return Tool.create({\n name: \"write_stdin\",\n description:\n \"Write input to a live interactive session (from interactive_shell) and read the output it \" +\n \"produces during the wait window. Include a trailing newline to submit a line. Returns \" +\n \"{ ok, output, alive } (alive:false means the session exited) or { ok: false, error }.\",\n inputSchema: z.object({\n session_id: z.string().min(1).describe(\"The session_id returned by interactive_shell.\"),\n input: z.string().describe(\"Text to write to stdin (add a trailing '\\\\n' to submit a line).\"),\n yield_time_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"How long to wait for output before returning (clamped by the backend).\"),\n }),\n handler: async ({ session_id, input, yield_time_ms }, ctx) => {\n try {\n const backend = await resolveInteractive(interactive, ctx ?? {});\n const { output, alive } = await backend.writeStdin(session_id, input, {\n yieldMs: yield_time_ms,\n });\n return JSON.stringify({ ok: true, output, alive });\n } catch (err) {\n return toErrorJson(err);\n }\n },\n });\n}\n","/**\n * Catastrophic-command guardrail for `shell_exec` (M3-2; hardened V3-1).\n *\n * `catastrophicShellReason` is a pure, segment-aware deny-list ported from\n * theocode's security-reviewed `shell-guard.ts` (the proven spec: 42-blocked +\n * 24-allowed corpus, 0 misses / 0 false-positives). It splits a command on shell\n * separators (`;`, `&&`, `||`, `|`, `&`, newline), inspects EVERY segment (so a\n * chained `rm -rf <safe>; rm -rf /` cannot hide), and matches at COMMAND POSITION\n * (the executable, not an arbitrary substring) so a mention like `echo \"rm -rf /\"`\n * is not over-blocked. Returns a human reason for the first catastrophic segment,\n * else `null`.\n *\n * Categories: recursive-force `rm` of an absolute/home/parent path; destructive git\n * (force-push, `reset --hard`, `clean -fd`); remote-code-execution (curl/wget piped\n * OR command-substitution `$( )` / `<( )` / eval / source); disk/raw-device wipe\n * (mkfs, `dd of=/dev/`, `truncate /dev/`, `> /dev/<blockdev>`); recursive chmod/chown\n * of a root path (SDK extra); fork bomb; `find -delete` / `-exec rm`; secret-file\n * exfiltration over the network.\n *\n * This is a heuristic GUARDRAIL, NOT a sandbox: it is bypassable by deep obfuscation\n * (base64/env-indirection) and is best-effort. POSIX `/bin/sh` only; Windows\n * PowerShell is out of scope. True isolation needs a container.\n * referencia: .claude/knowledge-base/references/theocode-shell-guard/server-lib/shell-guard.ts\n */\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\n/** Thrown / reported when a command matches the catastrophic deny-list. */\nexport class CatastrophicCommandError extends ConfigurationError {\n override readonly name = \"CatastrophicCommandError\";\n constructor(reason: string) {\n super(`Refused a catastrophic shell command: ${reason} (shell guardrail).`, {\n code: \"catastrophic_command\",\n });\n }\n}\n\n/** Strip a single layer of surrounding quotes from a token (so `\"/\"` -> `/`). */\nfunction unquote(token: string): string {\n return token.replace(/^(['\"])(.*)\\1$/, \"$2\").replace(/^['\"]|['\"]$/g, \"\");\n}\n\n/**\n * Split a command line into statement segments on shell separators\n * (`;`, `&&`, `||`, `|`, `&`, newline). The rm screen inspects EVERY segment (C1).\n * Quote-aware splitting is out of scope (a guardrail, not a parser).\n */\nfunction commandSegments(command: string): string[] {\n return command\n .split(/&&|\\|\\||[;|&\\n]/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/** Arg tokens of a segment whose command is `name` (after an optional `sudo`); `null` otherwise. */\nfunction commandArgs(segment: string, name: string): string[] | null {\n const tokens = segment.split(/\\s+/);\n let i = 0;\n if (tokens[i] === \"sudo\") i += 1;\n if (tokens[i] !== name) return null; // must be the COMMAND, not a substring/arg\n return tokens.slice(i + 1);\n}\n\n/** Every segment whose command is `name` -> its arg list. */\nfunction commandSegmentsNamed(command: string, name: string): string[][] {\n return commandSegments(command)\n .map((s) => commandArgs(s, name))\n .filter((args): args is string[] => args !== null);\n}\n\n/** Does an arg list carry BOTH a recursive and a force flag, in ANY position/spelling? */\nfunction isRecursiveForce(args: string[]): boolean {\n const flags = args.filter((t) => t.startsWith(\"-\")).join(\" \");\n if (flags.length === 0) return false;\n const recursive = /-[a-z]*r/i.test(flags) || /--recursive/.test(flags);\n const force = /-[a-z]*f/i.test(flags) || /--force/.test(flags);\n return recursive && force;\n}\n\n/** Does an arg list carry a recursive flag (for chmod/chown -R)? */\nfunction isRecursive(args: string[]): boolean {\n const flags = args.filter((t) => t.startsWith(\"-\")).join(\" \");\n return /-[a-z]*r/i.test(flags) || /--recursive/.test(flags);\n}\n\n/** Absolute paths that are safe to recursively delete (scratch/throwaway). */\nconst SAFE_ABSOLUTE_TARGET = /^\\/(tmp|var\\/tmp)(\\/|$)/;\n\n/** True when an arg list targets root, home, `$HOME`, an absolute path, or `..`. */\nfunction targetsDangerousPath(args: string[]): boolean {\n const targets = args.filter((token) => token.length > 0 && !token.startsWith(\"-\")).map(unquote);\n return targets.some((raw) => {\n const t = raw.replace(/\\/+/g, \"/\"); // collapse `//` -> `/` (SDK extra)\n if (t === \"/dev/null\" || SAFE_ABSOLUTE_TARGET.test(t)) return false;\n return (\n /^\\/($|\\*)/.test(t) || // \"/\" or \"/*\"\n /^\\/[^/]/.test(t) || // an absolute path like /etc, /usr/local, /home/user/x\n t === \"~\" ||\n t.startsWith(\"~/\") ||\n /\\$\\{?HOME\\b\\}?/.test(t) || // $HOME or ${HOME}\n t === \"..\" ||\n t.startsWith(\"../\") ||\n t.includes(\"/..\") ||\n t === \"*\"\n );\n });\n}\n\n/** mkfs / dd-to-device / truncate-device / redirect-to-blockdev (families incl. SDK extras). */\nconst DEVICE_WIPE = [\n /\\bmkfs(\\.\\w+)?\\b/,\n /\\bdd\\b[^\\n]*\\bof=\\/dev\\//,\n /\\btruncate\\b[^\\n]*\\s\\/dev\\//,\n />\\s*\\/dev\\/(sd|nvme|hd|vd|mmcblk|disk|loop|dm-)/,\n];\n\n/** A single catastrophic-category screen: returns a reason or `null`. */\ntype CategoryCheck = (cmd: string) => string | null;\n\n/** Remote code execution: a remote download fed into an interpreter (pipe / `$( )` / `<( )` / eval / source). */\nconst checkRemoteExec: CategoryCheck = (cmd) =>\n /\\b(curl|wget|fetch)\\b[^\\n]*\\|\\s*(sudo\\s+)?(sh|bash|zsh|dash|python[0-9.]*|node|ruby|perl)\\b/i.test(\n cmd,\n ) ||\n /(\\$\\(|<\\()\\s*(sudo\\s+)?(curl|wget|fetch)\\b/i.test(cmd) ||\n /\\b(eval|source)\\b[^\\n]*\\b(curl|wget|fetch)\\b/i.test(cmd)\n ? \"executes a remote download (pipe / command-substitution / eval) — remote code execution\"\n : null;\n\n/** Disk / raw block-device wipe (mkfs, dd-to-device, truncate-device, redirect-to-blockdev). */\nconst checkDeviceWipe: CategoryCheck = (cmd) =>\n DEVICE_WIPE.some((re) => re.test(cmd)) ? \"writes to a raw block device / formats a disk\" : null;\n\n/** Fork bomb. */\nconst checkForkBomb: CategoryCheck = (cmd) =>\n /:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:/.test(cmd) ? \"fork bomb\" : null;\n\n/** Destructive git: force-push (NOT --force-with-lease), hard reset, aggressive clean. */\nconst checkDestructiveGit: CategoryCheck = (cmd) => {\n if (/\\bgit\\b[^\\n]*\\bpush\\b[^\\n]*(--force(?!-with-lease)\\b|\\s-f\\b|\\s\\+\\S)/.test(cmd)) {\n return \"git force-push (overwrites remote history)\";\n }\n if (/\\bgit\\b[^\\n]*\\breset\\b[^\\n]*--hard\\b/.test(cmd)) {\n return \"git reset --hard (discards committed and working changes)\";\n }\n if (/\\bgit\\b[^\\n]*\\bclean\\b[^\\n]*(-[a-z]*f[a-z]*d|-[a-z]*d[a-z]*f)/.test(cmd)) {\n return \"git clean -fd (permanently deletes untracked files)\";\n }\n return null;\n};\n\n/** Recursive force-delete of a path outside the workspace — checked on EVERY rm segment (C1). */\nconst checkRm: CategoryCheck = (cmd) =>\n commandSegmentsNamed(cmd, \"rm\").some((a) => isRecursiveForce(a) && targetsDangerousPath(a))\n ? \"recursive force-delete of an absolute, home, or parent path\"\n : null;\n\n/** Recursive chmod/chown of a root/home/parent path (SDK extra — not in theocode). */\nconst checkPerm: CategoryCheck = (cmd) =>\n ([\"chmod\", \"chown\"] as const).some((name) =>\n commandSegmentsNamed(cmd, name).some((a) => isRecursive(a) && targetsDangerousPath(a)),\n )\n ? \"recursive permission change on an absolute, home, or parent path\"\n : null;\n\n/** find with -delete / -exec rm targeting an absolute or home root. */\nconst checkFind: CategoryCheck = (cmd) =>\n /\\bfind\\s+(\\/\\S*|~\\S*|\\$\\{?HOME\\}?\\S*)\\s[^\\n]*(-delete\\b|-exec\\s+rm\\b)/.test(cmd)\n ? \"find -delete / -exec rm on an absolute or home path\"\n : null;\n\n/** Exfiltration: a secret/credential file referenced together with a network sender. */\nconst checkExfiltration: CategoryCheck = (cmd) => {\n const touchesSecret =\n /(^|[\\s/'\"])(\\.env(\\.\\w+)?|id_rsa|id_ed25519|\\.ssh(\\/|\\b)|credentials|\\.aws(\\/|\\b)|\\.npmrc)\\b/.test(\n cmd,\n );\n const sendsNetwork =\n /\\b(curl|wget|nc|netcat|scp|ftp|telnet)\\b/.test(cmd) || /\\bpython[0-9.]*\\s+-m\\s+http/.test(cmd);\n return touchesSecret && sendsNetwork\n ? \"sends a secret/credential file over the network (exfiltration)\"\n : null;\n};\n\nconst CATEGORY_CHECKS: readonly CategoryCheck[] = [\n checkRemoteExec,\n checkDeviceWipe,\n checkForkBomb,\n checkDestructiveGit,\n checkRm,\n checkPerm,\n checkFind,\n checkExfiltration,\n];\n\n/**\n * Return a human-readable reason when `command` is catastrophic/irreversible, or `null`.\n * The message is surfaced to the model so it self-corrects.\n */\nexport function catastrophicShellReason(command: string): string | null {\n const cmd = command.trim();\n if (cmd.length === 0) return null;\n for (const check of CATEGORY_CHECKS) {\n const reason = check(cmd);\n if (reason) return reason;\n }\n return null;\n}\n","/**\n * Composable command-permission policy layer (M3-6).\n *\n * A `CommandPolicy` is a pure predicate returning a deny REASON (or `null` to\n * allow). `denyCatastrophicCommands()` COMPOSES the M3-2 `catastrophicShellReason`\n * guardrail (it does not duplicate the deny-list). `commandDenialReason` combines\n * a policy array with deny-wins semantics (the first policy returning a reason\n * denies); an empty array denies nothing. `isCommandAllowed` is the boolean view.\n *\n * Framework-agnostic: a consumer wires it at their permission layer — e.g. inside\n * an ACP `pre_tool_call` hook — `@theokit/agents` is not required. Inherits the\n * M3-2 honesty: a heuristic gate, not a sandbox. Design: blueprint m3-command-policy.\n */\n\nimport { catastrophicShellReason } from \"./shell-guard.js\";\n\n/**\n * A pure command-permission predicate: returns a non-empty deny reason, or `null`\n * to allow. NOTE: return `null` to allow — NOT `\"\"`. An empty string is treated\n * as a deny with a blank reason (`\"\" !== null`), which is almost never intended.\n */\nexport type CommandPolicy = (command: string) => string | null;\n\n/** A policy that denies catastrophic commands by composing the M3-2 guardrail. */\nexport function denyCatastrophicCommands(): CommandPolicy {\n return (command) => catastrophicShellReason(command);\n}\n\n/**\n * The first deny reason across `policies` (deny-wins), or `null` if every policy\n * allows. An empty `policies` array denies nothing (returns `null`).\n */\nexport function commandDenialReason(command: string, policies: CommandPolicy[]): string | null {\n for (const policy of policies) {\n const reason = policy(command);\n if (reason !== null) return reason;\n }\n return null;\n}\n\n/** `true` when no policy denies `command` (an empty policy array allows everything). */\nexport function isCommandAllowed(command: string, policies: CommandPolicy[]): boolean {\n return commandDenialReason(command, policies) === null;\n}\n","/**\n * SSRF guard for network tools (M3-1).\n *\n * `isBlockedIp` is a pure block-list of the canonical private/loopback/link-local/\n * CGNAT/metadata/reserved ranges (IPv4 + IPv6, with IPv4-mapped unwrap).\n * `resolveAndScreen` resolves ALL of a host's addresses and rejects if any is\n * blocked. `screenedFetch` fetches with `redirect:\"manual\"` and re-screens every\n * hop. `lookup`/`fetchImpl` are injectable so the DNS + redirect paths are\n * deterministically testable without real network access.\n *\n * Design: blueprint m3-ssrf-guard ADRs D1-D6. Node builtins only (zero new deps).\n */\n\nimport { lookup as dnsLookup } from \"node:dns/promises\";\nimport { isIP } from \"node:net\";\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\n/** Thrown when a host/redirect resolves to a blocked (private/reserved) address. */\nexport class SsrfBlockedError extends ConfigurationError {\n override readonly name = \"SsrfBlockedError\";\n constructor(host: string, detail?: string) {\n super(\n `Blocked request to \"${host}\"${detail ? ` (${detail})` : \"\"}: address is private, loopback, link-local, or reserved (SSRF guard).`,\n { code: \"ssrf_blocked\" },\n );\n }\n}\n\n/**\n * Thrown when a request is refused by the REDIRECT policy (the `maxRedirects` hop limit was\n * exceeded) — a distinct event from {@link SsrfBlockedError} (a blocked host). With `maxRedirects: 0`\n * this fires on the first 3xx (block-all-redirects). Carries `code: \"redirect_blocked\"`.\n */\nexport class RedirectBlockedError extends ConfigurationError {\n override readonly name = \"RedirectBlockedError\";\n constructor(url: string, detail?: string) {\n super(\n `Blocked redirect for \"${url}\"${detail ? ` (${detail})` : \"\"}: redirect-hop limit exceeded (redirect policy).`,\n { code: \"redirect_blocked\" },\n );\n }\n}\n\n/** Parse an IPv4 dotted-quad to a 32-bit unsigned integer (assumes a valid literal). */\nfunction v4ToInt(ip: string): number {\n const parts = ip.split(\".\");\n return (\n ((Number(parts[0]) << 24) |\n (Number(parts[1]) << 16) |\n (Number(parts[2]) << 8) |\n Number(parts[3])) >>>\n 0\n );\n}\n\n/** True if the IPv4 address (as int) falls inside `base/prefix`. */\nfunction inV4Cidr(ipInt: number, base: string, prefix: number): boolean {\n const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;\n return (ipInt & mask) === (v4ToInt(base) & mask);\n}\n\nconst V4_BLOCKED: ReadonlyArray<readonly [string, number]> = [\n [\"0.0.0.0\", 8], // \"this host\"\n [\"10.0.0.0\", 8], // private\n [\"100.64.0.0\", 10], // CGNAT\n [\"127.0.0.0\", 8], // loopback\n [\"169.254.0.0\", 16], // link-local + cloud metadata\n [\"172.16.0.0\", 12], // private\n [\"192.168.0.0\", 16], // private\n [\"224.0.0.0\", 4], // multicast\n [\"240.0.0.0\", 4], // reserved\n];\n\nfunction isBlockedV4(ip: string): boolean {\n const n = v4ToInt(ip);\n return V4_BLOCKED.some(([base, prefix]) => inV4Cidr(n, base, prefix));\n}\n\n/** Fold a trailing dotted-quad (`…:1.2.3.4`) into two hex hextets; `null` if invalid. */\nfunction foldDottedTail(s: string): string | null {\n const lastColon = s.lastIndexOf(\":\");\n const tail = s.slice(lastColon + 1);\n if (!tail.includes(\".\")) return s;\n if (isIP(tail) !== 4) return null;\n const o = tail.split(\".\").map(Number);\n const hi = (((o[0] as number) << 8) | (o[1] as number)).toString(16);\n const lo = (((o[2] as number) << 8) | (o[3] as number)).toString(16);\n return `${s.slice(0, lastColon + 1)}${hi}:${lo}`;\n}\n\n/** Expand a (validated) IPv6 string to exactly 8 hextet strings; `null` if malformed. */\nfunction expandHextets(s: string): string[] | null {\n const halves = s.split(\"::\");\n if (halves.length > 2) return null;\n const head = halves[0] ? halves[0].split(\":\") : [];\n const tailGroups = halves.length === 2 && halves[1] ? halves[1].split(\":\") : [];\n if (halves.length === 1) return head.length === 8 ? head : null;\n const missing = 8 - head.length - tailGroups.length;\n if (missing < 0) return null;\n return [...head, ...Array(missing).fill(\"0\"), ...tailGroups];\n}\n\n/**\n * Expand a (net.isIP-validated) IPv6 literal to its 16 bytes. Handles `::`\n * compression and a trailing dotted-quad (`::ffff:1.2.3.4`). Returns `null` if it\n * cannot be parsed (caller then fails closed).\n */\nfunction ipv6ToBytes(ip: string): number[] | null {\n const folded = foldDottedTail(ip.toLowerCase().split(\"%\")[0] ?? \"\");\n if (folded === null) return null;\n const groups = expandHextets(folded);\n if (groups === null || groups.length !== 8) return null;\n const bytes: number[] = [];\n for (const g of groups) {\n const n = Number.parseInt(g || \"0\", 16);\n bytes.push(n >> 8, n & 0xff);\n }\n return bytes;\n}\n\nfunction allZero(bytes: number[], from: number, to: number): boolean {\n for (let i = from; i < to; i += 1) if (bytes[i] !== 0) return false;\n return true;\n}\n\n/** Numeric IPv6 classification over the parsed 16 bytes (no string-prefix guesswork). */\nfunction isBlockedV6Bytes(b: number[]): boolean {\n // IPv4-mapped (::ffff:a.b.c.d, any spelling) → re-check the embedded IPv4.\n if (allZero(b, 0, 10) && b[10] === 0xff && b[11] === 0xff) {\n return isBlockedV4(`${b[12]}.${b[13]}.${b[14]}.${b[15]}`);\n }\n // ::1 loopback and :: unspecified.\n if (allZero(b, 0, 15) && (b[15] === 1 || b[15] === 0)) return true;\n // IPv4-compatible (deprecated) ::a.b.c.d → re-check embedded IPv4.\n if (allZero(b, 0, 12)) return isBlockedV4(`${b[12]}.${b[13]}.${b[14]}.${b[15]}`);\n // fe80::/10 link-local.\n if (b[0] === 0xfe && ((b[1] as number) & 0xc0) === 0x80) return true;\n // fc00::/7 unique-local.\n return ((b[0] as number) & 0xfe) === 0xfc;\n}\n\n/**\n * True if `ip` is a blocked address (private/loopback/link-local/CGNAT/metadata/\n * reserved). A non-IP literal returns `true` (fail closed — callers resolve names\n * to IPs first via {@link resolveAndScreen}).\n */\nexport function isBlockedIp(ip: string): boolean {\n const fam = isIP(ip);\n if (fam === 4) return isBlockedV4(ip);\n if (fam === 6) {\n const bytes = ipv6ToBytes(ip);\n return bytes === null ? true : isBlockedV6Bytes(bytes);\n }\n return true;\n}\n\ntype LookupFn = (host: string, opts: { all: true }) => Promise<Array<{ address: string }>>;\n\n/** Options for {@link resolveAndScreen}. */\nexport interface ResolveAndScreenOptions {\n /** DNS resolver (injectable for tests); defaults to `node:dns/promises` lookup. */\n lookup?: LookupFn;\n}\n\n/**\n * Resolve `host` to ALL its addresses and screen each. Throws {@link SsrfBlockedError}\n * if any resolved address is blocked (or if `host` is a blocked IP literal, or if\n * resolution yields no address). Returns the resolved IPs otherwise.\n */\nexport async function resolveAndScreen(\n rawHost: string,\n options: ResolveAndScreenOptions = {},\n): Promise<string[]> {\n // `URL.hostname` wraps IPv6 literals in brackets (`[::1]`) — strip them so\n // `net.isIP` recognizes the address.\n const host = rawHost.replace(/^\\[|\\]$/g, \"\");\n if (isIP(host) !== 0) {\n if (isBlockedIp(host)) throw new SsrfBlockedError(host);\n return [host];\n }\n const lookup = options.lookup ?? (dnsLookup as unknown as LookupFn);\n const addrs = await lookup(host, { all: true });\n if (addrs.length === 0) throw new SsrfBlockedError(host, \"no addresses\");\n for (const a of addrs) {\n if (isBlockedIp(a.address)) throw new SsrfBlockedError(host, a.address);\n }\n return addrs.map((a) => a.address);\n}\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise<Response>;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * The next URL to follow for a redirect response, or `undefined` if `res` is not a\n * followable redirect. Throws {@link SsrfBlockedError} for a non-http(s) target.\n */\nfunction redirectTarget(res: Response, current: string, originalUrl: string): string | undefined {\n const location = res.headers.get(\"location\");\n if (!REDIRECT_STATUSES.has(res.status) || !location) return undefined;\n const next = new URL(location, current);\n if (next.protocol !== \"http:\" && next.protocol !== \"https:\") {\n throw new SsrfBlockedError(originalUrl, `non-http redirect to ${next.protocol}`);\n }\n return next.href;\n}\n\n/** Options for {@link screenedFetch}. */\nexport interface ScreenedFetchOptions {\n /** Fetch implementation (injectable for tests); defaults to global `fetch`. */\n fetchImpl?: FetchFn;\n /** DNS resolver (injectable for tests). */\n lookup?: LookupFn;\n /** Max redirect hops to follow (default 5). */\n maxRedirects?: number;\n /** Skip SSRF screening entirely (opt-out for local-dev tools). Default false. */\n allowPrivateHosts?: boolean;\n /** Abort signal forwarded to fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * Fetch `url` with SSRF screening: screens the host (unless `allowPrivateHosts`),\n * sets `redirect:\"manual\"`, and re-screens every redirect hop (rejecting a hop to a\n * blocked host or a non-http(s) target). Throws {@link SsrfBlockedError} on a block\n * or on exceeding `maxRedirects`.\n */\nexport async function screenedFetch(\n url: string,\n options: ScreenedFetchOptions = {},\n): Promise<Response> {\n const fetchImpl = options.fetchImpl ?? (fetch as FetchFn);\n const maxRedirects = options.maxRedirects ?? 5;\n let current = url;\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n if (!options.allowPrivateHosts) {\n await resolveAndScreen(new URL(current).hostname, { lookup: options.lookup });\n }\n const res = await fetchImpl(current, { redirect: \"manual\", signal: options.signal });\n const next = redirectTarget(res, current, url);\n if (next === undefined) return res;\n current = next;\n }\n throw new RedirectBlockedError(url, \"too many redirects\");\n}\n","/**\n * Repo-map / env-context builders for orienting an LLM coding agent (M3-3).\n *\n * `buildEnvContext(cwd)` renders a short `<env>` block (cwd, platform, node,\n * is-git, date, project docs, manifests). `buildRepoMap(cwd, opts)` renders a\n * char-bounded, depth-limited directory tree. Both are node:fs-only and NEVER\n * throw — a missing/unreadable path yields a best-effort partial string or an\n * `(unavailable)` marker (distinct from the M3-1/M3-2 guards, which throw).\n *\n * Design: blueprint m3-repo-map. Zero new dependencies. A best-effort\n * orientation aid, not a complete or secure listing (bounded + skips on error).\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RepoMapOptions {\n /** Max characters of tree output before truncation. Default 8000. */\n budget?: number;\n /** Directory/file names to skip (merged with the built-in ignore set). */\n ignore?: string[];\n /** Max directory depth to descend. Default 4. */\n maxDepth?: number;\n}\n\nconst DEFAULT_BUDGET = 8000;\nconst DEFAULT_MAX_DEPTH = 4;\nconst PER_DIR_CAP = 200;\nconst TRUNCATED_MARKER = \"… (truncated)\";\nconst DOC_HEAD_CHARS = 200;\nconst DEFAULT_REPO_MAP_IGNORE = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \".theo\",\n \".next\",\n \"build\",\n \"coverage\",\n \"target\",\n \"out\",\n];\nconst PROJECT_DOCS = [\"AGENTS.md\", \"CLAUDE.md\", \"README.md\"];\nconst MANIFESTS = [\"package.json\", \"pyproject.toml\", \"Cargo.toml\", \"go.mod\"];\n\nfunction safeExists(p: string): boolean {\n try {\n return existsSync(p);\n } catch {\n return false;\n }\n}\n\nfunction safeReadHead(p: string, n: number): string {\n try {\n return readFileSync(p, \"utf-8\").slice(0, n).replace(/\\s+/g, \" \").trim();\n } catch {\n return \"\";\n }\n}\n\nexport interface EnvContextOptions {\n /** Injectable clock for the date line (deterministic tests). Default `new Date()`. */\n now?: Date;\n /** Path to the git `HEAD` file. Default `<cwd>/.git/HEAD`. */\n gitHeadPath?: string;\n}\n\n/**\n * Read the current git branch from `HEAD` — a PURE file read (never a\n * `child_process` spawn, which could hang the request path or expose\n * arg-injection). Returns `undefined` for a detached HEAD, a missing file,\n * or any read error. Borrowed from theocode's `project-context.ts`.\n */\nfunction gitBranch(headPath: string): string | undefined {\n try {\n const head = readFileSync(headPath, \"utf-8\").trim();\n const match = head.match(/^ref:\\s*refs\\/heads\\/(.+)$/);\n return match ? match[1] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Render a portable `<env>` orientation block. Never throws. */\nexport function buildEnvContext(cwd: string, opts: EnvContextOptions = {}): string {\n const lines = [\n \"<env>\",\n ` Working directory: ${cwd}`,\n ` Platform: ${process.platform} (${process.arch})`,\n ` Node: ${process.version}`,\n ` Is git repo: ${safeExists(join(cwd, \".git\")) ? \"yes\" : \"no\"}`,\n ];\n const branch = gitBranch(opts.gitHeadPath ?? join(cwd, \".git\", \"HEAD\"));\n if (branch) lines.push(` Branch: ${branch}`);\n lines.push(` Today's date: ${(opts.now ?? new Date()).toDateString()}`);\n const docs = PROJECT_DOCS.filter((d) => safeExists(join(cwd, d)));\n if (docs.length > 0) {\n lines.push(` Project docs: ${docs.join(\", \")}`);\n const head = safeReadHead(join(cwd, docs[0] as string), DOC_HEAD_CHARS);\n if (head) lines.push(` ${docs[0]} (head): ${head}`);\n }\n const manifests = MANIFESTS.filter((m) => safeExists(join(cwd, m)));\n if (manifests.length > 0) lines.push(` Manifests: ${manifests.join(\", \")}`);\n lines.push(\"</env>\");\n return lines.join(\"\\n\");\n}\n\n/** dirs-first, then alphabetical. Symlinks count as leaves (not followed). */\nfunction compareEntries(a: Dirent, b: Dirent): number {\n const ad = a.isDirectory() ? 0 : 1;\n const bd = b.isDirectory() ? 0 : 1;\n return ad !== bd ? ad - bd : a.name.localeCompare(b.name);\n}\n\nfunction visibleEntries(dir: string, ignore: Set<string>): Dirent[] {\n let entries: Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries.filter((e) => !ignore.has(e.name) && !e.name.startsWith(\".\")).sort(compareEntries);\n}\n\ninterface WalkCtx {\n ignore: Set<string>;\n maxDepth: number;\n budget: number;\n lines: string[];\n used: number;\n truncated: boolean;\n}\n\n/** Append a line if it fits the budget; flag truncation and return false otherwise. */\nfunction pushLine(ctx: WalkCtx, line: string): boolean {\n if (ctx.used + line.length + 1 > ctx.budget) {\n ctx.truncated = true;\n return false;\n }\n ctx.lines.push(line);\n ctx.used += line.length + 1;\n return true;\n}\n\n/** Emit one entry (and recurse into a real sub-dir). Returns false when budget is hit. */\nfunction emitEntry(ctx: WalkCtx, dir: string, e: Dirent, depth: number, indent: string): boolean {\n const isDir = e.isDirectory(); // symlink-to-dir → false → treated as a leaf, not followed\n if (!pushLine(ctx, `${indent}${isDir ? `${e.name}/` : e.name}`)) return false;\n if (isDir && depth + 1 < ctx.maxDepth) return walkDir(ctx, join(dir, e.name), depth + 1);\n return true;\n}\n\nfunction walkDir(ctx: WalkCtx, dir: string, depth: number): boolean {\n const entries = visibleEntries(dir, ctx.ignore);\n const shown = entries.slice(0, PER_DIR_CAP);\n const indent = \" \".repeat(depth);\n for (const e of shown) {\n if (!emitEntry(ctx, dir, e, depth, indent)) return false;\n }\n if (entries.length > shown.length) {\n return pushLine(ctx, `${indent}… (${entries.length - shown.length} more)`);\n }\n return true;\n}\n\n/** Render a char-bounded, depth-limited directory tree. Never throws. */\nexport function buildRepoMap(cwd: string, opts: RepoMapOptions = {}): string {\n try {\n if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {\n return `(unavailable: ${cwd} is not a readable directory)`;\n }\n } catch {\n return `(unavailable: ${cwd})`;\n }\n\n const ctx: WalkCtx = {\n ignore: new Set([...DEFAULT_REPO_MAP_IGNORE, ...(opts.ignore ?? [])]),\n maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH,\n budget: opts.budget ?? DEFAULT_BUDGET,\n lines: [],\n used: 0,\n truncated: false,\n };\n walkDir(ctx, cwd, 0);\n return ctx.truncated ? `${ctx.lines.join(\"\\n\")}\\n${TRUNCATED_MARKER}` : ctx.lines.join(\"\\n\");\n}\n","/**\n * ACI (Agent-Computer Interface) helpers for tools (M3-5).\n *\n * `withDescription(tool, description)` immutably overrides a tool's LLM-facing\n * description (the wording that drives tool-selection accuracy) — returning a\n * NEW `CustomTool` and leaving the original untouched. `renderToolList(tools)`\n * renders a `<tools>` block FROM THE SAME `CustomTool[]` the agent runs, so the\n * rendered list cannot drift from the real tools (single source of truth).\n *\n * Both are pure, zero-dependency, and never throw. The `<tools>` block is a\n * system-prompt orientation aid — NOT the provider tool-call schema (that stays\n * each tool's `inputSchema`). Design: blueprint m3-aci-tools.\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\n/**\n * Return a new `CustomTool` with `description` replaced. Preserves\n * name/inputSchema/handler; does NOT mutate the original tool.\n */\nexport function withDescription(tool: CustomTool, description: string): CustomTool {\n return {\n name: tool.name,\n description,\n inputSchema: tool.inputSchema,\n handler: tool.handler,\n };\n}\n\n/**\n * Return a new `CustomTool` exposed under a different `name`, sharing the SAME\n * `inputSchema` + `handler` (alias parity). Preserves description; does NOT mutate\n * the original. This is how an agent exposes a built-in under its preferred name —\n * e.g. a Codex-style agent aliases `search_text` → `grep`, `shell_exec` → `run_shell`\n * — without re-implementing the tool. Pure, never throws: the final `name` is\n * validated by the SDK at tool-registration time (the single authority for the\n * `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$` + reserved-name rules), so this helper does not\n * re-validate (no duplicated contract).\n */\nexport function withName(tool: CustomTool, name: string): CustomTool {\n return {\n name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: tool.handler,\n };\n}\n\n/** XML-escape for the `<tools>` block. `&` MUST be replaced first (no double-escape). */\nfunction esc(s: string): string {\n // String() guards the never-throw contract against an untyped/`as any` caller\n // passing a non-string name/description.\n return String(s).replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n\n/** Render mode for {@link renderToolList}. Local — the published `renderToolList`\n * signature inlines this union into its `.d.ts`, so consumers pass the literal\n * (\"summary\" | \"names\" | \"full\") without needing the named type exported. */\ntype ToolListMode = \"full\" | \"summary\" | \"names\";\n\n/**\n * Extract the first sentence of a description, abbreviation-safe: a period is\n * only a sentence boundary when followed by whitespace + a capital/paren/EOF, so\n * `e.g.`, `i.e.`, `vs.` do NOT split. Falls back to the whole (trimmed) string.\n */\nfunction firstSentence(d: string): string {\n const m = d.trim().match(/\\.\\s+(?=[A-Z(]|$)/);\n return m?.index == null ? d.trim() : d.trim().slice(0, m.index + 1);\n}\n\n/**\n * Render the agent's actual `CustomTool[]` — single source of truth, so an\n * overridden/added/removed tool is reflected automatically. Never throws.\n *\n * Modes (`options.mode`, default `\"full\"`):\n * - `\"full\"`: a `<tools>` XML block (name + description per tool, XML-escaped).\n * An empty array yields `<tools></tools>`.\n * - `\"summary\"`: markdown `- name: <first sentence>` per tool (NOT XML-escaped).\n * - `\"names\"`: markdown `- name` per tool (NOT XML-escaped).\n *\n * Markdown modes on an empty array yield `\"\"`. A non-object `options` arg (e.g. a\n * map index from `tools.map(renderToolList)`) has no `.mode` → falls back to `\"full\"`.\n */\nexport function renderToolList(tools: CustomTool[], options?: { mode?: ToolListMode }): string {\n const mode = options?.mode ?? \"full\";\n if (mode === \"summary\") {\n return tools.map((t) => `- ${t.name}: ${firstSentence(t.description)}`).join(\"\\n\");\n }\n if (mode === \"names\") {\n return tools.map((t) => `- ${t.name}`).join(\"\\n\");\n }\n if (tools.length === 0) return \"<tools></tools>\";\n const lines = [\"<tools>\"];\n for (const t of tools) {\n lines.push(\n \" <tool>\",\n ` <name>${esc(t.name)}</name>`,\n ` <description>${esc(t.description)}</description>`,\n \" </tool>\",\n );\n }\n lines.push(\"</tools>\");\n return lines.join(\"\\n\");\n}\n","/**\n * Rich-error guidance for tool failures (M3-4).\n *\n * `withToolResultGuidance(tool, guidance)` wraps a `CustomTool` so a failing\n * `{ ok: false, error }` JSON result gains an LLM-actionable `guidance` string\n * telling the model how to self-correct. The injection is ADDITIVE (only on\n * `ok:false`), IDEMPOTENT (never overwrites an existing `guidance`), and\n * NEVER-THROW (a non-JSON / non-object / `ok:true` / unknown-code result is\n * returned unchanged). Composes over the existing built-in tools (and custom\n * tools) — no factory edits required.\n *\n * Design: blueprint m3-rich-errors. Zero new dependencies (JSON transform).\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\n/** Maps a tool error code to a short, LLM-actionable self-correction hint. */\nexport type ToolGuidanceMap = Record<string, string>;\n\n/** Curated hints for the common cross-tool error codes. Consumers may extend. */\nexport const DEFAULT_TOOL_GUIDANCE: ToolGuidanceMap = {\n not_found:\n \"The path does not exist. Use `list_dir` or `glob_files` to find the correct path, then retry.\",\n path_traversal: \"That path escapes the project root. Use a path inside the project directory.\",\n forbidden_path:\n \"That path is a protected file (.env, .git, lock files, etc.). Choose a different, non-sensitive path.\",\n no_match:\n \"The search text was not found verbatim. Re-read the file with `read_file` and copy the exact text (including whitespace/indentation) before editing.\",\n timeout: \"The operation timed out. Narrow the scope or pass a larger `timeout_ms`.\",\n invalid_url: \"The URL is malformed. Provide a full absolute http(s):// URL.\",\n ssrf_blocked: \"That host is private/loopback/reserved and is blocked. Use a public URL.\",\n catastrophic_command:\n \"That command is blocked as catastrophic. Use a safer, scoped command (e.g. a relative path instead of `/`).\",\n binary_file: \"The file is binary and cannot be read as text. Use a tool suited to binary data.\",\n too_large:\n \"The target is too large to process directly. Use a bounded range or a narrower scope.\",\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Pure: parse a tool handler's JSON output and ADD a `guidance` hint when the\n * result is an `{ ok: false, error }` object whose code has a hint and that does\n * not already carry guidance. Any other input is returned UNCHANGED (never throws).\n */\nexport function injectGuidance(handlerOutput: string, guidance: ToolGuidanceMap): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(handlerOutput);\n } catch {\n return handlerOutput; // non-JSON tool output → passthrough\n }\n if (!isRecord(parsed) || parsed.ok !== false) return handlerOutput;\n if (\"guidance\" in parsed) return handlerOutput; // idempotent — never touch an existing key\n const code = parsed.error;\n if (typeof code !== \"string\") return handlerOutput;\n const hint = guidance[code];\n if (!hint) return handlerOutput; // unknown code → no guidance\n return JSON.stringify({ ...parsed, guidance: hint });\n}\n\n/**\n * Wrap a `CustomTool` so its failed results gain a `guidance` hint from `guidance`.\n * Preserves name/description/inputSchema; only the handler output is augmented.\n */\nexport function withToolResultGuidance(tool: CustomTool, guidance: ToolGuidanceMap): CustomTool {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: async (input) => {\n const out = await tool.handler(input);\n // SE7 — guidance injection is a string-JSON concern; a handler returning\n // structured content blocks passes through untouched.\n return typeof out === \"string\" ? injectGuidance(out, guidance) : out;\n },\n };\n}\n\n/** `withToolResultGuidance` pre-bound to {@link DEFAULT_TOOL_GUIDANCE}. */\nexport function withDefaultGuidance(tool: CustomTool): CustomTool {\n return withToolResultGuidance(tool, DEFAULT_TOOL_GUIDANCE);\n}\n\n/**\n * Wrap `shell_exec` so a SOFT failure — `{ ok: true, exit_code != 0 }` (the TOOL ran, the COMMAND\n * failed) — gains a `guidance` hint. This is the one case {@link injectGuidance} does not cover (it\n * is `ok:false`-only by design). ADDITIVE, IDEMPOTENT, NEVER-THROW; a no-op for any other tool, for\n * `exit_code 0`, and for non-JSON output. Compose AFTER {@link withDefaultGuidance} (the two domains —\n * `ok:false` vs `ok:true` soft-fail — are disjoint, so there is no double-injection).\n */\nexport function withShellExitGuidance(tool: CustomTool): CustomTool {\n if (tool.name !== \"shell_exec\") return tool;\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: async (input) => {\n const out = await tool.handler(input);\n // SE7 — structured content blocks are not JSON guidance-injectable; passthrough.\n if (typeof out !== \"string\") return out;\n let parsed: unknown;\n try {\n parsed = JSON.parse(out);\n } catch {\n return out; // non-JSON tool output → passthrough\n }\n if (\n isRecord(parsed) &&\n parsed.ok === true &&\n typeof parsed.exit_code === \"number\" &&\n parsed.exit_code !== 0 &&\n !(\"guidance\" in parsed)\n ) {\n const guidance = `The command exited ${parsed.exit_code}. Read the stderr above, fix the cause, then retry.`;\n return JSON.stringify({ ...parsed, guidance });\n }\n return out;\n },\n };\n}\n","/**\n * `list_dir` — built-in tool for coding agents.\n *\n * Returns the direct entries of a project-relative directory. Hardened\n * against the same four bug families as `read_file` plus the\n * **EC-6 unbounded output** failure mode: in a project with 10k files,\n * a naive listing returns a 5 MB JSON payload that freezes the browser\n * and (more importantly) blows past the LLM context window.\n *\n * Defaults:\n * - `max = 500` entries (override via factory option `{ max }`)\n * - Result includes `{ truncated: boolean, totalCount: number }` so the\n * agent can decide whether to drill deeper or call `search_text` instead\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, entries: Array<{ name, type }>, truncated, totalCount }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'not_found' }`\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n type FilesystemProvider,\n FilesystemSecurityError,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { ehProibidoEmQualquerProfundidade } from \"./path-scope.js\";\n\nconst DEFAULT_MAX_ENTRIES = 500;\n\nexport interface CreateListDirToolOptions {\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ o literal de hoje (aditivo).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision key —\n * three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName` remains\n * for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /**\n * M76 — opt-in \"lista-em-qualquer-lugar\": honra um `path` ABSOLUTO fora de `projectRoot`\n * (paridade com `createReadFileTool`/`createSearchTextTool`, sandbox read-only do Codex).\n *\n * The ANY-segment secret guard still applies, and is not separable: `isForbiddenPath`\n * only blocks the sensitive item when it is the FIRST segment, so a `/home/u/proj/.env/sub`\n * would pass. Enabling the flag without the guard opens exfiltration. Default `false` => absolute rejected.\n */\n allowAbsolute?: boolean;\n /** Absolute path to the project root. Every listing is gated against this boundary. */\n projectRoot: string;\n /** Maximum number of entries returned per call. Default 500. */\n max?: number;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver. When provided, listings route through the backend\n * (its own boundary + `basePath`) instead of the local `projectRoot`; omitted\n * ⇒ identical current behavior (multi-tenant / per-request roots).\n */\n filesystem?: FilesystemProvider;\n}\n\nexport function createListDirTool(opts: CreateListDirToolOptions): CustomTool {\n const { projectRoot, max = DEFAULT_MAX_ENTRIES, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"list_dir\",\n description:\n opts.description ??\n `Return the direct entries of a project-relative directory. ` +\n `Refuses paths outside the project root or in the sensitive-file ` +\n `blocklist (.env, .git/, node_modules/, .theo/, lock files). Caps ` +\n `at ${String(max)} entries by default; result carries truncated + totalCount.`,\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative directory path. Use '.' for root.\"),\n }),\n handler: async ({ path }, ctx) => {\n const relative = path === \"\" || path === \".\" ? \".\" : path;\n const verdict = decidirEscopo(relative, path, opts.allowAbsolute === true);\n if (verdict.error !== undefined) return verdict.error;\n if (verdict.absoluteRoot !== undefined) {\n return listViaLocalFs(verdict.absoluteRoot, \".\", path, max);\n }\n // SE31 — route through the pluggable backend when one is configured; else\n // the local `projectRoot` fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return listViaBackend(backend, relative, path, max);\n }\n return listViaLocalFs(projectRoot, relative, path, max);\n },\n });\n}\n\n/**\n * `list_dir`'s scope decision, separated from the handler.\n *\n * Extracted because the SDK's complexity gate separated it for us — and it was right: DECIDING whether the\n * path may be read is the part with a security consequence, and deserves to be read alone. The handler\n * merely orchestrates afterwards.\n *\n * Returns `{ error }` when the path is refused, `{ absoluteRoot }` when it is an honored absolute, or\n * `{}` for the usual relative case.\n */\nfunction decidirEscopo(\n relative: string,\n original: string,\n allowAbsolute: boolean,\n): { error?: string; absoluteRoot?: string } {\n const refuse = (error: string): { error: string } => ({\n error: JSON.stringify({ ok: false, error, path: original }),\n });\n\n if (relative !== \".\" && isForbiddenPath(relative)) return refuse(\"forbidden_path\");\n if (!isAbsolute(relative)) return {};\n\n // M76 — absolute only with opt-in, and ALWAYS with the per-segment guard: `isForbiddenPath` above only looks at\n // the FIRST segment, so a `/home/u/proj/.env/sub` would slip past it.\n if (!allowAbsolute) return refuse(\"path_traversal\");\n if (ehProibidoEmQualquerProfundidade(relative)) return refuse(\"forbidden_path\");\n return { absoluteRoot: relative };\n}\n\n/** Local-`projectRoot` listing: boundary + readdir + bounded format. */\nasync function listViaLocalFs(\n projectRoot: string,\n relative: string,\n originalPath: string,\n max: number,\n): Promise<string> {\n const boundary = resolveDirBoundary(relative, projectRoot, originalPath);\n if (\"error\" in boundary) return boundary.error;\n const readResult = await readDirSafe(boundary.absolutePath, originalPath);\n if (\"error\" in readResult) return readResult.error;\n return formatListing(readResult.dirents, max);\n}\n\n/**\n * SE31 — list through a {@link FilesystemBackend}. The minimal backend `list()`\n * returns names only, so each entry's type is resolved via `stat()` (bounded by\n * `max`, so an entry with a transient stat failure defaults to `file`). Typed\n * backend errors map to the tool's `{ ok: false, error }` JSON.\n */\nasync function listViaBackend(\n backend: FilesystemBackend,\n relative: string,\n originalPath: string,\n max: number,\n): Promise<string> {\n let names: string[];\n try {\n names = await backend.list(relative);\n } catch (err) {\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path: originalPath });\n }\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path: originalPath });\n }\n throw err;\n }\n const totalCount = names.length;\n const windowed = names.slice(0, max);\n const entries = await Promise.all(\n windowed.map(async (name) => {\n const child = relative === \".\" ? name : `${relative}/${name}`;\n let type: \"file\" | \"directory\" = \"file\";\n try {\n type = (await backend.stat(child)).isDirectory ? \"directory\" : \"file\";\n } catch {\n // A transient stat failure (e.g. a symlink the backend rejects) defaults\n // to `file` — the listing still returns the entry name, never crashes.\n }\n return { name, type };\n }),\n );\n return JSON.stringify({ ok: true, entries, truncated: totalCount > max, totalCount });\n}\n\nfunction resolveDirBoundary(\n relative: string,\n projectRoot: string,\n originalPath: string,\n): { absolutePath: string } | { error: string } {\n try {\n const absolutePath = relative === \".\" ? projectRoot : safePathJoin(projectRoot, relative);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n return { absolutePath };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path: originalPath }) };\n }\n throw err;\n }\n}\n\nasync function readDirSafe(\n absolutePath: string,\n originalPath: string,\n): Promise<{ dirents: Dirent[] } | { error: string }> {\n try {\n const dirents = await readdir(absolutePath, { withFileTypes: true });\n return { dirents };\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\" || e.code === \"ENOTDIR\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: originalPath }) };\n }\n throw err;\n }\n}\n\nfunction formatListing(dirents: Dirent[], max: number): string {\n const totalCount = dirents.length;\n const truncated = totalCount > max;\n const entries = dirents.slice(0, max).map((d) => ({\n name: d.name,\n type: d.isDirectory() ? (\"directory\" as const) : (\"file\" as const),\n }));\n return JSON.stringify({ ok: true, entries, truncated, totalCount });\n}\n","/**\n * `plan_mode` — tool for toggling between normal and planning mode.\n *\n * In plan mode, the agent focuses on outlining steps rather than executing them.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, mode: string, message: string }`\n * - `{ ok: false, error: \"invalid_action\" }`\n *\n * Opt-in persistence (M4-4): `createPlanModeTool({ artifactStore })` returns a\n * variant whose async handler persists the submitted `plan` on `exit`.\n */\n\nimport type { SessionArtifactStore } from \"./artifact-store.js\";\n\ntype Mode = \"normal\" | \"plan\";\n\nconst PLAN_INSTRUCTIONS = [\n \"You are now in PLAN MODE.\",\n \"Outline the steps you will take before executing any code changes.\",\n \"Number each step. Include file paths and what will change.\",\n \"Do NOT make any edits or tool calls other than reading files.\",\n \"When ready, use plan_mode with action 'exit' to return to normal mode.\",\n].join(\"\\n\");\n\nconst NORMAL_INSTRUCTIONS = \"Returned to NORMAL MODE. You may now execute changes.\";\n\nexport interface PlanModeTool {\n name: string;\n description: string;\n inputSchema: unknown;\n handler: (input: { action: string }) => string;\n /** Expose current mode for testing. */\n currentMode: () => Mode;\n}\n\n/**\n * Plan-mode tool with opt-in artifact persistence (M4-4). Same surface as\n * {@link PlanModeTool} but the handler is ASYNC (it may write to the store) and\n * accepts an optional `plan` to persist on `exit`.\n *\n * @public\n */\nexport interface PlanModeToolWithStore {\n name: string;\n description: string;\n inputSchema: unknown;\n handler: (input: { action: string; plan?: string }) => Promise<string>;\n currentMode: () => Mode;\n}\n\n/**\n * Options for the persistence-enabled {@link createPlanModeTool} overload.\n *\n * @public\n */\nexport interface PlanModeToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Store the submitted `plan` is persisted to on `exit`. */\n artifactStore: SessionArtifactStore;\n /** Artifact id under which the plan is stored. Default `\"plan\"`. */\n artifactId?: string;\n}\n\nconst DESCRIPTION =\n \"Toggle between normal and plan mode. \" +\n \"Actions: 'enter' (switch to plan mode), 'exit' (return to normal), 'status' (check current mode). \" +\n \"Returns { ok, mode, message }.\";\n\nfunction planModeSchema(withPlan: boolean): unknown {\n const properties: Record<string, unknown> = {\n action: {\n type: \"string\",\n enum: [\"enter\", \"exit\", \"status\"],\n description: \"The action to perform.\",\n },\n };\n if (withPlan) {\n properties.plan = {\n type: \"string\",\n description: \"On 'exit', the plan text to persist to the artifact store.\",\n };\n }\n return { type: \"object\" as const, properties, required: [\"action\"] };\n}\n\nfunction renderMode(action: string, mode: Mode): string | undefined {\n switch (action) {\n case \"enter\":\n return JSON.stringify({ ok: true, mode, message: PLAN_INSTRUCTIONS });\n case \"exit\":\n return JSON.stringify({ ok: true, mode, message: NORMAL_INSTRUCTIONS });\n case \"status\":\n return JSON.stringify({ ok: true, mode, message: `Current mode: ${mode}` });\n default:\n return undefined;\n }\n}\n\nfunction invalidAction(action: string): string {\n return JSON.stringify({\n ok: false,\n error: \"invalid_action\",\n message: `Unknown action '${action}'. Valid: enter, exit, status.`,\n });\n}\n\nexport function createPlanModeTool(): PlanModeTool;\nexport function createPlanModeTool(options: PlanModeToolOptions): PlanModeToolWithStore;\nexport function createPlanModeTool(\n options?: PlanModeToolOptions,\n): PlanModeTool | PlanModeToolWithStore {\n let mode: Mode = \"normal\";\n\n if (options === undefined) {\n return {\n name: \"plan_mode\",\n description: DESCRIPTION,\n inputSchema: planModeSchema(false),\n handler: (input: { action: string }): string => {\n if (input.action === \"enter\") mode = \"plan\";\n else if (input.action === \"exit\") mode = \"normal\";\n return renderMode(input.action, mode) ?? invalidAction(input.action);\n },\n currentMode: () => mode,\n };\n }\n\n const { artifactStore, artifactId = \"plan\" } = options;\n return {\n name: options.name ?? \"plan_mode\",\n description: options.description ?? DESCRIPTION,\n inputSchema: planModeSchema(true),\n handler: async (input: { action: string; plan?: string }): Promise<string> => {\n if (input.action === \"enter\") {\n mode = \"plan\";\n return JSON.stringify({ ok: true, mode, message: PLAN_INSTRUCTIONS });\n }\n if (input.action === \"exit\") {\n mode = \"normal\";\n // Persist only a non-empty plan (EC-1); enter/status never persist (EC-2).\n if (typeof input.plan === \"string\" && input.plan.length > 0) {\n const path = await artifactStore.write(artifactId, input.plan);\n return JSON.stringify({\n ok: true,\n mode,\n message: NORMAL_INSTRUCTIONS,\n persisted: true,\n path,\n });\n }\n return JSON.stringify({ ok: true, mode, message: NORMAL_INSTRUCTIONS, persisted: false });\n }\n return renderMode(input.action, mode) ?? invalidAction(input.action);\n },\n currentMode: () => mode,\n };\n}\n","/**\n * `question` — interactive tool that asks the user a question and waits for a response.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, answer: string }`\n * - `{ ok: false, error: \"timeout\" }`\n */\n\nexport interface QuestionToolOptions {\n /**\n * Callback that presents the question to the user and resolves with the answer.\n *\n * M76 — passou a ser OPCIONAL: o asker preferencial vem do contexto da run\n * (`ctx.context.askUser`), because a value pinned here is the \"baked into each factory\" that the\n * `CustomTool.handler` aponta como o problema que `ctx.context` existe para resolver. Este campo\n * remains as a fallback, for callers building the tool with a fixed asker (backward-compatible).\n */\n askUser?: (question: string, threadId?: string) => Promise<string>;\n /**\n * Called when the question is ABANDONED (timeout or run cancellation), so the UI side can\n * release the slot. Without it the timeout leaves the question pending forever — the UI keeps showing\n * a prompt nobody is waiting on and the next question fails with \"one is already pending\".\n */\n onAbandon?: (threadId?: string) => void;\n /** Maximum time to wait for user response in ms. Default: 300_000 (5 min). */\n timeoutMs?: number;\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ `\"question\"` (aditivo).\n *\n * The consumer needed this: Codex calls the tool `request_user_input`, and without the option it\n * had to rebuild the whole object by hand — the two-cast adapter T3.3\n * eliminou.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n}\n\n/**\n * M76 — aligned with the SDK's `CustomTool`. It used to be its own interface with `inputSchema: unknown`, which\n * forced every consumer to write a cast to register the tool — and a cast does not fix a contract,\n * it only silences the compiler, turning a future signature change into a RUNTIME error.\n *\n * Narrowing was additive: the value has always been an object (`{ type: \"object\", properties, required }`\n * just below); only the declared type was loose. The handler accepts the contract's optional 2nd\n * argument (`ctx`), through which M76 now resolves the asker per session.\n */\nexport interface QuestionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n /**\n * M76 — the input is `Record<string, unknown>`, not `{ question: string }`, by CONTRAVARIANCE: a\n * handler accepting only the narrow type is not assignable to one accepting the wide type, and `CustomTool`\n * SDK declares the wide one. Declaring narrow here forced the consumer into a cast — which was\n * exactly the defect. Narrowing happens INSIDE the handler, where validation lives.\n */\n handler: (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ) => Promise<string>;\n}\n\n/**\n * Extrai o asker do contexto da run, se houver.\n *\n * `ctx.context` is `unknown` by contract — it is user data, and the SDK does not type it. A `context`\n * present but WITHOUT `askUser` (e.g. only `projectRoot`) must not be mistaken for \"an asker exists\": the\n * check is on the function, not on the object's presence.\n */\nfunction askerDoContexto(\n context: unknown,\n): ((question: string, threadId?: string) => Promise<string>) | undefined {\n if (typeof context !== \"object\" || context === null) return undefined;\n const candidato = (context as { askUser?: unknown }).askUser;\n return typeof candidato === \"function\"\n ? (candidato as (question: string, threadId?: string) => Promise<string>)\n : undefined;\n}\n\nexport function createQuestionTool(opts: QuestionToolOptions): QuestionTool {\n const timeoutMs = opts.timeoutMs ?? 300_000;\n\n return {\n name: opts.name ?? \"question\",\n description:\n opts.description ??\n \"Ask the user a question and wait for their response. \" +\n \"Use when you need clarification or confirmation before proceeding. \" +\n \"Returns { ok, answer } or { ok: false, error: 'timeout' }.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n question: { type: \"string\", description: \"The question to ask the user.\" },\n },\n required: [\"question\"],\n },\n handler: async (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ): Promise<string> => {\n // M76 — precedence: run context > factory. `ctx.threadId` identifies the session, so a\n // tool shared across sessions now scopes the asker per session instead of leaking it.\n const askUser = askerDoContexto(ctx?.context) ?? opts.askUser;\n if (askUser === undefined) {\n // NEVER a pending promise: with no asker, waiting out the 5 min timeout would stall the whole turn\n // with nobody knowing why. Typed error, immediate (`error-handling.md` § 2).\n return JSON.stringify({\n ok: false,\n error: \"no_asker\",\n message:\n \"No asker available: pass `askUser` to createQuestionTool, or provide \" +\n \"`context.askUser` via SendOptions.context.\",\n });\n }\n const timeout = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"timeout\")), timeoutMs);\n });\n\n try {\n // M76 review — the `threadId` is FORWARDED to the asker. Without it the chain ctx.threadId -> bridge\n // did not exist: the bridge always fell into the default slot and the Map had one key forever — the\n // `let pending` under another name. The capability existed; the wiring did not.\n const answer = await Promise.race([\n askUser(String(input.question ?? \"\"), ctx?.threadId),\n timeout,\n ]);\n return JSON.stringify({ ok: true, answer });\n } catch (err) {\n if (err instanceof Error && err.message === \"timeout\") {\n // M76 review (MEDIUM-1) — tells the asker the question DIED. Without it the slot stayed\n // occupied forever: the UI kept rendering an orphaned prompt, and every subsequent question\n // got \"one is already pending\" — a permanent error for something nobody awaits anymore.\n opts.onAbandon?.(ctx?.threadId);\n return JSON.stringify({\n ok: false,\n error: \"timeout\",\n message: \"User did not respond within timeout.\",\n });\n }\n throw err;\n }\n },\n };\n}\n","/**\n * `read_file` — built-in tool for coding agents.\n *\n * Reads a project-relative file as UTF-8 and returns its contents.\n * Hardened against the four bug families a coding agent normally hits:\n *\n * 1. **Path traversal** — `safePathJoin` rejects literal `..`,\n * normalised escape, absolute segments, null-byte injection.\n * 2. **Symlink escape** — `assertNoSymlinkEscape` follows the full\n * chain (and any intermediate symlinks; defence-in-depth fix v1.x).\n * 3. **Sensitive files** — `isForbiddenPath` blocks `.env*` (except\n * `.env.example`), `.git/`, `node_modules/`, `.theo/`, lock files.\n * 4. **Binary files** — null-byte check on the first 8 KB. PNG/JPEG/\n * compiled binaries return a structured `binary_file` error\n * instead of garbled UTF-8 (EC-5 from the TheoKit Studio review).\n *\n * Return shape (always a JSON string the LLM consumes):\n * - `{ ok: true, content: string }` on success\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' |\n * 'binary_file' | 'not_found' | 'too_large' }` on refusal\n *\n * The handler intentionally never throws on a \"user mistake\"\n * (traversal / forbidden / not found). Throwing reserved for SDK-side\n * mistakes that should crash the agent loop (input parse errors).\n */\n\nimport { type FileHandle, open } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n type FilesystemProvider,\n FilesystemSecurityError,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { ehProibidoEmQualquerProfundidade } from \"./path-scope.js\";\nimport type { ReadTracker } from \"./read-tracker.js\";\n\n/** Max single-file read size, in bytes. 5 MB ceiling — enough for any source file. */\nconst MAX_FILE_SIZE = 5 * 1024 * 1024;\n\n/** Byte window inspected for null bytes when deciding binary vs text. */\nconst BINARY_PROBE_BYTES = 8 * 1024;\n\nexport interface CreateReadFileToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every read is gated against this boundary. */\n projectRoot: string;\n /**\n * SE32 — optional read-before-write tracker. When provided, a successful read\n * records the file's mtime so a paired `write_file` (with\n * `requireReadBeforeWrite`) can refuse a blind or stale overwrite.\n */\n readTracker?: ReadTracker;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver. When provided, reads route through the backend (its\n * own boundary + `basePath`) instead of the local `projectRoot`; omitted ⇒\n * identical current behavior (multi-tenant / per-request roots).\n */\n filesystem?: FilesystemProvider;\n /**\n * M17 — render a `cat -n`-style numbered view (`<n>\\t<line>`) instead of raw content, so the model can\n * cite / edit by line number (Codex / Claude-Code read idiom). Default `false` ⇒ raw content (unchanged).\n */\n lineNumbers?: boolean;\n /**\n * M17 — opt-in \"reads-anywhere\" (Codex read-only sandbox): honor an ABSOLUTE `path` outside `projectRoot`\n * instead of rejecting it as traversal. The `isForbiddenPath` secret guard STILL fires first, so `.env`/\n * `.git`/lock files remain blocked. Default `false` ⇒ absolute paths rejected (unchanged). Opt-in only —\n * this widens the read boundary to the whole filesystem; enable only for a trusted local agent.\n */\n allowAbsolute?: boolean;\n}\n\n/** Sensitive path segments — secret-bearing dirs/files that must never be read at ANY depth. */\n\n/** Secret guard for both read paths — the project-relative first-segment check plus, for an honored\n * absolute path (`allowAbsolute`), an any-depth check. Returns an error JSON string, or null if safe. */\nfunction forbiddenReadError(path: string, allowAbsolute: boolean): string | null {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n if (allowAbsolute && isAbsolute(path) && ehProibidoEmQualquerProfundidade(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n return null;\n}\n\n/** Render `content` as a raw string, or a paginated `<n>\\t<line>` numbered view. Pure. */\nfunction renderView(\n content: string,\n opts: { lineNumbers?: boolean; offset?: number; limit?: number },\n): string {\n const paginated = opts.offset !== undefined || opts.limit !== undefined;\n if (!opts.lineNumbers && !paginated) return content; // default — byte-identical\n const lines = content.split(\"\\n\");\n const start = Math.max(1, opts.offset ?? 1);\n const end =\n opts.limit !== undefined ? Math.min(lines.length, start - 1 + opts.limit) : lines.length;\n const slice = lines.slice(start - 1, end);\n return opts.lineNumbers ? slice.map((l, i) => `${start + i}\\t${l}`).join(\"\\n\") : slice.join(\"\\n\");\n}\n\nexport function createReadFileTool(opts: CreateReadFileToolOptions): CustomTool {\n const { projectRoot, readTracker, filesystem, lineNumbers, allowAbsolute } = opts;\n const numbered = lineNumbers === true ? \" Returns a cat -n numbered view (`<n>\\\\t<line>`).\" : \"\";\n const abs = allowAbsolute === true ? \" Absolute paths outside the project are honored.\" : \"\";\n\n return Tool.create({\n name: opts.name ?? \"read_file\",\n description:\n opts.description ??\n \"Read a text file as UTF-8. ALWAYS read a file before you edit it (edit_file) or overwrite it \" +\n \"(write_file), so your old_string / new content matches the real bytes exactly.\" +\n numbered +\n abs +\n \" By default returns the whole file; use the optional offset (1-based first line) + limit to page \" +\n \"through a large file, or search_text to locate a symbol. Refuses sensitive files (.env, .git/, \" +\n \"node_modules/, .theo/, lock files) and \" +\n \"binary files (null byte in the first 8 KB); caps at 5 MB. Returns { ok, content, size } or \" +\n \"{ ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"File path (project-relative; absolute when allowed).\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-based first line to read (default 1).\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Max number of lines to read (default: all).\"),\n }),\n handler: async ({ path, offset, limit }, ctx) => {\n const forbidden = forbiddenReadError(path, allowAbsolute === true);\n if (forbidden !== null) return forbidden;\n const view = { lineNumbers, offset, limit };\n // SE31 — route through the pluggable backend when one is configured (the\n // backend owns its own boundary); else the local `projectRoot` fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return readViaBackend(backend, path, view, (mtimeMs) => readTracker?.record(path, mtimeMs));\n }\n const boundary = resolveBoundary(path, projectRoot, allowAbsolute === true);\n if (\"error\" in boundary) return boundary.error;\n const opened = await openHandleSafe(boundary.absolutePath, path);\n if (\"error\" in opened) return opened.error;\n try {\n return await readContent(opened.handle, path, view, (mtimeMs) =>\n readTracker?.record(path, mtimeMs),\n );\n } finally {\n await opened.handle.close();\n }\n },\n });\n}\n\n/** Render options threaded from the handler into the read paths. */\ninterface ViewOpts {\n lineNumbers?: boolean;\n offset?: number;\n limit?: number;\n}\n\n/**\n * SE31 — read through a {@link FilesystemBackend}, mapping its typed errors to\n * the tool's `{ ok: false, error }` JSON (never throws on a user mistake). The\n * binary/too-large guards mirror the local path; a null byte in the decoded\n * content flags a binary file.\n */\nasync function readViaBackend(\n backend: FilesystemBackend,\n path: string,\n view: ViewOpts,\n onRead?: (mtimeMs: number) => void,\n): Promise<string> {\n try {\n const stat = await backend.stat(path);\n if (stat.size > MAX_FILE_SIZE) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n path,\n size: stat.size,\n limit: MAX_FILE_SIZE,\n });\n }\n const raw = await backend.readFile(path);\n if (raw.includes(\"\\u0000\")) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path, size: stat.size });\n }\n onRead?.(stat.mtimeMs);\n return JSON.stringify({ ok: true, content: renderView(raw, view), size: stat.size });\n } catch (err) {\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\nfunction resolveBoundary(\n path: string,\n projectRoot: string,\n allowAbsolute: boolean,\n): { absolutePath: string } | { error: string } {\n // M17 — reads-anywhere: honor an absolute path (isForbiddenPath already ran; no projectRoot boundary).\n if (allowAbsolute && isAbsolute(path)) {\n return { absolutePath: path };\n }\n try {\n const absolutePath = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n return { absolutePath };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function openHandleSafe(\n absolutePath: string,\n path: string,\n): Promise<{ handle: FileHandle } | { error: string }> {\n try {\n const handle = await open(absolutePath, \"r\");\n return { handle };\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path }) };\n }\n throw err;\n }\n}\n\nasync function readContent(\n handle: FileHandle,\n path: string,\n view: ViewOpts,\n onRead?: (mtimeMs: number) => void,\n): Promise<string> {\n const stat = await handle.stat();\n if (stat.size > MAX_FILE_SIZE) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n path,\n size: stat.size,\n limit: MAX_FILE_SIZE,\n });\n }\n if (await isBinaryProbe(handle, Number(stat.size))) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path, size: stat.size });\n }\n const raw = await handle.readFile({ encoding: \"utf-8\" });\n // SE32 — record the mtime read-before-write compares against. This is the\n // mtime captured at `handle.stat()` above; a concurrent external write between\n // that stat and this readFile is an accepted TOCTOU (the recorded snapshot may\n // trail the delivered content by one write — same-user local context). The\n // write-side guard still catches the common \"edited after I read it\" case.\n onRead?.(stat.mtimeMs);\n return JSON.stringify({ ok: true, content: renderView(raw, view), size: stat.size });\n}\n\nasync function isBinaryProbe(handle: FileHandle, size: number): Promise<boolean> {\n const probeLen = Math.min(BINARY_PROBE_BYTES, size);\n if (probeLen <= 0) return false;\n const probe = Buffer.alloc(probeLen);\n const { bytesRead } = await handle.read(probe, 0, probeLen, 0);\n for (let i = 0; i < bytesRead; i += 1) {\n if (probe[i] === 0) return true;\n }\n return false;\n}\n","/**\n * `ReadTracker` — SE32 read-before-write safety.\n *\n * A per-run map of `path → mtimeMs` recorded whenever the read tool reads a\n * file. The write tool (with `requireReadBeforeWrite` on) consults it before an\n * overwrite: a file that was never read, or that changed on disk since it was\n * read, is refused instead of silently clobbered. Scope one tracker per run /\n * session — it is deliberately NOT a global singleton (no cross-run leak).\n *\n * @public\n */\nexport class ReadTracker {\n private readonly seen = new Map<string, number>();\n\n /** Record the mtime observed when `path` was read. */\n record(path: string, mtimeMs: number): void {\n this.seen.set(path, mtimeMs);\n }\n\n /** The mtime last recorded for `path`, or `undefined` if never read. */\n expected(path: string): number | undefined {\n return this.seen.get(path);\n }\n}\n\n/** The verdict of a read-before-write check for one write (internal). */\ntype WriteDecision = \"ok\" | \"read_required\" | \"stale\";\n\n/**\n * Decide whether a write to `path` is allowed, given the file's CURRENT on-disk\n * mtime (`null` ⇒ the file does not exist yet). Pure — no I/O.\n *\n * - absent file → `ok` (a new file cannot clobber anything)\n * - present, unread → `read_required` (must read before a blind overwrite)\n * - present, changed → `stale` (mtime differs from the read snapshot)\n * - present, unchanged → `ok`\n */\nexport function evaluateReadBeforeWrite(\n tracker: ReadTracker,\n path: string,\n currentMtimeMs: number | null,\n): WriteDecision {\n if (currentMtimeMs === null) return \"ok\";\n const recorded = tracker.expected(path);\n if (recorded === undefined) return \"read_required\";\n if (recorded !== currentMtimeMs) return \"stale\";\n return \"ok\";\n}\n","/**\n * SE37 — the public reasoning toolkit: `ReasoningTools.create()` returns a\n * `think` + `analyze` scratchpad (no-side-effect tools that echo the model's\n * structured reasoning back as an observation, so the ReAct loop feeds it\n * forward). Mirrors Anthropic's \"think\" tool + a peer's `ReasoningTools`.\n *\n * Lives in `@theokit/sdk-tools` (not core) so the full toolkit stays out of the\n * core bundle. The `reasoning: true` agent flag auto-attaches an equivalent\n * lean `think` from core; add these explicitly (`tools: [...ReasoningTools.create()]`)\n * when you want the model to reason with a scratchpad on any model.\n *\n * @public\n */\n\nimport { type CustomTool, Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\n/** Reasoning scratchpad tools. `ReasoningTools.create()` → `[think, analyze]`. */\nexport class ReasoningTools {\n private constructor() {}\n\n /** Build the tools. Pass `{ analyze: false }` for `think` only. */\n static create(opts?: { analyze?: boolean }): CustomTool[] {\n const think = Tool.create({\n name: \"think\",\n description:\n \"Use this as a scratchpad to think step by step BEFORE answering or acting. Write out your \" +\n \"reasoning for one step. Nothing else happens — it is only your private reasoning space. \" +\n \"Call it as many times as you need before the final answer.\",\n inputSchema: z.object({\n thought: z.string().min(1, \"think: `thought` must be a non-empty string.\"),\n }),\n handler: ({ thought }) => thought,\n });\n if (opts?.analyze === false) return [think];\n\n const analyze = Tool.create({\n name: \"analyze\",\n description:\n \"Analyze the result of a previous step or tool call. State what you looked at, your \" +\n \"analysis, and whether to `continue` reasoning, `validate` (double-check) your work, or \" +\n \"give the `final_answer`. Use this to catch your own mistakes before answering.\",\n inputSchema: z.object({\n title: z.string().optional(),\n result: z.string().min(1, \"analyze: `result` must describe what you are analyzing.\"),\n analysis: z.string().min(1, \"analyze: `analysis` must contain your reasoning.\"),\n next_action: z.enum([\"continue\", \"validate\", \"final_answer\"]),\n }),\n handler: ({ title, result, analysis, next_action }) =>\n `${title ? `# ${title}\\n` : \"\"}Result: ${result}\\nAnalysis: ${analysis}\\nNext: ${next_action}`,\n });\n return [think, analyze];\n }\n}\n","/**\n * `run_vitest` — built-in tool for coding agents.\n *\n * Runs vitest against an optional file/pattern scope and returns the\n * parsed JSON report. Hardened against the same subprocess failure\n * modes as `git_diff`:\n *\n * - 120s wall clock timeout (vitest can be slow on first run)\n * - Process group kill on timeout (EC-7 — defeats vitest workers as\n * grandchildren of the spawned shell)\n * - **EC-12**: vitest stdout may contain deprecation warnings BEFORE\n * the JSON payload. The parser scans line-by-line and extracts the\n * LAST valid JSON object, not the first.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, summary: { numTotalTests, numPassedTests, numFailedTests, success } }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'timeout' |\n * 'no_vitest' | 'unparseable_output' }`\n *\n * Implementation note: invokes vitest via `npx --no-install vitest`. The\n * `--no-install` avoids the agent triggering a multi-megabyte download\n * mid-turn if vitest is missing — the tool fails cleanly with\n * `no_vitest` instead.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\nimport { isForbiddenPath } from \"./internal/path-guard.js\";\nimport { checkPathScope } from \"./path-scope.js\";\nimport { armTimeoutKill, attachChildSettlers } from \"./subprocess.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst DEFAULT_MAX_STDOUT_BYTES = 10 * 1024 * 1024;\n\nexport interface CreateRunVitestToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n timeoutMs?: number;\n maxStdoutBytes?: number;\n}\n\nexport interface VitestSummary {\n numTotalTests?: number;\n numPassedTests?: number;\n numFailedTests?: number;\n success?: boolean;\n}\n\nexport function createRunVitestTool(opts: CreateRunVitestToolOptions): CustomTool {\n const {\n projectRoot,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"run_vitest\",\n description:\n opts.description ??\n \"Run the project's vitest suite, optionally scoped to a file or \" +\n \"pattern via 'path'. Returns parsed { ok, summary } or { ok: false, \" +\n \"error }. Vitest stdout warnings are stripped — the parser extracts \" +\n \"the trailing JSON report.\",\n inputSchema: z.object({\n path: z\n .string()\n .optional()\n .describe(\"Optional vitest pattern or file path (project-relative).\"),\n }),\n handler: async ({ path }) => {\n const scopeError = validateVitestScope(path, projectRoot);\n if (scopeError !== null) return scopeError;\n\n const args = [\"--no-install\", \"vitest\", \"run\", \"--reporter=json\"];\n if (path !== undefined && path !== \"\") args.push(path);\n\n const result = await runProcess(projectRoot, \"npx\", args, timeoutMs, maxStdoutBytes);\n return formatVitestResult(result, timeoutMs);\n },\n });\n}\n\nfunction validateVitestScope(path: string | undefined, projectRoot: string): string | null {\n if (path !== undefined && path !== \"\" && isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n return checkPathScope(path, projectRoot);\n}\n\nfunction formatVitestResult(result: ProcessResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n }\n if (result.kind === \"spawn_error\") {\n return JSON.stringify({ ok: false, error: \"no_vitest\", detail: result.message });\n }\n const summary = extractTrailingJson(result.stdout) as VitestSummary | null;\n if (summary === null) {\n return JSON.stringify({\n ok: false,\n error: \"unparseable_output\",\n stderrPreview: result.stderr.slice(0, 500),\n });\n }\n return JSON.stringify({ ok: true, summary });\n}\n\n/**\n * Find the LAST line in `stdout` that parses as a JSON object. Vitest\n * prepends node deprecation warnings to its JSON reporter output — if\n * we naively `JSON.parse(stdout)` we get a SyntaxError. Workaround: walk\n * lines bottom-up and return the first one that parses.\n *\n * Exported for direct unit testing without spawning vitest.\n */\nexport function extractTrailingJson(stdout: string): unknown {\n const lines = stdout.split(/\\r?\\n/);\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]!.trim();\n if (line.length === 0) continue;\n if (line[0] !== \"{\" && line[0] !== \"[\") continue;\n try {\n return JSON.parse(line) as unknown;\n } catch {\n // not valid JSON — keep looking\n }\n }\n return null;\n}\n\nfunction appendCapped(chunks: Buffer[], chunk: Buffer, current: number, cap: number): number {\n if (current >= cap) return current;\n const remaining = cap - current;\n if (chunk.length > remaining) {\n chunks.push(chunk.subarray(0, remaining));\n return cap;\n }\n chunks.push(chunk);\n return current + chunk.length;\n}\n\ntype ProcessResult =\n | { kind: \"ok\"; stdout: string; stderr: string; exitCode: number }\n | { kind: \"timeout\" }\n | { kind: \"spawn_error\"; message: string };\n\nfunction runProcess(\n cwd: string,\n command: string,\n args: string[],\n timeoutMs: number,\n maxStdoutBytes: number,\n): Promise<ProcessResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd,\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n\n const gate = armTimeoutKill<ProcessResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n resolve,\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n stdoutBytes = appendCapped(stdoutChunks, chunk, stdoutBytes, maxStdoutBytes);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk);\n });\n\n attachChildSettlers<ProcessResult>(\n child,\n gate,\n (code) => ({\n kind: \"ok\",\n stdout: Buffer.concat(stdoutChunks).toString(\"utf-8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf-8\"),\n exitCode: code ?? 0,\n }),\n (err) => ({ kind: \"spawn_error\", message: err.message }),\n resolve,\n );\n });\n}\n","/**\n * `search_text` — built-in tool for coding agents.\n *\n * Literal text search across the project tree (recursive). Sensible\n * defaults:\n *\n * - Skips forbidden directories (`.env`, `.git/`, `node_modules/`,\n * `.theo/`) so the agent never wastes context on dependency soup\n * or VCS internals.\n * - Skips files larger than `maxFileSize` (default 1 MB) and binary\n * files (null-byte detection on first 8 KB) so a megabyte of\n * minified JS never blows up the result.\n * - Caps total matches at `maxMatches` (default 100) — the agent\n * should refine the query if it gets close to the cap.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, matches: Array<{ file, line, preview }>, truncated, totalMatches }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'not_found' }`\n *\n * Implementation note: this is a plain JS recursive walk. For very\n * large repos a future iteration can shell out to `rg` (ripgrep) when\n * present, but the JS path stays as the dependency-free fallback.\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { isAbsolute, join, relative as relativePath } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type FilesystemBackend,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nconst DEFAULT_MAX_MATCHES = 100;\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024; // 1 MB\nconst BINARY_PROBE_BYTES = 8 * 1024;\nconst PREVIEW_MAX = 200;\n/**\n * Depth cap for the BACKEND walk only. The local `readdir(withFileTypes)` walk skips symlinks and can\n * never loop; the backend walk decides type via `stat` (which follows symlinks), so an in-boundary\n * symlink cycle would recurse until PATH_MAX. This bound stops that pathological case; real trees never\n * approach it.\n */\nconst MAX_BACKEND_WALK_DEPTH = 64;\n\nexport interface CreateSearchTextToolOptions {\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ o literal de hoje (aditivo).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n /** Cap on total matches returned. Default 100. */\n maxMatches?: number;\n /** Skip files larger than this (bytes). Default 1 MB. */\n maxFileSize?: number;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the recursive walk reads\n * through the backend (surface-agnostic); omitted ⇒ the local `readdir`/`readFile` walk (unchanged). */\n filesystem?: FilesystemProvider;\n /** M17 — treat `query` as a JavaScript RegExp instead of a literal substring (grep semantics). An\n * invalid pattern returns `{ ok: false, error: 'invalid_regex' }`. Default `false` ⇒ literal (unchanged). */\n regex?: boolean;\n /** M17 — opt-in \"reads-anywhere\": honor an ABSOLUTE `path` scope outside `projectRoot` (Codex read-only\n * sandbox). Forbidden dirs are still skipped. Default `false` ⇒ absolute scope rejected (unchanged). */\n allowAbsolute?: boolean;\n}\n\ninterface Match {\n file: string;\n line: number;\n preview: string;\n}\n\nexport function createSearchTextTool(opts: CreateSearchTextToolOptions): CustomTool {\n const {\n projectRoot,\n maxMatches = DEFAULT_MAX_MATCHES,\n maxFileSize = DEFAULT_MAX_FILE_SIZE,\n filesystem,\n regex = false,\n allowAbsolute = false,\n } = opts;\n const queryKind = regex ? \"a JavaScript REGULAR EXPRESSION\" : \"LITERAL, CASE-SENSITIVE text\";\n const queryMatch = regex ? \"matched as a regex\" : \"matched as a substring, not a regex\";\n\n return Tool.create({\n name: opts.name ?? \"search_text\",\n description:\n opts.description ??\n `Search file CONTENTS for ${queryKind} across the project tree (the query is ${queryMatch}). ` +\n `Use search_text when you know the content; use glob_files when you know the filename shape; use ` +\n `read_file when you know the exact path. Skips sensitive dirs (.env/.git/node_modules/.theo), ` +\n `binary files, and files over 1 MB; 'path' scopes the search to a subdirectory. Returns up to ` +\n `${String(maxMatches)} matches as { file, line, preview } — cite locations to the user as ` +\n `file:line. Returns { ok, matches } or { ok: false, error }.`,\n inputSchema: z.object({\n query: regex\n ? z.string().min(1).describe(\"A JavaScript regular expression, e.g. 'function\\\\\\\\s+main'.\")\n : z.string().min(1).describe(\"Literal text to search for. Case-sensitive.\"),\n path: z\n .string()\n .optional()\n .describe(\n \"Optional directory to scope the search (project-relative; absolute when allowed).\",\n ),\n }),\n handler: async ({ query, path }, ctx) => {\n // M17 — build the line matcher once (regex or literal). An invalid regex fails clear before walking.\n const built = buildMatcher(query, regex);\n if (\"error\" in built) return built.error;\n const matcher = built.matcher;\n const state: SearchState = {\n matches: [],\n totalMatches: 0,\n truncated: false,\n matcher,\n maxMatches,\n maxFileSize,\n projectRoot,\n };\n\n // Injected filesystem (surface-agnostic) ⇒ walk via the backend in project-relative path space;\n // absent ⇒ the local `readdir`/`readFile` walk (byte-identical to before).\n if (filesystem !== undefined) {\n const scopeRel = resolveScopeRel(path, projectRoot, allowAbsolute);\n if (\"error\" in scopeRel) return scopeRel.error;\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n await walkBackend(backend, scopeRel.rel, state, 0);\n return JSON.stringify({\n ok: true,\n matches: state.matches,\n truncated: state.truncated,\n totalMatches: state.totalMatches,\n });\n }\n\n const scope = resolveSearchScope(path, projectRoot, allowAbsolute);\n if (\"error\" in scope) return scope.error;\n await walk(scope.scopeAbs, state);\n return JSON.stringify({\n ok: true,\n matches: state.matches,\n truncated: state.truncated,\n totalMatches: state.totalMatches,\n });\n },\n });\n}\n\n/** Build the per-line predicate: a compiled RegExp (M17 grep mode) or a literal substring test. */\nfunction buildMatcher(\n query: string,\n regex: boolean,\n): { matcher: (line: string) => boolean } | { error: string } {\n if (!regex) return { matcher: (line) => line.includes(query) };\n try {\n const re = new RegExp(query);\n return { matcher: (line) => re.test(line) };\n } catch {\n return { error: JSON.stringify({ ok: false, error: \"invalid_regex\", query }) };\n }\n}\n\ninterface SearchState {\n matches: Match[];\n totalMatches: number;\n truncated: boolean;\n /** Per-line predicate — literal substring or compiled regex (M17). */\n matcher: (line: string) => boolean;\n maxMatches: number;\n maxFileSize: number;\n projectRoot: string;\n}\n\nfunction resolveSearchScope(\n path: string | undefined,\n projectRoot: string,\n allowAbsolute: boolean,\n): { scopeAbs: string } | { error: string } {\n const scopeRel = path === undefined || path === \"\" || path === \".\" ? \".\" : path;\n // M17 — reads-anywhere: honor an absolute scope (Codex read-only sandbox); forbidden dirs still skipped.\n if (allowAbsolute && isAbsolute(scopeRel)) {\n return { scopeAbs: scopeRel };\n }\n try {\n const scopeAbs = scopeRel === \".\" ? projectRoot : safePathJoin(projectRoot, scopeRel);\n assertNoSymlinkEscape(scopeAbs, projectRoot);\n return { scopeAbs };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function handleEntry(entry: Dirent, absDir: string, state: SearchState): Promise<void> {\n const entryAbs = join(absDir, entry.name);\n const entryRel = relativePath(state.projectRoot, entryAbs);\n if (isForbiddenPath(entryRel)) return;\n if (entry.isDirectory()) {\n await walk(entryAbs, state);\n return;\n }\n if (entry.isFile()) await scanFile(entryAbs, entryRel, state);\n}\n\nasync function walk(absDir: string, state: SearchState): Promise<void> {\n if (state.truncated) return;\n const entries = await readEntriesQuiet(absDir);\n if (entries === null) return;\n for (const entry of entries) {\n if (state.truncated) return;\n await handleEntry(entry, absDir, state);\n }\n}\n\nasync function readEntriesQuiet(absDir: string): Promise<Dirent[] | null> {\n try {\n return await readdir(absDir, { withFileTypes: true });\n } catch {\n return null;\n }\n}\n\nasync function readBufferQuiet(absPath: string): Promise<Buffer | null> {\n try {\n return await readFile(absPath);\n } catch {\n return null;\n }\n}\n\nfunction isBinaryBuffer(buffer: Buffer): boolean {\n const probeEnd = Math.min(buffer.length, BINARY_PROBE_BYTES);\n for (let i = 0; i < probeEnd; i += 1) {\n if (buffer[i] === 0) return true;\n }\n return false;\n}\n\nfunction recordMatch(state: SearchState, file: string, line: number, lineText: string): boolean {\n state.totalMatches += 1;\n if (state.matches.length < state.maxMatches) {\n state.matches.push({\n file,\n line,\n preview: lineText.length > PREVIEW_MAX ? `${lineText.slice(0, PREVIEW_MAX)}…` : lineText,\n });\n return true;\n }\n state.truncated = true;\n return false;\n}\n\nasync function scanFile(absPath: string, relPath: string, state: SearchState): Promise<void> {\n const buffer = await readBufferQuiet(absPath);\n if (buffer === null || buffer.length > state.maxFileSize) return;\n if (isBinaryBuffer(buffer)) return;\n const lines = buffer.toString(\"utf-8\").split(\"\\n\");\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i]!;\n if (!state.matcher(line)) continue;\n if (!recordMatch(state, relPath, i + 1, line)) return;\n }\n}\n\n// --- Surface-agnostic backend walk (mirrors the local walk in PROJECT-RELATIVE path space) ---\n\n/** Resolve the scope to a project-relative dir (`\"\"` = root) with the same security guard as the local\n * path — a traversal/forbidden scope is rejected identically. */\nfunction resolveScopeRel(\n path: string | undefined,\n projectRoot: string,\n allowAbsolute: boolean,\n): { rel: string } | { error: string } {\n const scopeRel = path === undefined || path === \"\" || path === \".\" ? \"\" : path;\n if (scopeRel === \"\") return { rel: \"\" };\n // M17 — reads-anywhere: pass an absolute scope through to the backend (it owns its own boundary).\n if (allowAbsolute && isAbsolute(scopeRel)) return { rel: scopeRel };\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, scopeRel), projectRoot);\n return { rel: scopeRel };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function walkBackend(\n backend: FilesystemBackend,\n dirRel: string,\n state: SearchState,\n depth: number,\n): Promise<void> {\n if (state.truncated) return;\n if (depth > MAX_BACKEND_WALK_DEPTH) return; // symlink-cycle guard (see MAX_BACKEND_WALK_DEPTH)\n let names: string[];\n try {\n names = await backend.list(dirRel);\n } catch {\n return;\n }\n for (const name of names) {\n if (state.truncated) return;\n await handleBackendEntry(backend, dirRel, name, state, depth);\n }\n}\n\n/** Handle one backend directory entry: skip forbidden, stat, recurse on dirs, scan files. */\nasync function handleBackendEntry(\n backend: FilesystemBackend,\n dirRel: string,\n name: string,\n state: SearchState,\n depth: number,\n): Promise<void> {\n const entryRel = dirRel === \"\" ? name : `${dirRel}/${name}`;\n if (isForbiddenPath(entryRel)) return;\n let st: { isDirectory: boolean; isFile: boolean; size: number };\n try {\n st = await backend.stat(entryRel);\n } catch {\n return;\n }\n if (st.isDirectory) {\n await walkBackend(backend, entryRel, state, depth + 1);\n } else if (st.isFile) {\n await scanFileBackend(backend, entryRel, st.size, state);\n }\n}\n\nasync function scanFileBackend(\n backend: FilesystemBackend,\n relPath: string,\n size: number,\n state: SearchState,\n): Promise<void> {\n if (size > state.maxFileSize) return;\n let content: string;\n try {\n content = await backend.readFile(relPath);\n } catch {\n return;\n }\n // Null-byte ⇒ binary; skip (parity with the local isBinaryBuffer probe, string-side).\n if (content.slice(0, BINARY_PROBE_BYTES).includes(\"\\u0000\")) return;\n const lines = content.split(\"\\n\");\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i]!;\n if (!state.matcher(line)) continue;\n if (!recordMatch(state, relPath, i + 1, line)) return;\n }\n}\n","/**\n * `shell_exec` — built-in tool for coding agents.\n *\n * Executes a shell command via `/bin/sh -c` with a configurable timeout\n * and output size cap.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, stdout, stderr, exit_code }`\n * - `{ ok: false, error: 'timeout' | 'exec_failed' }`\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { resolveSandbox, type SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { CatastrophicCommandError, catastrophicShellReason } from \"./internal/shell-guard.js\";\nimport { armTimeoutKill, attachChildSettlers } from \"./subprocess.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 300_000; // 5 minutes hard ceiling\nconst MAX_OUTPUT_BYTES = 5 * 1024 * 1024; // 5 MB\n\n/** Run `command` through an injected SandboxBackend, mapping its result to shell_exec's JSON shape. */\nasync function execViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n command: string,\n timeoutMs: number,\n): Promise<string> {\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n return r.timedOut\n ? JSON.stringify({ ok: false, error: \"timeout\", timeout_ms: timeoutMs })\n : JSON.stringify({ ok: true, stdout: r.stdout, stderr: r.stderr, exit_code: r.exitCode });\n}\n\nexport interface CreateShellToolOptions {\n /**\n * M76 — nome exposto ao modelo. Omitido ⇒ o literal de hoje (aditivo).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Commands execute in this cwd. */\n projectRoot: string;\n /** Default timeout in ms. Capped at 300s. */\n defaultTimeoutMs?: number;\n /**\n * Opt out of the catastrophic-command guardrail. Default `false` (the\n * guardrail screens every command before spawn). Set `true` only when the\n * agent legitimately needs destructive power flows — it is a heuristic\n * guardrail, not a sandbox.\n */\n allowCatastrophic?: boolean;\n /**\n * Optional injected execution backend (`@theokit/sdk/sandbox`) — a backend or a per-request resolver.\n * When provided, the command runs via `SandboxBackend.execute` (Local/Docker/E2B) so the tool is\n * surface-agnostic (a cluster/desktop host runs it in the sandbox, not the local host); omitted ⇒ the\n * local `/bin/sh -c` child process (byte-identical to before). The catastrophic-command guard runs\n * before either path.\n */\n sandbox?: SandboxProvider;\n}\n\nexport function createShellTool(opts: CreateShellToolOptions): CustomTool {\n const {\n projectRoot,\n defaultTimeoutMs = DEFAULT_TIMEOUT_MS,\n allowCatastrophic = false,\n sandbox,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"shell_exec\",\n description:\n opts.description ??\n \"Execute a shell command in the project directory. Use this for terminal operations — running \" +\n \"tests, git, package managers, build tools. Do NOT use it for file operations (reading, \" +\n \"writing, editing, finding files): prefer the specialized read_file/write_file/edit_file/\" +\n \"glob_files/search_text tools, which are path-checked and safer. Only commit, push, or change \" +\n \"git state when the user explicitly asks. timeout_ms defaults to 30000 (max 300000); \" +\n \"stdout/stderr are capped (~5 MB). Returns { ok, stdout, stderr, exit_code } or \" +\n \"{ ok: false, error }.\",\n inputSchema: z.object({\n command: z.string().min(1).describe(\"Shell command to execute.\"),\n timeout_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Timeout in milliseconds (default 30000, max 300000).\"),\n }),\n handler: async ({ command, timeout_ms }, ctx) => {\n if (!allowCatastrophic) {\n const reason = catastrophicShellReason(command);\n if (reason) {\n // Construct the typed error so its `code` is the single source of the\n // error string (mirrors web_fetch's SsrfBlockedError handling).\n const err = new CatastrophicCommandError(reason);\n return JSON.stringify({ ok: false, error: err.code, reason });\n }\n }\n const timeoutMs = Math.min(timeout_ms ?? defaultTimeoutMs, MAX_TIMEOUT_MS);\n // Injected backend (surface-agnostic) ⇒ run in the sandbox; absent ⇒ the local child (unchanged).\n if (sandbox !== undefined) return execViaSandbox(sandbox, ctx, command, timeoutMs);\n return runShell(projectRoot, command, timeoutMs);\n },\n });\n}\n\ntype ShellResult =\n | { kind: \"ok\"; stdout: string; stderr: string; exitCode: number | null }\n | { kind: \"timeout\" }\n | { kind: \"error\"; message: string };\n\nfunction runShell(cwd: string, command: string, timeoutMs: number): Promise<string> {\n return new Promise((resolve) => {\n const child = spawn(\"/bin/sh\", [\"-c\", command], {\n cwd,\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n let stderrBytes = 0;\n\n const gate = armTimeoutKill<ShellResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n (result) => resolve(formatResult(result, timeoutMs)),\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stdoutBytes >= MAX_OUTPUT_BYTES) {\n return;\n }\n const remaining = MAX_OUTPUT_BYTES - stdoutBytes;\n if (chunk.length > remaining) {\n stdoutChunks.push(chunk.subarray(0, remaining));\n stdoutBytes = MAX_OUTPUT_BYTES;\n } else {\n stdoutChunks.push(chunk);\n stdoutBytes += chunk.length;\n }\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stderrBytes >= MAX_OUTPUT_BYTES) return;\n const remaining = MAX_OUTPUT_BYTES - stderrBytes;\n if (chunk.length > remaining) {\n stderrChunks.push(chunk.subarray(0, remaining));\n stderrBytes = MAX_OUTPUT_BYTES;\n } else {\n stderrChunks.push(chunk);\n stderrBytes += chunk.length;\n }\n });\n\n attachChildSettlers<ShellResult>(\n child,\n gate,\n (code) => ({\n kind: \"ok\",\n stdout: Buffer.concat(stdoutChunks).toString(\"utf-8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf-8\"),\n exitCode: code,\n }),\n (err) => ({ kind: \"error\", message: err.message }),\n (result) => resolve(formatResult(result, timeoutMs)),\n );\n });\n}\n\nfunction formatResult(result: ShellResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeout_ms: timeoutMs });\n }\n if (result.kind === \"error\") {\n return JSON.stringify({ ok: false, error: \"exec_failed\", message: result.message });\n }\n return JSON.stringify({\n ok: true,\n stdout: result.stdout,\n stderr: result.stderr,\n exit_code: result.exitCode,\n });\n}\n","import type { TodoItem } from \"./todolist.js\";\n\n/**\n * A flat plan-render node — the stable shape a UI/plan layer consumes. Mirrors\n * the `TodoItem` status union; `label` is the item title.\n *\n * @public\n */\nexport interface PlanNode {\n id: string;\n label: string;\n status: \"pending\" | \"in_progress\" | \"done\";\n}\n\n/**\n * Convert structured todo items (from a `todolist` tool result's `items`, M4-5)\n * into versioned `PlanNode`s for rendering. Pure: projects EXACTLY\n * `{ id, label, status }` (timestamps are intentionally dropped), preserving\n * input order. Replaces consumer-side hand-rolled mappers.\n *\n * @public\n */\nexport function todoItemsToPlanNodes(items: readonly TodoItem[]): PlanNode[] {\n return items.map((item) => ({ id: item.id, label: item.title, status: item.status }));\n}\n","/**\n * `todolist` — in-session task tracking for multi-step work.\n *\n * The agent uses this to plan complex tasks and track progress.\n * Inspired by a peer project's todo.ts and Claude Code's TodoWrite.\n *\n * Actions:\n * - add(title) → add a new todo item\n * - complete(id) → mark an item done\n * - remove(id) → remove an item\n * - list() → show all items with status\n * - clear_completed() → remove all done items\n *\n * #119 — state is keyed by `ctx.threadId` (the run's session identity, injected by the\n * SDK from `Agent.getOrCreate(sessionId, …)`). One tool object served to many sessions\n * from a single process keeps each session's list isolated. When no `threadId` is present\n * (single-session CLI usage) every call shares one default session — behavior unchanged.\n */\n\nexport interface TodoItem {\n id: string;\n title: string;\n status: \"pending\" | \"in_progress\" | \"done\";\n createdAt: number;\n completedAt?: number;\n}\n\nexport interface TodolistTool {\n name: string;\n description: string;\n inputSchema: unknown;\n /**\n * #119 — the optional 2nd `ctx` carries the run's `threadId`; state is scoped to it.\n * Single-argument callers (CLI / tests) share one default session.\n */\n handler: (input: TodoInput, ctx?: { threadId?: string }) => string;\n /** Expose a session's items for testing (defaults to the no-threadId session). */\n getItems: (threadId?: string) => TodoItem[];\n}\n\ntype TodoInput =\n | { action: \"add\"; title: string }\n | { action: \"complete\"; id: string }\n | { action: \"in_progress\"; id: string }\n | { action: \"remove\"; id: string }\n | { action: \"list\" }\n | { action: \"clear_completed\" };\n\nfunction ok(data: Record<string, unknown>): string {\n return JSON.stringify({ ok: true, ...data });\n}\n\nfunction fail(data: Record<string, unknown>): string {\n return JSON.stringify({ ok: false, ...data });\n}\n\nfunction requireId(input: TodoInput): string | null {\n if (!(\"id\" in input) || !input.id) return null;\n return input.id;\n}\n\n/** The stateful machinery for ONE session — its own `items` array and id counter. */\nfunction makeSessionOps(): { handle: (input: TodoInput) => string; getItems: () => TodoItem[] } {\n const items: TodoItem[] = [];\n let nextId = 1;\n\n function genId(): string {\n return `todo-${nextId++}`;\n }\n\n function findById(id: string): TodoItem | undefined {\n return items.find((i) => i.id === id);\n }\n\n // M4-5: every list-bearing success result carries BOTH the human `items_summary`\n // (for the LLM) AND the structured `items` snapshot (for programmatic consumers\n // that render a plan/UI).\n function listResult(extra: Record<string, unknown>): string {\n return ok({ ...extra, items: [...items], items_summary: formatList() });\n }\n\n function formatList(): string {\n if (items.length === 0) return \"No tasks. Use action 'add' to create one.\";\n const lines = items.map((item) => {\n const icon = item.status === \"done\" ? \"[x]\" : item.status === \"in_progress\" ? \"[>]\" : \"[ ]\";\n return `${icon} ${item.id}: ${item.title}`;\n });\n const pending = items.filter((i) => i.status === \"pending\").length;\n const inProg = items.filter((i) => i.status === \"in_progress\").length;\n const done = items.filter((i) => i.status === \"done\").length;\n lines.push(`\\n${done}/${items.length} done | ${inProg} in progress | ${pending} pending`);\n return lines.join(\"\\n\");\n }\n\n function handleAdd(input: TodoInput): string {\n if (!(\"title\" in input) || !input.title) return fail({ error: \"missing_title\" });\n const item: TodoItem = {\n id: genId(),\n title: input.title,\n status: \"pending\",\n createdAt: Date.now(),\n };\n items.push(item);\n return listResult({ id: item.id, message: `Added: ${item.title}` });\n }\n\n function handleSetStatus(input: TodoInput, status: \"in_progress\" | \"done\"): string {\n const id = requireId(input);\n if (!id) return fail({ error: \"missing_id\" });\n const item = findById(id);\n if (!item) return fail({ error: \"not_found\", id });\n item.status = status;\n if (status === \"done\") item.completedAt = Date.now();\n const verb = status === \"done\" ? \"Completed\" : \"Started\";\n return listResult({ message: `${verb}: ${item.title}` });\n }\n\n function handleRemove(input: TodoInput): string {\n const id = requireId(input);\n if (!id) return fail({ error: \"missing_id\" });\n const idx = items.findIndex((i) => i.id === id);\n if (idx === -1) return fail({ error: \"not_found\", id });\n const removed = items.splice(idx, 1)[0]!;\n return listResult({ message: `Removed: ${removed.title}` });\n }\n\n function handleClearCompleted(): string {\n const before = items.length;\n const kept = items.filter((i) => i.status !== \"done\");\n items.length = 0;\n items.push(...kept);\n return listResult({ message: `Cleared ${before - items.length} completed items` });\n }\n\n const actions: Record<string, (input: TodoInput) => string> = {\n add: handleAdd,\n in_progress: (input) => handleSetStatus(input, \"in_progress\"),\n complete: (input) => handleSetStatus(input, \"done\"),\n remove: handleRemove,\n list: () => listResult({}),\n clear_completed: handleClearCompleted,\n };\n\n return {\n handle: (input: TodoInput): string => {\n const action = actions[input.action];\n if (!action) return fail({ error: \"invalid_action\" });\n return action(input);\n },\n getItems: () => [...items],\n };\n}\n\nexport function createTodolistTool(): TodolistTool {\n // #119 — one session-ops bundle per threadId; lazily created on first touch.\n const sessions = new Map<string, ReturnType<typeof makeSessionOps>>();\n function ops(threadId?: string): ReturnType<typeof makeSessionOps> {\n const key = threadId ?? \"__default__\";\n let session = sessions.get(key);\n if (session === undefined) {\n session = makeSessionOps();\n sessions.set(key, session);\n }\n return session;\n }\n\n return {\n name: \"todolist\",\n description:\n \"Create and maintain a structured task list for the current session — tracks progress and \" +\n \"keeps a multi-step plan visible across turns. Use it proactively when the work has 3+ steps \" +\n \"or the user gave multiple tasks; skip it for a single trivial step. Keep exactly ONE item \" +\n \"'in_progress' at a time, and mark 'complete' only after the work is actually done. \" +\n \"Actions: 'add' (create with title), 'in_progress' (mark started by id), 'complete' (mark done \" +\n \"by id), 'remove' (delete by id), 'list' (show all), 'clear_completed' (remove done items). \" +\n \"Returns { ok, items, items_summary } (items = structured array; items_summary = formatted text).\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n action: {\n type: \"string\",\n enum: [\"add\", \"complete\", \"in_progress\", \"remove\", \"list\", \"clear_completed\"],\n description: \"The action to perform.\",\n },\n title: {\n type: \"string\",\n description: \"Title for a new todo item (required for 'add').\",\n },\n id: {\n type: \"string\",\n description: \"ID of the todo item (required for 'complete', 'in_progress', 'remove').\",\n },\n },\n required: [\"action\"],\n },\n handler: (input: TodoInput, ctx?: { threadId?: string }): string =>\n ops(ctx?.threadId).handle(input),\n getItems: (threadId?: string): TodoItem[] => ops(threadId).getItems(),\n };\n}\n","/**\n * `truncateOutput` — utility for truncating large tool output.\n *\n * When output exceeds `maxBytes`, writes the full content to a temp file and returns a truncated\n * version with a reference to the full output.\n *\n * ## M77 — why this grew instead of a new truncator being written\n *\n * The M77 discovery measured **six** output ceilings across `sdk-tools`, with five different values\n * and no coordination between them (`web-fetch.ts` 1 MB, `shell-exec.ts` 5 MB, `git-diff.ts` 5 MB,\n * `run-vitest.ts` 10 MB, `git-status.ts` configurable, and this helper's 30 000 B). It also found\n * that this helper — exported from the barrel — had **zero production consumers**: the SDK had\n * already paid for a shared truncator that nobody used while every tool rolled its own.\n *\n * Adding a seventh ceiling in the runtime would have been the defect, not the fix. So `toolResultBudget`\n * extends this one instead (parsimony-ladder rung 4), gaining the two things it lacked:\n *\n * - **`head-tail` mode** — the previous cut was head-only, which for command output discards\n * exactly the part that matters: the error, the summary, the final prompt.\n * - **`originalBytes`** — a machine-readable marker. The only prior signal was an English sentence\n * injected into the text (`\"[Output truncated. Full output: …]\"`), so a consumer wanting to know\n * how much was lost had to parse prose.\n *\n * Consolidating the MECHANISM is deliberately not the same as unifying the VALUES: 1 MB for\n * `web-fetch` and 10 MB for `run-vitest` may differ for good reasons. That second step is out of\n * scope here (plan ADR D2).\n *\n * Return shape:\n * - `{ content, truncated: false, originalBytes }`\n * - `{ content, truncated: true, originalBytes, overflowPath }`\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** How the middle is dropped when output exceeds the budget. */\nexport type TruncationMode = \"head\" | \"head-tail\";\n\nexport interface TruncationOptions {\n /** Maximum output size in bytes before truncation. Default: 30_000. */\n maxBytes?: number;\n /** Directory for overflow files. Default: \".theocode/tool-output\". */\n outputDir?: string;\n /**\n * `\"head\"` (default) keeps the first `maxBytes` — the historical behaviour, preserved because this\n * helper is public API. `\"head-tail\"` splits the budget between the start and the END, which is\n * where command output usually carries its conclusion.\n */\n mode?: TruncationMode;\n}\n\nexport interface TruncationResult {\n /** The (possibly truncated) content. */\n content: string;\n /** Whether the output was truncated. */\n truncated: boolean;\n /**\n * Byte length of the ORIGINAL output, present on both paths. Always present by design: a field\n * that only appears on failure forces every consumer through an `undefined` check, which is the\n * door magic values come in through.\n */\n originalBytes: number;\n /** Path to the full output file, present only when truncated. */\n overflowPath?: string;\n}\n\n/**\n * Cut a UTF-8 buffer at a byte boundary WITHOUT splitting a code point.\n *\n * `Buffer.subarray(0, n).toString()` on a boundary inside a multi-byte character yields U+FFFD, and\n * the model reads garbage. `TextDecoder` with `stream: true` withholds the incomplete tail instead of\n * substituting it — stdlib doing the work (parsimony-ladder rung 2).\n */\nfunction decodeWholeCodePoints(buf: Buffer): string {\n return new TextDecoder(\"utf-8\").decode(buf, { stream: true });\n}\n\nexport function truncateOutput(output: string, opts?: TruncationOptions): TruncationResult {\n const maxBytes = opts?.maxBytes ?? 30_000;\n const outputDir = opts?.outputDir ?? \".theocode/tool-output\";\n const mode = opts?.mode ?? \"head\";\n\n // EC-3: strict > comparison — exactly at limit is NOT truncated\n const originalBytes = Buffer.byteLength(output, \"utf-8\");\n if (originalBytes <= maxBytes) {\n return { content: output, truncated: false, originalBytes };\n }\n\n // Write full output to overflow file\n mkdirSync(outputDir, { recursive: true });\n // M77 — the name used to be `overflow-${Date.now()}.txt`, which COLLIDES: two truncations inside\n // the same millisecond resolve to the same path, and the second silently overwrites the first. The\n // `overflowPath` handed back to the caller then points at somebody else's output — a wrong answer,\n // not an error. Surfaced as an intermittent failure while running two truncation suites together;\n // `rules/testing.md § 3` treats a flake as a bug, and the root cause was in production code, not\n // in the test. `randomUUID` is stdlib (parsimony-ladder rung 2).\n const filename = `overflow-${Date.now()}-${randomUUID().slice(0, 8)}.txt`;\n const overflowPath = join(outputDir, filename);\n writeFileSync(overflowPath, output, \"utf-8\");\n\n const buf = Buffer.from(output, \"utf-8\");\n const trailer = `\\n\\n[Output truncated. Full output: ${overflowPath}]`;\n\n if (mode === \"head-tail\") {\n // Split the budget in half. The tail decode starts mid-buffer, so its first bytes may be a\n // continuation of a split code point; `decodeWholeCodePoints` drops the incomplete lead rather\n // than emitting U+FFFD.\n const half = Math.floor(maxBytes / 2);\n const head = decodeWholeCodePoints(buf.subarray(0, half));\n const tail = decodeWholeCodePoints(buf.subarray(buf.length - half));\n return {\n content: `${head}\\n\\n[… ${String(originalBytes - maxBytes)} bytes omitted …]\\n\\n${tail}${trailer}`,\n truncated: true,\n originalBytes,\n overflowPath,\n };\n }\n\n return {\n content: decodeWholeCodePoints(buf.subarray(0, maxBytes)) + trailer,\n truncated: true,\n originalBytes,\n overflowPath,\n };\n}\n","/**\n * `update_plan` — built-in tool for coding agents.\n *\n * Codex-faithful: the model posts a DECLARATIVE plan — an ordered list of short steps, each\n * `pending | in_progress | completed` — and refreshes it as work proceeds. Codex's invariant is\n * \"exactly one step in_progress until everything is done\"; this tool WARNS (never rejects) when that\n * doesn't hold, so the agent self-corrects on the next update rather than failing the turn.\n *\n * Surface-agnostic by design (M17 DX): the result is STRUCTURED (`{ ok, steps, warning? }`) — each\n * surface (terminal TUI, desktop, web) renders the checklist however it likes, rather than the package\n * hard-coding glyphs. Result shape (always a JSON string):\n * - `{ ok: true, explanation: string | null, steps: PlanStep[], warning?: string }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nconst STATUS = [\"pending\", \"in_progress\", \"completed\"] as const;\n\nconst planStepSchema = z.object({\n step: z.string().min(1).max(100).describe(\"A short step, ≤ ~7 words.\"),\n status: z.enum(STATUS),\n});\n\nexport function createUpdatePlanTool(): CustomTool {\n return Tool.create({\n name: \"update_plan\",\n description:\n \"Post or refresh a short plan so the user sees your progress on a multi-step task. Pass an ordered \" +\n \"`plan` of steps, each with a status (pending | in_progress | completed); keep exactly one step \" +\n \"in_progress at a time and mark steps completed as you finish. Returns { ok, steps, warning? } as a \" +\n \"JSON string — the surface renders the checklist. A `warning` is returned (not an error) if the \" +\n \"one-in_progress invariant is violated, so you can self-correct on the next update.\",\n inputSchema: z.object({\n explanation: z\n .string()\n .max(200)\n .optional()\n .describe(\"One line on what changed / why (optional).\"),\n plan: z.array(planStepSchema).min(1).describe(\"The ordered steps.\"),\n }),\n handler: ({ explanation, plan }) => {\n const inProgress = plan.filter((s) => s.status === \"in_progress\").length;\n const allDone = plan.every((s) => s.status === \"completed\");\n const warning =\n !allDone && inProgress !== 1\n ? `keep exactly one step in_progress until all are completed — found ${inProgress}`\n : undefined;\n return JSON.stringify({ ok: true, explanation: explanation ?? null, steps: plan, warning });\n },\n });\n}\n","/**\n * `web_fetch` — built-in tool for coding agents.\n *\n * Fetches a URL via native `fetch()`. Rejects non-http(s) protocols.\n * Size-capped at 1 MB response body.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, content, status_code, content_type }`\n * - `{ ok: false, error: 'invalid_url' | 'fetch_failed' |\n * 'timeout' | 'too_large' | 'ssrf_blocked' | 'redirect_blocked' }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nimport {\n RedirectBlockedError,\n type ScreenedFetchOptions,\n SsrfBlockedError,\n screenedFetch,\n} from \"./internal/network-guard.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MB\n\nexport interface CreateWebFetchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Default timeout in ms. */\n defaultTimeoutMs?: number;\n /**\n * Opt out of the SSRF guard (default `false`). When `true`, requests to\n * private/loopback/link-local/metadata addresses are NOT blocked — use only for\n * trusted local-dev tooling.\n */\n allowPrivateHosts?: boolean;\n /**\n * Max redirect hops to follow (each SSRF-screened). Default 5. Set `0` to BLOCK ALL\n * redirects — a 3xx then returns `{ ok: false, error: \"redirect_blocked\" }` (a strict\n * no-redirect policy for untrusted, model-chosen URLs).\n */\n maxRedirects?: number;\n /** Fetch implementation (injectable for tests — drive paths with no real network). */\n fetchImpl?: ScreenedFetchOptions[\"fetchImpl\"];\n /** DNS resolver (injectable for tests — drive the SSRF path with no real DNS). */\n lookup?: ScreenedFetchOptions[\"lookup\"];\n}\n\nexport function createWebFetchTool(opts?: CreateWebFetchToolOptions): CustomTool {\n const defaultTimeoutMs = opts?.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n const allowPrivateHosts = opts?.allowPrivateHosts ?? false;\n const maxRedirects = opts?.maxRedirects;\n const fetchImpl = opts?.fetchImpl;\n const lookup = opts?.lookup;\n\n return Tool.create({\n name: opts?.name ?? \"web_fetch\",\n description:\n opts?.description ??\n \"Fetch the contents of a URL via HTTP/HTTPS. Use only for URLs the user provided or that you \" +\n \"are confident help with the task; never invent or guess URLs. Rejects non-http(s) URLs and \" +\n \"is SSRF-guarded by default (private/loopback/link-local/cloud-metadata hosts are refused \" +\n \"with an ssrf_blocked error). The response body is capped at 1 MB. Returns \" +\n \"{ ok, content, status_code, content_type } or { ok: false, error }.\",\n inputSchema: z.object({\n url: z.string().min(1).describe(\"URL to fetch (http or https only).\"),\n timeout_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Timeout in milliseconds (default 30000).\"),\n }),\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: fetch with guards\n handler: async ({ url, timeout_ms }) => {\n // Validate protocol\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return JSON.stringify({ ok: false, error: \"invalid_url\", url });\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return JSON.stringify({\n ok: false,\n error: \"invalid_url\",\n url,\n detail: \"only http and https protocols allowed\",\n });\n }\n\n const timeoutMs = timeout_ms ?? defaultTimeoutMs;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await screenedFetch(url, {\n signal: controller.signal,\n allowPrivateHosts,\n ...(maxRedirects !== undefined ? { maxRedirects } : {}),\n ...(fetchImpl ? { fetchImpl } : {}),\n ...(lookup ? { lookup } : {}),\n });\n clearTimeout(timer);\n\n // Check content-length header before downloading\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength && Number(contentLength) > MAX_BODY_BYTES) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n url,\n size: Number(contentLength),\n limit: MAX_BODY_BYTES,\n });\n }\n\n const buffer = await response.arrayBuffer();\n if (buffer.byteLength > MAX_BODY_BYTES) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n url,\n size: buffer.byteLength,\n limit: MAX_BODY_BYTES,\n });\n }\n\n const content = new TextDecoder(\"utf-8\").decode(buffer);\n const contentType = response.headers.get(\"content-type\") ?? undefined;\n\n return JSON.stringify({\n ok: true,\n content,\n status_code: response.status,\n content_type: contentType,\n });\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof RedirectBlockedError) {\n return JSON.stringify({ ok: false, error: \"redirect_blocked\", url, reason: err.message });\n }\n if (err instanceof SsrfBlockedError) {\n return JSON.stringify({ ok: false, error: \"ssrf_blocked\", url, reason: err.message });\n }\n const e = err as { name?: string; message?: string };\n if (e.name === \"AbortError\") {\n return JSON.stringify({ ok: false, error: \"timeout\", url, timeout_ms: timeoutMs });\n }\n return JSON.stringify({\n ok: false,\n error: \"fetch_failed\",\n url,\n message: e.message ?? \"unknown\",\n });\n }\n },\n });\n}\n","/**\n * `web_search` — built-in tool for coding agents.\n *\n * Accepts a search callback via DIP (consumer provides the search\n * provider). The tool itself is provider-agnostic.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, results: Array<{ title, url, snippet }> }`\n * - `{ ok: false, error: 'search_failed' | 'no_provider' }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nexport interface WebSearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\nexport type WebSearchCallback = (query: string, maxResults: number) => Promise<WebSearchResult[]>;\n\nexport interface CreateWebSearchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Search provider callback — consumer injects the implementation. */\n search: WebSearchCallback;\n /** Default max results if not specified by the LLM. */\n defaultMaxResults?: number;\n}\n\nexport function createWebSearchTool(opts: CreateWebSearchToolOptions): CustomTool {\n const { search, defaultMaxResults = 5 } = opts;\n\n return Tool.create({\n name: opts.name ?? \"web_search\",\n description:\n opts.description ??\n \"Search the web for a query — use when you need current information beyond the repo or your \" +\n \"training cutoff (library docs, an error message, an API). Returns a list of results with \" +\n \"title, URL, and snippet; follow up with web_fetch on a promising result to read it in full. \" +\n \"The search provider is injected by the consumer. \" +\n \"Returns { ok, results } or { ok: false, error }.\",\n inputSchema: z.object({\n query: z.string().min(1).describe(\"Search query.\"),\n max_results: z\n .number()\n .int()\n .positive()\n .max(20)\n .optional()\n .describe(\"Maximum results to return (default 5, max 20).\"),\n }),\n handler: async ({ query, max_results }) => {\n const maxResults = max_results ?? defaultMaxResults;\n\n try {\n const results = await search(query, maxResults);\n return JSON.stringify({\n ok: true,\n results: results.slice(0, maxResults),\n count: Math.min(results.length, maxResults),\n });\n } catch (err) {\n const e = err as { message?: string };\n return JSON.stringify({\n ok: false,\n error: \"search_failed\",\n message: e.message ?? \"unknown\",\n });\n }\n },\n });\n}\n","/**\n * Brave Search adapter for `createWebSearchTool` (M3-7).\n *\n * `createBraveWebSearchAdapter()` returns a `WebSearchCallback` that queries the\n * Brave Search API using an env-driven key (`BRAVE_API_KEY`). It plugs into the\n * provider-agnostic `createWebSearchTool` via its callback seam — the tool is NOT\n * modified. The `fetch` impl is injectable (default `globalThis.fetch`) so the\n * adapter is offline-testable; a plain fetch (not `screenedFetch`) is used because\n * the endpoint host is fixed (no SSRF surface) and `screenedFetch` cannot carry\n * the required auth header. Zero new dependencies. Design: blueprint m3-websearch-adapter.\n */\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\nimport type { WebSearchCallback, WebSearchResult } from \"./web-search.js\";\n\nconst BRAVE_ENDPOINT = \"https://api.search.brave.com/res/v1/web/search\";\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\nexport interface CreateBraveWebSearchAdapterOptions {\n /** Brave API key. Defaults to `process.env.BRAVE_API_KEY`. */\n apiKey?: string;\n /** Injectable fetch (default `globalThis.fetch`) — set in tests for offline runs. */\n fetchImpl?: FetchLike;\n /** Override the Brave endpoint (self-host / test). */\n endpoint?: string;\n}\n\ninterface BraveResult {\n title?: unknown;\n url?: unknown;\n description?: unknown;\n}\n\n/**\n * Build a `WebSearchCallback` backed by the Brave Search API. Throws a typed\n * `ConfigurationError` (\"no_api_key\") at creation when no key is available.\n */\nexport function createBraveWebSearchAdapter(\n opts: CreateBraveWebSearchAdapterOptions = {},\n): WebSearchCallback {\n const apiKey = opts.apiKey ?? process.env.BRAVE_API_KEY;\n if (!apiKey) {\n throw new ConfigurationError(\"BRAVE_API_KEY is not set (pass { apiKey } or set the env var).\", {\n code: \"no_api_key\",\n });\n }\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n const endpoint = opts.endpoint ?? BRAVE_ENDPOINT;\n // Validate the endpoint at creation (fail-early symmetry with the key check).\n const base = new URL(endpoint);\n\n return async (query: string, maxResults: number): Promise<WebSearchResult[]> => {\n const url = new URL(base);\n url.searchParams.set(\"q\", query);\n url.searchParams.set(\"count\", String(maxResults));\n const res = await fetchImpl(url.toString(), {\n headers: { \"X-Subscription-Token\": apiKey, Accept: \"application/json\" },\n });\n if (!res.ok) throw new Error(`brave_search_failed: HTTP ${res.status}`);\n const json = (await res.json()) as { web?: { results?: BraveResult[] } } | null;\n const results = json?.web?.results ?? [];\n return results.map((r) => ({\n title: String(r?.title ?? \"\"),\n url: String(r?.url ?? \"\"),\n snippet: String(r?.description ?? \"\"),\n }));\n };\n}\n","/**\n * Generic HTTP web-search adapter for `createWebSearchTool` (RADAR #92.d).\n *\n * `createGenericHttpSearchAdapter()` returns a `WebSearchCallback` that queries\n * an arbitrary HTTP search endpoint keyed by env vars:\n * - `THEOKIT_SEARCH_API_URL` — endpoint returning `{ results: [{title,url,snippet}] }`\n * - `THEOKIT_SEARCH_API_KEY` — bearer token\n *\n * Request shape: `GET {endpoint}?q={query}&n={maxResults}` with\n * `Authorization: Bearer {apiKey}`. Both values may be passed explicitly (params\n * win over env). Unlike the Brave adapter (which fails early — fixed host, fixed\n * auth), this one is provider-agnostic and **degrades gracefully**: when\n * unconfigured OR on any network/parse failure it returns `[]` and never throws\n * into the agent turn. A recurring empty result is a provider-config issue, not\n * an agent bug. `fetchImpl` is injectable (default `globalThis.fetch`) for\n * offline tests. Zero new dependencies.\n *\n * Promoted from theocode's `server/lib/web-search.ts` (`createSearchProvider`),\n * re-keyed to neutral `THEOKIT_*` env vars.\n */\n\nimport type { WebSearchCallback, WebSearchResult } from \"./web-search.js\";\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\nexport interface CreateGenericHttpSearchAdapterOptions {\n /** Bearer token. Defaults to `process.env.THEOKIT_SEARCH_API_KEY`. */\n apiKey?: string;\n /** Search endpoint URL. Defaults to `process.env.THEOKIT_SEARCH_API_URL`. */\n endpoint?: string;\n /** Injectable fetch (default `globalThis.fetch`) — set in tests for offline runs. */\n fetchImpl?: FetchLike;\n}\n\ninterface GenericResult {\n title?: unknown;\n url?: unknown;\n snippet?: unknown;\n}\n\n/**\n * Build a `WebSearchCallback` backed by a generic HTTP search endpoint. Returns\n * `[]` (graceful no-op) when unconfigured or on any failure — never throws.\n */\nexport function createGenericHttpSearchAdapter(\n opts: CreateGenericHttpSearchAdapterOptions = {},\n): WebSearchCallback {\n const apiKey = opts.apiKey ?? process.env.THEOKIT_SEARCH_API_KEY;\n const endpoint = opts.endpoint ?? process.env.THEOKIT_SEARCH_API_URL;\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n\n return async (query: string, maxResults: number): Promise<WebSearchResult[]> => {\n if (!apiKey || !endpoint) return []; // no provider configured — graceful no-op\n try {\n const url = `${endpoint}?q=${encodeURIComponent(query)}&n=${maxResults}`;\n const res = await fetchImpl(url, { headers: { Authorization: `Bearer ${apiKey}` } });\n if (!res.ok) return [];\n const data = (await res.json()) as { results?: GenericResult[] } | null;\n return (data?.results ?? []).slice(0, maxResults).map((r) => ({\n title: String(r?.title ?? \"\"),\n url: String(r?.url ?? \"\"),\n snippet: String(r?.snippet ?? \"\"),\n }));\n } catch {\n // Network/parse failure → no results (never throws into the agent turn).\n return [];\n }\n };\n}\n","/**\n * `write_file` — built-in tool for coding agents.\n *\n * Writes UTF-8 content to a project-relative path. Creates parent\n * directories recursively. Refuses binary-file overwrites, path\n * traversal, and sensitive paths.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, path, bytes }` on success\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' |\n * 'binary_file' }` on refusal\n */\n\nimport { stat as fsStat, mkdir, open, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n FilesystemError,\n type FilesystemProvider,\n FilesystemReadOnlyError,\n FilesystemSecurityError,\n resolveFilesystem,\n StaleFileError,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { evaluateReadBeforeWrite, type ReadTracker } from \"./read-tracker.js\";\n\n/** Byte window inspected for null bytes when deciding binary vs text. */\nconst BINARY_PROBE_BYTES = 8 * 1024;\n\n/** The run-scoped context a `defineTool` handler receives as its 2nd argument. */\ntype WriteToolContext = { signal?: AbortSignal; context?: unknown };\n\nexport interface CreateWriteFileToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every write is gated against this boundary. */\n projectRoot: string;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver `(ctx) => FilesystemBackend`. When provided, writes\n * route through it (its own boundary + `readOnly` + per-request root) instead\n * of the local project fs. Omitted ⇒ identical current behavior (local\n * `projectRoot`). The `.env`/`.git` policy still applies (storage-independent).\n */\n filesystem?: FilesystemProvider<WriteToolContext>;\n /**\n * SE32 — when true (and a {@link ReadTracker} is supplied), refuse to\n * overwrite an existing file that was not read first, or that changed on disk\n * since it was read (`read_required` / `stale_file`). A NEW file writes\n * freely. Default OFF (unchanged behavior).\n */\n requireReadBeforeWrite?: boolean;\n /** SE32 — the per-run tracker populated by the paired `read_file` tool. */\n readTracker?: ReadTracker;\n}\n\nexport function createWriteFileTool(opts: CreateWriteFileToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n // SE32 — fail fast on a misconfiguration: requiring read-before-write without\n // a tracker would SILENTLY disable the guard (a dangerous false sense of\n // safety). Refuse at construction (Rule 8) instead of a silent no-op.\n if (opts.requireReadBeforeWrite && !opts.readTracker) {\n throw new Error(\n \"createWriteFileTool: requireReadBeforeWrite is true but no readTracker was provided — \" +\n \"pass the same ReadTracker instance to createReadFileTool and createWriteFileTool.\",\n );\n }\n // The tracker is only consulted when read-before-write is enabled.\n const guard = opts.requireReadBeforeWrite ? opts.readTracker : undefined;\n\n return Tool.create({\n name: opts.name ?? \"write_file\",\n description:\n opts.description ??\n \"Write UTF-8 content to a project-relative file, creating parent directories as needed. \" +\n \"OVERWRITES any existing file at the path. Prefer editing an existing file with edit_file \" +\n \"over rewriting it; use write_file to create a NEW file or fully replace a small one. If the \" +\n \"file already exists, read_file it first so you do not discard content you have not seen. \" +\n \"Refuses paths that escape the write root and sensitive files (.env, .git/, node_modules/, \" +\n \".theo/, lock files); the default local root also refuses binary-file overwrites. Returns \" +\n \"{ ok, path, bytes } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative file path.\"),\n content: z.string().describe(\"UTF-8 content to write.\"),\n }),\n handler: async ({ path, content }, ctx) => {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n // SE31 — route through the pluggable backend when one is configured (the\n // backend owns its own boundary, readOnly, and provider); else local fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return writeViaBackend(backend, path, content, guard);\n }\n return writeViaLocalFs(projectRoot, path, content, guard);\n },\n });\n}\n\n/**\n * SE32 — map a read-before-write decision to the tool's error JSON, or `null`\n * when the write may proceed. `currentMtimeMs` is `null` for a not-yet-existing\n * file. No-op (returns null) when no tracker guards this write.\n */\nfunction readBeforeWriteError(\n guard: ReadTracker | undefined,\n path: string,\n currentMtimeMs: number | null,\n): string | null {\n if (!guard) return null;\n const decision = evaluateReadBeforeWrite(guard, path, currentMtimeMs);\n if (decision === \"read_required\")\n return JSON.stringify({ ok: false, error: \"read_required\", path });\n if (decision === \"stale\") return JSON.stringify({ ok: false, error: \"stale_file\", path });\n return null;\n}\n\n/** Local-`projectRoot` write path: boundary + read-before-write + binary guard + write. */\nasync function writeViaLocalFs(\n projectRoot: string,\n path: string,\n content: string,\n guard: ReadTracker | undefined,\n): Promise<string> {\n let absolutePath: string;\n try {\n absolutePath = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n\n // SE32 — read-before-write check against the current on-disk mtime. NOTE: the\n // local path detects a file that CHANGED between read and write, but the\n // window between this stat and the writeFile below is an accepted TOCTOU\n // (same-user local context — matching @theokit/sdk/filesystem's LocalFilesystem\n // disclaimer). The `filesystem` backend path additionally forwards\n // `expectedMtime` for a tighter write-time re-check.\n const rbw = readBeforeWriteError(guard, path, await statMtimeOrNull(absolutePath));\n if (rbw) return rbw;\n\n // Binary file guard: probe existing file for null bytes before overwriting\n if (await isBinaryFile(absolutePath)) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path });\n }\n\n await mkdir(dirname(absolutePath), { recursive: true });\n await writeFile(absolutePath, content, \"utf-8\");\n const bytes = Buffer.byteLength(content, \"utf-8\");\n\n return JSON.stringify({ ok: true, path, bytes });\n}\n\n/** Current mtime of `absolutePath`, or `null` when the file does not exist. */\nasync function statMtimeOrNull(absolutePath: string): Promise<number | null> {\n try {\n return (await fsStat(absolutePath)).mtimeMs;\n } catch (err) {\n if ((err as { code?: string }).code === \"ENOENT\") return null;\n throw err;\n }\n}\n\n/**\n * Current mtime of `path` via the backend, or `null` when absent. A single\n * `stat()` with a typed-not-found catch — avoids the exists()+stat() TOCTOU\n * where the file could vanish between the two calls (a `FileNotFoundError`\n * would otherwise escape the write handler's catch and crash the loop).\n */\nasync function backendMtimeOrNull(\n backend: FilesystemBackend,\n path: string,\n): Promise<number | null> {\n try {\n return (await backend.stat(path)).mtimeMs;\n } catch (err) {\n if (err instanceof FileNotFoundError) return null;\n throw err;\n }\n}\n\n/**\n * SE31 — write through a {@link FilesystemBackend}, mapping its typed errors to\n * the tool's `{ ok: false, error }` JSON shape (never throws on a user mistake).\n */\nasync function writeViaBackend(\n backend: FilesystemBackend,\n path: string,\n content: string,\n guard: ReadTracker | undefined,\n): Promise<string> {\n try {\n // SE32 — read-before-write against the backend's current mtime; on pass,\n // forward `expectedMtime` so the backend re-checks at write time (TOCTOU).\n let expectedMtime: number | undefined;\n if (guard) {\n const current = await backendMtimeOrNull(backend, path);\n const rbw = readBeforeWriteError(guard, path, current);\n if (rbw) return rbw;\n expectedMtime = current ?? undefined;\n }\n const stat = await backend.writeFile(\n path,\n content,\n expectedMtime !== undefined ? { expectedMtime } : undefined,\n );\n return JSON.stringify({ ok: true, path, bytes: stat.size });\n } catch (err) {\n return backendErrorToJson(err, path);\n }\n}\n\n/**\n * Map a {@link FilesystemBackend} typed error to the tool's `{ ok: false }` JSON\n * (a recoverable \"bad path\"/\"stale\" the agent should see, not a loop-crashing\n * throw). Rethrows anything untyped (a genuine bug should surface).\n */\nfunction backendErrorToJson(err: unknown, path: string): string {\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n if (err instanceof FilesystemReadOnlyError) {\n return JSON.stringify({ ok: false, error: \"read_only\", path });\n }\n if (err instanceof StaleFileError) {\n return JSON.stringify({ ok: false, error: \"stale_file\", path });\n }\n if (err instanceof FilesystemError) {\n return JSON.stringify({ ok: false, error: \"write_failed\", path });\n }\n throw err;\n}\n\nasync function isBinaryFile(absolutePath: string): Promise<boolean> {\n let handle: import(\"node:fs/promises\").FileHandle | undefined;\n try {\n handle = await open(absolutePath, \"r\");\n } catch {\n return false; // file doesn't exist yet — not binary\n }\n try {\n const stat = await handle.stat();\n const probeLen = Math.min(BINARY_PROBE_BYTES, Number(stat.size));\n if (probeLen <= 0) return false;\n const probe = Buffer.alloc(probeLen);\n const { bytesRead } = await handle.read(probe, 0, probeLen, 0);\n for (let i = 0; i < bytesRead; i += 1) {\n if (probe[i] === 0) return true;\n }\n return false;\n } finally {\n await handle.close();\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/v4a-patch.ts","../src/apply-patch.ts","../src/artifact-store.ts","../src/current-time.ts","../src/internal/context-match.ts","../src/edit-file.ts","../src/formatter.ts","../src/subprocess.ts","../src/internal/git-exec.ts","../src/path-scope.ts","../src/git-diff.ts","../src/git-status.ts","../src/glob-files.ts","../src/interactive-shell.ts","../src/internal/shell-guard.ts","../src/internal/command-policy.ts","../src/internal/network-guard.ts","../src/internal/repo-map.ts","../src/internal/tool-aci.ts","../src/internal/tool-guidance.ts","../src/list-dir.ts","../src/plan-mode.ts","../src/question.ts","../src/read-file.ts","../src/read-tracker.ts","../src/reasoning-tools.ts","../src/run-vitest.ts","../src/search-text.ts","../src/shell-exec.ts","../src/todo-plan-nodes.ts","../src/todolist.ts","../src/truncation.ts","../src/update-plan.ts","../src/web-fetch.ts","../src/web-search.ts","../src/web-search-brave.ts","../src/web-search-http.ts","../src/write-file.ts"],"names":["safePathJoin","mkdir","readFile","stat","Tool","z","matchesAt","writeFile","existsSync","join","resolveSandbox","resolveFilesystem","relative","readdir","ConfigurationError","lookup","dnsLookup","walkDir","FileNotFoundError","isAbsolute","FilesystemSecurityError","DEFAULT_TIMEOUT_MS","DEFAULT_MAX_STDOUT_BYTES","spawn","BINARY_PROBE_BYTES","MAX_BACKEND_WALK_DEPTH","relativePath","dirname","fsStat","open"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,KAAA,GAAQ,iBAAA;AACd,IAAM,GAAA,GAAM,eAAA;AACZ,IAAM,GAAA,GAAM,gBAAA;AACZ,IAAM,MAAA,GAAS,mBAAA;AACf,IAAM,MAAA,GAAS,mBAAA;AACf,IAAM,IAAA,GAAO,eAAA;AACb,IAAM,QAAA,GAAW,iBAAA;AACjB,IAAM,GAAA,GAAM,KAAA;AACZ,IAAM,SAAA,GAAY,IAAA;AAcX,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF,CAAA;AAGO,SAAS,SAAS,KAAA,EAA0B;AACjD,EAAA,MAAM,QAAQ,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA,CAAE,IAAI,CAAC,CAAA,KAAO,CAAA,CAAE,QAAA,CAAS,IAAI,CAAA,GAAI,CAAA,CAAE,MAAM,CAAA,EAAG,EAAE,IAAI,CAAE,CAAA;AAClF,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,E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A,CAAM,QAAQ,CAAA;AACnC,IAAA,MAAM,EAAE,WAAU,GAAI,MAAM,OAAO,IAAA,CAAK,KAAA,EAAO,CAAA,EAAG,QAAA,EAAU,CAAC,CAAA;AAC7D,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,SAAA,EAAW,KAAK,CAAA,EAAG;AACrC,MAAA,IAAI,KAAA,CAAM,CAAC,CAAA,KAAM,CAAA,EAAG,OAAO,IAAA;AAAA,IAC7B;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,SAAE;AACA,IAAA,MAAM,OAAO,KAAA,EAAM;AAAA,EACrB;AACF","file":"index.js","sourcesContent":["/**\n * V4A patch format — Codex's `apply_patch` grammar (`*** Begin Patch` … `*** End Patch`).\n *\n * A faithful TypeScript reimplementation of the Codex `apply-patch` crate (parser + seek_sequence matcher\n * + apply), with ONE deliberate hardening: the apply is STRICT — the whole plan (every new file content +\n * path check) is computed first, and only if all succeed is anything written. A mismatch/error anywhere\n * ⇒ typed error, zero writes (Codex writes file-by-file and can leave partial writes on an IO error).\n *\n * Grammar:\n * *** Begin Patch / *** End Patch envelope (markers matched after trim; CRLF stripped)\n * *** Add File: <path> then `+`lines create (strip one `+`; always trailing newline)\n * *** Delete File: <path> delete\n * *** Update File: <path> (*** Move to: <path>)? update (+ optional rename)\n * change chunks: `@@` | `@@ <ctx>` then lines:\n * ` `=context (old+new) `+`=add (new) `-`=remove (old) optional `*** End of File`\n */\n\nconst BEGIN = \"*** Begin Patch\";\nconst END = \"*** End Patch\";\nconst ADD = \"*** Add File: \";\nconst DELETE = \"*** Delete File: \";\nconst UPDATE = \"*** Update File: \";\nconst MOVE = \"*** Move to: \";\nconst EOF_MARK = \"*** End of File\";\nconst CTX = \"@@ \";\nconst CTX_EMPTY = \"@@\";\n\nexport type V4AHunk =\n | { kind: \"add\"; path: string; content: string }\n | { kind: \"delete\"; path: string }\n | { kind: \"update\"; path: string; movePath: string | null; chunks: V4AChunk[] };\n\nexport interface V4AChunk {\n context: string | null;\n oldLines: string[];\n newLines: string[];\n eof: boolean;\n}\n\nexport class V4APatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"V4APatchError\";\n }\n}\n\n/** Parse a V4A patch string into hunks. Throws {@link V4APatchError} on any structural problem. */\nexport function parseV4A(patch: string): V4AHunk[] {\n const lines = patch.split(\"\\n\").map((l) => (l.endsWith(\"\\r\") ? l.slice(0, -1) : l));\n let i = 0;\n while (i < lines.length && lines[i]!.trim() !== BEGIN) i++;\n if (i >= lines.length) throw new V4APatchError(\"Invalid patch: missing '*** Begin Patch'\");\n i++; // consume Begin Patch\n\n const hunks: V4AHunk[] = [];\n while (i < lines.length) {\n if (lines[i]!.trim() === END) return hunks;\n const step = parseNextHunk(lines, i);\n if (step.hunk) hunks.push(step.hunk);\n i = step.next;\n }\n throw new V4APatchError(\"Invalid patch: missing '*** End Patch'\");\n}\n\n/** Dispatch on the hunk-header at `i`. Returns the parsed hunk (or none, for a blank line) + next index. */\nfunction parseNextHunk(lines: string[], i: number): { hunk?: V4AHunk; next: number } {\n const line = lines[i]!;\n if (line.startsWith(ADD)) {\n const [hunk, next] = parseAdd(lines, i);\n return { hunk, next };\n }\n if (line.startsWith(DELETE)) {\n return { hunk: { kind: \"delete\", path: line.slice(DELETE.length).trim() }, next: i + 1 };\n }\n if (line.startsWith(UPDATE)) {\n const [hunk, next] = parseUpdate(lines, i);\n return { hunk, next };\n }\n if (line.trim() === \"\") return { next: i + 1 }; // tolerate blank lines between hunks\n throw new V4APatchError(`Invalid patch hunk on line ${i + 1}: unexpected '${line}'`);\n}\n\nfunction parseAdd(lines: string[], start: number): [V4AHunk, number] {\n const path = lines[start]!.slice(ADD.length).trim();\n let i = start + 1;\n const body: string[] = [];\n while (i < lines.length && lines[i]!.startsWith(\"+\")) {\n body.push(lines[i]!.slice(1));\n i++;\n }\n // Every added line (incl. the last) is followed by a newline ⇒ file always ends with a trailing newline.\n const content = body.length > 0 ? `${body.join(\"\\n\")}\\n` : \"\";\n return [{ kind: \"add\", path, content }, i];\n}\n\nfunction parseUpdate(lines: string[], start: number): [V4AHunk, number] {\n const path = lines[start]!.slice(UPDATE.length).trim();\n let i = start + 1;\n let movePath: string | null = null;\n if (i < lines.length && lines[i]!.startsWith(MOVE)) {\n movePath = lines[i]!.slice(MOVE.length).trim();\n i++;\n }\n const chunks: V4AChunk[] = [];\n let cur: V4AChunk | null = null;\n for (; i < lines.length; i++) {\n const line = lines[i]!;\n if (isHunkBoundary(line)) break;\n cur = feedLine(chunks, cur, line, path, i + 1);\n }\n pushChunk(chunks, cur, path);\n if (chunks.length === 0) throw new V4APatchError(`Update file hunk for '${path}' is empty`);\n return [{ kind: \"update\", path, movePath, chunks }, i];\n}\n\nfunction isHunkBoundary(line: string): boolean {\n return (\n line.trim() === END ||\n line.startsWith(ADD) ||\n line.startsWith(DELETE) ||\n line.startsWith(UPDATE)\n );\n}\n\nfunction emptyChunk(): V4AChunk {\n return { context: null, oldLines: [], newLines: [], eof: false };\n}\n\n/** Push a completed chunk (rejecting an empty change block), or no-op when there is no current chunk. */\nfunction pushChunk(chunks: V4AChunk[], cur: V4AChunk | null, path: string): void {\n if (!cur) return;\n if (cur.oldLines.length === 0 && cur.newLines.length === 0) {\n throw new V4APatchError(`Update hunk for '${path}' has an empty change block`);\n }\n chunks.push(cur);\n}\n\n/** Route one line inside an Update hunk: a `@@` marker starts a chunk, `*** End of File` flags eof,\n * everything else is a change line. Returns the current chunk. */\nfunction feedLine(\n chunks: V4AChunk[],\n cur: V4AChunk | null,\n line: string,\n path: string,\n lineNum: number,\n): V4AChunk {\n if (line === CTX_EMPTY || line.startsWith(CTX)) {\n pushChunk(chunks, cur, path);\n return {\n context: line === CTX_EMPTY ? null : line.slice(CTX.length),\n oldLines: [],\n newLines: [],\n eof: false,\n };\n }\n if (line.trim() === EOF_MARK) {\n if (!cur) throw new V4APatchError(`'*** End of File' before any change in '${path}'`);\n cur.eof = true;\n return cur;\n }\n return appendChangeLine(cur, line, path, lineNum);\n}\n\n/** Classify a `+`add / `-`remove / ` `|empty context line into the chunk. */\nfunction appendChangeLine(\n cur: V4AChunk | null,\n line: string,\n path: string,\n lineNum: number,\n): V4AChunk {\n const c = cur ?? emptyChunk();\n if (line.startsWith(\"+\")) {\n c.newLines.push(line.slice(1));\n return c;\n }\n if (line.startsWith(\"-\")) {\n c.oldLines.push(line.slice(1));\n return c;\n }\n if (line === \"\" || line.startsWith(\" \")) {\n const content = line === \"\" ? \"\" : line.slice(1); // bare empty line = empty context line\n c.oldLines.push(content);\n c.newLines.push(content);\n return c;\n }\n throw new V4APatchError(\n `Unexpected line in update hunk for '${path}' (line ${lineNum}): every line must start with ' ', '+', or '-': '${line}'`,\n );\n}\n\n// --- Matching: the seek_sequence ladder (exact → rstrip → trim → unicode) ---\n\nconst UNICODE_MAP: Record<string, string> = {\n \"‐\": \"-\",\n \"‑\": \"-\",\n \"‒\": \"-\",\n \"–\": \"-\",\n \"—\": \"-\",\n \"―\": \"-\",\n \"‘\": \"'\",\n \"’\": \"'\",\n \"“\": '\"',\n \"”\": '\"',\n \" \": \" \",\n \" \": \" \",\n \" \": \" \",\n};\nfunction normalise(s: string): string {\n let out = \"\";\n for (const ch of s) out += UNICODE_MAP[ch] ?? ch;\n return out.trim();\n}\n\nconst LADDER: Array<(a: string, b: string) => boolean> = [\n (a, b) => a === b,\n (a, b) => a.replace(/\\s+$/, \"\") === b.replace(/\\s+$/, \"\"),\n (a, b) => a.trim() === b.trim(),\n (a, b) => normalise(a) === normalise(b),\n];\n\nfunction matchesAt(\n lines: string[],\n pattern: string[],\n at: number,\n eq: (a: string, b: string) => boolean,\n): boolean {\n for (let k = 0; k < pattern.length; k++) {\n if (!eq(lines[at + k]!, pattern[k]!)) return false;\n }\n return true;\n}\n\n/** First index ≥ searchStart where `pattern` matches `lines` under increasing leniency; null if none.\n * `eof` forces the search to start at the tail. Mirrors Codex `seek_sequence`. */\nexport function seekSequence(\n lines: string[],\n pattern: string[],\n searchStart: number,\n eof: boolean,\n): number | null {\n if (pattern.length === 0) return searchStart;\n if (pattern.length > lines.length) return null;\n // `eof` is a HINT: prefer a match anchored at the tail, but fall back to a general forward search —\n // otherwise a last-line edit fails, because `\"a\\nb\\n\".split(\"\\n\")` has a phantom trailing \"\" that\n // pushes the tail anchor one past the real last line.\n const starts = eof\n ? [Math.max(searchStart, lines.length - pattern.length), searchStart]\n : [searchStart];\n for (const start of starts) {\n const hit = searchFrom(lines, pattern, start);\n if (hit !== null) return hit;\n }\n return null;\n}\n\n/** Scan `lines` from `start` under the leniency ladder; the first matching index, or null. */\nfunction searchFrom(lines: string[], pattern: string[], start: number): number | null {\n for (const eq of LADDER) {\n for (let i = start; i <= lines.length - pattern.length; i++) {\n if (matchesAt(lines, pattern, i, eq)) return i;\n }\n }\n return null;\n}\n\n/** Apply an update hunk's chunks to file content (forward cursor, sequential). Throws on a context/region miss. */\nexport function applyUpdateChunks(content: string, path: string, chunks: V4AChunk[]): string {\n const lines = content.split(\"\\n\");\n // Collect (start, oldLen, newLines) forward-only, then splice descending so indices stay valid.\n const edits: Array<{ start: number; oldLen: number; newLines: string[] }> = [];\n let cursor = 0;\n for (const chunk of chunks) {\n if (chunk.context !== null) {\n const ctxAt = seekSequence(lines, [chunk.context], cursor, false);\n if (ctxAt === null) {\n throw new V4APatchError(`Failed to find context '${chunk.context}' in ${path}`);\n }\n cursor = ctxAt + 1;\n }\n const at = seekSequence(lines, chunk.oldLines, cursor, chunk.eof);\n if (at === null) {\n throw new V4APatchError(\n `Failed to find expected lines in ${path}:\\n${chunk.oldLines.join(\"\\n\")}`,\n );\n }\n edits.push({ start: at, oldLen: chunk.oldLines.length, newLines: chunk.newLines });\n cursor = at + chunk.oldLines.length;\n }\n edits.sort((a, b) => b.start - a.start);\n for (const e of edits) {\n lines.splice(e.start, e.oldLen, ...e.newLines);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * `apply_patch` — built-in tool for coding agents.\n *\n * Codex's V4A patch grammar (`*** Begin Patch` … `*** End Patch`): `*** Add/Update/Delete File:`, an\n * optional `*** Move to:`, and `@@`-anchored `+`/`-`/context hunks matched with a context-tolerant ladder\n * (exact → rstrip → trim → unicode). See `internal/v4a-patch.ts` for the parser + matcher.\n *\n * Applied STRICTLY atomically: the whole patch is planned (every file read + new content computed + path\n * security-checked) before ANY write. A parse error, context mismatch, or path violation anywhere ⇒ typed\n * error and ZERO writes (stronger than Codex, which writes file-by-file and can leave partial writes).\n *\n * Return shape (always a JSON string — never throws on a bad patch):\n * - `{ ok: true, files_patched: string[] }`\n * - `{ ok: false, error: 'parse_error' | 'path_traversal' | 'forbidden_path' | 'not_found' |\n * 'patch_failed' | 'duplicate_target' | 'file_exists' | 'io_error' }`\n *\n * Security/robustness (M18 review): forbidden secrets (`.env`/`.git`/`node_modules`/`.theo`) are blocked\n * at ANY path depth and against absolute-path spelling; a file touched by two hunks is rejected\n * (`duplicate_target`); Add over an existing file is rejected (`file_exists`); Delete of a missing file\n * is `not_found`; any unexpected fs error maps to `io_error` (the handler never throws).\n */\n\nimport { mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { applyUpdateChunks, parseV4A, type V4AHunk, V4APatchError } from \"./internal/v4a-patch.js\";\n\nexport interface CreateApplyPatchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every hunk path is gated against this boundary. */\n projectRoot: string;\n}\n\nexport function createApplyPatchTool(opts: CreateApplyPatchToolOptions): CustomTool {\n const { projectRoot } = opts;\n\n return Tool.create({\n name: opts.name ?? \"apply_patch\",\n description:\n opts.description ??\n \"Apply a Codex-style V4A patch. The patch is `*** Begin Patch` … `*** End Patch` wrapping one or \" +\n \"more hunks: `*** Add File: <path>` (then `+`lines), `*** Delete File: <path>`, or `*** Update \" +\n \"File: <path>` (optional `*** Move to: <path>`) with `@@`-anchored `+` (add) / `-` (remove) / ` ` \" +\n \"(context) lines. Read a file first so your context/removed lines match. Applied atomically — a \" +\n \"mismatch anywhere aborts the whole patch with zero writes; each path is security-checked. Returns \" +\n \"{ ok, files_patched } or { ok: false, error }.\",\n inputSchema: z.object({\n patch: z.string().min(1).describe(\"V4A patch: *** Begin Patch … *** End Patch.\"),\n }),\n handler: async ({ patch }) => applyV4APatch(projectRoot, patch),\n });\n}\n\n/** A single filesystem mutation in the apply plan. A `move` is expressed as a write + an rm. */\ntype FsOp = { write: { abs: string; content: string } } | { rm: string };\n\ntype PlanResult = { ops: FsOp[]; patched: string[] } | { error: string };\n\nasync function applyV4APatch(projectRoot: string, patch: string): Promise<string> {\n let hunks: V4AHunk[];\n try {\n hunks = parseV4A(patch);\n } catch (err) {\n const detail = err instanceof V4APatchError ? err.message : String(err);\n return JSON.stringify({ ok: false, error: \"parse_error\", detail });\n }\n // Plan (verify) the WHOLE patch before any write; then execute. First failure ⇒ zero writes. An\n // unexpected fs error during execute maps to a typed `io_error` (honors the always-JSON contract).\n try {\n const plan = await buildPlan(projectRoot, hunks);\n if (\"error\" in plan) return plan.error;\n await executePlan(plan.ops);\n return JSON.stringify({ ok: true, files_patched: plan.patched });\n } catch (err) {\n return JSON.stringify({\n ok: false,\n error: \"io_error\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n}\n\n/** The file paths a hunk mutates (a move touches both its source and destination). */\nfunction hunkTargets(hunk: V4AHunk): string[] {\n if (hunk.kind === \"update\" && hunk.movePath) return [hunk.path, hunk.movePath];\n return [hunk.path];\n}\n\n/** Read + compute + path-check every hunk into a write plan (no writes). First failure aborts. A file\n * touched by two hunks is rejected (Codex forbids editing the same file twice — otherwise the second\n * read sees the original and the first edit is silently lost). */\nasync function buildPlan(projectRoot: string, hunks: V4AHunk[]): Promise<PlanResult> {\n const dup = firstDuplicateTarget(hunks);\n if (dup !== null) {\n return { error: JSON.stringify({ ok: false, error: \"duplicate_target\", path: dup }) };\n }\n const ops: FsOp[] = [];\n const patched: string[] = [];\n for (const hunk of hunks) {\n const planned = await planHunk(projectRoot, hunk);\n if (\"error\" in planned) return planned;\n ops.push(...planned.ops);\n patched.push(hunk.kind === \"update\" ? (hunk.movePath ?? hunk.path) : hunk.path);\n }\n return { ops, patched };\n}\n\n/** The first path touched by two hunks (Codex forbids editing the same file twice), or null. */\nfunction firstDuplicateTarget(hunks: V4AHunk[]): string | null {\n const seen = new Set<string>();\n for (const hunk of hunks) {\n for (const t of hunkTargets(hunk)) {\n if (seen.has(t)) return t;\n seen.add(t);\n }\n }\n return null;\n}\n\n/** Execute the write plan (all reads/computes/checks already passed). */\nasync function executePlan(ops: FsOp[]): Promise<void> {\n for (const op of ops) {\n if (\"rm\" in op) {\n await rm(op.rm, { force: true });\n } else {\n await mkdir(dirname(op.write.abs), { recursive: true });\n await writeFile(op.write.abs, op.write.content, \"utf-8\");\n }\n }\n}\n\n/** Does a path exist (any type)? */\nasync function pathExists(abs: string): Promise<boolean> {\n try {\n await stat(abs);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Plan one hunk (Codex Hunk-kind dispatch) into filesystem ops, or an error JSON string. */\nasync function planHunk(\n projectRoot: string,\n hunk: V4AHunk,\n): Promise<{ ops: FsOp[] } | { error: string }> {\n const scope = v4aScope(projectRoot, hunk.path);\n if (\"error\" in scope) return scope;\n if (hunk.kind === \"add\") {\n // Codex rejects Add over an existing file — never silently clobber.\n if (await pathExists(scope.abs)) {\n return { error: JSON.stringify({ ok: false, error: \"file_exists\", path: hunk.path }) };\n }\n return { ops: [{ write: { abs: scope.abs, content: hunk.content } }] };\n }\n if (hunk.kind === \"delete\") {\n if (!(await pathExists(scope.abs))) {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: hunk.path }) };\n }\n return { ops: [{ rm: scope.abs }] };\n }\n return planUpdate(projectRoot, hunk, scope.abs);\n}\n\n/** Plan an Update hunk: read the OLD file, compute the new content, then write-in-place or move. */\nasync function planUpdate(\n projectRoot: string,\n hunk: Extract<V4AHunk, { kind: \"update\" }>,\n abs: string,\n): Promise<{ ops: FsOp[] } | { error: string }> {\n let content: string;\n try {\n content = await readFile(abs, \"utf-8\");\n } catch (err) {\n if ((err as { code?: string }).code === \"ENOENT\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: hunk.path }) };\n }\n throw err;\n }\n let updated: string;\n try {\n updated = applyUpdateChunks(content, hunk.path, hunk.chunks);\n } catch (err) {\n if (err instanceof V4APatchError) {\n return {\n error: JSON.stringify({\n ok: false,\n error: \"patch_failed\",\n path: hunk.path,\n detail: err.message,\n }),\n };\n }\n throw err;\n }\n if (!hunk.movePath) return { ops: [{ write: { abs, content: updated } }] };\n const dest = v4aScope(projectRoot, hunk.movePath);\n if (\"error\" in dest) return dest;\n // transform-then-rename: write the new content to the destination, remove the original.\n return { ops: [{ write: { abs: dest.abs, content: updated } }, { rm: abs }] };\n}\n\n/** Sensitive path segments — secret-bearing dirs/files that must never be written at ANY depth. */\nconst FORBIDDEN_SEGMENTS = new Set([\".env\", \".git\", \"node_modules\", \".theo\"]);\n\n/** Any-segment forbidden check on a PROJECT-RELATIVE path. `isForbiddenPath` only inspects the first\n * segment (so a nested `sub/.git/hooks/…` or an absolute `<root>/.env` slips past); a writing tool must\n * block a sensitive segment at any depth. */\nfunction isForbiddenRel(rel: string): boolean {\n return rel\n .split(/[/\\\\]/)\n .filter(Boolean)\n .some((s) => s !== \".env.example\" && (FORBIDDEN_SEGMENTS.has(s) || /^\\.env\\./.test(s)));\n}\n\n/** Security-check a hunk path against the project root; returns the resolved abs path or an error JSON\n * string. Resolves FIRST (rejecting traversal/symlink/absolute escape), then checks the resulting\n * project-relative path for a forbidden segment at any depth (closes the nested/absolute `.env` hole). */\nfunction v4aScope(projectRoot: string, file: string): { abs: string } | { error: string } {\n let abs: string;\n try {\n abs = safePathJoin(projectRoot, file);\n assertNoSymlinkEscape(abs, projectRoot);\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path: file }) };\n }\n throw err;\n }\n if (isForbiddenPath(file) || isForbiddenRel(relative(projectRoot, abs))) {\n return { error: JSON.stringify({ ok: false, error: \"forbidden_path\", path: file }) };\n }\n return { abs };\n}\n","import { mkdir, readdir, readFile, stat } from \"node:fs/promises\";\nimport { safeFilenameForId, safePathJoin } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/**\n * Options for {@link createSessionArtifactStore}.\n *\n * @public\n */\nexport interface SessionArtifactStoreOptions {\n /** Directory holding one file per artifact (`<dir>/<idStrategy(id)><extension>`). */\n dir: string;\n /**\n * Map an opaque artifact id to a filesystem-safe filename stem.\n * Default: `safeFilenameForId` (accepts ANY id; deterministically hashes\n * non-conforming input). The result is additionally passed through\n * `safePathJoin`, so a traversal id can never escape `dir`.\n *\n * NOTE — the default `safeFilenameForId` is CASE-FOLDING: ids differing only\n * in case (`\"Run-1\"` vs `\"run-1\"`) map to the SAME file. If your ids are\n * case-sensitive (e.g. base64), supply a case-preserving `idStrategy`.\n */\n idStrategy?: (id: string) => string;\n /** File extension (with leading dot). Default `\".md\"`. */\n extension?: string;\n}\n\n/**\n * A generic, id-keyed, atomic artifact store. Generalizes the per-run\n * session-summary writer pattern: persist an opaque text artifact under a\n * stable id, read it back, and enumerate what's stored.\n *\n * @public\n */\nexport interface SessionArtifactStore {\n /**\n * Write (overwrite) the artifact atomically; returns the resolved path.\n * Content is persisted byte-for-byte. The id is mapped via `idStrategy`\n * (default case-folding — see {@link SessionArtifactStoreOptions.idStrategy}).\n */\n write(id: string, content: string): Promise<string>;\n /** Read the artifact, or `undefined` if absent/unreadable (never throws). */\n read(id: string): Promise<string | undefined>;\n /** Whether an artifact exists for `id` (never throws). */\n has(id: string): Promise<boolean>;\n /** The filename stems of all stored artifacts (never throws; `[]` if dir absent). */\n list(): Promise<string[]>;\n /** The resolved, traversal-safe path for `id`. */\n path(id: string): string;\n}\n\n/**\n * Create a generic artifact store rooted at `dir`. Composes the shipped\n * `safeFilenameForId`/`safePathJoin` path guard + the atomic `replaceFileAtomic`\n * writer — zero new dependencies. Reads never throw; writes fail loud.\n *\n * @public\n */\nexport function createSessionArtifactStore(\n options: SessionArtifactStoreOptions,\n): SessionArtifactStore {\n const { dir } = options;\n const idStrategy = options.idStrategy ?? ((id: string) => safeFilenameForId(id));\n const extension = options.extension ?? \".md\";\n\n function path(id: string): string {\n return safePathJoin(dir, `${idStrategy(id)}${extension}`);\n }\n\n async function write(id: string, content: string): Promise<string> {\n const target = path(id);\n await mkdir(dir, { recursive: true });\n await replaceFileAtomic(target, content);\n return target;\n }\n\n async function read(id: string): Promise<string | undefined> {\n try {\n return await readFile(path(id), \"utf8\");\n } catch {\n return undefined;\n }\n }\n\n async function has(id: string): Promise<boolean> {\n // stat (not read) — O(1) existence check, no full-file load. Never throws.\n try {\n await stat(path(id));\n return true;\n } catch {\n return false;\n }\n }\n\n async function list(): Promise<string[]> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(extension))\n .map((name) => name.slice(0, name.length - extension.length));\n }\n\n return { write, read, has, list, path };\n}\n","/**\n * `current_time` — built-in tool for coding agents.\n *\n * Returns the current date-time. Codex-faithful at the core (its `clock`/`curr_time` tool returns UTC\n * as `YYYY-MM-DD HH:MM:SS UTC`); this built-in keeps that default and adds an optional IANA `timezone`\n * (additive superset — omitted ⇒ UTC, exactly Codex's behavior) plus an unambiguous `iso` instant.\n *\n * The clock is injectable so the tool is deterministic under test (testing.md §6: never read the real\n * wall clock in a unit test).\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, current_time: \"YYYY-MM-DD HH:MM:SS <tz>\", iso: string, timezone: string }`\n * - `{ ok: false, error: \"invalid_timezone\", timezone }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nexport interface CreateCurrentTimeToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Injectable clock — defaults to `() => new Date()`. Pass a fixed clock for deterministic tests. */\n clock?: () => Date;\n}\n\n/** Format `now` as `YYYY-MM-DD HH:MM:SS <tz>` in the given IANA timezone. Throws RangeError on a bad tz\n * (Intl validates the zone); assembled from `formatToParts` so the layout is ICU-locale-independent. */\nfunction formatInTimezone(now: Date, tz: string): string {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n }).formatToParts(now);\n const p: Record<string, string> = {};\n for (const { type, value } of parts) p[type] = value;\n // ICU can emit \"24\" for midnight under hour12:false — normalize to \"00\".\n const hour = p.hour === \"24\" ? \"00\" : p.hour;\n return `${p.year}-${p.month}-${p.day} ${hour}:${p.minute}:${p.second} ${tz}`;\n}\n\nexport function createCurrentTimeTool(opts: CreateCurrentTimeToolOptions = {}): CustomTool {\n const clock = opts.clock ?? (() => new Date());\n\n return Tool.create({\n name: opts.name ?? \"current_time\",\n description:\n opts.description ??\n \"Get the current date and time. Returns { current_time, iso, timezone } as a JSON string, where \" +\n \"current_time is 'YYYY-MM-DD HH:MM:SS <timezone>' and iso is the ISO-8601 instant. Pass an optional \" +\n \"IANA timezone (e.g. 'America/Sao_Paulo', 'Europe/Lisbon'); defaults to UTC. Never state the date \" +\n \"or time from memory — always call this. Returns { ok: false, error: 'invalid_timezone' } for an \" +\n \"unknown timezone.\",\n inputSchema: z.object({\n timezone: z\n .string()\n .optional()\n .describe(\"IANA timezone, e.g. 'America/Sao_Paulo' or 'Europe/Lisbon'. Defaults to UTC.\"),\n }),\n handler: ({ timezone }) => {\n const tz = timezone ?? \"UTC\";\n const now = clock();\n try {\n return JSON.stringify({\n ok: true,\n current_time: formatInTimezone(now, tz),\n iso: now.toISOString(),\n timezone: tz,\n });\n } catch {\n // Fail-clear with a typed error shape (Rule 8) instead of a cryptic RangeError.\n return JSON.stringify({ ok: false, error: \"invalid_timezone\", timezone: tz });\n }\n },\n });\n}\n","/**\n * Context-tolerant single-occurrence text matching (`seek_sequence` parity, ported\n * from the AgentBuilder Codex clone, M10/M13). Where a naive `edit_file` matches\n * `old_string` byte-for-byte (or with a single whitespace-normalized fallback),\n * this matcher is safe AND forgiving:\n *\n * Stage 1 — exact byte substring, with an **ambiguity guard**: if the target\n * appears more than once it throws instead of silently editing the first hit\n * (a too-short `old_string` editing the wrong location is the classic footgun).\n * Stage 2 — line-based match down a **strictness ladder** (exact → rstrip → trim\n * → unicode-normalize), stopping at the first rung that yields exactly ONE\n * match; a rung matching 2+ positions throws (ambiguous), never picks one.\n *\n * Pure. Preserves the file's CRLF/LF style on the replaced region. Throws typed\n * {@link ContextMatchError} (`empty | ambiguous | not_found`) so the caller maps to\n * its own `{ ok: false, error }` shape.\n */\n\nexport type ContextMatchReason = \"empty\" | \"ambiguous\" | \"not_found\";\n\nexport class ContextMatchError extends Error {\n readonly reason: ContextMatchReason;\n constructor(reason: ContextMatchReason, message: string) {\n super(message);\n this.name = \"ContextMatchError\";\n this.reason = reason;\n }\n}\n\n/** Normalize common Unicode punctuation to ASCII (dashes/quotes/odd-spaces) — the loosest ladder rung,\n * mirroring `git apply`'s fuzz so an ASCII-authored edit still matches typographic source. */\nfunction normalizeUnicode(s: string): string {\n return s\n .replace(/[‐-―−]/g, \"-\")\n .replace(/[‘-‛]/g, \"'\")\n .replace(/[“-‟]/g, '\"')\n .replace(/[ -    ]/g, \" \");\n}\n\n/** The strictness ladder: each rung normalizes a line before comparison. */\nconst LINE_MATCH_LADDER: ReadonlyArray<(s: string) => string> = [\n (s) => s, // exact\n (s) => s.replace(/\\s+$/, \"\"), // rstrip (ignore trailing whitespace)\n (s) => s.trim(), // trim (ignore leading + trailing)\n (s) => normalizeUnicode(s).trim(), // unicode + trim (loosest)\n];\n\n/** Whether `pattern` matches `lines` starting at index `i`, comparing each line under `norm`. */\nfunction matchesAt(\n lines: string[],\n pattern: string[],\n i: number,\n norm: (s: string) => string,\n): boolean {\n for (let p = 0; p < pattern.length; p++) {\n const lineAt = lines[i + p];\n const patAt = pattern[p];\n if (lineAt === undefined || patAt === undefined || norm(lineAt) !== norm(patAt)) return false;\n }\n return true;\n}\n\n/** Every start index where `pattern` matches `lines` under `norm`. */\nfunction findHits(lines: string[], pattern: string[], norm: (s: string) => string): number[] {\n const hits: number[] = [];\n for (let i = 0; i + pattern.length <= lines.length; i++) {\n if (matchesAt(lines, pattern, i, norm)) hits.push(i);\n }\n return hits;\n}\n\n/**\n * Find the UNIQUE start line index where `pattern` matches `lines`, trying the ladder top-down.\n * Returns the index at the FIRST rung yielding exactly one match; `null` if none; throws (ambiguous)\n * if a rung matches 2+ positions. Empty or too-long pattern → null.\n */\nfunction seekUniqueLineMatch(lines: string[], pattern: string[], find: string): number | null {\n if (pattern.length === 0 || pattern.length > lines.length) return null;\n for (const norm of LINE_MATCH_LADDER) {\n const hits = findHits(lines, pattern, norm);\n if (hits.length === 1) return hits[0] ?? null;\n if (hits.length > 1) {\n throw new ContextMatchError(\n \"ambiguous\",\n `target text is ambiguous (multiple matches); include more context:\\n${find}`,\n );\n }\n }\n return null;\n}\n\n/**\n * Return `content` with the single occurrence of `find` replaced by `replace`, using the two-stage\n * context-tolerant matcher. Throws {@link ContextMatchError} on empty/ambiguous/not-found.\n */\nexport function replaceUnique(content: string, find: string, replace: string): string {\n if (find === \"\") {\n throw new ContextMatchError(\n \"empty\",\n \"empty find is not a valid target; provide the text to replace\",\n );\n }\n // Stage 1 — exact byte substring (fast path + uniqueness). The ambiguity re-scan starts at\n // `first + 1` (NOT `first + find.length`) so a self-OVERLAPPING find is still caught as ambiguous.\n const first = content.indexOf(find);\n if (first !== -1) {\n if (content.indexOf(find, first + 1) !== -1) {\n throw new ContextMatchError(\n \"ambiguous\",\n `target text is ambiguous (multiple matches); include more context:\\n${find}`,\n );\n }\n return content.slice(0, first) + replace + content.slice(first + find.length);\n }\n // Stage 2 — line-based tolerant match (seek_sequence ladder).\n const lines = content.split(\"\\n\");\n const at = seekUniqueLineMatch(lines, find.split(\"\\n\"), find);\n if (at === null) {\n throw new ContextMatchError(\"not_found\", `target text not found:\\n${find}`);\n }\n const patternLen = find.split(\"\\n\").length;\n // Preserve the file's line-ending style: a CRLF file split on '\\n' keeps a trailing '\\r' per line.\n // If the MATCHED region is CRLF, re-attach '\\r' to the (LF-authored) replace lines so the edit never\n // leaves mixed CRLF/LF endings behind.\n const matchedCrlf =\n patternLen > 0 && lines.slice(at, at + patternLen).every((l) => l.endsWith(\"\\r\"));\n const replaceLines = matchedCrlf\n ? replace.split(\"\\n\").map((l) => (l.endsWith(\"\\r\") ? l : `${l}\\r`))\n : replace.split(\"\\n\");\n return [...lines.slice(0, at), ...replaceLines, ...lines.slice(at + patternLen)].join(\"\\n\");\n}\n","/**\n * `edit_file` — built-in tool for coding agents.\n *\n * Replaces a string in a project-relative file. Tries exact match first,\n * then whitespace-normalized match. Creates a `.bak` backup before editing.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, replacements: 1 }` on success\n * - `{ ok: false, error: 'no_match' | 'not_found' | 'path_traversal' |\n * 'forbidden_path' }` on refusal\n */\n\nimport { copyFile, readFile, writeFile } from \"node:fs/promises\";\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport { ContextMatchError, replaceUnique } from \"./internal/context-match.js\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nexport interface CreateEditFileToolOptions {\n /**\n * M76 — the name exposed to the model. Omitted ⇒ today's literal (additive).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every edit is gated against this boundary. */\n projectRoot: string;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the read + `.bak` backup +\n * write go through the backend (surface-agnostic); omitted ⇒ the local `fs` path (byte-identical). */\n filesystem?: FilesystemProvider;\n}\n\ntype EditOutcome = { ok: true; result: string } | { ok: false; error: \"no_match\" };\n\n/** Pure string-replacement core shared by the local and backend paths (no I/O): exact → whitespace-\n * normalized → context-tolerant ladder. Extracting it keeps the matching algorithm single-sourced (DRY)\n * while both fs paths do their own read/backup/write. */\nfunction computeEdit(content: string, old_string: string, new_string: string): EditOutcome {\n const exactIdx = content.indexOf(old_string);\n if (exactIdx !== -1) {\n return {\n ok: true,\n result: content.slice(0, exactIdx) + new_string + content.slice(exactIdx + old_string.length),\n };\n }\n const normalizedContent = normalizeWhitespace(content);\n const normalizedOld = normalizeWhitespace(old_string);\n const normalizedIdx = normalizedContent.indexOf(normalizedOld);\n if (normalizedIdx !== -1) {\n const span = findOriginalSpan(content, normalizedContent, normalizedIdx, normalizedOld.length);\n return {\n ok: true,\n result: content.slice(0, span.start) + new_string + content.slice(span.end),\n };\n }\n try {\n return { ok: true, result: replaceUnique(content, old_string, new_string) };\n } catch (err) {\n if (err instanceof ContextMatchError) return { ok: false, error: \"no_match\" };\n throw err;\n }\n}\n\n/** Apply an edit through an injected FilesystemBackend (project-relative path space, like read_file):\n * read → write a `.bak` backup → write the result. The path-scope guards run in the caller. */\nasync function editViaBackend(\n filesystem: FilesystemProvider,\n ctx: unknown,\n path: string,\n old_string: string,\n new_string: string,\n): Promise<string> {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n let content: string;\n try {\n content = await backend.readFile(path);\n } catch (err) {\n // Mirror the local path: only a missing file maps to `not_found`; every other read failure\n // (a directory, a permission error, a security rejection) propagates — fail-loud, never swallowed.\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n throw err;\n }\n const outcome = computeEdit(content, old_string, new_string);\n if (!outcome.ok) return JSON.stringify({ ok: false, error: \"no_match\", path });\n await backend.writeFile(`${path}.bak`, content);\n await backend.writeFile(path, outcome.result);\n return JSON.stringify({ ok: true, replacements: 1 });\n}\n\n/** Apply an edit through the local `fs` (byte-identical to before): read → computeEdit → `.bak` → write. */\nasync function editViaLocal(\n projectRoot: string,\n path: string,\n old_string: string,\n new_string: string,\n): Promise<string> {\n const absolutePath = safePathJoin(projectRoot, path);\n let content: string;\n try {\n content = await readFile(absolutePath, \"utf-8\");\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\") {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n throw err;\n }\n const outcome = computeEdit(content, old_string, new_string);\n if (!outcome.ok) return JSON.stringify({ ok: false, error: \"no_match\", path });\n await copyFile(absolutePath, `${absolutePath}.bak`);\n await writeFile(absolutePath, outcome.result, \"utf-8\");\n return JSON.stringify({ ok: true, replacements: 1 });\n}\n\n/** Shared path-scope guard for both fs paths — returns an error JSON string, or null when the path is safe. */\nfunction editScopeError(path: string, projectRoot: string): string | null {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, path), projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\nexport function createEditFileTool(opts: CreateEditFileToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"edit_file\",\n description:\n opts.description ??\n \"Make an exact string replacement in a project-relative file. Replaces the FIRST occurrence \" +\n \"of old_string with new_string (a whitespace-normalized fallback is attempted if the exact \" +\n \"match fails) and writes a .bak backup first. Read the file first so old_string matches the \" +\n \"on-disk text exactly; include enough surrounding context to make it unique — only the first \" +\n \"match is replaced, so a too-short old_string can edit the wrong location. old_string must be \" +\n \"non-empty and differ from new_string; to change every occurrence, call edit_file repeatedly. \" +\n \"Returns { ok, replacements } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative file path.\"),\n old_string: z.string().min(1).describe(\"String to find in the file.\"),\n new_string: z.string().describe(\"Replacement string.\"),\n }),\n handler: async ({ path, old_string, new_string }, ctx) => {\n // A no-op edit (old === new) cannot change the file; refuse early so the description's\n // \"old_string must differ from new_string\" precondition is enforced, not just documented.\n if (old_string === new_string) {\n return JSON.stringify({ ok: false, error: \"no_change\", path });\n }\n\n // Path-scope guard (pure security) applies to both fs paths.\n const scopeErr = editScopeError(path, projectRoot);\n if (scopeErr !== null) return scopeErr;\n\n // Injected filesystem (surface-agnostic) ⇒ read/backup/write via the backend; absent ⇒ local `fs`.\n return filesystem !== undefined\n ? editViaBackend(filesystem, ctx, path, old_string, new_string)\n : editViaLocal(projectRoot, path, old_string, new_string);\n },\n });\n}\n\n/** Collapse runs of whitespace into a single space. */\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Map a position range in the whitespace-normalized string back to the\n * original string. Walks both strings in lockstep.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: parser logic\nfunction findOriginalSpan(\n original: string,\n _normalized: string,\n normStart: number,\n normLen: number,\n): { start: number; end: number } {\n let origIdx = 0;\n let normIdx = 0;\n\n // Skip leading whitespace that was trimmed\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n\n // Walk to normStart\n while (normIdx < normStart && origIdx < original.length) {\n if (/\\s/.test(original[origIdx]!)) {\n // skip entire whitespace run in original, counts as one in normalized\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n normIdx++; // the collapsed space\n } else {\n origIdx++;\n normIdx++;\n }\n }\n\n const start = origIdx;\n\n // Walk normLen characters\n let walked = 0;\n while (walked < normLen && origIdx < original.length) {\n if (/\\s/.test(original[origIdx]!)) {\n while (origIdx < original.length && /\\s/.test(original[origIdx]!)) {\n origIdx++;\n }\n walked++; // the collapsed space\n } else {\n origIdx++;\n walked++;\n }\n }\n\n return { start, end: origIdx };\n}\n","/**\n * `formatter` — output formatting utilities for tool results.\n *\n * Wraps code, diffs, file lists, errors, and truncated output references.\n */\n\n/**\n * Wrap code in a fenced code block with language tag.\n */\nexport function formatCode(language: string, code: string): string {\n return `\\`\\`\\`${language}\\n${code}\\n\\`\\`\\``;\n}\n\n/**\n * Format a unified diff with +/- prefixes preserved.\n */\nexport function formatDiff(diff: string): string {\n return `\\`\\`\\`diff\\n${diff}\\n\\`\\`\\``;\n}\n\n/**\n * Format a list of file paths as a bulleted markdown list.\n */\nexport function formatFileList(files: string[]): string {\n if (files.length === 0) return \"(no files)\";\n return files.map((f) => `- ${f}`).join(\"\\n\");\n}\n\n/**\n * Format an error message as a markdown block.\n */\nexport function formatError(message: string, code?: string): string {\n const prefix = code ? `[${code}] ` : \"\";\n return `> **Error:** ${prefix}${message}`;\n}\n\n/**\n * Format a truncated output reference.\n */\nexport function formatTruncated(overflowPath: string): string {\n return `...full output at: ${overflowPath}`;\n}\n","/**\n * Shared subprocess-watch helpers for built-in coding tools (git-diff,\n * run-vitest). Wires the on(close)/on(error) settle pattern in a single\n * place to eliminate the cross-file clone flagged by jscpd.\n *\n * @internal\n */\n\nimport type { ChildProcess } from \"node:child_process\";\n\n/**\n * Settle gate — guarantees the supplied callback fires exactly once across\n * the close/error/timeout race. Clears the timer on settle.\n */\ninterface SettleGate {\n /** True after first settle; subsequent calls are no-ops. */\n settled: () => boolean;\n /** Settle the gate, clear the timer, and call `onSettle()`. */\n fire: (onSettle: () => void) => void;\n}\n\nfunction createSettleGate(timer: NodeJS.Timeout): SettleGate {\n let done = false;\n return {\n settled: () => done,\n fire: (onSettle) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n onSettle();\n },\n };\n}\n\n/**\n * Wire SIGKILL-on-timeout for a detached process group. Returns the settle\n * gate so caller listeners can short-circuit when the timeout already fired.\n */\nexport function armTimeoutKill<T>(\n child: ChildProcess,\n timeoutMs: number,\n onTimeout: () => T,\n resolve: (value: T) => void,\n): SettleGate {\n const timer = setTimeout(() => {\n gate.fire(() => {\n try {\n process.kill(-(child.pid ?? 0), \"SIGKILL\");\n } catch {\n /* already dead */\n }\n resolve(onTimeout());\n });\n }, timeoutMs);\n const gate = createSettleGate(timer);\n return gate;\n}\n\n/**\n * Attach a close+error pair of listeners that resolve via the supplied\n * callbacks. Honors the gate so timeout-vs-close races settle exactly once.\n */\nexport function attachChildSettlers<T>(\n child: ChildProcess,\n gate: SettleGate,\n onClose: (code: number | null) => T,\n onError: (err: Error) => T,\n resolve: (value: T) => void,\n): void {\n child.on(\"close\", (code) => {\n gate.fire(() => resolve(onClose(code)));\n });\n child.on(\"error\", (err) => {\n gate.fire(() => resolve(onError(err)));\n });\n}\n","/**\n * `git` execution for tools — the engine shared by `git_diff` and `git_status`.\n *\n * M76 — promoted from `git-diff.ts`, where it was private. Duplicating it in `git-status` would duplicate\n * KNOWLEDGE: the stdout ceiling, the process-group kill on timeout and the mapping to a typed\n * typed error are the SAME rule for any git subcommand. Two copies would diverge at the first\n * fix, and the symptom would be one tool with a timeout and another that hangs the turn.\n */\nimport { spawn } from \"node:child_process\";\n\nimport { armTimeoutKill, attachChildSettlers } from \"../subprocess.js\";\n\n/** POSIX quoting for the command crossing the sandbox shell. Shared by git_diff and git_status. */\nexport function shq(arg: string): string {\n return `'${arg.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nexport function formatGitResult(result: GitProcessResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n }\n if (result.kind === \"error\") {\n return JSON.stringify({ ok: false, error: \"git_failed\", stderr: result.stderr });\n }\n return JSON.stringify({ ok: true, diff: result.stdout, truncated: result.truncated });\n}\n\ntype GitProcessResult =\n | { kind: \"ok\"; stdout: string; truncated: boolean }\n | { kind: \"error\"; stderr: string }\n | { kind: \"timeout\" };\n\nexport function runGitProcess(\n cwd: string,\n args: string[],\n timeoutMs: number,\n maxStdoutBytes: number,\n): Promise<GitProcessResult> {\n return new Promise((resolve) => {\n // Detached process group so we can kill the whole tree on timeout (EC-7).\n const child = spawn(\"git\", args, { cwd, detached: true, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n let truncated = false;\n\n const gate = armTimeoutKill<GitProcessResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n resolve,\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stdoutBytes >= maxStdoutBytes) {\n truncated = true;\n return;\n }\n const remaining = maxStdoutBytes - stdoutBytes;\n if (chunk.length > remaining) {\n stdoutChunks.push(chunk.subarray(0, remaining));\n stdoutBytes = maxStdoutBytes;\n truncated = true;\n } else {\n stdoutChunks.push(chunk);\n stdoutBytes += chunk.length;\n }\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk);\n });\n\n attachChildSettlers<GitProcessResult>(\n child,\n gate,\n (code) => {\n const stdout = Buffer.concat(stdoutChunks).toString(\"utf-8\");\n const stderr = Buffer.concat(stderrChunks).toString(\"utf-8\");\n return code === 0 ? { kind: \"ok\", stdout, truncated } : { kind: \"error\", stderr };\n },\n (err) => ({ kind: \"error\", stderr: err.message }),\n resolve,\n );\n });\n}\n","/**\n * Shared `safePathJoin + assertNoSymlinkEscape` helper for built-in coding\n * tools (git-diff, run-vitest, list-dir, read-file, search-text). Returns a\n * pre-formatted `path_traversal` JSON string on failure or `null` on pass.\n *\n * @internal\n */\n\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nexport function checkPathScope(path: string | undefined, projectRoot: string): string | null {\n if (path === undefined || path === \"\") return null;\n try {\n const abs = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(abs, projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\n/**\n * Segments that may never appear in a path honored by `allowAbsolute`.\n *\n * M76 — promoted from `read-file.ts`, where it was private. Duplicating it in `list-dir` would duplicate\n * security KNOWLEDGE: the copies would have to agree on what counts as a secret, and one fixed\n * without the other reopens the hole in the forgotten tool.\n */\nconst SENSITIVE_SEGMENTS = new Set([\".env\", \".git\", \"node_modules\", \".theo\"]);\n\n/**\n * ANY-segment secret guard — the half of `allowAbsolute` that cannot be separated.\n *\n * `isForbiddenPath` only blocks the sensitive item when it is the FIRST segment (relative to the\n * project). An absolute path (`/home/u/proj/.env/sub`) puts it deeper, and it would pass. This one\n * checks every segment, closing the \"reads-anywhere\" exfiltration.\n */\nexport function isForbiddenAtAnyDepth(path: string): boolean {\n const segs = path.replace(/\\\\/g, \"/\").split(\"/\").filter(Boolean);\n return segs.some((s) => {\n if (s === \".env.example\") return false; // a template — safe\n return SENSITIVE_SEGMENTS.has(s) || /^\\.env\\./.test(s);\n });\n}\n","/**\n * `git_diff` — built-in tool for coding agents.\n *\n * Returns the unified diff of the working tree (or staged changes when\n * `cached=true`). Implemented as a thin `git diff` subprocess wrapper\n * with a couple of hard limits:\n *\n * - 30s wall clock timeout (kills the process group on expiry)\n * - 5 MB stdout cap (truncate + flag `truncated=true`)\n * - Path scope validated through `safePathJoin` + `assertNoSymlinkEscape`\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, diff: string, truncated?: boolean }`\n * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' }`\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { resolveSandbox, type SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { formatGitResult, runGitProcess, shq } from \"./internal/git-exec.js\";\nimport { checkPathScope } from \"./path-scope.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_STDOUT_BYTES = 5 * 1024 * 1024;\n\nexport interface CreateGitDiffToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n timeoutMs?: number;\n maxStdoutBytes?: number;\n /** Optional injected execution backend (`@theokit/sdk/sandbox`) — when provided, `git diff` runs via\n * `SandboxBackend.execute` (surface-agnostic); omitted ⇒ the local `git` child process (unchanged). */\n sandbox?: SandboxProvider;\n}\n\n/** POSIX single-quote a `git diff` argument for the backend command string (safe against metacharacters). */\n\n/** Run `git diff` through an injected SandboxBackend, mapping its result to git_diff's JSON shape. The\n * scope check (pure security) still applies; the local `.git` existsSync check does not (the repo is in\n * the backend — a non-repo surfaces as git's own \"not a git repository\"). */\nasync function diffViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n cached: boolean | undefined,\n path: string | undefined,\n projectRoot: string,\n timeoutMs: number,\n): Promise<string> {\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n const command = [\"git\", ...buildDiffArgs(cached, path)].map(shq).join(\" \");\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n if (r.timedOut) return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n if (r.exitCode !== 0) {\n return /not a git repository/i.test(r.stderr)\n ? JSON.stringify({ ok: false, error: \"not_a_repo\" })\n : JSON.stringify({ ok: false, error: \"git_failed\", stderr: r.stderr });\n }\n return JSON.stringify({ ok: true, diff: r.stdout, truncated: false });\n}\n\nexport function createGitDiffTool(opts: CreateGitDiffToolOptions): CustomTool {\n const {\n projectRoot,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES,\n sandbox,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"git_diff\",\n description:\n opts.description ??\n \"Return the unified diff of the project's working tree (or staged \" +\n \"changes when cached=true). Scoped to a single file when 'path' is \" +\n \"provided. Requires the project to be a git repository. Returns \" +\n \"{ ok, diff, truncated? } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().optional().describe(\"Optional project-relative file or dir scope.\"),\n cached: z\n .boolean()\n .optional()\n .describe(\"If true, show staged changes (git diff --cached). Default false.\"),\n }),\n handler: async ({ path, cached }, ctx) => {\n // Injected backend (surface-agnostic) ⇒ run in the sandbox; absent ⇒ the local `git` (unchanged).\n if (sandbox !== undefined) {\n return diffViaSandbox(sandbox, ctx, cached, path, projectRoot, timeoutMs);\n }\n\n // Local path — UNCHANGED (byte-identical to before).\n if (!existsSync(join(projectRoot, \".git\"))) {\n return JSON.stringify({ ok: false, error: \"not_a_repo\" });\n }\n\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n\n const args = buildDiffArgs(cached, path);\n const result = await runGitProcess(projectRoot, args, timeoutMs, maxStdoutBytes);\n return formatGitResult(result, timeoutMs);\n },\n });\n}\n\nfunction buildDiffArgs(cached: boolean | undefined, path: string | undefined): string[] {\n const args = [\"diff\", \"--no-color\"];\n if (cached === true) args.push(\"--cached\");\n if (path !== undefined && path !== \"\") args.push(\"--\", path);\n return args;\n}\n","/**\n * `git_status` — built-in tool for coding agents.\n *\n * Returns the working-tree status in porcelain v1 format (`git status --porcelain`), which is the\n * stable machine-readable form — the human format is explicitly not guaranteed across git versions.\n *\n * M76 — born alongside `git_diff` and sharing the execution engine (`internal/git-exec.ts`): the stdout\n * ceiling, process-group kill on timeout and mapping to a typed error are the SAME rule\n * for any git subcommand. The consumer (agent-builder) had this locally in 62 LoC; nothing there\n * was specific to it.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, diff: string, truncated?: boolean }` — `diff` carries the porcelain output\n * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' | 'git_failed' }`\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport type { SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { resolveSandbox } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { formatGitResult, runGitProcess, shq } from \"./internal/git-exec.js\";\n\nimport { checkPathScope } from \"./path-scope.js\";\n\nexport interface CreateGitStatusToolOptions {\n /** Absolute path to the project root. Every invocation is gated against this boundary. */\n projectRoot: string;\n /** Wall-clock cap; the process group is killed on expiry. Default 30_000. */\n timeoutMs?: number;\n /** Cap on captured stdout; excess sets `truncated: true`. Default 5 MB. */\n maxStdoutBytes?: number;\n /**\n * Injected execution backend (`@theokit/sdk/sandbox`) — when present, `git status` runs via\n * `SandboxBackend.execute`; omitted ⇒ the local `git` (unchanged).\n *\n * Symmetry with `createGitDiffTool`, flagged by the M76 review: without it `git_diff` would run\n * confined and `git_status` not, in the same session — and the asymmetry would be invisible until someone\n * notice that one of the two escapes the sandbox.\n */\n sandbox?: SandboxProvider;\n /**\n * M76 — the name exposed to the model. Omitted ⇒ `\"git_status\"` (additive).\n *\n * The name is a contract: the approval key, what the model sees and what telemetry records.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => the literal below (additive). */\n description?: string;\n /**\n * Include the branch line (`-b`) at the start of the output. Default `true`.\n *\n * Without it the agent sees what changed but not WHERE — and \"am I on the right branch?\" is the question that\n * precedes any commit. The consumer (agent-builder) already depended on it; omitting it would make the\n * migration lose behavior silently, which is what deleting local code must not cost.\n */\n includeBranch?: boolean;\n}\n\nexport function createGitStatusTool(opts: CreateGitStatusToolOptions): CustomTool {\n const { projectRoot, timeoutMs = 30_000, maxStdoutBytes = 5 * 1024 * 1024 } = opts;\n\n return Tool.create({\n name: opts.name ?? \"git_status\",\n description:\n opts.description ??\n \"Show the working-tree status in porcelain format: staged, unstaged and untracked paths, one \" +\n \"per line with a two-character status code. Use before committing, or to see what changed \" +\n \"without reading the full diff. Optional 'path' scopes the report to a subdirectory.\",\n inputSchema: z.object({\n path: z\n .string()\n .optional()\n .describe(\"Optional project-relative path to scope the status report.\"),\n }),\n handler: async ({ path }, ctx) => {\n // Outside a repository, `git status` writes to stderr and exits non-zero. Returning an empty string\n // here would be worse than an error: the model would read it as \"no changes\" — indistinguishable from\n // the happy path, and false. `error-handling.md` § 2 requires a typed error.\n if (!existsSync(join(projectRoot, \".git\"))) {\n return JSON.stringify({ ok: false, error: \"not_a_repo\" });\n }\n\n const scopeCheck = checkPathScope(path, projectRoot);\n if (scopeCheck !== null) return scopeCheck;\n\n const args = buildArgs(path, opts.includeBranch !== false);\n\n if (opts.sandbox !== undefined) {\n return statusViaSandbox(opts.sandbox, ctx, args, timeoutMs);\n }\n const result = await runGitProcess(projectRoot, args, timeoutMs, maxStdoutBytes);\n return formatGitResult(result, timeoutMs);\n },\n });\n}\n\n/**\n * The arguments to `git status`.\n *\n * `--porcelain=v1` is deliberate: it is the stable contract for machine reading. The human format\n * changes across git versions and would break the consumer's parsing without warning.\n */\nfunction buildArgs(path: string | undefined, withBranch: boolean): string[] {\n const args = [\"status\", \"--porcelain=v1\"];\n if (withBranch) args.push(\"-b\");\n if (path !== undefined && path !== \"\") args.push(\"--\", path);\n return args;\n}\n\n/**\n * `git status` via `SandboxBackend` — the surface-agnostic path, mirroring `diffViaSandbox`.\n *\n * It exists for symmetry with `git_diff`: without it, in a confined session the diff would run inside the\n * sandbox and the status outside — and the asymmetry would be invisible until someone noticed one of the two escapes.\n */\nasync function statusViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n args: string[],\n timeoutMs: number,\n): Promise<string> {\n const command = [\"git\", ...args].map(shq).join(\" \");\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n if (r.timedOut) return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n if (r.exitCode !== 0) {\n return /not a git repository/i.test(r.stderr)\n ? JSON.stringify({ ok: false, error: \"not_a_repo\" })\n : JSON.stringify({ ok: false, error: \"git_failed\", stderr: r.stderr });\n }\n return JSON.stringify({ ok: true, diff: r.stdout, truncated: false });\n}\n","/**\n * `glob_files` — built-in tool for coding agents.\n *\n * Lists project files matching a glob pattern. Excludes node_modules,\n * .git, and dist by default. Returns relative paths.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, files: string[], count }` (an empty match is `ok: true` with `files: []`)\n * - `{ ok: false, error: 'path_traversal' }`\n */\n\nimport { readdir } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type FilesystemBackend,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\n/** Directories excluded from traversal by default. */\nconst DEFAULT_EXCLUDES = new Set([\"node_modules\", \".git\", \"dist\", \".theo\"]);\n\n/**\n * Depth cap for the BACKEND walk only. The local `readdir(withFileTypes)` walk skips symlinks (a\n * symlink entry is neither `isDirectory()` nor `isFile()`), so it can never loop. The backend walk\n * decides type via `stat`, which follows symlinks, so an in-boundary symlink cycle (e.g. `a → .`)\n * would recurse until the path exceeds PATH_MAX. This bound stops that pathological case; real project\n * trees never approach it.\n */\nconst MAX_BACKEND_WALK_DEPTH = 64;\n\nexport interface CreateGlobToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. */\n projectRoot: string;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the walk reads through the\n * backend (Local/remote), so the tool is surface-agnostic; omitted ⇒ the local `readdir` (unchanged). */\n filesystem?: FilesystemProvider;\n}\n\nexport function createGlobTool(opts: CreateGlobToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"glob_files\",\n description:\n opts.description ??\n \"Find files by glob pattern across the project — fast at any repo size. Use glob_files when \" +\n \"you know the filename SHAPE; use search_text when you know the file CONTENT; use read_file \" +\n \"when you know the exact path. The pattern supports * and ** wildcards (e.g. '**/*.ts', \" +\n \"'src/**/*.json'); node_modules/.git/dist/.theo are excluded and results are relative paths. \" +\n \"Returns { ok, files } or { ok: false, error }.\",\n inputSchema: z.object({\n pattern: z.string().min(1).describe(\"Glob pattern (e.g. '**/*.ts', 'src/**/*.json').\"),\n cwd: z.string().optional().describe(\"Project-relative subdirectory to search from.\"),\n }),\n handler: async ({ pattern, cwd }, ctx) => {\n // Path-scope guard (pure security) applies to both fs paths.\n const scopeErr = globScopeError(cwd, projectRoot);\n if (scopeErr !== null) return scopeErr;\n const regex = globToRegex(pattern);\n\n // Injected filesystem (surface-agnostic): walk via the backend in PROJECT-RELATIVE path space\n // (like read_file); absent ⇒ the local `readdir` walk (byte-identical to before).\n if (filesystem !== undefined) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n const searchRel = cwd ?? \"\";\n const found: string[] = [];\n await walkDirBackend(backend, searchRel, searchRel, regex, found, 0);\n return JSON.stringify({ ok: true, files: found.sort(), count: found.length });\n }\n\n const searchRoot = cwd ? safePathJoin(projectRoot, cwd) : projectRoot;\n const files: string[] = [];\n await walkDir(searchRoot, searchRoot, regex, files);\n const relativePaths = files.map((f) => relative(projectRoot, f)).sort();\n return JSON.stringify({ ok: true, files: relativePaths, count: relativePaths.length });\n },\n });\n}\n\n/** Shared cwd path-scope guard — returns an error JSON string, or null when the scope is safe. */\nfunction globScopeError(cwd: string | undefined, projectRoot: string): string | null {\n if (!cwd) return null;\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, cwd), projectRoot);\n return null;\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path: cwd });\n }\n throw err;\n }\n}\n\nasync function walkDir(\n base: string,\n dir: string,\n pattern: RegExp,\n results: string[],\n): Promise<void> {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return; // directory doesn't exist or unreadable\n }\n\n for (const entry of entries) {\n if (DEFAULT_EXCLUDES.has(entry.name)) continue;\n\n const fullPath = join(dir, entry.name);\n const relPath = relative(base, fullPath);\n\n if (entry.isDirectory()) {\n await walkDir(base, fullPath, pattern, results);\n } else if (entry.isFile() && pattern.test(relPath)) {\n results.push(fullPath);\n }\n }\n}\n\n/** Backend walk (surface-agnostic): mirrors {@link walkDir} in PROJECT-RELATIVE path space via\n * `backend.list` + `backend.stat` (the FilesystemBackend interface returns untyped names, so a\n * `stat` per entry supplies isDirectory/isFile). Collects project-relative paths. */\nasync function walkDirBackend(\n backend: FilesystemBackend,\n base: string,\n dir: string,\n pattern: RegExp,\n results: string[],\n depth: number,\n): Promise<void> {\n if (depth > MAX_BACKEND_WALK_DEPTH) return; // symlink-cycle guard (see MAX_BACKEND_WALK_DEPTH)\n let names: string[];\n try {\n names = await backend.list(dir);\n } catch {\n return; // directory doesn't exist or unreadable\n }\n for (const name of names) {\n await walkBackendEntry(backend, base, dir, name, pattern, results, depth);\n }\n}\n\n/** Handle one backend directory entry: stat it, recurse on dirs, collect matching files. */\nasync function walkBackendEntry(\n backend: FilesystemBackend,\n base: string,\n dir: string,\n name: string,\n pattern: RegExp,\n results: string[],\n depth: number,\n): Promise<void> {\n if (DEFAULT_EXCLUDES.has(name)) return;\n const fullRel = dir === \"\" ? name : `${dir}/${name}`;\n const relPath = base === \"\" ? fullRel : relative(base, fullRel);\n let st: { isDirectory: boolean; isFile: boolean };\n try {\n st = await backend.stat(fullRel);\n } catch {\n return;\n }\n if (st.isDirectory) {\n await walkDirBackend(backend, base, fullRel, pattern, results, depth + 1);\n } else if (st.isFile && pattern.test(relPath)) {\n results.push(fullRel);\n }\n}\n\n/** Convert a simple glob pattern to a RegExp. Supports * and ** wildcards. */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: parser logic\nfunction globToRegex(pattern: string): RegExp {\n let regexStr = \"\";\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i]!;\n if (ch === \"*\" && pattern[i + 1] === \"*\") {\n // ** matches any path segment(s)\n regexStr += \".*\";\n i += 2;\n if (pattern[i] === \"/\") i++; // skip trailing slash after **\n } else if (ch === \"*\") {\n // * matches anything except /\n regexStr += \"[^/]*\";\n i++;\n } else if (ch === \"?\") {\n regexStr += \"[^/]\";\n i++;\n // biome-ignore lint/suspicious/noTemplateCurlyInString: regex escape chars, not template\n } else if (\".+^${}()|[]\\\\\".includes(ch)) {\n regexStr += `\\\\${ch}`;\n i++;\n } else {\n regexStr += ch;\n i++;\n }\n }\n return new RegExp(`^${regexStr}$`);\n}\n","/**\n * `interactive_shell` + `write_stdin` — built-in tools for driving an interactive\n * session (a REPL, `git rebase -i`, any command that PROMPTS for stdin).\n *\n * Surface-agnostic by construction: both tools depend on an INJECTED\n * `InteractiveProvider` (`@theokit/sdk/interactive`) exactly as `read_file`\n * depends on `FilesystemProvider`. The HOST supplies the backend — a local\n * `@theokit/sdk-pty` (terminal), a container/E2B backend (cluster/web), or a\n * Tauri backend (desktop) — so the SAME tool runs on every theokit surface with\n * NO native dependency here. When no backend is injected (or it cannot allocate\n * a session) the tool returns `{ ok: false, error: 'interactive_unavailable' }`\n * and the agent falls back to non-interactive exec.\n *\n * Return shapes (always a JSON string):\n * interactive_shell → `{ ok: true, session_id, output }` | `{ ok: false, error }`\n * write_stdin → `{ ok: true, output, alive }` | `{ ok: false, error }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type InteractiveProvider,\n InteractiveUnavailableError,\n NoSuchSessionError,\n resolveInteractive,\n} from \"@theokit/sdk/interactive\";\nimport { z } from \"zod\";\n\nexport interface CreateInteractiveShellToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** The interactive backend, or a per-request resolver of one (injected — never a direct native dep). */\n interactive: InteractiveProvider<unknown>;\n}\n\n/** Map the SDK's typed interactive errors to the tool's `{ ok: false, error }` JSON. Re-throws anything\n * else (a real bug), per the sdk-tools \"JSON on user mistakes, throw on SDK bugs\" contract. */\n/**\n * U-2 — a session cap carries `max` and `liveSessionIds`, and those are the only fields the model\n * can act on: without them \"interactive_unavailable\" cannot be told apart from a missing backend,\n * and the obvious remedy (reuse one of the open sessions) is invisible.\n *\n * Checked STRUCTURALLY rather than with `instanceof`. The class that raises it lives in\n * `@theokit/sdk-pty`, which this package does not depend on and should not — and the tool accepts an\n * INJECTED backend, so any provider reporting the same two fields deserves the same treatment.\n */\nfunction capFields(err: object): { max: number; liveSessionIds: readonly string[] } | undefined {\n const e = err as { max?: unknown; liveSessionIds?: unknown };\n if (typeof e.max !== \"number\") return undefined;\n if (!Array.isArray(e.liveSessionIds)) return undefined;\n if (!e.liveSessionIds.every((id) => typeof id === \"string\")) return undefined;\n return { max: e.max, liveSessionIds: e.liveSessionIds as readonly string[] };\n}\n\nfunction toErrorJson(err: unknown): string {\n // Before the superclass branch: `MaxSessionsError extends InteractiveUnavailableError`, so\n // matching the parent first flattened the subclass and dropped what made it actionable.\n if (typeof err === \"object\" && err !== null) {\n const cap = capFields(err);\n if (cap !== undefined) {\n return JSON.stringify({\n ok: false,\n error: \"interactive_session_limit\",\n max: cap.max,\n live_session_ids: [...cap.liveSessionIds],\n message: (err as { message?: unknown }).message,\n });\n }\n }\n if (err instanceof InteractiveUnavailableError) {\n return JSON.stringify({ ok: false, error: \"interactive_unavailable\" });\n }\n if (err instanceof NoSuchSessionError) {\n return JSON.stringify({ ok: false, error: \"no_such_session\" });\n }\n throw err;\n}\n\n/** Start an interactive session; returns a `session_id` to drive with `write_stdin`. */\nexport function createInteractiveShellTool(opts: CreateInteractiveShellToolOptions): CustomTool {\n const { interactive } = opts;\n return Tool.create({\n name: opts.name ?? \"interactive_shell\",\n description:\n opts.description ??\n \"Start an interactive shell session for a command that PROMPTS for input or is a REPL \" +\n \"(python, node, `git rebase -i`, a `read` prompt) — NOT for one-shot commands (use shell_exec). \" +\n \"Returns a session_id; drive it with write_stdin, reading the incremental output each step. \" +\n \"Returns { ok, session_id, output } or { ok: false, error }.\",\n inputSchema: z.object({\n command: z\n .string()\n .min(1)\n .describe(\"Command to run interactively, e.g. 'python3' or 'bash -i'.\"),\n yield_time_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"How long to wait for startup output before returning (clamped by the backend).\"),\n }),\n handler: async ({ command, yield_time_ms }, ctx) => {\n try {\n const backend = await resolveInteractive(interactive, ctx ?? {});\n const { sessionId, output } = await backend.startInteractive(command, {\n yieldMs: yield_time_ms,\n });\n return JSON.stringify({ ok: true, session_id: sessionId, output });\n } catch (err) {\n return toErrorJson(err);\n }\n },\n });\n}\n\n/** Write to a live interactive session's stdin and read the output it produces. */\nexport function createWriteStdinTool(opts: CreateInteractiveShellToolOptions): CustomTool {\n const { interactive } = opts;\n return Tool.create({\n name: \"write_stdin\",\n description:\n \"Write input to a live interactive session (from interactive_shell) and read the output it \" +\n \"produces during the wait window. Include a trailing newline to submit a line. Returns \" +\n \"{ ok, output, alive } (alive:false means the session exited) or { ok: false, error }.\",\n inputSchema: z.object({\n session_id: z.string().min(1).describe(\"The session_id returned by interactive_shell.\"),\n input: z.string().describe(\"Text to write to stdin (add a trailing '\\\\n' to submit a line).\"),\n yield_time_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"How long to wait for output before returning (clamped by the backend).\"),\n }),\n handler: async ({ session_id, input, yield_time_ms }, ctx) => {\n try {\n const backend = await resolveInteractive(interactive, ctx ?? {});\n const { output, alive } = await backend.writeStdin(session_id, input, {\n yieldMs: yield_time_ms,\n });\n return JSON.stringify({ ok: true, output, alive });\n } catch (err) {\n return toErrorJson(err);\n }\n },\n });\n}\n","/**\n * Catastrophic-command guardrail for `shell_exec` (M3-2; hardened V3-1).\n *\n * `catastrophicShellReason` is a pure, segment-aware deny-list ported from\n * theocode's security-reviewed `shell-guard.ts` (the proven spec: 42-blocked +\n * 24-allowed corpus, 0 misses / 0 false-positives). It splits a command on shell\n * separators (`;`, `&&`, `||`, `|`, `&`, newline), inspects EVERY segment (so a\n * chained `rm -rf <safe>; rm -rf /` cannot hide), and matches at COMMAND POSITION\n * (the executable, not an arbitrary substring) so a mention like `echo \"rm -rf /\"`\n * is not over-blocked. Returns a human reason for the first catastrophic segment,\n * else `null`.\n *\n * Categories: recursive-force `rm` of an absolute/home/parent path; destructive git\n * (force-push, `reset --hard`, `clean -fd`); remote-code-execution (curl/wget piped\n * OR command-substitution `$( )` / `<( )` / eval / source); disk/raw-device wipe\n * (mkfs, `dd of=/dev/`, `truncate /dev/`, `> /dev/<blockdev>`); recursive chmod/chown\n * of a root path (SDK extra); fork bomb; `find -delete` / `-exec rm`; secret-file\n * exfiltration over the network.\n *\n * This is a heuristic GUARDRAIL, NOT a sandbox: it is bypassable by deep obfuscation\n * (base64/env-indirection) and is best-effort. POSIX `/bin/sh` only; Windows\n * PowerShell is out of scope. True isolation needs a container.\n * reference: .claude/knowledge-base/references/theocode-shell-guard/server-lib/shell-guard.ts\n */\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\n/** Thrown / reported when a command matches the catastrophic deny-list. */\nexport class CatastrophicCommandError extends ConfigurationError {\n override readonly name = \"CatastrophicCommandError\";\n constructor(reason: string) {\n super(`Refused a catastrophic shell command: ${reason} (shell guardrail).`, {\n code: \"catastrophic_command\",\n });\n }\n}\n\n/** Strip a single layer of surrounding quotes from a token (so `\"/\"` -> `/`). */\nfunction unquote(token: string): string {\n return token.replace(/^(['\"])(.*)\\1$/, \"$2\").replace(/^['\"]|['\"]$/g, \"\");\n}\n\n/**\n * Split a command line into statement segments on shell separators\n * (`;`, `&&`, `||`, `|`, `&`, newline). The rm screen inspects EVERY segment (C1).\n * Quote-aware splitting is out of scope (a guardrail, not a parser).\n */\nfunction commandSegments(command: string): string[] {\n return command\n .split(/&&|\\|\\||[;|&\\n]/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/** Arg tokens of a segment whose command is `name` (after an optional `sudo`); `null` otherwise. */\nfunction commandArgs(segment: string, name: string): string[] | null {\n const tokens = segment.split(/\\s+/);\n let i = 0;\n if (tokens[i] === \"sudo\") i += 1;\n if (tokens[i] !== name) return null; // must be the COMMAND, not a substring/arg\n return tokens.slice(i + 1);\n}\n\n/** Every segment whose command is `name` -> its arg list. */\nfunction commandSegmentsNamed(command: string, name: string): string[][] {\n return commandSegments(command)\n .map((s) => commandArgs(s, name))\n .filter((args): args is string[] => args !== null);\n}\n\n/** Does an arg list carry BOTH a recursive and a force flag, in ANY position/spelling? */\nfunction isRecursiveForce(args: string[]): boolean {\n const flags = args.filter((t) => t.startsWith(\"-\")).join(\" \");\n if (flags.length === 0) return false;\n const recursive = /-[a-z]*r/i.test(flags) || /--recursive/.test(flags);\n const force = /-[a-z]*f/i.test(flags) || /--force/.test(flags);\n return recursive && force;\n}\n\n/** Does an arg list carry a recursive flag (for chmod/chown -R)? */\nfunction isRecursive(args: string[]): boolean {\n const flags = args.filter((t) => t.startsWith(\"-\")).join(\" \");\n return /-[a-z]*r/i.test(flags) || /--recursive/.test(flags);\n}\n\n/** Absolute paths that are safe to recursively delete (scratch/throwaway). */\nconst SAFE_ABSOLUTE_TARGET = /^\\/(tmp|var\\/tmp)(\\/|$)/;\n\n/** True when an arg list targets root, home, `$HOME`, an absolute path, or `..`. */\nfunction targetsDangerousPath(args: string[]): boolean {\n const targets = args.filter((token) => token.length > 0 && !token.startsWith(\"-\")).map(unquote);\n return targets.some((raw) => {\n const t = raw.replace(/\\/+/g, \"/\"); // collapse `//` -> `/` (SDK extra)\n if (t === \"/dev/null\" || SAFE_ABSOLUTE_TARGET.test(t)) return false;\n return (\n /^\\/($|\\*)/.test(t) || // \"/\" or \"/*\"\n /^\\/[^/]/.test(t) || // an absolute path like /etc, /usr/local, /home/user/x\n t === \"~\" ||\n t.startsWith(\"~/\") ||\n /\\$\\{?HOME\\b\\}?/.test(t) || // $HOME or ${HOME}\n t === \"..\" ||\n t.startsWith(\"../\") ||\n t.includes(\"/..\") ||\n t === \"*\"\n );\n });\n}\n\n/** mkfs / dd-to-device / truncate-device / redirect-to-blockdev (families incl. SDK extras). */\nconst DEVICE_WIPE = [\n /\\bmkfs(\\.\\w+)?\\b/,\n /\\bdd\\b[^\\n]*\\bof=\\/dev\\//,\n /\\btruncate\\b[^\\n]*\\s\\/dev\\//,\n />\\s*\\/dev\\/(sd|nvme|hd|vd|mmcblk|disk|loop|dm-)/,\n];\n\n/** A single catastrophic-category screen: returns a reason or `null`. */\ntype CategoryCheck = (cmd: string) => string | null;\n\n/** Remote code execution: a remote download fed into an interpreter (pipe / `$( )` / `<( )` / eval / source). */\nconst checkRemoteExec: CategoryCheck = (cmd) =>\n /\\b(curl|wget|fetch)\\b[^\\n]*\\|\\s*(sudo\\s+)?(sh|bash|zsh|dash|python[0-9.]*|node|ruby|perl)\\b/i.test(\n cmd,\n ) ||\n /(\\$\\(|<\\()\\s*(sudo\\s+)?(curl|wget|fetch)\\b/i.test(cmd) ||\n /\\b(eval|source)\\b[^\\n]*\\b(curl|wget|fetch)\\b/i.test(cmd)\n ? \"executes a remote download (pipe / command-substitution / eval) — remote code execution\"\n : null;\n\n/** Disk / raw block-device wipe (mkfs, dd-to-device, truncate-device, redirect-to-blockdev). */\nconst checkDeviceWipe: CategoryCheck = (cmd) =>\n DEVICE_WIPE.some((re) => re.test(cmd)) ? \"writes to a raw block device / formats a disk\" : null;\n\n/** Fork bomb. */\nconst checkForkBomb: CategoryCheck = (cmd) =>\n /:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:/.test(cmd) ? \"fork bomb\" : null;\n\n/** Destructive git: force-push (NOT --force-with-lease), hard reset, aggressive clean. */\nconst checkDestructiveGit: CategoryCheck = (cmd) => {\n if (/\\bgit\\b[^\\n]*\\bpush\\b[^\\n]*(--force(?!-with-lease)\\b|\\s-f\\b|\\s\\+\\S)/.test(cmd)) {\n return \"git force-push (overwrites remote history)\";\n }\n if (/\\bgit\\b[^\\n]*\\breset\\b[^\\n]*--hard\\b/.test(cmd)) {\n return \"git reset --hard (discards committed and working changes)\";\n }\n if (/\\bgit\\b[^\\n]*\\bclean\\b[^\\n]*(-[a-z]*f[a-z]*d|-[a-z]*d[a-z]*f)/.test(cmd)) {\n return \"git clean -fd (permanently deletes untracked files)\";\n }\n return null;\n};\n\n/** Recursive force-delete of a path outside the workspace — checked on EVERY rm segment (C1). */\nconst checkRm: CategoryCheck = (cmd) =>\n commandSegmentsNamed(cmd, \"rm\").some((a) => isRecursiveForce(a) && targetsDangerousPath(a))\n ? \"recursive force-delete of an absolute, home, or parent path\"\n : null;\n\n/** Recursive chmod/chown of a root/home/parent path (SDK extra — not in theocode). */\nconst checkPerm: CategoryCheck = (cmd) =>\n ([\"chmod\", \"chown\"] as const).some((name) =>\n commandSegmentsNamed(cmd, name).some((a) => isRecursive(a) && targetsDangerousPath(a)),\n )\n ? \"recursive permission change on an absolute, home, or parent path\"\n : null;\n\n/** find with -delete / -exec rm targeting an absolute or home root. */\nconst checkFind: CategoryCheck = (cmd) =>\n /\\bfind\\s+(\\/\\S*|~\\S*|\\$\\{?HOME\\}?\\S*)\\s[^\\n]*(-delete\\b|-exec\\s+rm\\b)/.test(cmd)\n ? \"find -delete / -exec rm on an absolute or home path\"\n : null;\n\n/** Exfiltration: a secret/credential file referenced together with a network sender. */\nconst checkExfiltration: CategoryCheck = (cmd) => {\n const touchesSecret =\n /(^|[\\s/'\"])(\\.env(\\.\\w+)?|id_rsa|id_ed25519|\\.ssh(\\/|\\b)|credentials|\\.aws(\\/|\\b)|\\.npmrc)\\b/.test(\n cmd,\n );\n const sendsNetwork =\n /\\b(curl|wget|nc|netcat|scp|ftp|telnet)\\b/.test(cmd) || /\\bpython[0-9.]*\\s+-m\\s+http/.test(cmd);\n return touchesSecret && sendsNetwork\n ? \"sends a secret/credential file over the network (exfiltration)\"\n : null;\n};\n\nconst CATEGORY_CHECKS: readonly CategoryCheck[] = [\n checkRemoteExec,\n checkDeviceWipe,\n checkForkBomb,\n checkDestructiveGit,\n checkRm,\n checkPerm,\n checkFind,\n checkExfiltration,\n];\n\n/**\n * Return a human-readable reason when `command` is catastrophic/irreversible, or `null`.\n * The message is surfaced to the model so it self-corrects.\n */\nexport function catastrophicShellReason(command: string): string | null {\n const cmd = command.trim();\n if (cmd.length === 0) return null;\n for (const check of CATEGORY_CHECKS) {\n const reason = check(cmd);\n if (reason) return reason;\n }\n return null;\n}\n","/**\n * Composable command-permission policy layer (M3-6).\n *\n * A `CommandPolicy` is a pure predicate returning a deny REASON (or `null` to\n * allow). `denyCatastrophicCommands()` COMPOSES the M3-2 `catastrophicShellReason`\n * guardrail (it does not duplicate the deny-list). `commandDenialReason` combines\n * a policy array with deny-wins semantics (the first policy returning a reason\n * denies); an empty array denies nothing. `isCommandAllowed` is the boolean view.\n *\n * Framework-agnostic: a consumer wires it at their permission layer — e.g. inside\n * an ACP `pre_tool_call` hook — `@theokit/agents` is not required. Inherits the\n * M3-2 honesty: a heuristic gate, not a sandbox. Design: blueprint m3-command-policy.\n */\n\nimport { catastrophicShellReason } from \"./shell-guard.js\";\n\n/**\n * A pure command-permission predicate: returns a non-empty deny reason, or `null`\n * to allow. NOTE: return `null` to allow — NOT `\"\"`. An empty string is treated\n * as a deny with a blank reason (`\"\" !== null`), which is almost never intended.\n */\nexport type CommandPolicy = (command: string) => string | null;\n\n/** A policy that denies catastrophic commands by composing the M3-2 guardrail. */\nexport function denyCatastrophicCommands(): CommandPolicy {\n return (command) => catastrophicShellReason(command);\n}\n\n/**\n * The first deny reason across `policies` (deny-wins), or `null` if every policy\n * allows. An empty `policies` array denies nothing (returns `null`).\n */\nexport function commandDenialReason(command: string, policies: CommandPolicy[]): string | null {\n for (const policy of policies) {\n const reason = policy(command);\n if (reason !== null) return reason;\n }\n return null;\n}\n\n/** `true` when no policy denies `command` (an empty policy array allows everything). */\nexport function isCommandAllowed(command: string, policies: CommandPolicy[]): boolean {\n return commandDenialReason(command, policies) === null;\n}\n","/**\n * SSRF guard for network tools (M3-1).\n *\n * `isBlockedIp` is a pure block-list of the canonical private/loopback/link-local/\n * CGNAT/metadata/reserved ranges (IPv4 + IPv6, with IPv4-mapped unwrap).\n * `resolveAndScreen` resolves ALL of a host's addresses and rejects if any is\n * blocked. `screenedFetch` fetches with `redirect:\"manual\"` and re-screens every\n * hop. `lookup`/`fetchImpl` are injectable so the DNS + redirect paths are\n * deterministically testable without real network access.\n *\n * Design: blueprint m3-ssrf-guard ADRs D1-D6. Node builtins only (zero new deps).\n */\n\nimport { lookup as dnsLookup } from \"node:dns/promises\";\nimport { isIP } from \"node:net\";\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\n/** Thrown when a host/redirect resolves to a blocked (private/reserved) address. */\nexport class SsrfBlockedError extends ConfigurationError {\n override readonly name = \"SsrfBlockedError\";\n constructor(host: string, detail?: string) {\n super(\n `Blocked request to \"${host}\"${detail ? ` (${detail})` : \"\"}: address is private, loopback, link-local, or reserved (SSRF guard).`,\n { code: \"ssrf_blocked\" },\n );\n }\n}\n\n/**\n * Thrown when a request is refused by the REDIRECT policy (the `maxRedirects` hop limit was\n * exceeded) — a distinct event from {@link SsrfBlockedError} (a blocked host). With `maxRedirects: 0`\n * this fires on the first 3xx (block-all-redirects). Carries `code: \"redirect_blocked\"`.\n */\nexport class RedirectBlockedError extends ConfigurationError {\n override readonly name = \"RedirectBlockedError\";\n constructor(url: string, detail?: string) {\n super(\n `Blocked redirect for \"${url}\"${detail ? ` (${detail})` : \"\"}: redirect-hop limit exceeded (redirect policy).`,\n { code: \"redirect_blocked\" },\n );\n }\n}\n\n/** Parse an IPv4 dotted-quad to a 32-bit unsigned integer (assumes a valid literal). */\nfunction v4ToInt(ip: string): number {\n const parts = ip.split(\".\");\n return (\n ((Number(parts[0]) << 24) |\n (Number(parts[1]) << 16) |\n (Number(parts[2]) << 8) |\n Number(parts[3])) >>>\n 0\n );\n}\n\n/** True if the IPv4 address (as int) falls inside `base/prefix`. */\nfunction inV4Cidr(ipInt: number, base: string, prefix: number): boolean {\n const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;\n return (ipInt & mask) === (v4ToInt(base) & mask);\n}\n\nconst V4_BLOCKED: ReadonlyArray<readonly [string, number]> = [\n [\"0.0.0.0\", 8], // \"this host\"\n [\"10.0.0.0\", 8], // private\n [\"100.64.0.0\", 10], // CGNAT\n [\"127.0.0.0\", 8], // loopback\n [\"169.254.0.0\", 16], // link-local + cloud metadata\n [\"172.16.0.0\", 12], // private\n [\"192.168.0.0\", 16], // private\n [\"224.0.0.0\", 4], // multicast\n [\"240.0.0.0\", 4], // reserved\n];\n\nfunction isBlockedV4(ip: string): boolean {\n const n = v4ToInt(ip);\n return V4_BLOCKED.some(([base, prefix]) => inV4Cidr(n, base, prefix));\n}\n\n/** Fold a trailing dotted-quad (`…:1.2.3.4`) into two hex hextets; `null` if invalid. */\nfunction foldDottedTail(s: string): string | null {\n const lastColon = s.lastIndexOf(\":\");\n const tail = s.slice(lastColon + 1);\n if (!tail.includes(\".\")) return s;\n if (isIP(tail) !== 4) return null;\n const o = tail.split(\".\").map(Number);\n const hi = (((o[0] as number) << 8) | (o[1] as number)).toString(16);\n const lo = (((o[2] as number) << 8) | (o[3] as number)).toString(16);\n return `${s.slice(0, lastColon + 1)}${hi}:${lo}`;\n}\n\n/** Expand a (validated) IPv6 string to exactly 8 hextet strings; `null` if malformed. */\nfunction expandHextets(s: string): string[] | null {\n const halves = s.split(\"::\");\n if (halves.length > 2) return null;\n const head = halves[0] ? halves[0].split(\":\") : [];\n const tailGroups = halves.length === 2 && halves[1] ? halves[1].split(\":\") : [];\n if (halves.length === 1) return head.length === 8 ? head : null;\n const missing = 8 - head.length - tailGroups.length;\n if (missing < 0) return null;\n return [...head, ...Array(missing).fill(\"0\"), ...tailGroups];\n}\n\n/**\n * Expand a (net.isIP-validated) IPv6 literal to its 16 bytes. Handles `::`\n * compression and a trailing dotted-quad (`::ffff:1.2.3.4`). Returns `null` if it\n * cannot be parsed (caller then fails closed).\n */\nfunction ipv6ToBytes(ip: string): number[] | null {\n const folded = foldDottedTail(ip.toLowerCase().split(\"%\")[0] ?? \"\");\n if (folded === null) return null;\n const groups = expandHextets(folded);\n if (groups === null || groups.length !== 8) return null;\n const bytes: number[] = [];\n for (const g of groups) {\n const n = Number.parseInt(g || \"0\", 16);\n bytes.push(n >> 8, n & 0xff);\n }\n return bytes;\n}\n\nfunction allZero(bytes: number[], from: number, to: number): boolean {\n for (let i = from; i < to; i += 1) if (bytes[i] !== 0) return false;\n return true;\n}\n\n/** Numeric IPv6 classification over the parsed 16 bytes (no string-prefix guesswork). */\nfunction isBlockedV6Bytes(b: number[]): boolean {\n // IPv4-mapped (::ffff:a.b.c.d, any spelling) → re-check the embedded IPv4.\n if (allZero(b, 0, 10) && b[10] === 0xff && b[11] === 0xff) {\n return isBlockedV4(`${b[12]}.${b[13]}.${b[14]}.${b[15]}`);\n }\n // ::1 loopback and :: unspecified.\n if (allZero(b, 0, 15) && (b[15] === 1 || b[15] === 0)) return true;\n // IPv4-compatible (deprecated) ::a.b.c.d → re-check embedded IPv4.\n if (allZero(b, 0, 12)) return isBlockedV4(`${b[12]}.${b[13]}.${b[14]}.${b[15]}`);\n // fe80::/10 link-local.\n if (b[0] === 0xfe && ((b[1] as number) & 0xc0) === 0x80) return true;\n // fc00::/7 unique-local.\n return ((b[0] as number) & 0xfe) === 0xfc;\n}\n\n/**\n * True if `ip` is a blocked address (private/loopback/link-local/CGNAT/metadata/\n * reserved). A non-IP literal returns `true` (fail closed — callers resolve names\n * to IPs first via {@link resolveAndScreen}).\n */\nexport function isBlockedIp(ip: string): boolean {\n const fam = isIP(ip);\n if (fam === 4) return isBlockedV4(ip);\n if (fam === 6) {\n const bytes = ipv6ToBytes(ip);\n return bytes === null ? true : isBlockedV6Bytes(bytes);\n }\n return true;\n}\n\ntype LookupFn = (host: string, opts: { all: true }) => Promise<Array<{ address: string }>>;\n\n/** Options for {@link resolveAndScreen}. */\nexport interface ResolveAndScreenOptions {\n /** DNS resolver (injectable for tests); defaults to `node:dns/promises` lookup. */\n lookup?: LookupFn;\n}\n\n/**\n * Resolve `host` to ALL its addresses and screen each. Throws {@link SsrfBlockedError}\n * if any resolved address is blocked (or if `host` is a blocked IP literal, or if\n * resolution yields no address). Returns the resolved IPs otherwise.\n */\nexport async function resolveAndScreen(\n rawHost: string,\n options: ResolveAndScreenOptions = {},\n): Promise<string[]> {\n // `URL.hostname` wraps IPv6 literals in brackets (`[::1]`) — strip them so\n // `net.isIP` recognizes the address.\n const host = rawHost.replace(/^\\[|\\]$/g, \"\");\n if (isIP(host) !== 0) {\n if (isBlockedIp(host)) throw new SsrfBlockedError(host);\n return [host];\n }\n const lookup = options.lookup ?? (dnsLookup as unknown as LookupFn);\n const addrs = await lookup(host, { all: true });\n if (addrs.length === 0) throw new SsrfBlockedError(host, \"no addresses\");\n for (const a of addrs) {\n if (isBlockedIp(a.address)) throw new SsrfBlockedError(host, a.address);\n }\n return addrs.map((a) => a.address);\n}\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise<Response>;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * The next URL to follow for a redirect response, or `undefined` if `res` is not a\n * followable redirect. Throws {@link SsrfBlockedError} for a non-http(s) target.\n */\nfunction redirectTarget(res: Response, current: string, originalUrl: string): string | undefined {\n const location = res.headers.get(\"location\");\n if (!REDIRECT_STATUSES.has(res.status) || !location) return undefined;\n const next = new URL(location, current);\n if (next.protocol !== \"http:\" && next.protocol !== \"https:\") {\n throw new SsrfBlockedError(originalUrl, `non-http redirect to ${next.protocol}`);\n }\n return next.href;\n}\n\n/** Options for {@link screenedFetch}. */\nexport interface ScreenedFetchOptions {\n /** Fetch implementation (injectable for tests); defaults to global `fetch`. */\n fetchImpl?: FetchFn;\n /** DNS resolver (injectable for tests). */\n lookup?: LookupFn;\n /** Max redirect hops to follow (default 5). */\n maxRedirects?: number;\n /** Skip SSRF screening entirely (opt-out for local-dev tools). Default false. */\n allowPrivateHosts?: boolean;\n /** Abort signal forwarded to fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * Fetch `url` with SSRF screening: screens the host (unless `allowPrivateHosts`),\n * sets `redirect:\"manual\"`, and re-screens every redirect hop (rejecting a hop to a\n * blocked host or a non-http(s) target). Throws {@link SsrfBlockedError} on a block\n * or on exceeding `maxRedirects`.\n */\nexport async function screenedFetch(\n url: string,\n options: ScreenedFetchOptions = {},\n): Promise<Response> {\n const fetchImpl = options.fetchImpl ?? (fetch as FetchFn);\n const maxRedirects = options.maxRedirects ?? 5;\n let current = url;\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n if (!options.allowPrivateHosts) {\n await resolveAndScreen(new URL(current).hostname, { lookup: options.lookup });\n }\n const res = await fetchImpl(current, { redirect: \"manual\", signal: options.signal });\n const next = redirectTarget(res, current, url);\n if (next === undefined) return res;\n current = next;\n }\n throw new RedirectBlockedError(url, \"too many redirects\");\n}\n","/**\n * Repo-map / env-context builders for orienting an LLM coding agent (M3-3).\n *\n * `buildEnvContext(cwd)` renders a short `<env>` block (cwd, platform, node,\n * is-git, date, project docs, manifests). `buildRepoMap(cwd, opts)` renders a\n * char-bounded, depth-limited directory tree. Both are node:fs-only and NEVER\n * throw — a missing/unreadable path yields a best-effort partial string or an\n * `(unavailable)` marker (distinct from the M3-1/M3-2 guards, which throw).\n *\n * Design: blueprint m3-repo-map. Zero new dependencies. A best-effort\n * orientation aid, not a complete or secure listing (bounded + skips on error).\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RepoMapOptions {\n /** Max characters of tree output before truncation. Default 8000. */\n budget?: number;\n /** Directory/file names to skip (merged with the built-in ignore set). */\n ignore?: string[];\n /** Max directory depth to descend. Default 4. */\n maxDepth?: number;\n}\n\nconst DEFAULT_BUDGET = 8000;\nconst DEFAULT_MAX_DEPTH = 4;\nconst PER_DIR_CAP = 200;\nconst TRUNCATED_MARKER = \"… (truncated)\";\nconst DOC_HEAD_CHARS = 200;\nconst DEFAULT_REPO_MAP_IGNORE = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \".theo\",\n \".next\",\n \"build\",\n \"coverage\",\n \"target\",\n \"out\",\n];\nconst PROJECT_DOCS = [\"AGENTS.md\", \"CLAUDE.md\", \"README.md\"];\nconst MANIFESTS = [\"package.json\", \"pyproject.toml\", \"Cargo.toml\", \"go.mod\"];\n\nfunction safeExists(p: string): boolean {\n try {\n return existsSync(p);\n } catch {\n return false;\n }\n}\n\nfunction safeReadHead(p: string, n: number): string {\n try {\n return readFileSync(p, \"utf-8\").slice(0, n).replace(/\\s+/g, \" \").trim();\n } catch {\n return \"\";\n }\n}\n\nexport interface EnvContextOptions {\n /** Injectable clock for the date line (deterministic tests). Default `new Date()`. */\n now?: Date;\n /** Path to the git `HEAD` file. Default `<cwd>/.git/HEAD`. */\n gitHeadPath?: string;\n}\n\n/**\n * Read the current git branch from `HEAD` — a PURE file read (never a\n * `child_process` spawn, which could hang the request path or expose\n * arg-injection). Returns `undefined` for a detached HEAD, a missing file,\n * or any read error. Borrowed from theocode's `project-context.ts`.\n */\nfunction gitBranch(headPath: string): string | undefined {\n try {\n const head = readFileSync(headPath, \"utf-8\").trim();\n const match = head.match(/^ref:\\s*refs\\/heads\\/(.+)$/);\n return match ? match[1] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Render a portable `<env>` orientation block. Never throws. */\nexport function buildEnvContext(cwd: string, opts: EnvContextOptions = {}): string {\n const lines = [\n \"<env>\",\n ` Working directory: ${cwd}`,\n ` Platform: ${process.platform} (${process.arch})`,\n ` Node: ${process.version}`,\n ` Is git repo: ${safeExists(join(cwd, \".git\")) ? \"yes\" : \"no\"}`,\n ];\n const branch = gitBranch(opts.gitHeadPath ?? join(cwd, \".git\", \"HEAD\"));\n if (branch) lines.push(` Branch: ${branch}`);\n lines.push(` Today's date: ${(opts.now ?? new Date()).toDateString()}`);\n const docs = PROJECT_DOCS.filter((d) => safeExists(join(cwd, d)));\n if (docs.length > 0) {\n lines.push(` Project docs: ${docs.join(\", \")}`);\n const head = safeReadHead(join(cwd, docs[0] as string), DOC_HEAD_CHARS);\n if (head) lines.push(` ${docs[0]} (head): ${head}`);\n }\n const manifests = MANIFESTS.filter((m) => safeExists(join(cwd, m)));\n if (manifests.length > 0) lines.push(` Manifests: ${manifests.join(\", \")}`);\n lines.push(\"</env>\");\n return lines.join(\"\\n\");\n}\n\n/** dirs-first, then alphabetical. Symlinks count as leaves (not followed). */\nfunction compareEntries(a: Dirent, b: Dirent): number {\n const ad = a.isDirectory() ? 0 : 1;\n const bd = b.isDirectory() ? 0 : 1;\n return ad !== bd ? ad - bd : a.name.localeCompare(b.name);\n}\n\nfunction visibleEntries(dir: string, ignore: Set<string>): Dirent[] {\n let entries: Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries.filter((e) => !ignore.has(e.name) && !e.name.startsWith(\".\")).sort(compareEntries);\n}\n\ninterface WalkCtx {\n ignore: Set<string>;\n maxDepth: number;\n budget: number;\n lines: string[];\n used: number;\n truncated: boolean;\n}\n\n/** Append a line if it fits the budget; flag truncation and return false otherwise. */\nfunction pushLine(ctx: WalkCtx, line: string): boolean {\n if (ctx.used + line.length + 1 > ctx.budget) {\n ctx.truncated = true;\n return false;\n }\n ctx.lines.push(line);\n ctx.used += line.length + 1;\n return true;\n}\n\n/** Emit one entry (and recurse into a real sub-dir). Returns false when budget is hit. */\nfunction emitEntry(ctx: WalkCtx, dir: string, e: Dirent, depth: number, indent: string): boolean {\n const isDir = e.isDirectory(); // symlink-to-dir → false → treated as a leaf, not followed\n if (!pushLine(ctx, `${indent}${isDir ? `${e.name}/` : e.name}`)) return false;\n if (isDir && depth + 1 < ctx.maxDepth) return walkDir(ctx, join(dir, e.name), depth + 1);\n return true;\n}\n\nfunction walkDir(ctx: WalkCtx, dir: string, depth: number): boolean {\n const entries = visibleEntries(dir, ctx.ignore);\n const shown = entries.slice(0, PER_DIR_CAP);\n const indent = \" \".repeat(depth);\n for (const e of shown) {\n if (!emitEntry(ctx, dir, e, depth, indent)) return false;\n }\n if (entries.length > shown.length) {\n return pushLine(ctx, `${indent}… (${entries.length - shown.length} more)`);\n }\n return true;\n}\n\n/** Render a char-bounded, depth-limited directory tree. Never throws. */\nexport function buildRepoMap(cwd: string, opts: RepoMapOptions = {}): string {\n try {\n if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {\n return `(unavailable: ${cwd} is not a readable directory)`;\n }\n } catch {\n return `(unavailable: ${cwd})`;\n }\n\n const ctx: WalkCtx = {\n ignore: new Set([...DEFAULT_REPO_MAP_IGNORE, ...(opts.ignore ?? [])]),\n maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH,\n budget: opts.budget ?? DEFAULT_BUDGET,\n lines: [],\n used: 0,\n truncated: false,\n };\n walkDir(ctx, cwd, 0);\n return ctx.truncated ? `${ctx.lines.join(\"\\n\")}\\n${TRUNCATED_MARKER}` : ctx.lines.join(\"\\n\");\n}\n","/**\n * ACI (Agent-Computer Interface) helpers for tools (M3-5).\n *\n * `withDescription(tool, description)` immutably overrides a tool's LLM-facing\n * description (the wording that drives tool-selection accuracy) — returning a\n * NEW `CustomTool` and leaving the original untouched. `renderToolList(tools)`\n * renders a `<tools>` block FROM THE SAME `CustomTool[]` the agent runs, so the\n * rendered list cannot drift from the real tools (single source of truth).\n *\n * Both are pure, zero-dependency, and never throw. The `<tools>` block is a\n * system-prompt orientation aid — NOT the provider tool-call schema (that stays\n * each tool's `inputSchema`). Design: blueprint m3-aci-tools.\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\n/**\n * Return a new `CustomTool` with `description` replaced. Preserves\n * name/inputSchema/handler; does NOT mutate the original tool.\n */\nexport function withDescription(tool: CustomTool, description: string): CustomTool {\n return {\n name: tool.name,\n description,\n inputSchema: tool.inputSchema,\n handler: tool.handler,\n };\n}\n\n/**\n * Return a new `CustomTool` exposed under a different `name`, sharing the SAME\n * `inputSchema` + `handler` (alias parity). Preserves description; does NOT mutate\n * the original. This is how an agent exposes a built-in under its preferred name —\n * e.g. a Codex-style agent aliases `search_text` → `grep`, `shell_exec` → `run_shell`\n * — without re-implementing the tool. Pure, never throws: the final `name` is\n * validated by the SDK at tool-registration time (the single authority for the\n * `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$` + reserved-name rules), so this helper does not\n * re-validate (no duplicated contract).\n */\nexport function withName(tool: CustomTool, name: string): CustomTool {\n return {\n name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: tool.handler,\n };\n}\n\n/** XML-escape for the `<tools>` block. `&` MUST be replaced first (no double-escape). */\nfunction esc(s: string): string {\n // String() guards the never-throw contract against an untyped/`as any` caller\n // passing a non-string name/description.\n return String(s).replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n\n/** Render mode for {@link renderToolList}. Local — the published `renderToolList`\n * signature inlines this union into its `.d.ts`, so consumers pass the literal\n * (\"summary\" | \"names\" | \"full\") without needing the named type exported. */\ntype ToolListMode = \"full\" | \"summary\" | \"names\";\n\n/**\n * Extract the first sentence of a description, abbreviation-safe: a period is\n * only a sentence boundary when followed by whitespace + a capital/paren/EOF, so\n * `e.g.`, `i.e.`, `vs.` do NOT split. Falls back to the whole (trimmed) string.\n */\nfunction firstSentence(d: string): string {\n const m = d.trim().match(/\\.\\s+(?=[A-Z(]|$)/);\n return m?.index == null ? d.trim() : d.trim().slice(0, m.index + 1);\n}\n\n/**\n * Render the agent's actual `CustomTool[]` — single source of truth, so an\n * overridden/added/removed tool is reflected automatically. Never throws.\n *\n * Modes (`options.mode`, default `\"full\"`):\n * - `\"full\"`: a `<tools>` XML block (name + description per tool, XML-escaped).\n * An empty array yields `<tools></tools>`.\n * - `\"summary\"`: markdown `- name: <first sentence>` per tool (NOT XML-escaped).\n * - `\"names\"`: markdown `- name` per tool (NOT XML-escaped).\n *\n * Markdown modes on an empty array yield `\"\"`. A non-object `options` arg (e.g. a\n * map index from `tools.map(renderToolList)`) has no `.mode` → falls back to `\"full\"`.\n */\nexport function renderToolList(tools: CustomTool[], options?: { mode?: ToolListMode }): string {\n const mode = options?.mode ?? \"full\";\n if (mode === \"summary\") {\n return tools.map((t) => `- ${t.name}: ${firstSentence(t.description)}`).join(\"\\n\");\n }\n if (mode === \"names\") {\n return tools.map((t) => `- ${t.name}`).join(\"\\n\");\n }\n if (tools.length === 0) return \"<tools></tools>\";\n const lines = [\"<tools>\"];\n for (const t of tools) {\n lines.push(\n \" <tool>\",\n ` <name>${esc(t.name)}</name>`,\n ` <description>${esc(t.description)}</description>`,\n \" </tool>\",\n );\n }\n lines.push(\"</tools>\");\n return lines.join(\"\\n\");\n}\n","/**\n * Rich-error guidance for tool failures (M3-4).\n *\n * `withToolResultGuidance(tool, guidance)` wraps a `CustomTool` so a failing\n * `{ ok: false, error }` JSON result gains an LLM-actionable `guidance` string\n * telling the model how to self-correct. The injection is ADDITIVE (only on\n * `ok:false`), IDEMPOTENT (never overwrites an existing `guidance`), and\n * NEVER-THROW (a non-JSON / non-object / `ok:true` / unknown-code result is\n * returned unchanged). Composes over the existing built-in tools (and custom\n * tools) — no factory edits required.\n *\n * Design: blueprint m3-rich-errors. Zero new dependencies (JSON transform).\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\n/** Maps a tool error code to a short, LLM-actionable self-correction hint. */\nexport type ToolGuidanceMap = Record<string, string>;\n\n/** Curated hints for the common cross-tool error codes. Consumers may extend. */\nexport const DEFAULT_TOOL_GUIDANCE: ToolGuidanceMap = {\n not_found:\n \"The path does not exist. Use `list_dir` or `glob_files` to find the correct path, then retry.\",\n path_traversal: \"That path escapes the project root. Use a path inside the project directory.\",\n forbidden_path:\n \"That path is a protected file (.env, .git, lock files, etc.). Choose a different, non-sensitive path.\",\n no_match:\n \"The search text was not found verbatim. Re-read the file with `read_file` and copy the exact text (including whitespace/indentation) before editing.\",\n timeout: \"The operation timed out. Narrow the scope or pass a larger `timeout_ms`.\",\n invalid_url: \"The URL is malformed. Provide a full absolute http(s):// URL.\",\n ssrf_blocked: \"That host is private/loopback/reserved and is blocked. Use a public URL.\",\n catastrophic_command:\n \"That command is blocked as catastrophic. Use a safer, scoped command (e.g. a relative path instead of `/`).\",\n binary_file: \"The file is binary and cannot be read as text. Use a tool suited to binary data.\",\n too_large:\n \"The target is too large to process directly. Use a bounded range or a narrower scope.\",\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Pure: parse a tool handler's JSON output and ADD a `guidance` hint when the\n * result is an `{ ok: false, error }` object whose code has a hint and that does\n * not already carry guidance. Any other input is returned UNCHANGED (never throws).\n */\nexport function injectGuidance(handlerOutput: string, guidance: ToolGuidanceMap): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(handlerOutput);\n } catch {\n return handlerOutput; // non-JSON tool output → passthrough\n }\n if (!isRecord(parsed) || parsed.ok !== false) return handlerOutput;\n if (\"guidance\" in parsed) return handlerOutput; // idempotent — never touch an existing key\n const code = parsed.error;\n if (typeof code !== \"string\") return handlerOutput;\n const hint = guidance[code];\n if (!hint) return handlerOutput; // unknown code → no guidance\n return JSON.stringify({ ...parsed, guidance: hint });\n}\n\n/**\n * Wrap a `CustomTool` so its failed results gain a `guidance` hint from `guidance`.\n * Preserves name/description/inputSchema; only the handler output is augmented.\n */\nexport function withToolResultGuidance(tool: CustomTool, guidance: ToolGuidanceMap): CustomTool {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: async (input) => {\n const out = await tool.handler(input);\n // SE7 — guidance injection is a string-JSON concern; a handler returning\n // structured content blocks passes through untouched.\n return typeof out === \"string\" ? injectGuidance(out, guidance) : out;\n },\n };\n}\n\n/** `withToolResultGuidance` pre-bound to {@link DEFAULT_TOOL_GUIDANCE}. */\nexport function withDefaultGuidance(tool: CustomTool): CustomTool {\n return withToolResultGuidance(tool, DEFAULT_TOOL_GUIDANCE);\n}\n\n/**\n * Wrap `shell_exec` so a SOFT failure — `{ ok: true, exit_code != 0 }` (the TOOL ran, the COMMAND\n * failed) — gains a `guidance` hint. This is the one case {@link injectGuidance} does not cover (it\n * is `ok:false`-only by design). ADDITIVE, IDEMPOTENT, NEVER-THROW; a no-op for any other tool, for\n * `exit_code 0`, and for non-JSON output. Compose AFTER {@link withDefaultGuidance} (the two domains —\n * `ok:false` vs `ok:true` soft-fail — are disjoint, so there is no double-injection).\n */\nexport function withShellExitGuidance(tool: CustomTool): CustomTool {\n if (tool.name !== \"shell_exec\") return tool;\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: async (input) => {\n const out = await tool.handler(input);\n // SE7 — structured content blocks are not JSON guidance-injectable; passthrough.\n if (typeof out !== \"string\") return out;\n let parsed: unknown;\n try {\n parsed = JSON.parse(out);\n } catch {\n return out; // non-JSON tool output → passthrough\n }\n if (\n isRecord(parsed) &&\n parsed.ok === true &&\n typeof parsed.exit_code === \"number\" &&\n parsed.exit_code !== 0 &&\n !(\"guidance\" in parsed)\n ) {\n const guidance = `The command exited ${parsed.exit_code}. Read the stderr above, fix the cause, then retry.`;\n return JSON.stringify({ ...parsed, guidance });\n }\n return out;\n },\n };\n}\n","/**\n * `list_dir` — built-in tool for coding agents.\n *\n * Returns the direct entries of a project-relative directory. Hardened\n * against the same four bug families as `read_file` plus the\n * **EC-6 unbounded output** failure mode: in a project with 10k files,\n * a naive listing returns a 5 MB JSON payload that freezes the browser\n * and (more importantly) blows past the LLM context window.\n *\n * Defaults:\n * - `max = 500` entries (override via factory option `{ max }`)\n * - Result includes `{ truncated: boolean, totalCount: number }` so the\n * agent can decide whether to drill deeper or call `search_text` instead\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, entries: Array<{ name, type }>, truncated, totalCount }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'not_found' }`\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n type FilesystemProvider,\n FilesystemSecurityError,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { isForbiddenAtAnyDepth } from \"./path-scope.js\";\n\nconst DEFAULT_MAX_ENTRIES = 500;\n\nexport interface CreateListDirToolOptions {\n /**\n * M76 — the name exposed to the model. Omitted ⇒ today's literal (additive).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision key —\n * three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName` remains\n * for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /**\n * M76 — opt-in \"list anywhere\": honours an ABSOLUTE `path` outside `projectRoot`\n * (parity with `createReadFileTool`/`createSearchTextTool`, Codex's read-only sandbox).\n *\n * The ANY-segment secret guard still applies, and is not separable: `isForbiddenPath`\n * only blocks the sensitive item when it is the FIRST segment, so a `/home/u/proj/.env/sub`\n * would pass. Enabling the flag without the guard opens exfiltration. Default `false` => absolute rejected.\n */\n allowAbsolute?: boolean;\n /** Absolute path to the project root. Every listing is gated against this boundary. */\n projectRoot: string;\n /** Maximum number of entries returned per call. Default 500. */\n max?: number;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver. When provided, listings route through the backend\n * (its own boundary + `basePath`) instead of the local `projectRoot`; omitted\n * ⇒ identical current behavior (multi-tenant / per-request roots).\n */\n filesystem?: FilesystemProvider;\n}\n\nexport function createListDirTool(opts: CreateListDirToolOptions): CustomTool {\n const { projectRoot, max = DEFAULT_MAX_ENTRIES, filesystem } = opts;\n\n return Tool.create({\n name: opts.name ?? \"list_dir\",\n description:\n opts.description ??\n `Return the direct entries of a project-relative directory. ` +\n `Refuses paths outside the project root or in the sensitive-file ` +\n `blocklist (.env, .git/, node_modules/, .theo/, lock files). Caps ` +\n `at ${String(max)} entries by default; result carries truncated + totalCount.`,\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative directory path. Use '.' for root.\"),\n }),\n handler: async ({ path }, ctx) => {\n const relative = path === \"\" || path === \".\" ? \".\" : path;\n const verdict = decideScope(relative, path, opts.allowAbsolute === true);\n if (verdict.error !== undefined) return verdict.error;\n if (verdict.absoluteRoot !== undefined) {\n return listViaLocalFs(verdict.absoluteRoot, \".\", path, max);\n }\n // SE31 — route through the pluggable backend when one is configured; else\n // the local `projectRoot` fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return listViaBackend(backend, relative, path, max);\n }\n return listViaLocalFs(projectRoot, relative, path, max);\n },\n });\n}\n\n/**\n * `list_dir`'s scope decision, separated from the handler.\n *\n * Extracted because the SDK's complexity gate separated it for us — and it was right: DECIDING whether the\n * path may be read is the part with a security consequence, and deserves to be read alone. The handler\n * merely orchestrates afterwards.\n *\n * Returns `{ error }` when the path is refused, `{ absoluteRoot }` when it is an honored absolute, or\n * `{}` for the usual relative case.\n */\nfunction decideScope(\n relative: string,\n original: string,\n allowAbsolute: boolean,\n): { error?: string; absoluteRoot?: string } {\n const refuse = (error: string): { error: string } => ({\n error: JSON.stringify({ ok: false, error, path: original }),\n });\n\n if (relative !== \".\" && isForbiddenPath(relative)) return refuse(\"forbidden_path\");\n if (!isAbsolute(relative)) return {};\n\n // M76 — absolute only with opt-in, and ALWAYS with the per-segment guard: `isForbiddenPath` above only looks at\n // the FIRST segment, so a `/home/u/proj/.env/sub` would slip past it.\n if (!allowAbsolute) return refuse(\"path_traversal\");\n if (isForbiddenAtAnyDepth(relative)) return refuse(\"forbidden_path\");\n return { absoluteRoot: relative };\n}\n\n/** Local-`projectRoot` listing: boundary + readdir + bounded format. */\nasync function listViaLocalFs(\n projectRoot: string,\n relative: string,\n originalPath: string,\n max: number,\n): Promise<string> {\n const boundary = resolveDirBoundary(relative, projectRoot, originalPath);\n if (\"error\" in boundary) return boundary.error;\n const readResult = await readDirSafe(boundary.absolutePath, originalPath);\n if (\"error\" in readResult) return readResult.error;\n return formatListing(readResult.dirents, max);\n}\n\n/**\n * SE31 — list through a {@link FilesystemBackend}. The minimal backend `list()`\n * returns names only, so each entry's type is resolved via `stat()` (bounded by\n * `max`, so an entry with a transient stat failure defaults to `file`). Typed\n * backend errors map to the tool's `{ ok: false, error }` JSON.\n */\nasync function listViaBackend(\n backend: FilesystemBackend,\n relative: string,\n originalPath: string,\n max: number,\n): Promise<string> {\n let names: string[];\n try {\n names = await backend.list(relative);\n } catch (err) {\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path: originalPath });\n }\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path: originalPath });\n }\n throw err;\n }\n const totalCount = names.length;\n const windowed = names.slice(0, max);\n const entries = await Promise.all(\n windowed.map(async (name) => {\n const child = relative === \".\" ? name : `${relative}/${name}`;\n let type: \"file\" | \"directory\" = \"file\";\n try {\n type = (await backend.stat(child)).isDirectory ? \"directory\" : \"file\";\n } catch {\n // A transient stat failure (e.g. a symlink the backend rejects) defaults\n // to `file` — the listing still returns the entry name, never crashes.\n }\n return { name, type };\n }),\n );\n return JSON.stringify({ ok: true, entries, truncated: totalCount > max, totalCount });\n}\n\nfunction resolveDirBoundary(\n relative: string,\n projectRoot: string,\n originalPath: string,\n): { absolutePath: string } | { error: string } {\n try {\n const absolutePath = relative === \".\" ? projectRoot : safePathJoin(projectRoot, relative);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n return { absolutePath };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path: originalPath }) };\n }\n throw err;\n }\n}\n\nasync function readDirSafe(\n absolutePath: string,\n originalPath: string,\n): Promise<{ dirents: Dirent[] } | { error: string }> {\n try {\n const dirents = await readdir(absolutePath, { withFileTypes: true });\n return { dirents };\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\" || e.code === \"ENOTDIR\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path: originalPath }) };\n }\n throw err;\n }\n}\n\nfunction formatListing(dirents: Dirent[], max: number): string {\n const totalCount = dirents.length;\n const truncated = totalCount > max;\n const entries = dirents.slice(0, max).map((d) => ({\n name: d.name,\n type: d.isDirectory() ? (\"directory\" as const) : (\"file\" as const),\n }));\n return JSON.stringify({ ok: true, entries, truncated, totalCount });\n}\n","/**\n * `plan_mode` — tool for toggling between normal and planning mode.\n *\n * In plan mode, the agent focuses on outlining steps rather than executing them.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, mode: string, message: string }`\n * - `{ ok: false, error: \"invalid_action\" }`\n *\n * Opt-in persistence (M4-4): `createPlanModeTool({ artifactStore })` returns a\n * variant whose async handler persists the submitted `plan` on `exit`.\n */\n\nimport type { SessionArtifactStore } from \"./artifact-store.js\";\n\ntype Mode = \"normal\" | \"plan\";\n\nconst PLAN_INSTRUCTIONS = [\n \"You are now in PLAN MODE.\",\n \"Outline the steps you will take before executing any code changes.\",\n \"Number each step. Include file paths and what will change.\",\n \"Do NOT make any edits or tool calls other than reading files.\",\n \"When ready, use plan_mode with action 'exit' to return to normal mode.\",\n].join(\"\\n\");\n\nconst NORMAL_INSTRUCTIONS = \"Returned to NORMAL MODE. You may now execute changes.\";\n\nexport interface PlanModeTool {\n name: string;\n description: string;\n inputSchema: unknown;\n handler: (input: { action: string }) => string;\n /** Expose current mode for testing. */\n currentMode: () => Mode;\n}\n\n/**\n * Plan-mode tool with opt-in artifact persistence (M4-4). Same surface as\n * {@link PlanModeTool} but the handler is ASYNC (it may write to the store) and\n * accepts an optional `plan` to persist on `exit`.\n *\n * @public\n */\nexport interface PlanModeToolWithStore {\n name: string;\n description: string;\n inputSchema: unknown;\n handler: (input: { action: string; plan?: string }) => Promise<string>;\n currentMode: () => Mode;\n}\n\n/**\n * Options for the persistence-enabled {@link createPlanModeTool} overload.\n *\n * @public\n */\nexport interface PlanModeToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Store the submitted `plan` is persisted to on `exit`. */\n artifactStore: SessionArtifactStore;\n /** Artifact id under which the plan is stored. Default `\"plan\"`. */\n artifactId?: string;\n}\n\nconst DESCRIPTION =\n \"Toggle between normal and plan mode. \" +\n \"Actions: 'enter' (switch to plan mode), 'exit' (return to normal), 'status' (check current mode). \" +\n \"Returns { ok, mode, message }.\";\n\nfunction planModeSchema(withPlan: boolean): unknown {\n const properties: Record<string, unknown> = {\n action: {\n type: \"string\",\n enum: [\"enter\", \"exit\", \"status\"],\n description: \"The action to perform.\",\n },\n };\n if (withPlan) {\n properties.plan = {\n type: \"string\",\n description: \"On 'exit', the plan text to persist to the artifact store.\",\n };\n }\n return { type: \"object\" as const, properties, required: [\"action\"] };\n}\n\nfunction renderMode(action: string, mode: Mode): string | undefined {\n switch (action) {\n case \"enter\":\n return JSON.stringify({ ok: true, mode, message: PLAN_INSTRUCTIONS });\n case \"exit\":\n return JSON.stringify({ ok: true, mode, message: NORMAL_INSTRUCTIONS });\n case \"status\":\n return JSON.stringify({ ok: true, mode, message: `Current mode: ${mode}` });\n default:\n return undefined;\n }\n}\n\nfunction invalidAction(action: string): string {\n return JSON.stringify({\n ok: false,\n error: \"invalid_action\",\n message: `Unknown action '${action}'. Valid: enter, exit, status.`,\n });\n}\n\nexport function createPlanModeTool(): PlanModeTool;\nexport function createPlanModeTool(options: PlanModeToolOptions): PlanModeToolWithStore;\nexport function createPlanModeTool(\n options?: PlanModeToolOptions,\n): PlanModeTool | PlanModeToolWithStore {\n let mode: Mode = \"normal\";\n\n if (options === undefined) {\n return {\n name: \"plan_mode\",\n description: DESCRIPTION,\n inputSchema: planModeSchema(false),\n handler: (input: { action: string }): string => {\n if (input.action === \"enter\") mode = \"plan\";\n else if (input.action === \"exit\") mode = \"normal\";\n return renderMode(input.action, mode) ?? invalidAction(input.action);\n },\n currentMode: () => mode,\n };\n }\n\n const { artifactStore, artifactId = \"plan\" } = options;\n return {\n name: options.name ?? \"plan_mode\",\n description: options.description ?? DESCRIPTION,\n inputSchema: planModeSchema(true),\n handler: async (input: { action: string; plan?: string }): Promise<string> => {\n if (input.action === \"enter\") {\n mode = \"plan\";\n return JSON.stringify({ ok: true, mode, message: PLAN_INSTRUCTIONS });\n }\n if (input.action === \"exit\") {\n mode = \"normal\";\n // Persist only a non-empty plan (EC-1); enter/status never persist (EC-2).\n if (typeof input.plan === \"string\" && input.plan.length > 0) {\n const path = await artifactStore.write(artifactId, input.plan);\n return JSON.stringify({\n ok: true,\n mode,\n message: NORMAL_INSTRUCTIONS,\n persisted: true,\n path,\n });\n }\n return JSON.stringify({ ok: true, mode, message: NORMAL_INSTRUCTIONS, persisted: false });\n }\n return renderMode(input.action, mode) ?? invalidAction(input.action);\n },\n currentMode: () => mode,\n };\n}\n","/**\n * `question` — interactive tool that asks the user a question and waits for a response.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, answer: string }`\n * - `{ ok: false, error: \"timeout\" }`\n */\n\nexport interface QuestionToolOptions {\n /**\n * Callback that presents the question to the user and resolves with the answer.\n *\n * M76 — became OPTIONAL: the preferred asker comes from the run context\n * (`ctx.context.askUser`), because a value pinned here is the \"baked into each factory\" that the\n * `CustomTool.handler` names as the problem `ctx.context` exists to solve. This field\n * remains as a fallback, for callers building the tool with a fixed asker (backward-compatible).\n */\n askUser?: (question: string, threadId?: string) => Promise<string>;\n /**\n * Called when the question is ABANDONED (timeout or run cancellation), so the UI side can\n * release the slot. Without it the timeout leaves the question pending forever — the UI keeps showing\n * a prompt nobody is waiting on and the next question fails with \"one is already pending\".\n */\n onAbandon?: (threadId?: string) => void;\n /** Maximum time to wait for user response in ms. Default: 300_000 (5 min). */\n timeoutMs?: number;\n /**\n * M76 — the name exposed to the model. Omitted ⇒ `\"question\"` (additive).\n *\n * The consumer needed this: Codex calls the tool `request_user_input`, and without the option it\n * had to rebuild the whole object by hand — the two-cast adapter T3.3\n * removed.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n}\n\n/**\n * M76 — aligned with the SDK's `CustomTool`. It used to be its own interface with `inputSchema: unknown`, which\n * forced every consumer to write a cast to register the tool — and a cast does not fix a contract,\n * it only silences the compiler, turning a future signature change into a RUNTIME error.\n *\n * Narrowing was additive: the value has always been an object (`{ type: \"object\", properties, required }`\n * just below); only the declared type was loose. The handler accepts the contract's optional 2nd\n * argument (`ctx`), through which M76 now resolves the asker per session.\n */\nexport interface QuestionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n /**\n * M76 — the input is `Record<string, unknown>`, not `{ question: string }`, by CONTRAVARIANCE: a\n * handler accepting only the narrow type is not assignable to one accepting the wide type, and `CustomTool`\n * SDK declares the wide one. Declaring narrow here forced the consumer into a cast — which was\n * exactly the defect. Narrowing happens INSIDE the handler, where validation lives.\n */\n handler: (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ) => Promise<string>;\n}\n\n/**\n * Extracts the asker from the run context, when there is one.\n *\n * `ctx.context` is `unknown` by contract — it is user data, and the SDK does not type it. A `context`\n * present but WITHOUT `askUser` (e.g. only `projectRoot`) must not be mistaken for \"an asker exists\": the\n * check is on the function, not on the object's presence.\n */\nfunction askerFromContext(\n context: unknown,\n): ((question: string, threadId?: string) => Promise<string>) | undefined {\n if (typeof context !== \"object\" || context === null) return undefined;\n const candidate = (context as { askUser?: unknown }).askUser;\n return typeof candidate === \"function\"\n ? (candidate as (question: string, threadId?: string) => Promise<string>)\n : undefined;\n}\n\nexport function createQuestionTool(opts: QuestionToolOptions): QuestionTool {\n const timeoutMs = opts.timeoutMs ?? 300_000;\n\n return {\n name: opts.name ?? \"question\",\n description:\n opts.description ??\n \"Ask the user a question and wait for their response. \" +\n \"Use when you need clarification or confirmation before proceeding. \" +\n \"Returns { ok, answer } or { ok: false, error: 'timeout' }.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n question: { type: \"string\", description: \"The question to ask the user.\" },\n },\n required: [\"question\"],\n },\n handler: async (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ): Promise<string> => {\n // M76 — precedence: run context > factory. `ctx.threadId` identifies the session, so a\n // tool shared across sessions now scopes the asker per session instead of leaking it.\n const askUser = askerFromContext(ctx?.context) ?? opts.askUser;\n if (askUser === undefined) {\n // NEVER a pending promise: with no asker, waiting out the 5 min timeout would stall the whole turn\n // with nobody knowing why. Typed error, immediate (`error-handling.md` § 2).\n return JSON.stringify({\n ok: false,\n error: \"no_asker\",\n message:\n \"No asker available: pass `askUser` to createQuestionTool, or provide \" +\n \"`context.askUser` via SendOptions.context.\",\n });\n }\n const timeout = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"timeout\")), timeoutMs);\n });\n\n try {\n // M76 review — the `threadId` is FORWARDED to the asker. Without it the chain ctx.threadId -> bridge\n // did not exist: the bridge always fell into the default slot and the Map had one key forever — the\n // `let pending` under another name. The capability existed; the wiring did not.\n const answer = await Promise.race([\n askUser(String(input.question ?? \"\"), ctx?.threadId),\n timeout,\n ]);\n return JSON.stringify({ ok: true, answer });\n } catch (err) {\n if (err instanceof Error && err.message === \"timeout\") {\n // M76 review (MEDIUM-1) — tells the asker the question DIED. Without it the slot stayed\n // occupied forever: the UI kept rendering an orphaned prompt, and every subsequent question\n // got \"one is already pending\" — a permanent error for something nobody awaits anymore.\n opts.onAbandon?.(ctx?.threadId);\n return JSON.stringify({\n ok: false,\n error: \"timeout\",\n message: \"User did not respond within timeout.\",\n });\n }\n throw err;\n }\n },\n };\n}\n","/**\n * `read_file` — built-in tool for coding agents.\n *\n * Reads a project-relative file as UTF-8 and returns its contents.\n * Hardened against the four bug families a coding agent normally hits:\n *\n * 1. **Path traversal** — `safePathJoin` rejects literal `..`,\n * normalised escape, absolute segments, null-byte injection.\n * 2. **Symlink escape** — `assertNoSymlinkEscape` follows the full\n * chain (and any intermediate symlinks; defence-in-depth fix v1.x).\n * 3. **Sensitive files** — `isForbiddenPath` blocks `.env*` (except\n * `.env.example`), `.git/`, `node_modules/`, `.theo/`, lock files.\n * 4. **Binary files** — null-byte check on the first 8 KB. PNG/JPEG/\n * compiled binaries return a structured `binary_file` error\n * instead of garbled UTF-8 (EC-5 from the TheoKit Studio review).\n *\n * Return shape (always a JSON string the LLM consumes):\n * - `{ ok: true, content: string }` on success\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' |\n * 'binary_file' | 'not_found' | 'too_large' }` on refusal\n *\n * The handler intentionally never throws on a \"user mistake\"\n * (traversal / forbidden / not found). Throwing reserved for SDK-side\n * mistakes that should crash the agent loop (input parse errors).\n */\n\nimport { type FileHandle, open } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n type FilesystemProvider,\n FilesystemSecurityError,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { isForbiddenAtAnyDepth } from \"./path-scope.js\";\nimport type { ReadTracker } from \"./read-tracker.js\";\n\n/** Max single-file read size, in bytes. 5 MB ceiling — enough for any source file. */\nconst MAX_FILE_SIZE = 5 * 1024 * 1024;\n\n/** Byte window inspected for null bytes when deciding binary vs text. */\nconst BINARY_PROBE_BYTES = 8 * 1024;\n\nexport interface CreateReadFileToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every read is gated against this boundary. */\n projectRoot: string;\n /**\n * SE32 — optional read-before-write tracker. When provided, a successful read\n * records the file's mtime so a paired `write_file` (with\n * `requireReadBeforeWrite`) can refuse a blind or stale overwrite.\n */\n readTracker?: ReadTracker;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver. When provided, reads route through the backend (its\n * own boundary + `basePath`) instead of the local `projectRoot`; omitted ⇒\n * identical current behavior (multi-tenant / per-request roots).\n */\n filesystem?: FilesystemProvider;\n /**\n * M17 — render a `cat -n`-style numbered view (`<n>\\t<line>`) instead of raw content, so the model can\n * cite / edit by line number (Codex / Claude-Code read idiom). Default `false` ⇒ raw content (unchanged).\n */\n lineNumbers?: boolean;\n /**\n * M17 — opt-in \"reads-anywhere\" (Codex read-only sandbox): honor an ABSOLUTE `path` outside `projectRoot`\n * instead of rejecting it as traversal. The `isForbiddenPath` secret guard STILL fires first, so `.env`/\n * `.git`/lock files remain blocked. Default `false` ⇒ absolute paths rejected (unchanged). Opt-in only —\n * this widens the read boundary to the whole filesystem; enable only for a trusted local agent.\n */\n allowAbsolute?: boolean;\n}\n\n/** Sensitive path segments — secret-bearing dirs/files that must never be read at ANY depth. */\n\n/** Secret guard for both read paths — the project-relative first-segment check plus, for an honored\n * absolute path (`allowAbsolute`), an any-depth check. Returns an error JSON string, or null if safe. */\nfunction forbiddenReadError(path: string, allowAbsolute: boolean): string | null {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n if (allowAbsolute && isAbsolute(path) && isForbiddenAtAnyDepth(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n return null;\n}\n\n/** Render `content` as a raw string, or a paginated `<n>\\t<line>` numbered view. Pure. */\nfunction renderView(\n content: string,\n opts: { lineNumbers?: boolean; offset?: number; limit?: number },\n): string {\n const paginated = opts.offset !== undefined || opts.limit !== undefined;\n if (!opts.lineNumbers && !paginated) return content; // default — byte-identical\n const lines = content.split(\"\\n\");\n const start = Math.max(1, opts.offset ?? 1);\n const end =\n opts.limit !== undefined ? Math.min(lines.length, start - 1 + opts.limit) : lines.length;\n const slice = lines.slice(start - 1, end);\n return opts.lineNumbers ? slice.map((l, i) => `${start + i}\\t${l}`).join(\"\\n\") : slice.join(\"\\n\");\n}\n\nexport function createReadFileTool(opts: CreateReadFileToolOptions): CustomTool {\n const { projectRoot, readTracker, filesystem, lineNumbers, allowAbsolute } = opts;\n const numbered = lineNumbers === true ? \" Returns a cat -n numbered view (`<n>\\\\t<line>`).\" : \"\";\n const abs = allowAbsolute === true ? \" Absolute paths outside the project are honored.\" : \"\";\n\n return Tool.create({\n name: opts.name ?? \"read_file\",\n description:\n opts.description ??\n \"Read a text file as UTF-8. ALWAYS read a file before you edit it (edit_file) or overwrite it \" +\n \"(write_file), so your old_string / new content matches the real bytes exactly.\" +\n numbered +\n abs +\n \" By default returns the whole file; use the optional offset (1-based first line) + limit to page \" +\n \"through a large file, or search_text to locate a symbol. Refuses sensitive files (.env, .git/, \" +\n \"node_modules/, .theo/, lock files) and \" +\n \"binary files (null byte in the first 8 KB); caps at 5 MB. Returns { ok, content, size } or \" +\n \"{ ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"File path (project-relative; absolute when allowed).\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-based first line to read (default 1).\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Max number of lines to read (default: all).\"),\n }),\n handler: async ({ path, offset, limit }, ctx) => {\n const forbidden = forbiddenReadError(path, allowAbsolute === true);\n if (forbidden !== null) return forbidden;\n const view = { lineNumbers, offset, limit };\n // SE31 — route through the pluggable backend when one is configured (the\n // backend owns its own boundary); else the local `projectRoot` fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return readViaBackend(backend, path, view, (mtimeMs) => readTracker?.record(path, mtimeMs));\n }\n const boundary = resolveBoundary(path, projectRoot, allowAbsolute === true);\n if (\"error\" in boundary) return boundary.error;\n const opened = await openHandleSafe(boundary.absolutePath, path);\n if (\"error\" in opened) return opened.error;\n try {\n return await readContent(opened.handle, path, view, (mtimeMs) =>\n readTracker?.record(path, mtimeMs),\n );\n } finally {\n await opened.handle.close();\n }\n },\n });\n}\n\n/** Render options threaded from the handler into the read paths. */\ninterface ViewOpts {\n lineNumbers?: boolean;\n offset?: number;\n limit?: number;\n}\n\n/**\n * SE31 — read through a {@link FilesystemBackend}, mapping its typed errors to\n * the tool's `{ ok: false, error }` JSON (never throws on a user mistake). The\n * binary/too-large guards mirror the local path; a null byte in the decoded\n * content flags a binary file.\n */\nasync function readViaBackend(\n backend: FilesystemBackend,\n path: string,\n view: ViewOpts,\n onRead?: (mtimeMs: number) => void,\n): Promise<string> {\n try {\n const stat = await backend.stat(path);\n if (stat.size > MAX_FILE_SIZE) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n path,\n size: stat.size,\n limit: MAX_FILE_SIZE,\n });\n }\n const raw = await backend.readFile(path);\n if (raw.includes(\"\\u0000\")) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path, size: stat.size });\n }\n onRead?.(stat.mtimeMs);\n return JSON.stringify({ ok: true, content: renderView(raw, view), size: stat.size });\n } catch (err) {\n if (err instanceof FileNotFoundError) {\n return JSON.stringify({ ok: false, error: \"not_found\", path });\n }\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n}\n\nfunction resolveBoundary(\n path: string,\n projectRoot: string,\n allowAbsolute: boolean,\n): { absolutePath: string } | { error: string } {\n // M17 — reads-anywhere: honor an absolute path (isForbiddenPath already ran; no projectRoot boundary).\n if (allowAbsolute && isAbsolute(path)) {\n return { absolutePath: path };\n }\n try {\n const absolutePath = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n return { absolutePath };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function openHandleSafe(\n absolutePath: string,\n path: string,\n): Promise<{ handle: FileHandle } | { error: string }> {\n try {\n const handle = await open(absolutePath, \"r\");\n return { handle };\n } catch (err) {\n const e = err as { code?: string };\n if (e.code === \"ENOENT\") {\n return { error: JSON.stringify({ ok: false, error: \"not_found\", path }) };\n }\n throw err;\n }\n}\n\nasync function readContent(\n handle: FileHandle,\n path: string,\n view: ViewOpts,\n onRead?: (mtimeMs: number) => void,\n): Promise<string> {\n const stat = await handle.stat();\n if (stat.size > MAX_FILE_SIZE) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n path,\n size: stat.size,\n limit: MAX_FILE_SIZE,\n });\n }\n if (await isBinaryProbe(handle, Number(stat.size))) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path, size: stat.size });\n }\n const raw = await handle.readFile({ encoding: \"utf-8\" });\n // SE32 — record the mtime read-before-write compares against. This is the\n // mtime captured at `handle.stat()` above; a concurrent external write between\n // that stat and this readFile is an accepted TOCTOU (the recorded snapshot may\n // trail the delivered content by one write — same-user local context). The\n // write-side guard still catches the common \"edited after I read it\" case.\n onRead?.(stat.mtimeMs);\n return JSON.stringify({ ok: true, content: renderView(raw, view), size: stat.size });\n}\n\nasync function isBinaryProbe(handle: FileHandle, size: number): Promise<boolean> {\n const probeLen = Math.min(BINARY_PROBE_BYTES, size);\n if (probeLen <= 0) return false;\n const probe = Buffer.alloc(probeLen);\n const { bytesRead } = await handle.read(probe, 0, probeLen, 0);\n for (let i = 0; i < bytesRead; i += 1) {\n if (probe[i] === 0) return true;\n }\n return false;\n}\n","/**\n * `ReadTracker` — SE32 read-before-write safety.\n *\n * A per-run map of `path → mtimeMs` recorded whenever the read tool reads a\n * file. The write tool (with `requireReadBeforeWrite` on) consults it before an\n * overwrite: a file that was never read, or that changed on disk since it was\n * read, is refused instead of silently clobbered. Scope one tracker per run /\n * session — it is deliberately NOT a global singleton (no cross-run leak).\n *\n * @public\n */\nexport class ReadTracker {\n private readonly seen = new Map<string, number>();\n\n /** Record the mtime observed when `path` was read. */\n record(path: string, mtimeMs: number): void {\n this.seen.set(path, mtimeMs);\n }\n\n /** The mtime last recorded for `path`, or `undefined` if never read. */\n expected(path: string): number | undefined {\n return this.seen.get(path);\n }\n}\n\n/** The verdict of a read-before-write check for one write (internal). */\ntype WriteDecision = \"ok\" | \"read_required\" | \"stale\";\n\n/**\n * Decide whether a write to `path` is allowed, given the file's CURRENT on-disk\n * mtime (`null` ⇒ the file does not exist yet). Pure — no I/O.\n *\n * - absent file → `ok` (a new file cannot clobber anything)\n * - present, unread → `read_required` (must read before a blind overwrite)\n * - present, changed → `stale` (mtime differs from the read snapshot)\n * - present, unchanged → `ok`\n */\nexport function evaluateReadBeforeWrite(\n tracker: ReadTracker,\n path: string,\n currentMtimeMs: number | null,\n): WriteDecision {\n if (currentMtimeMs === null) return \"ok\";\n const recorded = tracker.expected(path);\n if (recorded === undefined) return \"read_required\";\n if (recorded !== currentMtimeMs) return \"stale\";\n return \"ok\";\n}\n","/**\n * SE37 — the public reasoning toolkit: `ReasoningTools.create()` returns a\n * `think` + `analyze` scratchpad (no-side-effect tools that echo the model's\n * structured reasoning back as an observation, so the ReAct loop feeds it\n * forward). Mirrors Anthropic's \"think\" tool + a peer's `ReasoningTools`.\n *\n * Lives in `@theokit/sdk-tools` (not core) so the full toolkit stays out of the\n * core bundle. The `reasoning: true` agent flag auto-attaches an equivalent\n * lean `think` from core; add these explicitly (`tools: [...ReasoningTools.create()]`)\n * when you want the model to reason with a scratchpad on any model.\n *\n * @public\n */\n\nimport { type CustomTool, Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\n/** Reasoning scratchpad tools. `ReasoningTools.create()` → `[think, analyze]`. */\nexport class ReasoningTools {\n private constructor() {}\n\n /** Build the tools. Pass `{ analyze: false }` for `think` only. */\n static create(opts?: { analyze?: boolean }): CustomTool[] {\n const think = Tool.create({\n name: \"think\",\n description:\n \"Use this as a scratchpad to think step by step BEFORE answering or acting. Write out your \" +\n \"reasoning for one step. Nothing else happens — it is only your private reasoning space. \" +\n \"Call it as many times as you need before the final answer.\",\n inputSchema: z.object({\n thought: z.string().min(1, \"think: `thought` must be a non-empty string.\"),\n }),\n handler: ({ thought }) => thought,\n });\n if (opts?.analyze === false) return [think];\n\n const analyze = Tool.create({\n name: \"analyze\",\n description:\n \"Analyze the result of a previous step or tool call. State what you looked at, your \" +\n \"analysis, and whether to `continue` reasoning, `validate` (double-check) your work, or \" +\n \"give the `final_answer`. Use this to catch your own mistakes before answering.\",\n inputSchema: z.object({\n title: z.string().optional(),\n result: z.string().min(1, \"analyze: `result` must describe what you are analyzing.\"),\n analysis: z.string().min(1, \"analyze: `analysis` must contain your reasoning.\"),\n next_action: z.enum([\"continue\", \"validate\", \"final_answer\"]),\n }),\n handler: ({ title, result, analysis, next_action }) =>\n `${title ? `# ${title}\\n` : \"\"}Result: ${result}\\nAnalysis: ${analysis}\\nNext: ${next_action}`,\n });\n return [think, analyze];\n }\n}\n","/**\n * `run_vitest` — built-in tool for coding agents.\n *\n * Runs vitest against an optional file/pattern scope and returns the\n * parsed JSON report. Hardened against the same subprocess failure\n * modes as `git_diff`:\n *\n * - 120s wall clock timeout (vitest can be slow on first run)\n * - Process group kill on timeout (EC-7 — defeats vitest workers as\n * grandchildren of the spawned shell)\n * - **EC-12**: vitest stdout may contain deprecation warnings BEFORE\n * the JSON payload. The parser scans line-by-line and extracts the\n * LAST valid JSON object, not the first.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, summary: { numTotalTests, numPassedTests, numFailedTests, success } }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'timeout' |\n * 'no_vitest' | 'unparseable_output' }`\n *\n * Implementation note: invokes vitest via `npx --no-install vitest`. The\n * `--no-install` avoids the agent triggering a multi-megabyte download\n * mid-turn if vitest is missing — the tool fails cleanly with\n * `no_vitest` instead.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\nimport { isForbiddenPath } from \"./internal/path-guard.js\";\nimport { checkPathScope } from \"./path-scope.js\";\nimport { armTimeoutKill, attachChildSettlers } from \"./subprocess.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst DEFAULT_MAX_STDOUT_BYTES = 10 * 1024 * 1024;\n\nexport interface CreateRunVitestToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n timeoutMs?: number;\n maxStdoutBytes?: number;\n}\n\nexport interface VitestSummary {\n numTotalTests?: number;\n numPassedTests?: number;\n numFailedTests?: number;\n success?: boolean;\n}\n\nexport function createRunVitestTool(opts: CreateRunVitestToolOptions): CustomTool {\n const {\n projectRoot,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"run_vitest\",\n description:\n opts.description ??\n \"Run the project's vitest suite, optionally scoped to a file or \" +\n \"pattern via 'path'. Returns parsed { ok, summary } or { ok: false, \" +\n \"error }. Vitest stdout warnings are stripped — the parser extracts \" +\n \"the trailing JSON report.\",\n inputSchema: z.object({\n path: z\n .string()\n .optional()\n .describe(\"Optional vitest pattern or file path (project-relative).\"),\n }),\n handler: async ({ path }) => {\n const scopeError = validateVitestScope(path, projectRoot);\n if (scopeError !== null) return scopeError;\n\n const args = [\"--no-install\", \"vitest\", \"run\", \"--reporter=json\"];\n if (path !== undefined && path !== \"\") args.push(path);\n\n const result = await runProcess(projectRoot, \"npx\", args, timeoutMs, maxStdoutBytes);\n return formatVitestResult(result, timeoutMs);\n },\n });\n}\n\nfunction validateVitestScope(path: string | undefined, projectRoot: string): string | null {\n if (path !== undefined && path !== \"\" && isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n return checkPathScope(path, projectRoot);\n}\n\nfunction formatVitestResult(result: ProcessResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeoutMs });\n }\n if (result.kind === \"spawn_error\") {\n return JSON.stringify({ ok: false, error: \"no_vitest\", detail: result.message });\n }\n const summary = extractTrailingJson(result.stdout) as VitestSummary | null;\n if (summary === null) {\n return JSON.stringify({\n ok: false,\n error: \"unparseable_output\",\n stderrPreview: result.stderr.slice(0, 500),\n });\n }\n return JSON.stringify({ ok: true, summary });\n}\n\n/**\n * Find the LAST line in `stdout` that parses as a JSON object. Vitest\n * prepends node deprecation warnings to its JSON reporter output — if\n * we naively `JSON.parse(stdout)` we get a SyntaxError. Workaround: walk\n * lines bottom-up and return the first one that parses.\n *\n * Exported for direct unit testing without spawning vitest.\n */\nexport function extractTrailingJson(stdout: string): unknown {\n const lines = stdout.split(/\\r?\\n/);\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]!.trim();\n if (line.length === 0) continue;\n if (line[0] !== \"{\" && line[0] !== \"[\") continue;\n try {\n return JSON.parse(line) as unknown;\n } catch {\n // not valid JSON — keep looking\n }\n }\n return null;\n}\n\nfunction appendCapped(chunks: Buffer[], chunk: Buffer, current: number, cap: number): number {\n if (current >= cap) return current;\n const remaining = cap - current;\n if (chunk.length > remaining) {\n chunks.push(chunk.subarray(0, remaining));\n return cap;\n }\n chunks.push(chunk);\n return current + chunk.length;\n}\n\ntype ProcessResult =\n | { kind: \"ok\"; stdout: string; stderr: string; exitCode: number }\n | { kind: \"timeout\" }\n | { kind: \"spawn_error\"; message: string };\n\nfunction runProcess(\n cwd: string,\n command: string,\n args: string[],\n timeoutMs: number,\n maxStdoutBytes: number,\n): Promise<ProcessResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd,\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n\n const gate = armTimeoutKill<ProcessResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n resolve,\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n stdoutBytes = appendCapped(stdoutChunks, chunk, stdoutBytes, maxStdoutBytes);\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk);\n });\n\n attachChildSettlers<ProcessResult>(\n child,\n gate,\n (code) => ({\n kind: \"ok\",\n stdout: Buffer.concat(stdoutChunks).toString(\"utf-8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf-8\"),\n exitCode: code ?? 0,\n }),\n (err) => ({ kind: \"spawn_error\", message: err.message }),\n resolve,\n );\n });\n}\n","/**\n * `search_text` — built-in tool for coding agents.\n *\n * Literal text search across the project tree (recursive). Sensible\n * defaults:\n *\n * - Skips forbidden directories (`.env`, `.git/`, `node_modules/`,\n * `.theo/`) so the agent never wastes context on dependency soup\n * or VCS internals.\n * - Skips files larger than `maxFileSize` (default 1 MB) and binary\n * files (null-byte detection on first 8 KB) so a megabyte of\n * minified JS never blows up the result.\n * - Caps total matches at `maxMatches` (default 100) — the agent\n * should refine the query if it gets close to the cap.\n *\n * Result shape (always a JSON string):\n * - `{ ok: true, matches: Array<{ file, line, preview }>, truncated, totalMatches }`\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' | 'not_found' }`\n *\n * Implementation note: this is a plain JS recursive walk. For very\n * large repos a future iteration can shell out to `rg` (ripgrep) when\n * present, but the JS path stays as the dependency-free fallback.\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { isAbsolute, join, relative as relativePath } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n type FilesystemBackend,\n type FilesystemProvider,\n resolveFilesystem,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\n\nconst DEFAULT_MAX_MATCHES = 100;\nconst DEFAULT_MAX_FILE_SIZE = 1024 * 1024; // 1 MB\nconst BINARY_PROBE_BYTES = 8 * 1024;\nconst PREVIEW_MAX = 200;\n/**\n * Depth cap for the BACKEND walk only. The local `readdir(withFileTypes)` walk skips symlinks and can\n * never loop; the backend walk decides type via `stat` (which follows symlinks), so an in-boundary\n * symlink cycle would recurse until PATH_MAX. This bound stops that pathological case; real trees never\n * approach it.\n */\nconst MAX_BACKEND_WALK_DEPTH = 64;\n\nexport interface CreateSearchTextToolOptions {\n /**\n * M76 — the name exposed to the model. Omitted ⇒ today's literal (additive).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n projectRoot: string;\n /** Cap on total matches returned. Default 100. */\n maxMatches?: number;\n /** Skip files larger than this (bytes). Default 1 MB. */\n maxFileSize?: number;\n /** Optional injected filesystem (`@theokit/sdk/filesystem`) — when provided, the recursive walk reads\n * through the backend (surface-agnostic); omitted ⇒ the local `readdir`/`readFile` walk (unchanged). */\n filesystem?: FilesystemProvider;\n /** M17 — treat `query` as a JavaScript RegExp instead of a literal substring (grep semantics). An\n * invalid pattern returns `{ ok: false, error: 'invalid_regex' }`. Default `false` ⇒ literal (unchanged). */\n regex?: boolean;\n /** M17 — opt-in \"reads-anywhere\": honor an ABSOLUTE `path` scope outside `projectRoot` (Codex read-only\n * sandbox). Forbidden dirs are still skipped. Default `false` ⇒ absolute scope rejected (unchanged). */\n allowAbsolute?: boolean;\n}\n\ninterface Match {\n file: string;\n line: number;\n preview: string;\n}\n\nexport function createSearchTextTool(opts: CreateSearchTextToolOptions): CustomTool {\n const {\n projectRoot,\n maxMatches = DEFAULT_MAX_MATCHES,\n maxFileSize = DEFAULT_MAX_FILE_SIZE,\n filesystem,\n regex = false,\n allowAbsolute = false,\n } = opts;\n const queryKind = regex ? \"a JavaScript REGULAR EXPRESSION\" : \"LITERAL, CASE-SENSITIVE text\";\n const queryMatch = regex ? \"matched as a regex\" : \"matched as a substring, not a regex\";\n\n return Tool.create({\n name: opts.name ?? \"search_text\",\n description:\n opts.description ??\n `Search file CONTENTS for ${queryKind} across the project tree (the query is ${queryMatch}). ` +\n `Use search_text when you know the content; use glob_files when you know the filename shape; use ` +\n `read_file when you know the exact path. Skips sensitive dirs (.env/.git/node_modules/.theo), ` +\n `binary files, and files over 1 MB; 'path' scopes the search to a subdirectory. Returns up to ` +\n `${String(maxMatches)} matches as { file, line, preview } — cite locations to the user as ` +\n `file:line. Returns { ok, matches } or { ok: false, error }.`,\n inputSchema: z.object({\n query: regex\n ? z.string().min(1).describe(\"A JavaScript regular expression, e.g. 'function\\\\\\\\s+main'.\")\n : z.string().min(1).describe(\"Literal text to search for. Case-sensitive.\"),\n path: z\n .string()\n .optional()\n .describe(\n \"Optional directory to scope the search (project-relative; absolute when allowed).\",\n ),\n }),\n handler: async ({ query, path }, ctx) => {\n // M17 — build the line matcher once (regex or literal). An invalid regex fails clear before walking.\n const built = buildMatcher(query, regex);\n if (\"error\" in built) return built.error;\n const matcher = built.matcher;\n const state: SearchState = {\n matches: [],\n totalMatches: 0,\n truncated: false,\n matcher,\n maxMatches,\n maxFileSize,\n projectRoot,\n };\n\n // Injected filesystem (surface-agnostic) ⇒ walk via the backend in project-relative path space;\n // absent ⇒ the local `readdir`/`readFile` walk (byte-identical to before).\n if (filesystem !== undefined) {\n const scopeRel = resolveScopeRel(path, projectRoot, allowAbsolute);\n if (\"error\" in scopeRel) return scopeRel.error;\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n await walkBackend(backend, scopeRel.rel, state, 0);\n return JSON.stringify({\n ok: true,\n matches: state.matches,\n truncated: state.truncated,\n totalMatches: state.totalMatches,\n });\n }\n\n const scope = resolveSearchScope(path, projectRoot, allowAbsolute);\n if (\"error\" in scope) return scope.error;\n await walk(scope.scopeAbs, state);\n return JSON.stringify({\n ok: true,\n matches: state.matches,\n truncated: state.truncated,\n totalMatches: state.totalMatches,\n });\n },\n });\n}\n\n/** Build the per-line predicate: a compiled RegExp (M17 grep mode) or a literal substring test. */\nfunction buildMatcher(\n query: string,\n regex: boolean,\n): { matcher: (line: string) => boolean } | { error: string } {\n if (!regex) return { matcher: (line) => line.includes(query) };\n try {\n const re = new RegExp(query);\n return { matcher: (line) => re.test(line) };\n } catch {\n return { error: JSON.stringify({ ok: false, error: \"invalid_regex\", query }) };\n }\n}\n\ninterface SearchState {\n matches: Match[];\n totalMatches: number;\n truncated: boolean;\n /** Per-line predicate — literal substring or compiled regex (M17). */\n matcher: (line: string) => boolean;\n maxMatches: number;\n maxFileSize: number;\n projectRoot: string;\n}\n\nfunction resolveSearchScope(\n path: string | undefined,\n projectRoot: string,\n allowAbsolute: boolean,\n): { scopeAbs: string } | { error: string } {\n const scopeRel = path === undefined || path === \"\" || path === \".\" ? \".\" : path;\n // M17 — reads-anywhere: honor an absolute scope (Codex read-only sandbox); forbidden dirs still skipped.\n if (allowAbsolute && isAbsolute(scopeRel)) {\n return { scopeAbs: scopeRel };\n }\n try {\n const scopeAbs = scopeRel === \".\" ? projectRoot : safePathJoin(projectRoot, scopeRel);\n assertNoSymlinkEscape(scopeAbs, projectRoot);\n return { scopeAbs };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function handleEntry(entry: Dirent, absDir: string, state: SearchState): Promise<void> {\n const entryAbs = join(absDir, entry.name);\n const entryRel = relativePath(state.projectRoot, entryAbs);\n if (isForbiddenPath(entryRel)) return;\n if (entry.isDirectory()) {\n await walk(entryAbs, state);\n return;\n }\n if (entry.isFile()) await scanFile(entryAbs, entryRel, state);\n}\n\nasync function walk(absDir: string, state: SearchState): Promise<void> {\n if (state.truncated) return;\n const entries = await readEntriesQuiet(absDir);\n if (entries === null) return;\n for (const entry of entries) {\n if (state.truncated) return;\n await handleEntry(entry, absDir, state);\n }\n}\n\nasync function readEntriesQuiet(absDir: string): Promise<Dirent[] | null> {\n try {\n return await readdir(absDir, { withFileTypes: true });\n } catch {\n return null;\n }\n}\n\nasync function readBufferQuiet(absPath: string): Promise<Buffer | null> {\n try {\n return await readFile(absPath);\n } catch {\n return null;\n }\n}\n\nfunction isBinaryBuffer(buffer: Buffer): boolean {\n const probeEnd = Math.min(buffer.length, BINARY_PROBE_BYTES);\n for (let i = 0; i < probeEnd; i += 1) {\n if (buffer[i] === 0) return true;\n }\n return false;\n}\n\nfunction recordMatch(state: SearchState, file: string, line: number, lineText: string): boolean {\n state.totalMatches += 1;\n if (state.matches.length < state.maxMatches) {\n state.matches.push({\n file,\n line,\n preview: lineText.length > PREVIEW_MAX ? `${lineText.slice(0, PREVIEW_MAX)}…` : lineText,\n });\n return true;\n }\n state.truncated = true;\n return false;\n}\n\nasync function scanFile(absPath: string, relPath: string, state: SearchState): Promise<void> {\n const buffer = await readBufferQuiet(absPath);\n if (buffer === null || buffer.length > state.maxFileSize) return;\n if (isBinaryBuffer(buffer)) return;\n const lines = buffer.toString(\"utf-8\").split(\"\\n\");\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i]!;\n if (!state.matcher(line)) continue;\n if (!recordMatch(state, relPath, i + 1, line)) return;\n }\n}\n\n// --- Surface-agnostic backend walk (mirrors the local walk in PROJECT-RELATIVE path space) ---\n\n/** Resolve the scope to a project-relative dir (`\"\"` = root) with the same security guard as the local\n * path — a traversal/forbidden scope is rejected identically. */\nfunction resolveScopeRel(\n path: string | undefined,\n projectRoot: string,\n allowAbsolute: boolean,\n): { rel: string } | { error: string } {\n const scopeRel = path === undefined || path === \"\" || path === \".\" ? \"\" : path;\n if (scopeRel === \"\") return { rel: \"\" };\n // M17 — reads-anywhere: pass an absolute scope through to the backend (it owns its own boundary).\n if (allowAbsolute && isAbsolute(scopeRel)) return { rel: scopeRel };\n try {\n assertNoSymlinkEscape(safePathJoin(projectRoot, scopeRel), projectRoot);\n return { rel: scopeRel };\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return { error: JSON.stringify({ ok: false, error: \"path_traversal\", path }) };\n }\n throw err;\n }\n}\n\nasync function walkBackend(\n backend: FilesystemBackend,\n dirRel: string,\n state: SearchState,\n depth: number,\n): Promise<void> {\n if (state.truncated) return;\n if (depth > MAX_BACKEND_WALK_DEPTH) return; // symlink-cycle guard (see MAX_BACKEND_WALK_DEPTH)\n let names: string[];\n try {\n names = await backend.list(dirRel);\n } catch {\n return;\n }\n for (const name of names) {\n if (state.truncated) return;\n await handleBackendEntry(backend, dirRel, name, state, depth);\n }\n}\n\n/** Handle one backend directory entry: skip forbidden, stat, recurse on dirs, scan files. */\nasync function handleBackendEntry(\n backend: FilesystemBackend,\n dirRel: string,\n name: string,\n state: SearchState,\n depth: number,\n): Promise<void> {\n const entryRel = dirRel === \"\" ? name : `${dirRel}/${name}`;\n if (isForbiddenPath(entryRel)) return;\n let st: { isDirectory: boolean; isFile: boolean; size: number };\n try {\n st = await backend.stat(entryRel);\n } catch {\n return;\n }\n if (st.isDirectory) {\n await walkBackend(backend, entryRel, state, depth + 1);\n } else if (st.isFile) {\n await scanFileBackend(backend, entryRel, st.size, state);\n }\n}\n\nasync function scanFileBackend(\n backend: FilesystemBackend,\n relPath: string,\n size: number,\n state: SearchState,\n): Promise<void> {\n if (size > state.maxFileSize) return;\n let content: string;\n try {\n content = await backend.readFile(relPath);\n } catch {\n return;\n }\n // Null-byte ⇒ binary; skip (parity with the local isBinaryBuffer probe, string-side).\n if (content.slice(0, BINARY_PROBE_BYTES).includes(\"\\u0000\")) return;\n const lines = content.split(\"\\n\");\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i]!;\n if (!state.matcher(line)) continue;\n if (!recordMatch(state, relPath, i + 1, line)) return;\n }\n}\n","/**\n * `shell_exec` — built-in tool for coding agents.\n *\n * Executes a shell command via `/bin/sh -c` with a configurable timeout\n * and output size cap.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, stdout, stderr, exit_code }`\n * - `{ ok: false, error: 'timeout' | 'exec_failed' }`\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { resolveSandbox, type SandboxProvider } from \"@theokit/sdk/sandbox\";\nimport { z } from \"zod\";\nimport { CatastrophicCommandError, catastrophicShellReason } from \"./internal/shell-guard.js\";\nimport { armTimeoutKill, attachChildSettlers } from \"./subprocess.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 300_000; // 5 minutes hard ceiling\nconst MAX_OUTPUT_BYTES = 5 * 1024 * 1024; // 5 MB\n\n/** Run `command` through an injected SandboxBackend, mapping its result to shell_exec's JSON shape. */\nasync function execViaSandbox(\n sandbox: SandboxProvider,\n ctx: unknown,\n command: string,\n timeoutMs: number,\n): Promise<string> {\n const backend = await resolveSandbox(sandbox, ctx ?? {});\n const r = await backend.execute(command, { timeoutMs });\n return r.timedOut\n ? JSON.stringify({ ok: false, error: \"timeout\", timeout_ms: timeoutMs })\n : JSON.stringify({ ok: true, stdout: r.stdout, stderr: r.stderr, exit_code: r.exitCode });\n}\n\nexport interface CreateShellToolOptions {\n /**\n * M76 — the name exposed to the model. Omitted ⇒ today's literal (additive).\n *\n * It exists because, in Codex, the name is BORN in the tool definition and is the approval decision\n * key — three consumers (model, approval, telemetry) of a string decided in one place. Renaming\n * after construction changes the identity of something already published to the model. `withName`\n * remains for the genuinely dynamic case.\n */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Commands execute in this cwd. */\n projectRoot: string;\n /** Default timeout in ms. Capped at 300s. */\n defaultTimeoutMs?: number;\n /**\n * Opt out of the catastrophic-command guardrail. Default `false` (the\n * guardrail screens every command before spawn). Set `true` only when the\n * agent legitimately needs destructive power flows — it is a heuristic\n * guardrail, not a sandbox.\n */\n allowCatastrophic?: boolean;\n /**\n * Optional injected execution backend (`@theokit/sdk/sandbox`) — a backend or a per-request resolver.\n * When provided, the command runs via `SandboxBackend.execute` (Local/Docker/E2B) so the tool is\n * surface-agnostic (a cluster/desktop host runs it in the sandbox, not the local host); omitted ⇒ the\n * local `/bin/sh -c` child process (byte-identical to before). The catastrophic-command guard runs\n * before either path.\n */\n sandbox?: SandboxProvider;\n}\n\nexport function createShellTool(opts: CreateShellToolOptions): CustomTool {\n const {\n projectRoot,\n defaultTimeoutMs = DEFAULT_TIMEOUT_MS,\n allowCatastrophic = false,\n sandbox,\n } = opts;\n\n return Tool.create({\n name: opts.name ?? \"shell_exec\",\n description:\n opts.description ??\n \"Execute a shell command in the project directory. Use this for terminal operations — running \" +\n \"tests, git, package managers, build tools. Do NOT use it for file operations (reading, \" +\n \"writing, editing, finding files): prefer the specialized read_file/write_file/edit_file/\" +\n \"glob_files/search_text tools, which are path-checked and safer. Only commit, push, or change \" +\n \"git state when the user explicitly asks. timeout_ms defaults to 30000 (max 300000); \" +\n \"stdout/stderr are capped (~5 MB). Returns { ok, stdout, stderr, exit_code } or \" +\n \"{ ok: false, error }.\",\n inputSchema: z.object({\n command: z.string().min(1).describe(\"Shell command to execute.\"),\n timeout_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Timeout in milliseconds (default 30000, max 300000).\"),\n }),\n handler: async ({ command, timeout_ms }, ctx) => {\n if (!allowCatastrophic) {\n const reason = catastrophicShellReason(command);\n if (reason) {\n // Construct the typed error so its `code` is the single source of the\n // error string (mirrors web_fetch's SsrfBlockedError handling).\n const err = new CatastrophicCommandError(reason);\n return JSON.stringify({ ok: false, error: err.code, reason });\n }\n }\n const timeoutMs = Math.min(timeout_ms ?? defaultTimeoutMs, MAX_TIMEOUT_MS);\n // Injected backend (surface-agnostic) ⇒ run in the sandbox; absent ⇒ the local child (unchanged).\n if (sandbox !== undefined) return execViaSandbox(sandbox, ctx, command, timeoutMs);\n return runShell(projectRoot, command, timeoutMs);\n },\n });\n}\n\ntype ShellResult =\n | { kind: \"ok\"; stdout: string; stderr: string; exitCode: number | null }\n | { kind: \"timeout\" }\n | { kind: \"error\"; message: string };\n\nfunction runShell(cwd: string, command: string, timeoutMs: number): Promise<string> {\n return new Promise((resolve) => {\n const child = spawn(\"/bin/sh\", [\"-c\", command], {\n cwd,\n detached: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let stdoutBytes = 0;\n let stderrBytes = 0;\n\n const gate = armTimeoutKill<ShellResult>(\n child,\n timeoutMs,\n () => ({ kind: \"timeout\" }),\n (result) => resolve(formatResult(result, timeoutMs)),\n );\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stdoutBytes >= MAX_OUTPUT_BYTES) {\n return;\n }\n const remaining = MAX_OUTPUT_BYTES - stdoutBytes;\n if (chunk.length > remaining) {\n stdoutChunks.push(chunk.subarray(0, remaining));\n stdoutBytes = MAX_OUTPUT_BYTES;\n } else {\n stdoutChunks.push(chunk);\n stdoutBytes += chunk.length;\n }\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n if (gate.settled()) return;\n if (stderrBytes >= MAX_OUTPUT_BYTES) return;\n const remaining = MAX_OUTPUT_BYTES - stderrBytes;\n if (chunk.length > remaining) {\n stderrChunks.push(chunk.subarray(0, remaining));\n stderrBytes = MAX_OUTPUT_BYTES;\n } else {\n stderrChunks.push(chunk);\n stderrBytes += chunk.length;\n }\n });\n\n attachChildSettlers<ShellResult>(\n child,\n gate,\n (code) => ({\n kind: \"ok\",\n stdout: Buffer.concat(stdoutChunks).toString(\"utf-8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf-8\"),\n exitCode: code,\n }),\n (err) => ({ kind: \"error\", message: err.message }),\n (result) => resolve(formatResult(result, timeoutMs)),\n );\n });\n}\n\nfunction formatResult(result: ShellResult, timeoutMs: number): string {\n if (result.kind === \"timeout\") {\n return JSON.stringify({ ok: false, error: \"timeout\", timeout_ms: timeoutMs });\n }\n if (result.kind === \"error\") {\n return JSON.stringify({ ok: false, error: \"exec_failed\", message: result.message });\n }\n return JSON.stringify({\n ok: true,\n stdout: result.stdout,\n stderr: result.stderr,\n exit_code: result.exitCode,\n });\n}\n","import type { TodoItem } from \"./todolist.js\";\n\n/**\n * A flat plan-render node — the stable shape a UI/plan layer consumes. Mirrors\n * the `TodoItem` status union; `label` is the item title.\n *\n * @public\n */\nexport interface PlanNode {\n id: string;\n label: string;\n status: \"pending\" | \"in_progress\" | \"done\";\n}\n\n/**\n * Convert structured todo items (from a `todolist` tool result's `items`, M4-5)\n * into versioned `PlanNode`s for rendering. Pure: projects EXACTLY\n * `{ id, label, status }` (timestamps are intentionally dropped), preserving\n * input order. Replaces consumer-side hand-rolled mappers.\n *\n * @public\n */\nexport function todoItemsToPlanNodes(items: readonly TodoItem[]): PlanNode[] {\n return items.map((item) => ({ id: item.id, label: item.title, status: item.status }));\n}\n","/**\n * `todolist` — in-session task tracking for multi-step work.\n *\n * The agent uses this to plan complex tasks and track progress.\n * Inspired by a peer project's todo.ts and Claude Code's TodoWrite.\n *\n * Actions:\n * - add(title) → add a new todo item\n * - complete(id) → mark an item done\n * - remove(id) → remove an item\n * - list() → show all items with status\n * - clear_completed() → remove all done items\n *\n * #119 — state is keyed by `ctx.threadId` (the run's session identity, injected by the\n * SDK from `Agent.getOrCreate(sessionId, …)`). One tool object served to many sessions\n * from a single process keeps each session's list isolated. When no `threadId` is present\n * (single-session CLI usage) every call shares one default session — behavior unchanged.\n */\n\nexport interface TodoItem {\n id: string;\n title: string;\n status: \"pending\" | \"in_progress\" | \"done\";\n createdAt: number;\n completedAt?: number;\n}\n\nexport interface TodolistTool {\n name: string;\n description: string;\n inputSchema: unknown;\n /**\n * #119 — the optional 2nd `ctx` carries the run's `threadId`; state is scoped to it.\n * Single-argument callers (CLI / tests) share one default session.\n */\n handler: (input: TodoInput, ctx?: { threadId?: string }) => string;\n /** Expose a session's items for testing (defaults to the no-threadId session). */\n getItems: (threadId?: string) => TodoItem[];\n}\n\ntype TodoInput =\n | { action: \"add\"; title: string }\n | { action: \"complete\"; id: string }\n | { action: \"in_progress\"; id: string }\n | { action: \"remove\"; id: string }\n | { action: \"list\" }\n | { action: \"clear_completed\" };\n\nfunction ok(data: Record<string, unknown>): string {\n return JSON.stringify({ ok: true, ...data });\n}\n\nfunction fail(data: Record<string, unknown>): string {\n return JSON.stringify({ ok: false, ...data });\n}\n\nfunction requireId(input: TodoInput): string | null {\n if (!(\"id\" in input) || !input.id) return null;\n return input.id;\n}\n\n/** The stateful machinery for ONE session — its own `items` array and id counter. */\nfunction makeSessionOps(): { handle: (input: TodoInput) => string; getItems: () => TodoItem[] } {\n const items: TodoItem[] = [];\n let nextId = 1;\n\n function genId(): string {\n return `todo-${nextId++}`;\n }\n\n function findById(id: string): TodoItem | undefined {\n return items.find((i) => i.id === id);\n }\n\n // M4-5: every list-bearing success result carries BOTH the human `items_summary`\n // (for the LLM) AND the structured `items` snapshot (for programmatic consumers\n // that render a plan/UI).\n function listResult(extra: Record<string, unknown>): string {\n return ok({ ...extra, items: [...items], items_summary: formatList() });\n }\n\n function formatList(): string {\n if (items.length === 0) return \"No tasks. Use action 'add' to create one.\";\n const lines = items.map((item) => {\n const icon = item.status === \"done\" ? \"[x]\" : item.status === \"in_progress\" ? \"[>]\" : \"[ ]\";\n return `${icon} ${item.id}: ${item.title}`;\n });\n const pending = items.filter((i) => i.status === \"pending\").length;\n const inProg = items.filter((i) => i.status === \"in_progress\").length;\n const done = items.filter((i) => i.status === \"done\").length;\n lines.push(`\\n${done}/${items.length} done | ${inProg} in progress | ${pending} pending`);\n return lines.join(\"\\n\");\n }\n\n function handleAdd(input: TodoInput): string {\n if (!(\"title\" in input) || !input.title) return fail({ error: \"missing_title\" });\n const item: TodoItem = {\n id: genId(),\n title: input.title,\n status: \"pending\",\n createdAt: Date.now(),\n };\n items.push(item);\n return listResult({ id: item.id, message: `Added: ${item.title}` });\n }\n\n function handleSetStatus(input: TodoInput, status: \"in_progress\" | \"done\"): string {\n const id = requireId(input);\n if (!id) return fail({ error: \"missing_id\" });\n const item = findById(id);\n if (!item) return fail({ error: \"not_found\", id });\n item.status = status;\n if (status === \"done\") item.completedAt = Date.now();\n const verb = status === \"done\" ? \"Completed\" : \"Started\";\n return listResult({ message: `${verb}: ${item.title}` });\n }\n\n function handleRemove(input: TodoInput): string {\n const id = requireId(input);\n if (!id) return fail({ error: \"missing_id\" });\n const idx = items.findIndex((i) => i.id === id);\n if (idx === -1) return fail({ error: \"not_found\", id });\n const removed = items.splice(idx, 1)[0]!;\n return listResult({ message: `Removed: ${removed.title}` });\n }\n\n function handleClearCompleted(): string {\n const before = items.length;\n const kept = items.filter((i) => i.status !== \"done\");\n items.length = 0;\n items.push(...kept);\n return listResult({ message: `Cleared ${before - items.length} completed items` });\n }\n\n const actions: Record<string, (input: TodoInput) => string> = {\n add: handleAdd,\n in_progress: (input) => handleSetStatus(input, \"in_progress\"),\n complete: (input) => handleSetStatus(input, \"done\"),\n remove: handleRemove,\n list: () => listResult({}),\n clear_completed: handleClearCompleted,\n };\n\n return {\n handle: (input: TodoInput): string => {\n const action = actions[input.action];\n if (!action) return fail({ error: \"invalid_action\" });\n return action(input);\n },\n getItems: () => [...items],\n };\n}\n\nexport function createTodolistTool(): TodolistTool {\n // #119 — one session-ops bundle per threadId; lazily created on first touch.\n const sessions = new Map<string, ReturnType<typeof makeSessionOps>>();\n function ops(threadId?: string): ReturnType<typeof makeSessionOps> {\n const key = threadId ?? \"__default__\";\n let session = sessions.get(key);\n if (session === undefined) {\n session = makeSessionOps();\n sessions.set(key, session);\n }\n return session;\n }\n\n return {\n name: \"todolist\",\n description:\n \"Create and maintain a structured task list for the current session — tracks progress and \" +\n \"keeps a multi-step plan visible across turns. Use it proactively when the work has 3+ steps \" +\n \"or the user gave multiple tasks; skip it for a single trivial step. Keep exactly ONE item \" +\n \"'in_progress' at a time, and mark 'complete' only after the work is actually done. \" +\n \"Actions: 'add' (create with title), 'in_progress' (mark started by id), 'complete' (mark done \" +\n \"by id), 'remove' (delete by id), 'list' (show all), 'clear_completed' (remove done items). \" +\n \"Returns { ok, items, items_summary } (items = structured array; items_summary = formatted text).\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n action: {\n type: \"string\",\n enum: [\"add\", \"complete\", \"in_progress\", \"remove\", \"list\", \"clear_completed\"],\n description: \"The action to perform.\",\n },\n title: {\n type: \"string\",\n description: \"Title for a new todo item (required for 'add').\",\n },\n id: {\n type: \"string\",\n description: \"ID of the todo item (required for 'complete', 'in_progress', 'remove').\",\n },\n },\n required: [\"action\"],\n },\n handler: (input: TodoInput, ctx?: { threadId?: string }): string =>\n ops(ctx?.threadId).handle(input),\n getItems: (threadId?: string): TodoItem[] => ops(threadId).getItems(),\n };\n}\n","/**\n * `truncateOutput` — utility for truncating large tool output.\n *\n * When output exceeds `maxBytes`, writes the full content to a temp file and returns a truncated\n * version with a reference to the full output.\n *\n * ## M77 — why this grew instead of a new truncator being written\n *\n * The M77 discovery measured **six** output ceilings across `sdk-tools`, with five different values\n * and no coordination between them (`web-fetch.ts` 1 MB, `shell-exec.ts` 5 MB, `git-diff.ts` 5 MB,\n * `run-vitest.ts` 10 MB, `git-status.ts` configurable, and this helper's 30 000 B). It also found\n * that this helper — exported from the barrel — had **zero production consumers**: the SDK had\n * already paid for a shared truncator that nobody used while every tool rolled its own.\n *\n * Adding a seventh ceiling in the runtime would have been the defect, not the fix. So `toolResultBudget`\n * extends this one instead (parsimony-ladder rung 4), gaining the two things it lacked:\n *\n * - **`head-tail` mode** — the previous cut was head-only, which for command output discards\n * exactly the part that matters: the error, the summary, the final prompt.\n * - **`originalBytes`** — a machine-readable marker. The only prior signal was an English sentence\n * injected into the text (`\"[Output truncated. Full output: …]\"`), so a consumer wanting to know\n * how much was lost had to parse prose.\n *\n * Consolidating the MECHANISM is deliberately not the same as unifying the VALUES: 1 MB for\n * `web-fetch` and 10 MB for `run-vitest` may differ for good reasons. That second step is out of\n * scope here (plan ADR D2).\n *\n * Return shape:\n * - `{ content, truncated: false, originalBytes }`\n * - `{ content, truncated: true, originalBytes, overflowPath }`\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** How the middle is dropped when output exceeds the budget. */\nexport type TruncationMode = \"head\" | \"head-tail\";\n\nexport interface TruncationOptions {\n /** Maximum output size in bytes before truncation. Default: 30_000. */\n maxBytes?: number;\n /** Directory for overflow files. Default: \".theocode/tool-output\". */\n outputDir?: string;\n /**\n * `\"head\"` (default) keeps the first `maxBytes` — the historical behaviour, preserved because this\n * helper is public API. `\"head-tail\"` splits the budget between the start and the END, which is\n * where command output usually carries its conclusion.\n */\n mode?: TruncationMode;\n}\n\nexport interface TruncationResult {\n /** The (possibly truncated) content. */\n content: string;\n /** Whether the output was truncated. */\n truncated: boolean;\n /**\n * Byte length of the ORIGINAL output, present on both paths. Always present by design: a field\n * that only appears on failure forces every consumer through an `undefined` check, which is the\n * door magic values come in through.\n */\n originalBytes: number;\n /** Path to the full output file, present only when truncated. */\n overflowPath?: string;\n}\n\n/**\n * Cut a UTF-8 buffer at a byte boundary WITHOUT splitting a code point.\n *\n * `Buffer.subarray(0, n).toString()` on a boundary inside a multi-byte character yields U+FFFD, and\n * the model reads garbage. `TextDecoder` with `stream: true` withholds the incomplete tail instead of\n * substituting it — stdlib doing the work (parsimony-ladder rung 2).\n */\nfunction decodeWholeCodePoints(buf: Buffer): string {\n return new TextDecoder(\"utf-8\").decode(buf, { stream: true });\n}\n\nexport function truncateOutput(output: string, opts?: TruncationOptions): TruncationResult {\n const maxBytes = opts?.maxBytes ?? 30_000;\n const outputDir = opts?.outputDir ?? \".theocode/tool-output\";\n const mode = opts?.mode ?? \"head\";\n\n // EC-3: strict > comparison — exactly at limit is NOT truncated\n const originalBytes = Buffer.byteLength(output, \"utf-8\");\n if (originalBytes <= maxBytes) {\n return { content: output, truncated: false, originalBytes };\n }\n\n // Write full output to overflow file\n mkdirSync(outputDir, { recursive: true });\n // M77 — the name used to be `overflow-${Date.now()}.txt`, which COLLIDES: two truncations inside\n // the same millisecond resolve to the same path, and the second silently overwrites the first. The\n // `overflowPath` handed back to the caller then points at somebody else's output — a wrong answer,\n // not an error. Surfaced as an intermittent failure while running two truncation suites together;\n // `rules/testing.md § 3` treats a flake as a bug, and the root cause was in production code, not\n // in the test. `randomUUID` is stdlib (parsimony-ladder rung 2).\n const filename = `overflow-${Date.now()}-${randomUUID().slice(0, 8)}.txt`;\n const overflowPath = join(outputDir, filename);\n writeFileSync(overflowPath, output, \"utf-8\");\n\n const buf = Buffer.from(output, \"utf-8\");\n const trailer = `\\n\\n[Output truncated. Full output: ${overflowPath}]`;\n\n if (mode === \"head-tail\") {\n // Split the budget in half. The tail decode starts mid-buffer, so its first bytes may be a\n // continuation of a split code point; `decodeWholeCodePoints` drops the incomplete lead rather\n // than emitting U+FFFD.\n const half = Math.floor(maxBytes / 2);\n const head = decodeWholeCodePoints(buf.subarray(0, half));\n const tail = decodeWholeCodePoints(buf.subarray(buf.length - half));\n return {\n content: `${head}\\n\\n[… ${String(originalBytes - maxBytes)} bytes omitted …]\\n\\n${tail}${trailer}`,\n truncated: true,\n originalBytes,\n overflowPath,\n };\n }\n\n return {\n content: decodeWholeCodePoints(buf.subarray(0, maxBytes)) + trailer,\n truncated: true,\n originalBytes,\n overflowPath,\n };\n}\n","/**\n * `update_plan` — built-in tool for coding agents.\n *\n * Codex-faithful: the model posts a DECLARATIVE plan — an ordered list of short steps, each\n * `pending | in_progress | completed` — and refreshes it as work proceeds. Codex's invariant is\n * \"exactly one step in_progress until everything is done\"; this tool WARNS (never rejects) when that\n * doesn't hold, so the agent self-corrects on the next update rather than failing the turn.\n *\n * Surface-agnostic by design (M17 DX): the result is STRUCTURED (`{ ok, steps, warning? }`) — each\n * surface (terminal TUI, desktop, web) renders the checklist however it likes, rather than the package\n * hard-coding glyphs. Result shape (always a JSON string):\n * - `{ ok: true, explanation: string | null, steps: PlanStep[], warning?: string }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nconst STATUS = [\"pending\", \"in_progress\", \"completed\"] as const;\n\nconst planStepSchema = z.object({\n step: z.string().min(1).max(100).describe(\"A short step, ≤ ~7 words.\"),\n status: z.enum(STATUS),\n});\n\nexport function createUpdatePlanTool(): CustomTool {\n return Tool.create({\n name: \"update_plan\",\n description:\n \"Post or refresh a short plan so the user sees your progress on a multi-step task. Pass an ordered \" +\n \"`plan` of steps, each with a status (pending | in_progress | completed); keep exactly one step \" +\n \"in_progress at a time and mark steps completed as you finish. Returns { ok, steps, warning? } as a \" +\n \"JSON string — the surface renders the checklist. A `warning` is returned (not an error) if the \" +\n \"one-in_progress invariant is violated, so you can self-correct on the next update.\",\n inputSchema: z.object({\n explanation: z\n .string()\n .max(200)\n .optional()\n .describe(\"One line on what changed / why (optional).\"),\n plan: z.array(planStepSchema).min(1).describe(\"The ordered steps.\"),\n }),\n handler: ({ explanation, plan }) => {\n const inProgress = plan.filter((s) => s.status === \"in_progress\").length;\n const allDone = plan.every((s) => s.status === \"completed\");\n const warning =\n !allDone && inProgress !== 1\n ? `keep exactly one step in_progress until all are completed — found ${inProgress}`\n : undefined;\n return JSON.stringify({ ok: true, explanation: explanation ?? null, steps: plan, warning });\n },\n });\n}\n","/**\n * `web_fetch` — built-in tool for coding agents.\n *\n * Fetches a URL via native `fetch()`. Rejects non-http(s) protocols.\n * Size-capped at 1 MB response body.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, content, status_code, content_type }`\n * - `{ ok: false, error: 'invalid_url' | 'fetch_failed' |\n * 'timeout' | 'too_large' | 'ssrf_blocked' | 'redirect_blocked' }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nimport {\n RedirectBlockedError,\n type ScreenedFetchOptions,\n SsrfBlockedError,\n screenedFetch,\n} from \"./internal/network-guard.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MB\n\nexport interface CreateWebFetchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Default timeout in ms. */\n defaultTimeoutMs?: number;\n /**\n * Opt out of the SSRF guard (default `false`). When `true`, requests to\n * private/loopback/link-local/metadata addresses are NOT blocked — use only for\n * trusted local-dev tooling.\n */\n allowPrivateHosts?: boolean;\n /**\n * Max redirect hops to follow (each SSRF-screened). Default 5. Set `0` to BLOCK ALL\n * redirects — a 3xx then returns `{ ok: false, error: \"redirect_blocked\" }` (a strict\n * no-redirect policy for untrusted, model-chosen URLs).\n */\n maxRedirects?: number;\n /** Fetch implementation (injectable for tests — drive paths with no real network). */\n fetchImpl?: ScreenedFetchOptions[\"fetchImpl\"];\n /** DNS resolver (injectable for tests — drive the SSRF path with no real DNS). */\n lookup?: ScreenedFetchOptions[\"lookup\"];\n}\n\nexport function createWebFetchTool(opts?: CreateWebFetchToolOptions): CustomTool {\n const defaultTimeoutMs = opts?.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n const allowPrivateHosts = opts?.allowPrivateHosts ?? false;\n const maxRedirects = opts?.maxRedirects;\n const fetchImpl = opts?.fetchImpl;\n const lookup = opts?.lookup;\n\n return Tool.create({\n name: opts?.name ?? \"web_fetch\",\n description:\n opts?.description ??\n \"Fetch the contents of a URL via HTTP/HTTPS. Use only for URLs the user provided or that you \" +\n \"are confident help with the task; never invent or guess URLs. Rejects non-http(s) URLs and \" +\n \"is SSRF-guarded by default (private/loopback/link-local/cloud-metadata hosts are refused \" +\n \"with an ssrf_blocked error). The response body is capped at 1 MB. Returns \" +\n \"{ ok, content, status_code, content_type } or { ok: false, error }.\",\n inputSchema: z.object({\n url: z.string().min(1).describe(\"URL to fetch (http or https only).\"),\n timeout_ms: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Timeout in milliseconds (default 30000).\"),\n }),\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: fetch with guards\n handler: async ({ url, timeout_ms }) => {\n // Validate protocol\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return JSON.stringify({ ok: false, error: \"invalid_url\", url });\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return JSON.stringify({\n ok: false,\n error: \"invalid_url\",\n url,\n detail: \"only http and https protocols allowed\",\n });\n }\n\n const timeoutMs = timeout_ms ?? defaultTimeoutMs;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await screenedFetch(url, {\n signal: controller.signal,\n allowPrivateHosts,\n ...(maxRedirects !== undefined ? { maxRedirects } : {}),\n ...(fetchImpl ? { fetchImpl } : {}),\n ...(lookup ? { lookup } : {}),\n });\n clearTimeout(timer);\n\n // Check content-length header before downloading\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength && Number(contentLength) > MAX_BODY_BYTES) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n url,\n size: Number(contentLength),\n limit: MAX_BODY_BYTES,\n });\n }\n\n const buffer = await response.arrayBuffer();\n if (buffer.byteLength > MAX_BODY_BYTES) {\n return JSON.stringify({\n ok: false,\n error: \"too_large\",\n url,\n size: buffer.byteLength,\n limit: MAX_BODY_BYTES,\n });\n }\n\n const content = new TextDecoder(\"utf-8\").decode(buffer);\n const contentType = response.headers.get(\"content-type\") ?? undefined;\n\n return JSON.stringify({\n ok: true,\n content,\n status_code: response.status,\n content_type: contentType,\n });\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof RedirectBlockedError) {\n return JSON.stringify({ ok: false, error: \"redirect_blocked\", url, reason: err.message });\n }\n if (err instanceof SsrfBlockedError) {\n return JSON.stringify({ ok: false, error: \"ssrf_blocked\", url, reason: err.message });\n }\n const e = err as { name?: string; message?: string };\n if (e.name === \"AbortError\") {\n return JSON.stringify({ ok: false, error: \"timeout\", url, timeout_ms: timeoutMs });\n }\n return JSON.stringify({\n ok: false,\n error: \"fetch_failed\",\n url,\n message: e.message ?? \"unknown\",\n });\n }\n },\n });\n}\n","/**\n * `web_search` — built-in tool for coding agents.\n *\n * Accepts a search callback via DIP (consumer provides the search\n * provider). The tool itself is provider-agnostic.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, results: Array<{ title, url, snippet }> }`\n * - `{ ok: false, error: 'search_failed' | 'no_provider' }`\n */\n\nimport type { CustomTool } from \"@theokit/sdk\";\n\nimport { Tool } from \"@theokit/sdk\";\nimport { z } from \"zod\";\n\nexport interface WebSearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\nexport type WebSearchCallback = (query: string, maxResults: number) => Promise<WebSearchResult[]>;\n\nexport interface CreateWebSearchToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Search provider callback — consumer injects the implementation. */\n search: WebSearchCallback;\n /** Default max results if not specified by the LLM. */\n defaultMaxResults?: number;\n}\n\nexport function createWebSearchTool(opts: CreateWebSearchToolOptions): CustomTool {\n const { search, defaultMaxResults = 5 } = opts;\n\n return Tool.create({\n name: opts.name ?? \"web_search\",\n description:\n opts.description ??\n \"Search the web for a query — use when you need current information beyond the repo or your \" +\n \"training cutoff (library docs, an error message, an API). Returns a list of results with \" +\n \"title, URL, and snippet; follow up with web_fetch on a promising result to read it in full. \" +\n \"The search provider is injected by the consumer. \" +\n \"Returns { ok, results } or { ok: false, error }.\",\n inputSchema: z.object({\n query: z.string().min(1).describe(\"Search query.\"),\n max_results: z\n .number()\n .int()\n .positive()\n .max(20)\n .optional()\n .describe(\"Maximum results to return (default 5, max 20).\"),\n }),\n handler: async ({ query, max_results }) => {\n const maxResults = max_results ?? defaultMaxResults;\n\n try {\n const results = await search(query, maxResults);\n return JSON.stringify({\n ok: true,\n results: results.slice(0, maxResults),\n count: Math.min(results.length, maxResults),\n });\n } catch (err) {\n const e = err as { message?: string };\n return JSON.stringify({\n ok: false,\n error: \"search_failed\",\n message: e.message ?? \"unknown\",\n });\n }\n },\n });\n}\n","/**\n * Brave Search adapter for `createWebSearchTool` (M3-7).\n *\n * `createBraveWebSearchAdapter()` returns a `WebSearchCallback` that queries the\n * Brave Search API using an env-driven key (`BRAVE_API_KEY`). It plugs into the\n * provider-agnostic `createWebSearchTool` via its callback seam — the tool is NOT\n * modified. The `fetch` impl is injectable (default `globalThis.fetch`) so the\n * adapter is offline-testable; a plain fetch (not `screenedFetch`) is used because\n * the endpoint host is fixed (no SSRF surface) and `screenedFetch` cannot carry\n * the required auth header. Zero new dependencies. Design: blueprint m3-websearch-adapter.\n */\n\nimport { ConfigurationError } from \"@theokit/sdk\";\n\nimport type { WebSearchCallback, WebSearchResult } from \"./web-search.js\";\n\nconst BRAVE_ENDPOINT = \"https://api.search.brave.com/res/v1/web/search\";\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\nexport interface CreateBraveWebSearchAdapterOptions {\n /** Brave API key. Defaults to `process.env.BRAVE_API_KEY`. */\n apiKey?: string;\n /** Injectable fetch (default `globalThis.fetch`) — set in tests for offline runs. */\n fetchImpl?: FetchLike;\n /** Override the Brave endpoint (self-host / test). */\n endpoint?: string;\n}\n\ninterface BraveResult {\n title?: unknown;\n url?: unknown;\n description?: unknown;\n}\n\n/**\n * Build a `WebSearchCallback` backed by the Brave Search API. Throws a typed\n * `ConfigurationError` (\"no_api_key\") at creation when no key is available.\n */\nexport function createBraveWebSearchAdapter(\n opts: CreateBraveWebSearchAdapterOptions = {},\n): WebSearchCallback {\n const apiKey = opts.apiKey ?? process.env.BRAVE_API_KEY;\n if (!apiKey) {\n throw new ConfigurationError(\"BRAVE_API_KEY is not set (pass { apiKey } or set the env var).\", {\n code: \"no_api_key\",\n });\n }\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n const endpoint = opts.endpoint ?? BRAVE_ENDPOINT;\n // Validate the endpoint at creation (fail-early symmetry with the key check).\n const base = new URL(endpoint);\n\n return async (query: string, maxResults: number): Promise<WebSearchResult[]> => {\n const url = new URL(base);\n url.searchParams.set(\"q\", query);\n url.searchParams.set(\"count\", String(maxResults));\n const res = await fetchImpl(url.toString(), {\n headers: { \"X-Subscription-Token\": apiKey, Accept: \"application/json\" },\n });\n if (!res.ok) throw new Error(`brave_search_failed: HTTP ${res.status}`);\n const json = (await res.json()) as { web?: { results?: BraveResult[] } } | null;\n const results = json?.web?.results ?? [];\n return results.map((r) => ({\n title: String(r?.title ?? \"\"),\n url: String(r?.url ?? \"\"),\n snippet: String(r?.description ?? \"\"),\n }));\n };\n}\n","/**\n * Generic HTTP web-search adapter for `createWebSearchTool` (RADAR #92.d).\n *\n * `createGenericHttpSearchAdapter()` returns a `WebSearchCallback` that queries\n * an arbitrary HTTP search endpoint keyed by env vars:\n * - `THEOKIT_SEARCH_API_URL` — endpoint returning `{ results: [{title,url,snippet}] }`\n * - `THEOKIT_SEARCH_API_KEY` — bearer token\n *\n * Request shape: `GET {endpoint}?q={query}&n={maxResults}` with\n * `Authorization: Bearer {apiKey}`. Both values may be passed explicitly (params\n * win over env). Unlike the Brave adapter (which fails early — fixed host, fixed\n * auth), this one is provider-agnostic and **degrades gracefully**: when\n * unconfigured OR on any network/parse failure it returns `[]` and never throws\n * into the agent turn. A recurring empty result is a provider-config issue, not\n * an agent bug. `fetchImpl` is injectable (default `globalThis.fetch`) for\n * offline tests. Zero new dependencies.\n *\n * Promoted from theocode's `server/lib/web-search.ts` (`createSearchProvider`),\n * re-keyed to neutral `THEOKIT_*` env vars.\n */\n\nimport type { WebSearchCallback, WebSearchResult } from \"./web-search.js\";\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\nexport interface CreateGenericHttpSearchAdapterOptions {\n /** Bearer token. Defaults to `process.env.THEOKIT_SEARCH_API_KEY`. */\n apiKey?: string;\n /** Search endpoint URL. Defaults to `process.env.THEOKIT_SEARCH_API_URL`. */\n endpoint?: string;\n /** Injectable fetch (default `globalThis.fetch`) — set in tests for offline runs. */\n fetchImpl?: FetchLike;\n}\n\ninterface GenericResult {\n title?: unknown;\n url?: unknown;\n snippet?: unknown;\n}\n\n/**\n * Build a `WebSearchCallback` backed by a generic HTTP search endpoint. Returns\n * `[]` (graceful no-op) when unconfigured or on any failure — never throws.\n */\nexport function createGenericHttpSearchAdapter(\n opts: CreateGenericHttpSearchAdapterOptions = {},\n): WebSearchCallback {\n const apiKey = opts.apiKey ?? process.env.THEOKIT_SEARCH_API_KEY;\n const endpoint = opts.endpoint ?? process.env.THEOKIT_SEARCH_API_URL;\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n\n return async (query: string, maxResults: number): Promise<WebSearchResult[]> => {\n if (!apiKey || !endpoint) return []; // no provider configured — graceful no-op\n try {\n const url = `${endpoint}?q=${encodeURIComponent(query)}&n=${maxResults}`;\n const res = await fetchImpl(url, { headers: { Authorization: `Bearer ${apiKey}` } });\n if (!res.ok) return [];\n const data = (await res.json()) as { results?: GenericResult[] } | null;\n return (data?.results ?? []).slice(0, maxResults).map((r) => ({\n title: String(r?.title ?? \"\"),\n url: String(r?.url ?? \"\"),\n snippet: String(r?.snippet ?? \"\"),\n }));\n } catch {\n // Network/parse failure → no results (never throws into the agent turn).\n return [];\n }\n };\n}\n","/**\n * `write_file` — built-in tool for coding agents.\n *\n * Writes UTF-8 content to a project-relative path. Creates parent\n * directories recursively. Refuses binary-file overwrites, path\n * traversal, and sensitive paths.\n *\n * Return shape (always a JSON string):\n * - `{ ok: true, path, bytes }` on success\n * - `{ ok: false, error: 'path_traversal' | 'forbidden_path' |\n * 'binary_file' }` on refusal\n */\n\nimport { stat as fsStat, mkdir, open, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { CustomTool } from \"@theokit/sdk\";\nimport { Tool } from \"@theokit/sdk\";\nimport {\n FileNotFoundError,\n type FilesystemBackend,\n FilesystemError,\n type FilesystemProvider,\n FilesystemReadOnlyError,\n FilesystemSecurityError,\n resolveFilesystem,\n StaleFileError,\n} from \"@theokit/sdk/filesystem\";\nimport { z } from \"zod\";\nimport {\n assertNoSymlinkEscape,\n ForbiddenPathError,\n isForbiddenPath,\n PathTraversalError,\n safePathJoin,\n} from \"./internal/path-guard.js\";\nimport { evaluateReadBeforeWrite, type ReadTracker } from \"./read-tracker.js\";\n\n/** Byte window inspected for null bytes when deciding binary vs text. */\nconst BINARY_PROBE_BYTES = 8 * 1024;\n\n/** The run-scoped context a `defineTool` handler receives as its 2nd argument. */\ntype WriteToolContext = { signal?: AbortSignal; context?: unknown };\n\nexport interface CreateWriteFileToolOptions {\n /** M76 — name exposed to the model. Omitted => today's literal (additive). The name is a contract:\n * the approval key, what the model sees and what telemetry records. */\n name?: string;\n /** M76 — description exposed to the model. Omitted => today's literal (additive). */\n description?: string;\n /** Absolute path to the project root. Every write is gated against this boundary. */\n projectRoot: string;\n /**\n * SE31 — optional pluggable filesystem backend (`@theokit/sdk/filesystem`), or\n * a per-request resolver `(ctx) => FilesystemBackend`. When provided, writes\n * route through it (its own boundary + `readOnly` + per-request root) instead\n * of the local project fs. Omitted ⇒ identical current behavior (local\n * `projectRoot`). The `.env`/`.git` policy still applies (storage-independent).\n */\n filesystem?: FilesystemProvider<WriteToolContext>;\n /**\n * SE32 — when true (and a {@link ReadTracker} is supplied), refuse to\n * overwrite an existing file that was not read first, or that changed on disk\n * since it was read (`read_required` / `stale_file`). A NEW file writes\n * freely. Default OFF (unchanged behavior).\n */\n requireReadBeforeWrite?: boolean;\n /** SE32 — the per-run tracker populated by the paired `read_file` tool. */\n readTracker?: ReadTracker;\n}\n\nexport function createWriteFileTool(opts: CreateWriteFileToolOptions): CustomTool {\n const { projectRoot, filesystem } = opts;\n // SE32 — fail fast on a misconfiguration: requiring read-before-write without\n // a tracker would SILENTLY disable the guard (a dangerous false sense of\n // safety). Refuse at construction (Rule 8) instead of a silent no-op.\n if (opts.requireReadBeforeWrite && !opts.readTracker) {\n throw new Error(\n \"createWriteFileTool: requireReadBeforeWrite is true but no readTracker was provided — \" +\n \"pass the same ReadTracker instance to createReadFileTool and createWriteFileTool.\",\n );\n }\n // The tracker is only consulted when read-before-write is enabled.\n const guard = opts.requireReadBeforeWrite ? opts.readTracker : undefined;\n\n return Tool.create({\n name: opts.name ?? \"write_file\",\n description:\n opts.description ??\n \"Write UTF-8 content to a project-relative file, creating parent directories as needed. \" +\n \"OVERWRITES any existing file at the path. Prefer editing an existing file with edit_file \" +\n \"over rewriting it; use write_file to create a NEW file or fully replace a small one. If the \" +\n \"file already exists, read_file it first so you do not discard content you have not seen. \" +\n \"Refuses paths that escape the write root and sensitive files (.env, .git/, node_modules/, \" +\n \".theo/, lock files); the default local root also refuses binary-file overwrites. Returns \" +\n \"{ ok, path, bytes } or { ok: false, error }.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Project-relative file path.\"),\n content: z.string().describe(\"UTF-8 content to write.\"),\n }),\n handler: async ({ path, content }, ctx) => {\n if (isForbiddenPath(path)) {\n return JSON.stringify({ ok: false, error: \"forbidden_path\", path });\n }\n // SE31 — route through the pluggable backend when one is configured (the\n // backend owns its own boundary, readOnly, and provider); else local fs.\n if (filesystem) {\n const backend = await resolveFilesystem(filesystem, ctx ?? {});\n return writeViaBackend(backend, path, content, guard);\n }\n return writeViaLocalFs(projectRoot, path, content, guard);\n },\n });\n}\n\n/**\n * SE32 — map a read-before-write decision to the tool's error JSON, or `null`\n * when the write may proceed. `currentMtimeMs` is `null` for a not-yet-existing\n * file. No-op (returns null) when no tracker guards this write.\n */\nfunction readBeforeWriteError(\n guard: ReadTracker | undefined,\n path: string,\n currentMtimeMs: number | null,\n): string | null {\n if (!guard) return null;\n const decision = evaluateReadBeforeWrite(guard, path, currentMtimeMs);\n if (decision === \"read_required\")\n return JSON.stringify({ ok: false, error: \"read_required\", path });\n if (decision === \"stale\") return JSON.stringify({ ok: false, error: \"stale_file\", path });\n return null;\n}\n\n/** Local-`projectRoot` write path: boundary + read-before-write + binary guard + write. */\nasync function writeViaLocalFs(\n projectRoot: string,\n path: string,\n content: string,\n guard: ReadTracker | undefined,\n): Promise<string> {\n let absolutePath: string;\n try {\n absolutePath = safePathJoin(projectRoot, path);\n assertNoSymlinkEscape(absolutePath, projectRoot);\n } catch (err) {\n if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n throw err;\n }\n\n // SE32 — read-before-write check against the current on-disk mtime. NOTE: the\n // local path detects a file that CHANGED between read and write, but the\n // window between this stat and the writeFile below is an accepted TOCTOU\n // (same-user local context — matching @theokit/sdk/filesystem's LocalFilesystem\n // disclaimer). The `filesystem` backend path additionally forwards\n // `expectedMtime` for a tighter write-time re-check.\n const rbw = readBeforeWriteError(guard, path, await statMtimeOrNull(absolutePath));\n if (rbw) return rbw;\n\n // Binary file guard: probe existing file for null bytes before overwriting\n if (await isBinaryFile(absolutePath)) {\n return JSON.stringify({ ok: false, error: \"binary_file\", path });\n }\n\n await mkdir(dirname(absolutePath), { recursive: true });\n await writeFile(absolutePath, content, \"utf-8\");\n const bytes = Buffer.byteLength(content, \"utf-8\");\n\n return JSON.stringify({ ok: true, path, bytes });\n}\n\n/** Current mtime of `absolutePath`, or `null` when the file does not exist. */\nasync function statMtimeOrNull(absolutePath: string): Promise<number | null> {\n try {\n return (await fsStat(absolutePath)).mtimeMs;\n } catch (err) {\n if ((err as { code?: string }).code === \"ENOENT\") return null;\n throw err;\n }\n}\n\n/**\n * Current mtime of `path` via the backend, or `null` when absent. A single\n * `stat()` with a typed-not-found catch — avoids the exists()+stat() TOCTOU\n * where the file could vanish between the two calls (a `FileNotFoundError`\n * would otherwise escape the write handler's catch and crash the loop).\n */\nasync function backendMtimeOrNull(\n backend: FilesystemBackend,\n path: string,\n): Promise<number | null> {\n try {\n return (await backend.stat(path)).mtimeMs;\n } catch (err) {\n if (err instanceof FileNotFoundError) return null;\n throw err;\n }\n}\n\n/**\n * SE31 — write through a {@link FilesystemBackend}, mapping its typed errors to\n * the tool's `{ ok: false, error }` JSON shape (never throws on a user mistake).\n */\nasync function writeViaBackend(\n backend: FilesystemBackend,\n path: string,\n content: string,\n guard: ReadTracker | undefined,\n): Promise<string> {\n try {\n // SE32 — read-before-write against the backend's current mtime; on pass,\n // forward `expectedMtime` so the backend re-checks at write time (TOCTOU).\n let expectedMtime: number | undefined;\n if (guard) {\n const current = await backendMtimeOrNull(backend, path);\n const rbw = readBeforeWriteError(guard, path, current);\n if (rbw) return rbw;\n expectedMtime = current ?? undefined;\n }\n const stat = await backend.writeFile(\n path,\n content,\n expectedMtime !== undefined ? { expectedMtime } : undefined,\n );\n return JSON.stringify({ ok: true, path, bytes: stat.size });\n } catch (err) {\n return backendErrorToJson(err, path);\n }\n}\n\n/**\n * Map a {@link FilesystemBackend} typed error to the tool's `{ ok: false }` JSON\n * (a recoverable \"bad path\"/\"stale\" the agent should see, not a loop-crashing\n * throw). Rethrows anything untyped (a genuine bug should surface).\n */\nfunction backendErrorToJson(err: unknown, path: string): string {\n if (err instanceof FilesystemSecurityError) {\n return JSON.stringify({ ok: false, error: \"path_traversal\", path });\n }\n if (err instanceof FilesystemReadOnlyError) {\n return JSON.stringify({ ok: false, error: \"read_only\", path });\n }\n if (err instanceof StaleFileError) {\n return JSON.stringify({ ok: false, error: \"stale_file\", path });\n }\n if (err instanceof FilesystemError) {\n return JSON.stringify({ ok: false, error: \"write_failed\", path });\n }\n throw err;\n}\n\nasync function isBinaryFile(absolutePath: string): Promise<boolean> {\n let handle: import(\"node:fs/promises\").FileHandle | undefined;\n try {\n handle = await open(absolutePath, \"r\");\n } catch {\n return false; // file doesn't exist yet — not binary\n }\n try {\n const stat = await handle.stat();\n const probeLen = Math.min(BINARY_PROBE_BYTES, Number(stat.size));\n if (probeLen <= 0) return false;\n const probe = Buffer.alloc(probeLen);\n const { bytesRead } = await handle.read(probe, 0, probeLen, 0);\n for (let i = 0; i < bytesRead; i += 1) {\n if (probe[i] === 0) return true;\n }\n return false;\n } finally {\n await handle.close();\n }\n}\n"]}