pi-braid 0.44.4 → 0.45.0

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/AGENTS.md CHANGED
@@ -154,7 +154,7 @@ command behind it is the same drift with a gate painted on it.
154
154
  ## Tool Inventory
155
155
 
156
156
  The canonical, source-derived inventory of every tool provided/exposed by this
157
- package is **`packages/core/TOOLS.md`** (33 documented tools: 24 braid-registered
157
+ package is **`packages/core/TOOLS.md`** (34 documented tools: 25 braid-registered
158
158
  via `pi.registerTool()` + 9 pi-native core builtins `read`/`bash`/`edit`/`write`/
159
159
  `grep`/`find`/`ls`/`powershell`/`tool_search` from pi's built-in tool-search
160
160
  extension, plus an appendix separating the standalone `pi-braid-contrib`
package/CHANGELOG.md CHANGED
@@ -254,6 +254,66 @@ same fixture's last arm, which asserted the operator's home instead of what ever
254
254
  now states the property it was meant to hold, that the shipped tree passes wherever the roots are. The tags
255
255
  for 0.44.1 and 0.44.3 stay where they are, each with its failed run beside it.
256
256
 
257
+ ## Core 0.45.0: one program and its argv, without a shell (2026-11-16)
258
+
259
+ The bash census measured 223,137 bash calls out of 504,124 tool calls in a frozen corpus, and ranked the
260
+ argv-shaped replacements it could support. `run` is the first of them and the largest: one program and its
261
+ arguments, no shell in between. It takes `argv` plus a required `timeout_ms`, with optional `cwd`, `env`,
262
+ `stdin` and `max_output_bytes`. stdout and stderr come back separately, each capped; a stream past the cap
263
+ keeps its head and its tail, states how many bytes it dropped, and leaves the full text in a file the
264
+ result names. A program that outlives the timeout is killed with its process group, and no call can hang
265
+ the session.
266
+
267
+ What it refuses is what a shell would have interpreted: an argument carrying `|`, `&&`, `;`, a backtick or
268
+ `$(`, a shell invoked with `-c`, and a glob at a path-segment boundary (`*.md`, `src/*`). The refusals
269
+ are the design, not a limitation: a tool that accepts those grows back into the shell the census was
270
+ trying to retire, and each refusal names the element and the tool that owns the case (`bash` for a
271
+ pipeline, `find` or `grep` for a pattern). A `*` inside an argument, such as a grep filter or a sed
272
+ quantifier, is left to the program. There is no TTY and no shell profile, and a glob is never expanded.
273
+
274
+ The destructive guard is narrow and shared: six verbs (`rm`, `mv`, `dd`, `chmod`, `shred`, `truncate`) are
275
+ refused when a path argument resolves outside the session workspace, and the resolution is canonical on
276
+ both sides, so a symlink out of the workspace is caught. The mechanism lives in
277
+ `packages/core/src/lib/tools/workspace-guard.ts` and takes the verb set as an argument; a later `git` tool passes its own
278
+ set to the same guard rather than copying it.
279
+
280
+ The differential control behind the release ran 120 commands sampled from the live corpus through `/bin/bash
281
+ -c` and through the tool, and all 120 agreed on exit code, stdout and stderr. The sample rule and the
282
+ per-reason exclusion counts are printed by `packages/core/test/manual/run-differential.mjs`, which reads
283
+ the corpus and is not part of the suite. `run-census.mjs` beside it re-measures the class the tool absorbs
284
+ and, with `--since`, the adoption in sessions started after a deploy.
285
+
286
+ Core moves a minor: a new tool surface a caller can reach, and nothing existing changes shape.
287
+
288
+ ## Core 0.44.5, Telegram 0.2.1: a label names the session, and the digest reads as a sentence (2026-11-15)
289
+
290
+ The identity line said `session unknown` on every message a seat sent. pi DELETES `PI_SESSION_ID`
291
+ from the environment it hands an extension and re-injects it only into bash children, so the label's
292
+ `process.env` read could never succeed, while the adherence digest beside it printed the real id from
293
+ the extension context. The session now comes from that context: the Telegram factory registers a
294
+ getter (`setIdentitySessionSource`) bound to the live `ExtensionContext` it already keeps for
295
+ `isIdle`, and the label prefers it to the environment, which stays the fallback the standalone
296
+ `node src/lib/identity.ts` command still has. The memo is keyed on the id the getter answers with, so
297
+ one session reads one line, a label rendered before the first `session_start` corrects itself, and a
298
+ reload inside one process relabels to the session that now sends.
299
+
300
+ The adherence digest was nine labelled lines, and the owner read it as a field dump. It is now one
301
+ thing that happened: a bold subject naming the rung and how many rules are in it, one sentence
302
+ carrying the counts and quoting the rule in full with the internal source token after it in
303
+ parentheses rather than in front, and one time stamp. Two fields are gone. The truncated session id,
304
+ because the message already opens with a label that names the session. The report path, because the
305
+ reader receives this on a chat client and the report is where the counts live, not somewhere to
306
+ navigate to. A digest that folded several crossings now says so and names how many, and a rule is no
307
+ longer clipped to 64 characters: a fragment of a regex told the owner nothing, and above the plain
308
+ cap the body carries the format the outbound gate asks for.
309
+
310
+ Both changes are fixes to what the owner sees, so both move a patch: core 0.44.5 and Telegram 0.2.1.
311
+ The new function is internal wiring between the package's own modules, not a documented command. The
312
+ three digest shapes are frozen in `packages/telegram/test/fixtures/adherence-digest-bodies.json`
313
+ because the two packages cannot import each other: the producer's fixture asserts the renderer emits
314
+ those lines, and the Telegram fixture pushes the same bytes through the gate and Telegram's own
315
+ parser.
316
+
257
317
  ## Core 0.44.0, Contrib 0.2.0, Providers 1.0.8 — the ruler gains eyes, and refusals learn to speak (2026-11-12)
258
318
 
259
319
  `design_audit` could measure a rendered page and say nothing about whether it looked cheap. The same
package/README.md CHANGED
@@ -41,7 +41,7 @@ build flow; [docs/SETUP.md](docs/SETUP.md) covers every install path.
41
41
  | Subagents | `orchestrate` keeps a per-project worker registry with admission, lifecycle, one branch per worker, file locks, conflict detection, and merge verification. |
42
42
  | Prompt assembly | The system prompt is composed from named sections and published through pi's section seam, so a changed section re-sends alone. `prompt_inspect` prints the assembled prompt at any point. |
43
43
 
44
- The suite is 29 extensions; `health-maintenance` and `error-tracking` are off by default, and the
44
+ The suite is 30 extensions; `health-maintenance` and `error-tracking` are off by default, and the
45
45
  list is [src/extensions/manifest.ts](src/extensions/manifest.ts). `set_tool_profile` switches the
46
46
  active tool set to a curated profile.
47
47
 
package/TOOLS.md CHANGED
@@ -26,9 +26,9 @@ fails until the other catches up.
26
26
 
27
27
  | Class | Count | Notes |
28
28
  | ---------------------------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
- | Braid-registered tools | 24 | Registered via `pi.registerTool()` in `src/extensions/` - owned by this package |
29
+ | Braid-registered tools | 25 | Registered via `pi.registerTool()` in `src/extensions/` - owned by this package |
30
30
  | pi-native core tools | 9 | `read`/`bash`/`edit`/`write`/`grep`/`find`/`ls`/`powershell` - pi builtins surfaced through the package with stable one-liners (`TOOL_GUIDELINES`, `prompt-builder/tool-guidelines.ts`); `tool_search` is pi's built-in tool-search extension, activated by braid at session start |
31
- | **Documented catalog** | **33** | the rows between the markers below |
31
+ | **Documented catalog** | **34** | the rows between the markers below |
32
32
  | In-repo sibling `pi-braid-contrib` | 14 extensions | browser, codebase, diff, healthcheck, observatory, repl, sleep, system-monitor - **not owned by this package**, see appendix |
33
33
  | Third-party npm packages | web_search/fetch_content/source_check/get_search_content (pi-web-access); herdr\*\* (@ogulcancelik/pi-herdr) | **not owned by this package**, see appendix |
34
34
 
@@ -65,6 +65,7 @@ enablement (see appendix).
65
65
  | `system_info` | Show the runtime environment (versions, paths, session, stats) | prompt-builder - alwaysOn (manifest.ts:111) | when: context or environment matters; args: detail=compact for essentials |
66
66
  | `workspace_snapshot` | Capture/list/diff/preview/restore workspace snapshots | workspace-snapshot - alwaysOn (manifest.ts:123) | when: before risky multi-file edits — capture, then restore on failure; args: action capture/restore; caveat: restore applies only changed files |
67
67
  | `set_tool_profile` | Switch curated tool profiles (lean/research/debugging/browser/deep) | context-management - alwaysOn (manifest.ts:268) | when: task scope is known — focused profiles cut prompt noise and token cost; args: lean/research/debugging/browser/deep |
68
+ | `run` | One program and its argv, without a shell | run-tool - default-enabled (manifest.ts) | when: one program and its argv, for tests, builds, git, wc, node, python; when-not: pipelines, redirection, heredocs, $(...) or globs (bash), or a destructive verb naming a path outside the workspace; args: argv + required timeout_ms (+ cwd/env/stdin/max_output_bytes); caveat: no TTY, no shell, no glob expansion; a stream past the cap keeps head and tail and names the file holding the rest |
68
69
  | `list_skills` | Discover skills on demand (paginated catalog, ordered by relevance to the current task, + per-row reach) | skills-tool - default-enabled (manifest.ts:228) | when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize/sectionsMax/rank; caveat: rows arrive ordered by relevance to the current task (rows with evidence carry relevance {score, reason}; the response carries ranking {tier, basis, policy}; rank: catalog for the plain order) and reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections) prices the read — read the WHOLE SKILL.md before acting in the domain |
69
70
  | `skill_stats` | Per-skill usage counters (suggested vs loaded) | skills-tool - default-enabled (manifest.ts:228) | when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json) |
70
71
  | `topic_drift` | Check output for drift or reset topic anchors | topic-drift - default-enabled (manifest.ts:136, dep agent-environment) | when: multi-part requests — check output against the original ask before responding; args: action check + output; caveat: reset re-anchors the topic |
package/build-info.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.44.4",
4
- "sha": "867ae9adcf06547838bf83c7c8dcf43e290eda3f",
5
- "shaShort": "867ae9ad",
3
+ "version": "0.45.0",
4
+ "sha": "977b8a12e0b10ced945c2ed42043023ab5a8aea8",
5
+ "shaShort": "977b8a12",
6
6
  "branch": "detached",
7
7
  "dirty": false,
8
- "packedAt": "2026-11-15T15:38:22.037Z"
8
+ "packedAt": "2026-11-16T00:40:55.253Z"
9
9
  }
@@ -64,6 +64,7 @@ const PROFILES = {
64
64
  "write",
65
65
  // search & shell
66
66
  "bash",
67
+ "run",
67
68
  "grep",
68
69
  "find",
69
70
  "ls",
@@ -92,6 +93,7 @@ const PROFILES = {
92
93
  "find",
93
94
  "ls",
94
95
  "bash",
96
+ "run",
95
97
  "think",
96
98
  "memory",
97
99
  "scratchpad",
@@ -112,6 +114,7 @@ const PROFILES = {
112
114
  "edit",
113
115
  "write",
114
116
  "bash",
117
+ "run",
115
118
  "grep",
116
119
  "find",
117
120
  "ls",
@@ -138,6 +141,7 @@ const PROFILES = {
138
141
  "browser_screenshot",
139
142
  "read",
140
143
  "bash",
144
+ "run",
141
145
  "think",
142
146
  "describe_image",
143
147
  "fetch_content",
@@ -158,6 +162,7 @@ const PROFILES = {
158
162
  "edit",
159
163
  "write",
160
164
  "bash",
165
+ "run",
161
166
  "grep",
162
167
  "find",
163
168
  "ls",
@@ -74,6 +74,8 @@ export const TOOL_GUIDELINES = {
74
74
  workspace_snapshot: "when: before risky multi-file edits — capture, then restore on failure; args: action capture/restore; caveat: restore applies only changed files",
75
75
  // ── context-management (alwaysOn) ──
76
76
  set_tool_profile: "when: task scope is known — focused profiles cut prompt noise and token cost; args: lean/research/debugging/browser/deep",
77
+ // ── run-tool (default-enabled) ──
78
+ run: "when: one program and its argv, for tests, builds, git, wc, node, python; when-not: pipelines, redirection, heredocs, $(...) or globs (bash), or a destructive verb naming a path outside the workspace; args: argv + required timeout_ms (+ cwd/env/stdin/max_output_bytes); caveat: no TTY, no shell, no glob expansion; a stream past the cap keeps head and tail and names the file holding the rest",
77
79
  // ── skills-tool (default-enabled) ──
78
80
  list_skills: "when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize/sectionsMax/rank; caveat: rows arrive ordered by relevance to the current task (rows with evidence carry relevance {score, reason}; the response carries ranking {tier, basis, policy}; rank: catalog for the plain order) and reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections) prices the read — read the WHOLE SKILL.md before acting in the domain",
79
81
  skill_stats: "when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json)",
@@ -0,0 +1,58 @@
1
+ /**
2
+ * run — one program and its argument list, without a shell.
3
+ *
4
+ * The census behind this tool measured 223,137 bash calls out of 504,124 tool
5
+ * calls in a frozen session corpus, of which 24,793 (11.1%) carry no shell
6
+ * metacharacter at all: one program and its arguments. Those are the calls this
7
+ * tool replaces exactly; the rest need a shell (pipelines, redirection,
8
+ * heredocs, command substitution, loops), and this tool refuses the operators
9
+ * that would have made a call a shell program rather than growing into one.
10
+ *
11
+ * Shape: `argv` is the call; `cwd`, `env` and `stdin` carry its context; the
12
+ * timeout is required so no call can hang a session; `max_output_bytes` bounds
13
+ * each stream, and a stream past the cap keeps its head and its tail while the
14
+ * dropped byte count and the file holding the full text are named.
15
+ *
16
+ * The destructive guard is narrow on purpose: six verbs, and only when a path
17
+ * argument resolves outside the session workspace. The guard itself lives in
18
+ * `lib/tools/workspace-guard.ts`, so a later argv-shaped tool (`git`) passes its
19
+ * own verb set to the same mechanism instead of copying it.
20
+ */
21
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
22
+ import { Type } from "typebox";
23
+ import type { Static } from "typebox";
24
+ declare const runParameters: Type.TObject<{
25
+ argv: Type.TArray<Type.TString>;
26
+ cwd: Type.TOptional<Type.TString>;
27
+ env: Type.TOptional<Type.TUnsafe<Record<string, string>>>;
28
+ stdin: Type.TOptional<Type.TString>;
29
+ timeout_ms: Type.TInteger;
30
+ max_output_bytes: Type.TOptional<Type.TInteger>;
31
+ }>;
32
+ export type RunParameters = Static<typeof runParameters>;
33
+ /** Structured result for rendering and scripts. */
34
+ export interface RunToolDetails {
35
+ /** Present when the call was refused before a program started. */
36
+ refused?: string;
37
+ cwd?: string;
38
+ exit_code?: number | null;
39
+ signal?: string | null;
40
+ timed_out?: boolean;
41
+ aborted?: boolean;
42
+ duration_ms?: number;
43
+ stdout?: StreamDetails;
44
+ stderr?: StreamDetails;
45
+ /** Present when the child could not be started at all. */
46
+ spawn_error?: string;
47
+ }
48
+ interface StreamDetails {
49
+ bytes: number;
50
+ shown_bytes: number;
51
+ dropped_bytes: number;
52
+ truncated: boolean;
53
+ full_text_path?: string;
54
+ }
55
+ export declare function createRunTool(): ToolDefinition<typeof runParameters, RunToolDetails>;
56
+ export default function runToolExtension(pi: ExtensionAPI): void;
57
+ export {};
58
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,215 @@
1
+ /**
2
+ * run — one program and its argument list, without a shell.
3
+ *
4
+ * The census behind this tool measured 223,137 bash calls out of 504,124 tool
5
+ * calls in a frozen session corpus, of which 24,793 (11.1%) carry no shell
6
+ * metacharacter at all: one program and its arguments. Those are the calls this
7
+ * tool replaces exactly; the rest need a shell (pipelines, redirection,
8
+ * heredocs, command substitution, loops), and this tool refuses the operators
9
+ * that would have made a call a shell program rather than growing into one.
10
+ *
11
+ * Shape: `argv` is the call; `cwd`, `env` and `stdin` carry its context; the
12
+ * timeout is required so no call can hang a session; `max_output_bytes` bounds
13
+ * each stream, and a stream past the cap keeps its head and its tail while the
14
+ * dropped byte count and the file holding the full text are named.
15
+ *
16
+ * The destructive guard is narrow on purpose: six verbs, and only when a path
17
+ * argument resolves outside the session workspace. The guard itself lives in
18
+ * `lib/tools/workspace-guard.ts`, so a later argv-shaped tool (`git`) passes its
19
+ * own verb set to the same mechanism instead of copying it.
20
+ */
21
+ import { copyFileSync, mkdirSync, statSync } from "node:fs";
22
+ import { dirname, resolve } from "node:path";
23
+ import { Type } from "typebox";
24
+ import { getOffloadFilePath } from "../../../lib/config/braid-paths.js";
25
+ import { DEFAULT_OUTPUT_BYTES, MAX_OUTPUT_BYTES, MAX_TIMEOUT_MS, MIN_OUTPUT_BYTES, boundStream, capturePathFor, discardCapture, executeArgv, findRefusal, } from "./run.js";
26
+ /** Whether a path is a directory, with a missing path answering false. */
27
+ function isDirectory(path) {
28
+ try {
29
+ return statSync(path).isDirectory();
30
+ }
31
+ catch {
32
+ // A path that cannot be stat'd is not a directory this call can run in; the
33
+ // refusal below names it, which is more useful than the errno.
34
+ return false;
35
+ }
36
+ }
37
+ const runParameters = Type.Object({
38
+ argv: Type.Array(Type.String(), {
39
+ minItems: 1,
40
+ description: "The program and its arguments, one element each. argv[0] is the executable. No shell: pipes, redirection, heredocs and $(...) are refused.",
41
+ }),
42
+ cwd: Type.Optional(Type.String({
43
+ description: "Working directory; relative to the session cwd. Defaults to the session cwd.",
44
+ })),
45
+ env: Type.Optional(
46
+ // A map of string to string, written as the keyword rather than a builder
47
+ // helper whose emitted schema the tool-surface gate would have to allow.
48
+ Type.Unsafe({
49
+ type: "object",
50
+ additionalProperties: { type: "string" },
51
+ description: "Environment overrides merged over the session environment. Nothing is removed.",
52
+ })),
53
+ stdin: Type.Optional(Type.String({ description: "Text written to the program's stdin; closed after writing." })),
54
+ timeout_ms: Type.Integer({
55
+ minimum: 1,
56
+ maximum: MAX_TIMEOUT_MS,
57
+ description: "Required. The program is killed when it outlives this many milliseconds.",
58
+ }),
59
+ max_output_bytes: Type.Optional(Type.Integer({
60
+ minimum: MIN_OUTPUT_BYTES,
61
+ maximum: MAX_OUTPUT_BYTES,
62
+ description: `Byte cap per stream (stdout and stderr separately). Default ${DEFAULT_OUTPUT_BYTES}. Past the cap the head and tail are kept and the full text is written to a file named in the result.`,
63
+ })),
64
+ });
65
+ function streamDetails(stream) {
66
+ return {
67
+ bytes: stream.bytes,
68
+ shown_bytes: stream.shownBytes,
69
+ dropped_bytes: stream.droppedBytes,
70
+ truncated: stream.truncated,
71
+ ...(stream.fullTextPath ? { full_text_path: stream.fullTextPath } : {}),
72
+ };
73
+ }
74
+ function numberLine(bytes) {
75
+ return bytes.toLocaleString("en-US");
76
+ }
77
+ /**
78
+ * The offload target for one truncated stream. The capture is copied, not moved:
79
+ * the temp file is the fallback when the copy fails, and the result names
80
+ * whichever path actually holds the text.
81
+ */
82
+ function offload(capture, stream, sessionId, toolCallId) {
83
+ const source = capturePathFor(capture, stream);
84
+ const target = getOffloadFilePath(sessionId, toolCallId, stream === "stdout" ? "run-stdout" : "run-stderr");
85
+ try {
86
+ mkdirSync(dirname(target), { recursive: true });
87
+ copyFileSync(source, target);
88
+ return target;
89
+ }
90
+ catch {
91
+ // The full text is still in the capture directory; keeping it there and
92
+ // naming that path is better than losing it to a failed copy.
93
+ return undefined;
94
+ }
95
+ }
96
+ /** Render one stream as a labelled section, with its truncation note. */
97
+ function renderStream(label, stream) {
98
+ const body = stream.text;
99
+ const sections = [];
100
+ const text = body.endsWith("\n") || body === "" ? body : `${body}\n`;
101
+ sections.push(`${label}:\n${text}`);
102
+ if (stream.truncated) {
103
+ sections.push(`[${label}: showing ${numberLine(stream.shownBytes)} of ${numberLine(stream.bytes)} bytes ` +
104
+ `with ${numberLine(stream.droppedBytes)} omitted; full text: ${stream.fullTextPath}]`);
105
+ }
106
+ return sections.join("\n");
107
+ }
108
+ /** The one-line outcome, so a failure is readable before the output. */
109
+ function statusLine(params, capture) {
110
+ if (capture.spawnError !== undefined) {
111
+ return `could not start ${params.argv[0]}: ${capture.spawnError}`;
112
+ }
113
+ if (capture.timedOut) {
114
+ return `timed out after ${params.timeout_ms}ms: killed`;
115
+ }
116
+ if (capture.aborted) {
117
+ return `aborted: killed after ${capture.durationMs}ms`;
118
+ }
119
+ if (capture.signal !== null) {
120
+ return `killed by ${capture.signal} after ${capture.durationMs}ms`;
121
+ }
122
+ const code = capture.exitCode ?? "none";
123
+ const cwd = params.cwd === undefined ? "" : ` · cwd ${capture.cwd}`;
124
+ return `exit ${code} · ${capture.durationMs}ms${cwd}`;
125
+ }
126
+ /** Whether the call is an error for the model: a refusal, a timeout, or a non-zero exit. */
127
+ function isFailure(capture) {
128
+ return (capture.spawnError !== undefined ||
129
+ capture.timedOut ||
130
+ capture.aborted ||
131
+ capture.exitCode !== 0);
132
+ }
133
+ export function createRunTool() {
134
+ return {
135
+ name: "run",
136
+ label: "Run",
137
+ description: "Execute one program with an argument list, without a shell. Returns stdout and stderr separately, each capped at max_output_bytes with the dropped bytes named and the full text in a file. Use for a single program and its arguments: tests, builds, git, wc, node, python, rg. A shell-only command keeps needing bash, and is refused here rather than reinterpreted: pipes, redirection, heredocs and command substitution (an argument carrying |, &&, ;, a backtick or $( is refused), glob expansion (a glob-shaped path such as *.md or src/* is refused; pass the paths or use find/grep), and a shell invoked with -c. argv[0] from a destructive set (rm, mv, dd, chmod, shred, truncate) is refused when a path argument resolves outside the session workspace. There is no TTY: a program that needs a terminal fails on its own terms. timeout_ms is required, and a program that outlives it is killed.",
138
+ parameters: runParameters,
139
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
140
+ const sessionCwd = ctx.cwd;
141
+ const workspaceRoot = sessionCwd;
142
+ const cwd = resolve(sessionCwd, params.cwd ?? ".");
143
+ const request = {
144
+ argv: params.argv,
145
+ ...(params.cwd === undefined ? {} : { cwd: params.cwd }),
146
+ ...(params.env === undefined ? {} : { env: params.env }),
147
+ ...(params.stdin === undefined ? {} : { stdin: params.stdin }),
148
+ timeout_ms: params.timeout_ms,
149
+ ...(params.max_output_bytes === undefined
150
+ ? {}
151
+ : { max_output_bytes: params.max_output_bytes }),
152
+ };
153
+ // The cwd is a filesystem fact, so it is read before the pure refusals:
154
+ // every path in the guard is resolved against it.
155
+ if (!isDirectory(cwd)) {
156
+ const message = `refused: cwd ${cwd} does not exist or is not a directory. A call is not run against a missing directory.`;
157
+ return {
158
+ content: [{ type: "text", text: message }],
159
+ details: { refused: "cwd", cwd },
160
+ isError: true,
161
+ };
162
+ }
163
+ const refusal = findRefusal(request, { cwd, workspaceRoot });
164
+ if (refusal) {
165
+ return {
166
+ content: [{ type: "text", text: refusal.message }],
167
+ details: { refused: refusal.kind, cwd },
168
+ isError: true,
169
+ };
170
+ }
171
+ const capture = await executeArgv(request, { cwd, workspaceRoot }, signal);
172
+ const cap = params.max_output_bytes ?? DEFAULT_OUTPUT_BYTES;
173
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? "anonymous";
174
+ const stdoutPath = capture.stdoutBytes > cap ? offload(capture, "stdout", sessionId, toolCallId) : undefined;
175
+ const stderrPath = capture.stderrBytes > cap ? offload(capture, "stderr", sessionId, toolCallId) : undefined;
176
+ const offloadFailed = (capture.stdoutBytes > cap && stdoutPath === undefined) ||
177
+ (capture.stderrBytes > cap && stderrPath === undefined);
178
+ const stdout = boundStream(capture.stdoutPath, cap, stdoutPath ?? (capture.stdoutBytes > cap ? capture.stdoutPath : undefined));
179
+ const stderr = boundStream(capture.stderrPath, cap, stderrPath ?? (capture.stderrBytes > cap ? capture.stderrPath : undefined));
180
+ // A failed offload keeps the capture directory: the result names that
181
+ // path, so it must still exist when the reader follows it.
182
+ if (!offloadFailed)
183
+ discardCapture(capture);
184
+ const lines = [statusLine(params, capture)];
185
+ if (stdout.text === "" && stderr.text === "") {
186
+ lines.push("(no output)");
187
+ }
188
+ else {
189
+ if (stdout.text !== "")
190
+ lines.push(renderStream("stdout", stdout));
191
+ if (stderr.text !== "")
192
+ lines.push(renderStream("stderr", stderr));
193
+ }
194
+ return {
195
+ content: [{ type: "text", text: lines.join("\n\n") }],
196
+ details: {
197
+ cwd: capture.cwd,
198
+ exit_code: capture.exitCode,
199
+ signal: capture.signal,
200
+ timed_out: capture.timedOut,
201
+ aborted: capture.aborted,
202
+ duration_ms: capture.durationMs,
203
+ stdout: streamDetails(stdout),
204
+ stderr: streamDetails(stderr),
205
+ ...(capture.spawnError === undefined ? {} : { spawn_error: capture.spawnError }),
206
+ },
207
+ isError: isFailure(capture),
208
+ };
209
+ },
210
+ };
211
+ }
212
+ export default function runToolExtension(pi) {
213
+ pi.registerTool(createRunTool());
214
+ }
215
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The execution core of the `run` tool: one program and its argv, no shell.
3
+ *
4
+ * What this module refuses is what a shell would have interpreted:
5
+ * - the five operators that make a command string a program (`|`, `&&`, `;`,
6
+ * a backtick, `$(`);
7
+ * - a shell invoked with a command string (`sh -c ...`), which is the same
8
+ * thing in a different spelling;
9
+ * - a glob at a path-segment boundary (`*.md`, `src/*`), because the caller
10
+ * passed an expression where a program expects a path.
11
+ * A `*` inside an argument (a sed quantifier, a grep `--include` filter) is
12
+ * not a boundary and is left to the program, which is where such a pattern
13
+ * belongs.
14
+ *
15
+ * What it does not do is as load-bearing: no TTY, no shell profile, no glob
16
+ * expansion, no environment invention. The child gets the caller's environment,
17
+ * a stdin that ends (or the text the caller supplied), and stdout/stderr to
18
+ * files so the bytes are exact and the memory is bounded. Both streams are
19
+ * returned separately; each is capped, and the dropped bytes and the file that
20
+ * holds the rest are named rather than dropped silently.
21
+ */
22
+ /** setTimeout's own ceiling: a longer timeout cannot be armed. */
23
+ export declare const MAX_TIMEOUT_MS = 2147483647;
24
+ /** The smallest cap worth reporting a window for. */
25
+ export declare const MIN_OUTPUT_BYTES = 1024;
26
+ /** A cap past the harness's own structured-output budget buys nothing. */
27
+ export declare const MAX_OUTPUT_BYTES = 1048576;
28
+ /** Per stream, when the call names no cap: the harness's truncation default. */
29
+ export declare const DEFAULT_OUTPUT_BYTES: number;
30
+ /**
31
+ * Verbs whose operand is destroyed or rewritten. The set is this tool's policy,
32
+ * not the guard's: `git` will bring its own.
33
+ */
34
+ export declare const DESTRUCTIVE_VERBS: ReadonlySet<string>;
35
+ /** A validated `run` call. */
36
+ export interface RunRequest {
37
+ argv: string[];
38
+ cwd?: string;
39
+ env?: Record<string, string>;
40
+ stdin?: string;
41
+ timeout_ms: number;
42
+ max_output_bytes?: number;
43
+ }
44
+ /** Why a call never reached a program. */
45
+ export interface RunRefusal {
46
+ kind: "argv" | "metacharacter" | "shell-string" | "glob" | "timeout" | "output-cap" | "cwd" | "destructive-escape";
47
+ message: string;
48
+ }
49
+ /** One stream after the cap was applied. */
50
+ export interface RunStream {
51
+ /** What the result text shows. */
52
+ text: string;
53
+ /** Bytes the program wrote to this stream. */
54
+ bytes: number;
55
+ /** Bytes the text shows, before the omission marker. */
56
+ shownBytes: number;
57
+ /** Bytes the text does not show. */
58
+ droppedBytes: number;
59
+ /** Whether the cap applied. */
60
+ truncated: boolean;
61
+ /** The file holding the full stream; present when `truncated`. */
62
+ fullTextPath?: string;
63
+ }
64
+ /** What one call captured, before the cap is applied to either stream. */
65
+ export interface RunCapture {
66
+ exitCode: number | null;
67
+ signal: string | null;
68
+ timedOut: boolean;
69
+ aborted: boolean;
70
+ durationMs: number;
71
+ cwd: string;
72
+ argv: string[];
73
+ /** Present when the child could not be spawned at all. */
74
+ spawnError?: string;
75
+ /** Full stdout, in a file this call owns. */
76
+ stdoutPath: string;
77
+ /** Full stderr, in a file this call owns. */
78
+ stderrPath: string;
79
+ stdoutBytes: number;
80
+ stderrBytes: number;
81
+ /** The capture directory, removed by `discardCapture`. */
82
+ captureDir?: string;
83
+ }
84
+ /** Where a call runs, and what bounds its destructive verbs. */
85
+ export interface RunContext {
86
+ /** Absolute directory the program runs in. */
87
+ cwd: string;
88
+ /** Boundary for the destructive guard. */
89
+ workspaceRoot: string;
90
+ }
91
+ /**
92
+ * A `*` at a path-segment boundary: the whole element, a leading `*.ext`, a
93
+ * trailing directory wildcard, or a wildcard between two segments. A star
94
+ * inside a word or a pattern is the program's business.
95
+ */
96
+ export declare function isGlobExpression(element: string): boolean;
97
+ /**
98
+ * Everything wrong with a call that can be known before a process starts: the
99
+ * argv shape, shell operators, a shell command string, a glob, the timeout, the
100
+ * cap, and a destructive verb reaching outside the workspace.
101
+ *
102
+ * Pure. The cwd is already resolved and its existence checked by the caller;
103
+ * the workspace boundary is passed in.
104
+ */
105
+ export declare function findRefusal(request: RunRequest, context: RunContext): RunRefusal | null;
106
+ /** Apply the byte cap to one captured stream, keeping a head and a tail. */
107
+ export declare function boundStream(file: string, cap: number, fullTextPath?: string): RunStream;
108
+ /**
109
+ * Run one program. The caller has already refused the shapes that never reach a
110
+ * program (see `findRefusal`) and resolved `context.cwd`.
111
+ *
112
+ * The child is spawned detached on POSIX so the timeout and an aborted tool call
113
+ * kill the whole tree, not only the leader; stdout and stderr are files rather
114
+ * than pipes, so a grandchild cannot hold the result open after the program
115
+ * exits, and the capture is byte-exact without buffering the stream in memory.
116
+ */
117
+ export declare function executeArgv(request: RunRequest, context: RunContext, signal?: AbortSignal): Promise<RunCapture>;
118
+ /** Remove the capture directory after the caller has offloaded what it needs. */
119
+ export declare function discardCapture(capture: RunCapture): void;
120
+ /** The capture file for one stream, while the capture directory still exists. */
121
+ export declare function capturePathFor(capture: RunCapture, stream: "stdout" | "stderr"): string;
122
+ //# sourceMappingURL=run.d.ts.map