pi-ptc-subagents 0.1.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/dist/index.js ADDED
@@ -0,0 +1,3127 @@
1
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, createBashTool, createEditTool, createFindTool, createGrepTool, createLsTool, createReadTool, createWriteTool, defineTool, formatSize, formatSkillsForPrompt, getAgentDir, truncateTail } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { validateToolArguments } from "@earendil-works/pi-ai";
4
+ import { spawn } from "node:child_process";
5
+ import * as fs from "node:fs";
6
+ import { readFileSync, writeFileSync } from "node:fs";
7
+ import * as os from "node:os";
8
+ import { tmpdir } from "node:os";
9
+ import * as path from "node:path";
10
+ import { join } from "node:path";
11
+ import { randomUUID } from "node:crypto";
12
+ import { MessageChannel, MessagePort, Worker } from "node:worker_threads";
13
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
14
+ //#region src/runtime/dispatch.ts
15
+ /**
16
+ * pi.dispatch: a parallel binding that spawns a fresh pi subprocess per call.
17
+ *
18
+ * ADR-0016 (2026-09-23) is the contract. This file is the type surface and the spawn
19
+ * skeleton; the actual subprocess plumbing (agent-md resolution, JSON-line parser,
20
+ * usage accumulator, signal propagation across worker_threads / child_process) is a
21
+ * follow-up. The stubs here are typed against the contract so call sites can land
22
+ * before the spawn path is finalised, and so a wrong shape is a compile error rather
23
+ * than a runtime one.
24
+ *
25
+ * Behaviourally compatible with pi's examples/extensions/subagent/index.ts reference
26
+ * (--mode json, -p, --no-session, --append-system-prompt <tmpfile>), but not cooperative:
27
+ * does not require the user to install pi's subagent extension. See ADR-0016 section 2.
28
+ */
29
+ /**
30
+ * The CLI command used to invoke a fresh pi subprocess for one dispatch.
31
+ *
32
+ * Always `"pi"` — pi-ptc is a library, not a CLI, and `dispatch` must spawn the
33
+ * separate `pi` binary regardless of how the host process was launched. An
34
+ * earlier copy of this function mirrored pi's own subagent extension and tried
35
+ * to reuse `process.execPath + process.argv[1]`, which works only when the host
36
+ * is `pi` itself; in any other host (test scripts, the dispatcher host process,
37
+ * etc.) the function would spawn the host script in place of `pi`, producing
38
+ * infinite recursion and a stdout pipe that never drains (so `proc.on('close')`
39
+ * never fires). The caller surfaces a missing-binary condition via the child's
40
+ * `error` event — `spawn` itself does not throw synchronously on ENOENT, the
41
+ * async `error` listener does.
42
+ */
43
+ const PI_COMMAND = "pi";
44
+ /**
45
+ * Compose the system prompt handed to the child subprocess.
46
+ *
47
+ * The agent's own markdown body is the user-supplied content; pi-ptc appends a
48
+ * `<pi-ptc-context depth="N" max-depth="M">...</pi-ptc-context>` hint so the child
49
+ * agent can see how much recursion room it has. The shape mirrors DSH's existing
50
+ * subagent-context injection so the field recognises it.
51
+ */
52
+ function appendDepthHint(systemPrompt, depth, maxDepth) {
53
+ const hint = [
54
+ "<pi-ptc-context depth=\"" + depth + "\" max-depth=\"" + maxDepth + "\">",
55
+ "You are a PTC run at depth " + depth + " (root is depth 0). You may write PTC programs and you may",
56
+ "call pi.dispatch(...) to spawn further children, but each level costs a fresh pi subprocess.",
57
+ "The remaining depth budget is " + maxDepth + " - " + depth + ". Beyond it, pi.dispatch rejects with",
58
+ "{ status: \"rejected\", errorMessage: \"dispatch depth limit reached\" }.",
59
+ "</pi-ptc-context>"
60
+ ].join("\n");
61
+ return systemPrompt.length === 0 ? hint : systemPrompt + "\n\n" + hint;
62
+ }
63
+ /** Default error returned when the depth limit is exceeded. */
64
+ function dispatchDepthLimitReached(currentDepth) {
65
+ return {
66
+ text: "",
67
+ status: "rejected",
68
+ agentName: "unknown",
69
+ durationMs: 0,
70
+ exitCode: -1,
71
+ errorMessage: "dispatch depth limit reached (current depth " + currentDepth + ", max-depth exceeded)"
72
+ };
73
+ }
74
+ /**
75
+ * Decide the outcome of one `dispatch(...)` based on the child's `close` event.
76
+ *
77
+ * Cancellation has priority over every other branch: when the host's signal
78
+ * aborted the run, the child exited because we asked it to, and the contract
79
+ * (ADR-0016 §4) is to surface "dispatch cancelled" rather than leave the
80
+ * caller guessing why an aborted run came back `rejected`.
81
+ *
82
+ * Non-cancellation cases follow the original close-handler ladder:
83
+ * - exit 0 with final text → fulfilled
84
+ * - exit 0 without final text → rejected (the model never answered)
85
+ * - any other exit code → rejected, no errorMessage (spawn-error path labels
86
+ * its own failures with `failed to spawn pi: ...`)
87
+ */
88
+ function decideCloseOutcome(input) {
89
+ if (input.aborted) return {
90
+ status: "rejected",
91
+ errorMessage: "dispatch cancelled"
92
+ };
93
+ if (input.exitCode === 0 && input.finalText.length > 0) return { status: "fulfilled" };
94
+ if (input.exitCode === 0) return {
95
+ status: "rejected",
96
+ errorMessage: "dispatch produced no final text"
97
+ };
98
+ return { status: "rejected" };
99
+ }
100
+ /**
101
+ * Send `signal` to `proc` iff the process is still attached, swallowing
102
+ * "process already gone" throws. Returns whether a kill was actually issued.
103
+ *
104
+ * `proc.pid === undefined` happens for processes spawned without a usable
105
+ * pid (rare, but TS-strict demands the guard); `proc.kill` throwing happens
106
+ * for processes that exited between the guard and the syscall (the OS hands
107
+ * back ESRCH). Both are "no-op successfully" for our purposes.
108
+ */
109
+ function safeKill(proc, signal) {
110
+ if (proc.pid === void 0) return false;
111
+ try {
112
+ proc.kill(signal);
113
+ return true;
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+ /**
119
+ * Minimal YAML frontmatter scalar parser. Returns the trimmed value, with surrounding
120
+ * double or single quotes stripped when both are present.
121
+ */
122
+ function extractYamlString(yaml, key) {
123
+ const m = yaml.match(new RegExp("^" + key + ":\\s*(.+)$", "m"));
124
+ if (!m) return void 0;
125
+ let v = (m[1] ?? "").trim();
126
+ if (v.length >= 2) {
127
+ const first = v[0];
128
+ const last = v[v.length - 1];
129
+ if (first === "\"" && last === "\"" || first === "'" && last === "'") v = v.slice(1, -1);
130
+ }
131
+ return v.length === 0 ? void 0 : v;
132
+ }
133
+ /**
134
+ * Minimal YAML list parser: accepts inline `[a, b, c]` and bare `a, b, c`.
135
+ */
136
+ function extractYamlList(yaml, key) {
137
+ const m = yaml.match(new RegExp("^" + key + ":\\s*(.+)$", "m"));
138
+ if (!m) return void 0;
139
+ let inner = (m[1] ?? "").trim();
140
+ if (inner.startsWith("[") && inner.endsWith("]")) inner = inner.slice(1, -1);
141
+ const parts = inner.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
142
+ return parts.length === 0 ? void 0 : parts;
143
+ }
144
+ /**
145
+ * Parse an agent markdown file: YAML frontmatter (name / description / model / tools)
146
+ * plus the body, returned as the system prompt. Tolerates a missing or partial
147
+ * frontmatter; the caller falls back to defaults when this returns null.
148
+ */
149
+ function parseAgentMarkdown(content) {
150
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
151
+ if (!fmMatch) return null;
152
+ const frontmatter = fmMatch[1] ?? "";
153
+ const body = fmMatch[2] ?? "";
154
+ const name = extractYamlString(frontmatter, "name");
155
+ if (!name) return null;
156
+ const description = extractYamlString(frontmatter, "description") ?? "";
157
+ const model = extractYamlString(frontmatter, "model") ?? "";
158
+ const tools = extractYamlList(frontmatter, "tools");
159
+ const out = {
160
+ name,
161
+ systemPrompt: body.trim()
162
+ };
163
+ if (description !== void 0) out.description = description;
164
+ if (model !== void 0) out.model = model;
165
+ if (tools !== void 0) out.tools = tools;
166
+ return out;
167
+ }
168
+ /**
169
+ * Discover an agent by name. Mirrors pi's subagent extension agentScope behaviour:
170
+ * user-level (`~/.pi/agent/agents/`) is loaded by default; project-level
171
+ * (`<cwd>/.pi/agents/`) is loaded only when agentScope includes it.
172
+ */
173
+ function discoverAgent(name, cwd, agentScope) {
174
+ const userDir = path.join(os.homedir(), ".pi", "agent", "agents");
175
+ const projectDir = path.join(cwd, ".pi", "agents");
176
+ const candidates = [];
177
+ if (agentScope === "user" || agentScope === "both") candidates.push({
178
+ path: path.join(userDir, name + ".md"),
179
+ source: "user"
180
+ });
181
+ if (agentScope === "project" || agentScope === "both") candidates.push({
182
+ path: path.join(projectDir, name + ".md"),
183
+ source: "project"
184
+ });
185
+ for (const c of candidates) {
186
+ let raw;
187
+ try {
188
+ raw = fs.readFileSync(c.path, "utf-8");
189
+ } catch {
190
+ continue;
191
+ }
192
+ const parsed = parseAgentMarkdown(raw);
193
+ if (parsed && parsed.name === name) {
194
+ const out = {
195
+ name: parsed.name,
196
+ source: c.source,
197
+ systemPrompt: parsed.systemPrompt
198
+ };
199
+ if (parsed.model !== void 0) out.model = parsed.model;
200
+ if (parsed.tools !== void 0) out.tools = parsed.tools;
201
+ return out;
202
+ }
203
+ }
204
+ return null;
205
+ }
206
+ /**
207
+ * Build the argv handed to the child pi subprocess. Model / thinking / tools / agentScope
208
+ * precedence: dispatch input (call site) > agent markdown frontmatter > nothing.
209
+ * The agent's system prompt (with the depth hint appended) is materialised to a tmpfile
210
+ * and passed via --append-system-prompt, exactly as the subagent extension does.
211
+ */
212
+ function buildArgv(input, agent, promptFilePath) {
213
+ const args = [
214
+ "--mode",
215
+ "json",
216
+ "-p",
217
+ "--no-session"
218
+ ];
219
+ const model = input.model ?? agent.model;
220
+ if (model) args.push("--model", model);
221
+ const thinking = input.thinkingLevel ?? "off";
222
+ args.push("--thinking", thinking);
223
+ if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
224
+ args.push("--append-system-prompt", promptFilePath);
225
+ args.push("Task: " + input.task);
226
+ return args;
227
+ }
228
+ function parseAgentEvent(line) {
229
+ const trimmed = line.trim();
230
+ if (trimmed.length === 0) return null;
231
+ try {
232
+ return JSON.parse(trimmed);
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+ /**
238
+ * Write the system prompt (with depth hint appended) to a tmpfile. The caller is
239
+ * responsible for cleanup; we use mkdtemp + 0o600 to keep the prompt private, then
240
+ * best-effort cleanup in the dispatch() Promise.
241
+ */
242
+ async function writePromptToTempFile(agentName, prompt) {
243
+ const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-dispatch-"));
244
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
245
+ const filePath = path.join(tmpDir, "prompt-" + safeName + ".md");
246
+ await fs.promises.writeFile(filePath, prompt, {
247
+ encoding: "utf-8",
248
+ mode: 384
249
+ });
250
+ return {
251
+ dir: tmpDir,
252
+ filePath
253
+ };
254
+ }
255
+ /**
256
+ * Best-effort cleanup of the tmpfile + dir used for the system prompt. Errors are
257
+ * deliberately swallowed: leaving a tmpfile around is preferable to crashing the run.
258
+ */
259
+ function cleanupTmp(tmp) {
260
+ try {
261
+ fs.unlinkSync(tmp.filePath);
262
+ } catch {}
263
+ try {
264
+ fs.rmdirSync(tmp.dir);
265
+ } catch {}
266
+ }
267
+ /**
268
+ * Spawn one pi subprocess for one dispatch and resolve with a DispatchResult.
269
+ *
270
+ * Behavioural contract (ADR-0016 sections 1, 3, 4):
271
+ * - Resolves with status: fulfilled when the child exits 0 and emits at least one
272
+ * assistant message whose text is non-empty.
273
+ * - Resolves with status: rejected on non-zero exit, signal kill, spawn failure,
274
+ * unknown agent, or no usable final text.
275
+ * - Never rejects. The caller can pattern-match on outcome.status the same way
276
+ * it would pattern-match a Promise.allSettled record.
277
+ * - Honours signal with SIGTERM, then SIGKILL after a 5s grace window.
278
+ */
279
+ async function dispatch(input, ctx) {
280
+ const childDepth = ctx.depth + 1;
281
+ if (childDepth > ctx.maxDepth) return dispatchDepthLimitReached(ctx.depth);
282
+ const cwd = input.cwd ?? ctx.cwd;
283
+ const agentScope = input.agentScope ?? "user";
284
+ const start = Date.now();
285
+ const agent = discoverAgent(input.agent, cwd, agentScope);
286
+ if (!agent) return {
287
+ text: "",
288
+ status: "rejected",
289
+ agentName: input.agent,
290
+ durationMs: Date.now() - start,
291
+ exitCode: 1,
292
+ errorMessage: "unknown agent: " + input.agent + " (agentScope=" + agentScope + ", cwd=" + cwd + ")"
293
+ };
294
+ const fullPrompt = appendDepthHint(agent.systemPrompt, childDepth, ctx.maxDepth);
295
+ const tmp = await writePromptToTempFile(agent.name, fullPrompt);
296
+ const argv = buildArgv(input, agent, tmp.filePath);
297
+ return await new Promise((resolve) => {
298
+ let stdoutBuffer = "";
299
+ let stderrBuf = "";
300
+ let finalText = "";
301
+ let usage;
302
+ let exitCode = -1;
303
+ let resolved = false;
304
+ let killTimer;
305
+ let proc;
306
+ let aborted = false;
307
+ const finalize = (status, errorMessage) => {
308
+ if (resolved) return;
309
+ resolved = true;
310
+ if (killTimer) clearTimeout(killTimer);
311
+ if (ctx.signal) ctx.signal.removeEventListener("abort", onAbort);
312
+ cleanupTmp(tmp);
313
+ const out = {
314
+ text: finalText,
315
+ status,
316
+ agentName: agent.name,
317
+ durationMs: Date.now() - start,
318
+ exitCode
319
+ };
320
+ if (usage) out.usage = usage;
321
+ if (stderrBuf.length > 0) out.stderr = stderrBuf;
322
+ if (errorMessage) out.errorMessage = errorMessage;
323
+ resolve(out);
324
+ };
325
+ const onAbort = () => {
326
+ if (!proc || proc.killed || resolved) return;
327
+ aborted = true;
328
+ safeKill(proc, "SIGTERM");
329
+ killTimer = setTimeout(() => {
330
+ if (proc && !proc.killed) safeKill(proc, "SIGKILL");
331
+ }, 5e3);
332
+ };
333
+ try {
334
+ proc = spawn(PI_COMMAND, argv, {
335
+ cwd,
336
+ shell: false,
337
+ stdio: [
338
+ "ignore",
339
+ "pipe",
340
+ "pipe"
341
+ ]
342
+ });
343
+ } catch (err) {
344
+ finalize("rejected", "failed to spawn pi: " + (err instanceof Error ? err.message : String(err)));
345
+ return;
346
+ }
347
+ if (ctx.signal) {
348
+ if (ctx.signal.aborted) onAbort();
349
+ else ctx.signal.addEventListener("abort", onAbort, { once: true });
350
+ }
351
+ const stdout = proc.stdout;
352
+ if (!stdout) return;
353
+ stdout.on("data", (data) => {
354
+ stdoutBuffer += data.toString("utf-8");
355
+ let nl = stdoutBuffer.indexOf("\n");
356
+ while (nl >= 0) {
357
+ const line = stdoutBuffer.slice(0, nl);
358
+ stdoutBuffer = stdoutBuffer.slice(nl + 1);
359
+ const ev = parseAgentEvent(line);
360
+ if (!ev) {
361
+ nl = stdoutBuffer.indexOf("\n");
362
+ continue;
363
+ }
364
+ if (ev.type === "message_end" && ev.message && ev.message.role === "assistant") {
365
+ const m = ev.message;
366
+ if (m.usage) {
367
+ const cur = usage ?? {
368
+ input: 0,
369
+ output: 0,
370
+ cacheRead: 0,
371
+ cacheWrite: 0,
372
+ cost: 0,
373
+ turns: 0
374
+ };
375
+ cur.input += m.usage.input ?? 0;
376
+ cur.output += m.usage.output ?? 0;
377
+ cur.cacheRead += m.usage.cacheRead ?? 0;
378
+ cur.cacheWrite += m.usage.cacheWrite ?? 0;
379
+ cur.cost += m.usage.cost?.total ?? 0;
380
+ cur.turns += 1;
381
+ usage = cur;
382
+ }
383
+ if (Array.isArray(m.content)) {
384
+ for (const part of m.content) if (part && part.type === "text" && typeof part.text === "string") finalText = part.text;
385
+ }
386
+ }
387
+ nl = stdoutBuffer.indexOf("\n");
388
+ }
389
+ });
390
+ const stderrStream = proc.stderr;
391
+ if (!stderrStream) return;
392
+ stderrStream.on("data", (data) => {
393
+ stderrBuf += data.toString("utf-8");
394
+ });
395
+ proc.on("close", (code) => {
396
+ exitCode = code ?? -1;
397
+ const { status, errorMessage } = decideCloseOutcome({
398
+ exitCode,
399
+ finalText,
400
+ aborted
401
+ });
402
+ finalize(status, errorMessage);
403
+ });
404
+ proc.on("error", (err) => {
405
+ stderrBuf += "[spawn-error] " + err.message + "\n";
406
+ finalize("rejected", "failed to spawn pi: " + err.message);
407
+ });
408
+ });
409
+ }
410
+ //#endregion
411
+ //#region src/runtime/bindings.ts
412
+ /**
413
+ * Bindings: the pi tools a PTC program may call as `tools.<name>(args)`.
414
+ *
415
+ * R5 found that pi's extension API exposes no tool-dispatch surface — `pi.on('tool_call')`
416
+ * only fires from the agent loop, `extensionsResult.runtime` is state plumbing, and
417
+ * `pi.exec` has no `execArgv`/`resourceLimits`/`stdio`. So a binding builds the tool with
418
+ * pi's own SDK factory and calls `execute()` on it directly. That keeps the tool
419
+ * implementation identical to the native one, but it also means worker-driven calls are
420
+ * **not** seen by pi's tool-call pipeline: `tool_call` guards, `protected-paths`-style
421
+ * extensions, permission gates and sandbox overrides never run for them. This is the
422
+ * inherited risk ADR-0005 accepts and records — it must not be described as resolved, and
423
+ * nothing here may pretend to route through `pi.on('tool_call')`.
424
+ *
425
+ * Arguments are validated with pi's own `validateToolArguments`, the same helper the agent
426
+ * loop uses, so a bad call fails with the same message (and the same coercion) it would
427
+ * get from the native pipeline.
428
+ */
429
+ /** pi's built-in tools that can be exposed as bindings, in native order. */
430
+ const BUILTIN_BINDING_NAMES = [
431
+ "read",
432
+ "bash",
433
+ "edit",
434
+ "write",
435
+ "grep",
436
+ "find",
437
+ "ls"
438
+ ];
439
+ /**
440
+ * Bindings exposed when the caller does not pass an explicit name list.
441
+ *
442
+ * `bash` is included on purpose: DSH's PTC preset still mounts `tool-bash`/`tool-pwsh`
443
+ * (R1 §2 — PTC mode hides the tools from the wire list and re-exposes the same registry
444
+ * as bindings), so a PTC program written against DSH may run shell commands. Leaving it
445
+ * out would silently shrink the surface relative to DSH. Callers that want a read-only
446
+ * PTC surface pass an explicit subset.
447
+ */
448
+ /** Parallel binding name (ADR-0016). Always bound alongside the builtin set;
449
+ * opt-out is the callers responsibility via an explicit subset to
450
+ * createBuiltinBindings (today the subset is restricted to builtin names,
451
+ * so opt-out is effectively use a future flag). */
452
+ const DISPATCH_BINDING_NAME = "pi.dispatch";
453
+ const DEFAULT_BINDING_NAMES = BUILTIN_BINDING_NAMES;
454
+ const BUILTIN_TOOL_FACTORIES = {
455
+ read: createReadTool,
456
+ bash: createBashTool,
457
+ edit: createEditTool,
458
+ write: createWriteTool,
459
+ grep: createGrepTool,
460
+ find: createFindTool,
461
+ ls: createLsTool
462
+ };
463
+ /**
464
+ * Build the binding table for one run.
465
+ *
466
+ * Tools are created once per table and reused across calls, matching pi's own extension
467
+ * examples (`createXxxTool(cwd)` caches nothing internally, so one instance per run is
468
+ * the intended granularity).
469
+ */
470
+ function createBuiltinBindings(options) {
471
+ const names = options.names ?? DEFAULT_BINDING_NAMES;
472
+ const table = /* @__PURE__ */ new Map();
473
+ for (const name of names) {
474
+ const factory = BUILTIN_TOOL_FACTORIES[name];
475
+ if (!factory) throw new TypeError(`unknown PTC binding "${name}"; known bindings: ${BUILTIN_BINDING_NAMES.join(", ")}`);
476
+ const tool = factory(options.cwd);
477
+ table.set(name, {
478
+ name,
479
+ execute: async (args, context) => {
480
+ const toolCallId = `ptc:${context.callId}`;
481
+ const toolCall = {
482
+ type: "toolCall",
483
+ id: toolCallId,
484
+ name: tool.name,
485
+ arguments: args
486
+ };
487
+ const validated = validateToolArguments(tool, toolCall);
488
+ const result = await tool.execute(toolCallId, validated, context.signal, void 0);
489
+ return {
490
+ content: result.content,
491
+ details: result.details === void 0 ? null : result.details
492
+ };
493
+ }
494
+ });
495
+ }
496
+ if (names === DEFAULT_BINDING_NAMES) table.set(DISPATCH_BINDING_NAME, {
497
+ name: DISPATCH_BINDING_NAME,
498
+ execute: async (args, context) => {
499
+ return dispatch(args, {
500
+ signal: context.signal,
501
+ callId: context.callId,
502
+ cwd: options.cwd,
503
+ depth: context.depth,
504
+ maxDepth: context.maxDispatchDepth
505
+ });
506
+ }
507
+ });
508
+ return table;
509
+ }
510
+ //#endregion
511
+ //#region src/runtime/limits.ts
512
+ const DEFAULT_CONFIG = Object.freeze({
513
+ timeoutMs: 12e4,
514
+ maxTimeoutMs: 6e5,
515
+ maxOutputBytes: 67108864,
516
+ maxMessageBytes: 134217728,
517
+ maxPendingCalls: 128,
518
+ maxParallelSubCalls: 10,
519
+ dispatchConcurrency: 8,
520
+ maxDispatchDepth: 3,
521
+ maxItemsPerCall: 4096,
522
+ graceMs: 3e3,
523
+ maxOldGenerationSizeMb: 512,
524
+ maxYoungGenerationSizeMb: 64
525
+ });
526
+ /**
527
+ * F1 — the only environment variables a PTC worker may inherit.
528
+ *
529
+ * These are what a shell needs to resolve binaries on each platform; everything
530
+ * else the host has (tokens, API keys, proxies, home paths) stays out of the worker.
531
+ */
532
+ const WORKER_ENV_ALLOW_LIST = Object.freeze([
533
+ "PATH",
534
+ "PATHEXT",
535
+ "SYSTEMROOT",
536
+ "WINDIR",
537
+ "TEMP",
538
+ "TMP"
539
+ ]);
540
+ /**
541
+ * Build the per-run environment snapshot: the allow-list entries that actually exist.
542
+ *
543
+ * Unset or empty entries are dropped rather than passed through as empty strings, so
544
+ * `Object.keys(workerEnv)` is exactly what the worker sees in `process.env`.
545
+ */
546
+ function createWorkerEnv(source = process.env) {
547
+ const env = {};
548
+ for (const name of WORKER_ENV_ALLOW_LIST) {
549
+ const value = source[name];
550
+ if (typeof value === "string" && value.length > 0) env[name] = value;
551
+ }
552
+ return env;
553
+ }
554
+ /**
555
+ * Merge per-run overrides onto `DEFAULT_CONFIG`.
556
+ *
557
+ * Overrides are validated rather than coerced: a negative or non-numeric limit is a
558
+ * caller bug, and silently substituting a default would hide it.
559
+ */
560
+ function resolveConfig(overrides = {}) {
561
+ const resolved = { ...DEFAULT_CONFIG };
562
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
563
+ const override = overrides[key];
564
+ if (override === void 0) continue;
565
+ if (typeof override !== "number" || !Number.isFinite(override) || override <= 0) throw new TypeError(`invalid PTC config override for ${key}: ${String(override)}`);
566
+ resolved[key] = override;
567
+ }
568
+ return resolved;
569
+ }
570
+ /**
571
+ * Resolve the effective deadline for one run.
572
+ *
573
+ * DSH semantics (R1 §3): `0` does not disable the deadline, it falls back to the
574
+ * default; anything larger is clamped to `maxTimeoutMs`.
575
+ */
576
+ function effectiveTimeoutMs(requested, config = DEFAULT_CONFIG) {
577
+ if (requested === void 0 || !Number.isFinite(requested) || requested <= 0) return config.timeoutMs;
578
+ return Math.min(requested, config.maxTimeoutMs);
579
+ }
580
+ const HOST_FRAME_KIND = Object.freeze({
581
+ connect: "connect",
582
+ init: "init",
583
+ callResult: "call-result",
584
+ cancel: "cancel"
585
+ });
586
+ const WORKER_FRAME_KIND = Object.freeze({
587
+ ready: "ready",
588
+ call: "call",
589
+ log: "log",
590
+ narration: "narration",
591
+ phase: "phase",
592
+ result: "result",
593
+ error: "error"
594
+ });
595
+ const PTC_LOG_LEVEL = Object.freeze({
596
+ log: "log",
597
+ info: "info",
598
+ warn: "warn",
599
+ error: "error",
600
+ debug: "debug"
601
+ });
602
+ const PTC_ERROR_KIND = Object.freeze({
603
+ /** Program parse error or thrown exception (includes `ReferenceError` from a helper that does not exist on this surface). */
604
+ exception: "exception",
605
+ /** Elapsed deadline expiry. */
606
+ timeout: "timeout",
607
+ /** Caller cancellation. */
608
+ abort: "abort",
609
+ /** Malformed or excessive control traffic. */
610
+ protocol: "protocol",
611
+ /** Early worker exit or a worker-level crash. */
612
+ workerExit: "worker-exit",
613
+ /** Completion value could not be materialized as lossless JSON. */
614
+ invalidOutput: "invalid-output",
615
+ /** Oversized outer result; collected logs are retained. */
616
+ outputLimit: "output-limit"
617
+ });
618
+ function isRecord(value) {
619
+ return typeof value === "object" && value !== null && !Array.isArray(value);
620
+ }
621
+ function isPtcLogLevel(value) {
622
+ return typeof value === "string" && Object.values(PTC_LOG_LEVEL).some((level) => level === value);
623
+ }
624
+ function isPtcErrorKind(value) {
625
+ return typeof value === "string" && Object.values(PTC_ERROR_KIND).some((kind) => kind === value);
626
+ }
627
+ function isPtcCancelReason(value) {
628
+ return value === "timeout" || value === "abort";
629
+ }
630
+ function isPtcConnectFrame(value) {
631
+ return isRecord(value) && value.kind === HOST_FRAME_KIND.connect && value.port instanceof MessagePort;
632
+ }
633
+ function isPtcInitFrame(value) {
634
+ return isRecord(value) && value.kind === HOST_FRAME_KIND.init && typeof value.runId === "string" && (value.surface === "run_code" || value.surface === "workflow") && typeof value.code === "string" && Array.isArray(value.bindings) && value.bindings.every((name) => typeof name === "string") && Array.isArray(value.bindingCandidates) && value.bindingCandidates.every((name) => typeof name === "string") && typeof value.maxItemsPerCall === "number" && Number.isFinite(value.maxItemsPerCall) && typeof value.maxPendingCalls === "number" && Number.isFinite(value.maxPendingCalls);
635
+ }
636
+ function isPtcCallResultFrame(value) {
637
+ if (!isRecord(value) || value.kind !== HOST_FRAME_KIND.callResult) return false;
638
+ if (!Number.isInteger(value.callId) || typeof value.tool !== "string") return false;
639
+ if (value.ok === true) return "value" in value;
640
+ return value.ok === false && typeof value.message === "string";
641
+ }
642
+ function isPtcCancelFrame(value) {
643
+ return isRecord(value) && value.kind === HOST_FRAME_KIND.cancel && isPtcCancelReason(value.reason);
644
+ }
645
+ function isPtcHostFrame(value) {
646
+ return isPtcConnectFrame(value) || isPtcInitFrame(value) || isPtcCallResultFrame(value) || isPtcCancelFrame(value);
647
+ }
648
+ function isPtcReadyFrame(value) {
649
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.ready;
650
+ }
651
+ function isPtcCallFrame(value) {
652
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.call && Number.isInteger(value.callId) && typeof value.tool === "string" && value.tool.length > 0 && "args" in value;
653
+ }
654
+ function isPtcLogFrame(value) {
655
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.log && isPtcLogLevel(value.level) && typeof value.text === "string";
656
+ }
657
+ function isPtcNarrationFrame(value) {
658
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.narration && typeof value.message === "string";
659
+ }
660
+ function isPtcPhaseFrame(value) {
661
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.phase && typeof value.title === "string";
662
+ }
663
+ function isPtcResultFrame(value) {
664
+ return isRecord(value) && value.kind === WORKER_FRAME_KIND.result;
665
+ }
666
+ function isPtcErrorFrame(value) {
667
+ if (!isRecord(value) || value.kind !== WORKER_FRAME_KIND.error) return false;
668
+ const error = value.error;
669
+ return isRecord(error) && isPtcErrorKind(error.kind) && typeof error.message === "string" && (error.stack === void 0 || typeof error.stack === "string");
670
+ }
671
+ function isPtcWorkerFrame(value) {
672
+ return isPtcReadyFrame(value) || isPtcCallFrame(value) || isPtcLogFrame(value) || isPtcNarrationFrame(value) || isPtcPhaseFrame(value) || isPtcResultFrame(value) || isPtcErrorFrame(value);
673
+ }
674
+ function workerProtocolSpec() {
675
+ return {
676
+ hostFrame: HOST_FRAME_KIND,
677
+ workerFrame: WORKER_FRAME_KIND,
678
+ logLevel: PTC_LOG_LEVEL,
679
+ errorKind: PTC_ERROR_KIND
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region src/runtime/worker-main.ts
684
+ function workerMain(deps) {
685
+ const hostFrame = deps.protocol.hostFrame;
686
+ const workerFrame = deps.protocol.workerFrame;
687
+ const logLevel = deps.protocol.logLevel;
688
+ const errorKind = deps.protocol.errorKind;
689
+ /** Wrapper name used to compile a program body (`return …` is legal inside it). */
690
+ const programName = "__ptcProgram";
691
+ let control;
692
+ let started = false;
693
+ let cancelled;
694
+ let nextCallId = 1;
695
+ /** Call frames posted and not yet answered; capped by `maxPendingCalls` (ADR-0004). */
696
+ let inFlightCalls = 0;
697
+ let maxPendingCalls = Number.POSITIVE_INFINITY;
698
+ const admissionWaiters = [];
699
+ const pending = /* @__PURE__ */ new Map();
700
+ const globals = () => globalThis;
701
+ class ToolCallError extends Error {
702
+ toolName;
703
+ constructor(toolName, message) {
704
+ super(message);
705
+ this.name = "ToolCallError";
706
+ this.toolName = toolName;
707
+ }
708
+ }
709
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
710
+ /**
711
+ * Trim a stack down to what a reader can act on.
712
+ *
713
+ * Frames inside the worker bootstrap point at the `data:` URL the worker was spawned
714
+ * from, which is tens of kilobytes of encoded source; dropping those lines and capping
715
+ * the depth keeps the model-facing stack (and the output budget) sane.
716
+ */
717
+ const stackOf = (error) => {
718
+ if (!(error instanceof Error) || typeof error.stack !== "string") return void 0;
719
+ const lines = error.stack.split("\n");
720
+ const kept = [lines[0] ?? ""];
721
+ for (const line of lines.slice(1)) {
722
+ if (line.includes("data:text/javascript")) continue;
723
+ kept.push(line);
724
+ if (kept.length >= 6) break;
725
+ }
726
+ return kept.join("\n");
727
+ };
728
+ const describeValue = (value) => {
729
+ if (value === null) return "null";
730
+ if (Array.isArray(value)) return "an array";
731
+ return `a ${typeof value}`;
732
+ };
733
+ const post = (frame) => {
734
+ if (!control) return false;
735
+ try {
736
+ control.postMessage(frame);
737
+ return true;
738
+ } catch {
739
+ return false;
740
+ }
741
+ };
742
+ const postLog = (level, text) => {
743
+ post({
744
+ kind: workerFrame.log,
745
+ level,
746
+ text
747
+ });
748
+ };
749
+ const postError = (kind, message, stack) => {
750
+ post(stack === void 0 ? {
751
+ kind: workerFrame.error,
752
+ error: {
753
+ kind,
754
+ message
755
+ }
756
+ } : {
757
+ kind: workerFrame.error,
758
+ error: {
759
+ kind,
760
+ message,
761
+ stack
762
+ }
763
+ });
764
+ };
765
+ const abortError = (reason) => {
766
+ const error = /* @__PURE__ */ new Error(reason === "timeout" ? "PTC run timed out" : "PTC run was cancelled");
767
+ error.name = "AbortError";
768
+ return error;
769
+ };
770
+ const closedError = () => {
771
+ const error = /* @__PURE__ */ new Error("the PTC control channel closed before the call completed");
772
+ error.name = "AbortError";
773
+ return error;
774
+ };
775
+ /**
776
+ * Admission control for host binding calls.
777
+ *
778
+ * "Maximum simultaneous host binding calls" is the worker's invariant to keep: a call
779
+ * frame is only posted once fewer than `maxPendingCalls` are outstanding, so a wide
780
+ * `Promise.all` / `parallel()` burst queues here rather than arriving at the host in one
781
+ * tick. The host still counts arrivals as a backstop, but it must never see this budget
782
+ * exceeded by a well-behaved program.
783
+ *
784
+ * Waiting for a slot is cancel-aware: `cancel` and a closed control port reject waiters
785
+ * immediately, so an oversized burst unwinds at once instead of waiting out the grace
786
+ * window before the host terminates the worker.
787
+ */
788
+ const acquireCallSlot = async () => {
789
+ if (inFlightCalls < maxPendingCalls) {
790
+ inFlightCalls += 1;
791
+ return;
792
+ }
793
+ await new Promise((resolve, reject) => {
794
+ admissionWaiters.push({
795
+ resolve,
796
+ reject
797
+ });
798
+ });
799
+ };
800
+ const releaseCallSlot = () => {
801
+ const next = admissionWaiters.shift();
802
+ if (next) {
803
+ next.resolve();
804
+ return;
805
+ }
806
+ inFlightCalls -= 1;
807
+ };
808
+ const rejectAdmissionWaiters = (error) => {
809
+ while (admissionWaiters.length > 0) {
810
+ const waiter = admissionWaiters.shift();
811
+ if (waiter) waiter.reject(error);
812
+ }
813
+ };
814
+ /** Settle every outstanding call and every admission wait, so nothing can hang. */
815
+ const flushPendingCalls = (error) => {
816
+ rejectAdmissionWaiters(error);
817
+ for (const [callId, entry] of pending) {
818
+ pending.delete(callId);
819
+ entry.reject(error);
820
+ }
821
+ };
822
+ /**
823
+ * F3 — reinstall the frozen per-run environment carried in `workerData`.
824
+ *
825
+ * The spawn already passes the same snapshot as the worker's `env` option; rebuilding
826
+ * `process.env` from `workerData` here is what makes the snapshot the authority: the
827
+ * program's environment is the frozen record, never whatever `process.env` happened
828
+ * to hold when a binding call crossed the wire.
829
+ */
830
+ const installFrozenEnv = () => {
831
+ const data = deps.workerData;
832
+ if (typeof data !== "object" || data === null) return;
833
+ const snapshot = data.env;
834
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) return;
835
+ const env = snapshot;
836
+ for (const key of Object.keys(process.env)) if (!(key in env)) delete process.env[key];
837
+ for (const key of Object.keys(env)) {
838
+ const value = env[key];
839
+ if (typeof value === "string") process.env[key] = value;
840
+ }
841
+ };
842
+ /**
843
+ * Lossless-JSON materialization of the program's return value (R1 §3 `invalid-output`).
844
+ *
845
+ * Plain JSON only: class instances, `Date`/`Map`/`Set`, functions, symbols, bigints,
846
+ * non-finite numbers and cycles are rejected with a path-qualified reason instead of
847
+ * being silently lossy through the transport. `undefined` follows `JSON.stringify`:
848
+ * object properties are dropped, array slots become `null`.
849
+ */
850
+ const toJsonValue = (value) => {
851
+ const seen = /* @__PURE__ */ new Set();
852
+ const walk = (candidate, path) => {
853
+ if (candidate === null) return {
854
+ ok: true,
855
+ value: null
856
+ };
857
+ if (typeof candidate === "string" || typeof candidate === "boolean") return {
858
+ ok: true,
859
+ value: candidate
860
+ };
861
+ if (typeof candidate === "undefined") return {
862
+ ok: true,
863
+ value: void 0
864
+ };
865
+ if (typeof candidate === "number") {
866
+ if (!Number.isFinite(candidate)) return {
867
+ ok: false,
868
+ reason: `${path} is ${String(candidate)}, which is not representable as JSON`
869
+ };
870
+ return {
871
+ ok: true,
872
+ value: candidate
873
+ };
874
+ }
875
+ if (typeof candidate !== "object") return {
876
+ ok: false,
877
+ reason: `${path} is ${describeValue(candidate)}; results must be lossless JSON`
878
+ };
879
+ if (Array.isArray(candidate)) {
880
+ if (seen.has(candidate)) return {
881
+ ok: false,
882
+ reason: `${path} is a circular reference`
883
+ };
884
+ seen.add(candidate);
885
+ const items = [];
886
+ for (let index = 0; index < candidate.length; index += 1) {
887
+ const item = walk(candidate[index], `${path}[${index}]`);
888
+ if (!item.ok) return item;
889
+ items.push(item.value === void 0 ? null : item.value);
890
+ }
891
+ seen.delete(candidate);
892
+ return {
893
+ ok: true,
894
+ value: items
895
+ };
896
+ }
897
+ const prototype = Object.getPrototypeOf(candidate);
898
+ if (prototype !== Object.prototype && prototype !== null) {
899
+ const ctor = candidate.constructor;
900
+ return {
901
+ ok: false,
902
+ reason: `${path} is a ${ctor && typeof ctor.name === "string" && ctor.name.length > 0 ? ctor.name : "an object"}; results must be plain JSON objects`
903
+ };
904
+ }
905
+ if (seen.has(candidate)) return {
906
+ ok: false,
907
+ reason: `${path} is a circular reference`
908
+ };
909
+ seen.add(candidate);
910
+ const entries = {};
911
+ for (const key of Object.keys(candidate)) {
912
+ const item = walk(candidate[key], `${path}.${key}`);
913
+ if (!item.ok) return item;
914
+ if (item.value !== void 0) entries[key] = item.value;
915
+ }
916
+ seen.delete(candidate);
917
+ return {
918
+ ok: true,
919
+ value: entries
920
+ };
921
+ };
922
+ return walk(value, "result");
923
+ };
924
+ const formatArgs = (args) => args.map((arg) => typeof arg === "string" ? arg : deps.inspect(arg, {
925
+ depth: 4,
926
+ breakLength: Infinity,
927
+ colors: false
928
+ })).join(" ");
929
+ /**
930
+ * Capture `console` instead of letting worker stdio reach the host terminal.
931
+ *
932
+ * Only the printing methods exist on this surface; everything routes to `log` frames
933
+ * so the model (not the terminal) sees the program's output.
934
+ */
935
+ const installConsole = () => {
936
+ const write = (level) => {
937
+ return (...args) => {
938
+ postLog(level, formatArgs(args));
939
+ };
940
+ };
941
+ globals().console = {
942
+ log: write(logLevel.log),
943
+ info: write(logLevel.info),
944
+ warn: write(logLevel.warn),
945
+ error: write(logLevel.error),
946
+ debug: write(logLevel.debug)
947
+ };
948
+ };
949
+ /**
950
+ * Route `process.emitWarning` output through `log` frames.
951
+ *
952
+ * Node's default warning printer writes to stderr, which is piped to the host terminal.
953
+ * `ExperimentalWarning`s are dropped rather than forwarded: the PTC runtime itself uses
954
+ * experimental Node APIs (type stripping, for one) and those warnings are about the
955
+ * harness, not about the program — forwarding them would put Node-internals noise into
956
+ * every run's logs.
957
+ */
958
+ const installWarningCapture = () => {
959
+ if (typeof process.removeAllListeners !== "function" || typeof process.on !== "function") return;
960
+ process.removeAllListeners("warning");
961
+ process.on("warning", (warning) => {
962
+ const record = typeof warning === "object" && warning !== null ? warning : void 0;
963
+ const name = record && typeof record.name === "string" ? record.name : "Warning";
964
+ if (name === "ExperimentalWarning") return;
965
+ const detail = record && typeof record.message === "string" ? record.message : String(warning);
966
+ postLog(logLevel.warn, `${name}: ${detail}`);
967
+ });
968
+ };
969
+ /**
970
+ * Compile a program body into a callable.
971
+ *
972
+ * The body is wrapped in an async function so `return` and `await` work at the top
973
+ * level, then run through `stripTypeScriptTypes` so the same body may carry type
974
+ * annotations (DSH's "type annotations are advisory, the code runs type-stripped").
975
+ * JavaScript the TypeScript parser rejects falls back to the unstripped source; a
976
+ * genuine syntax error then surfaces from the `Function` constructor instead.
977
+ */
978
+ const compileProgram = (code) => {
979
+ const wrapped = `async function ${programName}() {\n${code}\n}`;
980
+ let source = wrapped;
981
+ try {
982
+ source = deps.stripTypes(wrapped, { mode: "strip" });
983
+ } catch {
984
+ source = wrapped;
985
+ }
986
+ return new Function(`${source}\nreturn ${programName}();`);
987
+ };
988
+ const runProgram = async (code) => {
989
+ let program;
990
+ try {
991
+ program = compileProgram(code);
992
+ } catch (error) {
993
+ postError(errorKind.exception, `program failed to compile: ${messageOf(error)}`, stackOf(error));
994
+ return;
995
+ }
996
+ try {
997
+ const value = await program();
998
+ const normalized = toJsonValue(value);
999
+ if (!normalized.ok) {
1000
+ postError(errorKind.invalidOutput, normalized.reason);
1001
+ return;
1002
+ }
1003
+ post(normalized.value === void 0 ? { kind: workerFrame.result } : {
1004
+ kind: workerFrame.result,
1005
+ value: normalized.value
1006
+ });
1007
+ } catch (error) {
1008
+ postError(cancelled ?? errorKind.exception, messageOf(error), stackOf(error));
1009
+ }
1010
+ };
1011
+ /**
1012
+ * `tools.<name>(args)` — acquire an admission slot, post a call frame, and await the
1013
+ * matching `call-result`.
1014
+ *
1015
+ * The slot is released on every exit path (settled, admission refused by `post`, cancel),
1016
+ * which is what keeps a burst draining instead of deadlocking.
1017
+ */
1018
+ const makeBinding = (name) => {
1019
+ return async (args) => {
1020
+ if (cancelled) throw abortError(cancelled);
1021
+ await acquireCallSlot();
1022
+ try {
1023
+ if (cancelled) throw abortError(cancelled);
1024
+ const callId = nextCallId;
1025
+ nextCallId += 1;
1026
+ const promise = new Promise((resolve, reject) => {
1027
+ pending.set(callId, {
1028
+ resolve,
1029
+ reject
1030
+ });
1031
+ });
1032
+ if (!post({
1033
+ kind: workerFrame.call,
1034
+ callId,
1035
+ tool: name,
1036
+ args
1037
+ })) {
1038
+ pending.delete(callId);
1039
+ throw new ToolCallError(name, `${name}() could not be called: the arguments are not transferable or the run has ended`);
1040
+ }
1041
+ return await promise;
1042
+ } finally {
1043
+ releaseCallSlot();
1044
+ }
1045
+ };
1046
+ };
1047
+ const settleCall = (frame) => {
1048
+ const callId = frame.callId;
1049
+ if (typeof callId !== "number") return;
1050
+ const entry = pending.get(callId);
1051
+ if (!entry) return;
1052
+ pending.delete(callId);
1053
+ if (frame.ok === true) {
1054
+ entry.resolve(frame.value);
1055
+ return;
1056
+ }
1057
+ entry.reject(new ToolCallError(typeof frame.tool === "string" ? frame.tool : "unknown", typeof frame.message === "string" ? frame.message : "binding call failed"));
1058
+ };
1059
+ const cancelPending = (reason) => {
1060
+ cancelled = reason;
1061
+ flushPendingCalls(abortError(reason));
1062
+ };
1063
+ const assertItemCount = (helper, count, maxItemsPerCall) => {
1064
+ if (count > maxItemsPerCall) throw new RangeError(`${helper}() received ${count} items, exceeding maxItemsPerCall (${maxItemsPerCall})`);
1065
+ };
1066
+ const installWorkflowHelpers = (args, maxItemsPerCall) => {
1067
+ const target = globals();
1068
+ target.args = args === void 0 ? null : args;
1069
+ target.log = (message) => {
1070
+ if (typeof message !== "string") throw new TypeError(`log(message) expects a string, received ${describeValue(message)}`);
1071
+ post({
1072
+ kind: workerFrame.narration,
1073
+ message
1074
+ });
1075
+ };
1076
+ target.phase = (title) => {
1077
+ if (typeof title !== "string") throw new TypeError(`phase(title) expects a string, received ${describeValue(title)}`);
1078
+ post({
1079
+ kind: workerFrame.phase,
1080
+ title
1081
+ });
1082
+ };
1083
+ target.parallel = async (thunks) => {
1084
+ if (!Array.isArray(thunks)) throw new TypeError(`parallel(thunks) expects an array of functions, received ${describeValue(thunks)}`);
1085
+ assertItemCount("parallel", thunks.length, maxItemsPerCall);
1086
+ for (let index = 0; index < thunks.length; index += 1) if (typeof thunks[index] !== "function") throw new TypeError(`parallel(thunks) expects functions; item ${index} is ${describeValue(thunks[index])}`);
1087
+ return await Promise.all(thunks.map(async (thunk) => {
1088
+ try {
1089
+ return await thunk();
1090
+ } catch {
1091
+ return null;
1092
+ }
1093
+ }));
1094
+ };
1095
+ target.pipeline = async (items, ...stages) => {
1096
+ if (!Array.isArray(items)) throw new TypeError(`pipeline(items, ...stages) expects an array of items, received ${describeValue(items)}`);
1097
+ assertItemCount("pipeline", items.length, maxItemsPerCall);
1098
+ if (stages.length === 0) throw new TypeError("pipeline(items, ...stages) requires at least one stage function");
1099
+ for (let index = 0; index < stages.length; index += 1) if (typeof stages[index] !== "function") throw new TypeError(`pipeline(items, ...stages) expects stage functions; stage ${index} is ${describeValue(stages[index])}`);
1100
+ const stageFunctions = stages;
1101
+ return await Promise.all(items.map(async (item, index) => {
1102
+ try {
1103
+ let current = item;
1104
+ for (const stage of stageFunctions) current = await stage(current, item, index);
1105
+ return current;
1106
+ } catch {
1107
+ return null;
1108
+ }
1109
+ }));
1110
+ };
1111
+ };
1112
+ const startRun = (frame) => {
1113
+ installFrozenEnv();
1114
+ installConsole();
1115
+ maxPendingCalls = typeof frame.maxPendingCalls === "number" && Number.isFinite(frame.maxPendingCalls) && frame.maxPendingCalls > 0 ? frame.maxPendingCalls : Number.POSITIVE_INFINITY;
1116
+ const tools = {};
1117
+ const bindingNames = Array.isArray(frame.bindings) ? frame.bindings.filter((name) => typeof name === "string") : [];
1118
+ for (const name of bindingNames) tools[name] = makeBinding(name);
1119
+ const available = bindingNames.join(", ") || "(none)";
1120
+ const candidates = Array.isArray(frame.bindingCandidates) ? frame.bindingCandidates : [];
1121
+ for (const name of candidates) {
1122
+ if (typeof name !== "string" || tools[name]) continue;
1123
+ tools[name] = async () => {
1124
+ throw new ToolCallError(name, `no binding named "${name}" in this run; available bindings: ${available}`);
1125
+ };
1126
+ }
1127
+ globals().tools = tools;
1128
+ if (frame.surface === "workflow") {
1129
+ const maxItemsPerCall = typeof frame.maxItemsPerCall === "number" ? frame.maxItemsPerCall : 0;
1130
+ installWorkflowHelpers(frame.args, maxItemsPerCall);
1131
+ }
1132
+ runProgram(typeof frame.code === "string" ? frame.code : "");
1133
+ };
1134
+ const handleHostFrame = (raw) => {
1135
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return;
1136
+ const frame = raw;
1137
+ if (frame.kind === hostFrame.init) {
1138
+ if (started) return;
1139
+ started = true;
1140
+ startRun(frame);
1141
+ return;
1142
+ }
1143
+ if (frame.kind === hostFrame.callResult) {
1144
+ settleCall(frame);
1145
+ return;
1146
+ }
1147
+ if (frame.kind === hostFrame.cancel) cancelPending(frame.reason === "timeout" ? "timeout" : "abort");
1148
+ };
1149
+ deps.parentPort.on("message", (value) => {
1150
+ if (typeof value !== "object" || value === null) return;
1151
+ const frame = value;
1152
+ if (frame.kind !== hostFrame.connect) return;
1153
+ const port = frame.port;
1154
+ if (typeof port !== "object" || port === null || typeof port.on !== "function") return;
1155
+ control = port;
1156
+ control.on("message", handleHostFrame);
1157
+ control.on("close", () => {
1158
+ flushPendingCalls(closedError());
1159
+ });
1160
+ installWarningCapture();
1161
+ post({ kind: workerFrame.ready });
1162
+ });
1163
+ }
1164
+ //#endregion
1165
+ //#region src/runtime/worker-source.ts
1166
+ /** Build the worker module source for one spawn. */
1167
+ function buildWorkerSource(protocol) {
1168
+ return [
1169
+ `import { parentPort, workerData } from "node:worker_threads";`,
1170
+ `import { inspect } from "node:util";`,
1171
+ `import { stripTypeScriptTypes } from "node:module";`,
1172
+ `const ptcDeps = ${JSON.stringify({ protocol })};`,
1173
+ `(${workerMain.toString()})({ ...ptcDeps, parentPort, workerData, inspect, stripTypes: stripTypeScriptTypes });`
1174
+ ].join("\n");
1175
+ }
1176
+ /** The worker entry as a `data:` module URL, ready for `new Worker(url, options)`. */
1177
+ function buildWorkerUrl(protocol) {
1178
+ return new URL(`data:text/javascript,${encodeURIComponent(buildWorkerSource(protocol))}`);
1179
+ }
1180
+ //#endregion
1181
+ //#region src/runtime/dispatcher.ts
1182
+ /**
1183
+ * Host-side dispatcher: one `runPtcProgram()` call = one worker = one program.
1184
+ *
1185
+ * Responsibilities:
1186
+ * - spawn a hardened worker (F1 env scrub, F2 V8 caps, F3 frozen per-run env in
1187
+ * `workerData`, F4 `cwd` carried in the run config and handed to the bindings),
1188
+ * - complete the `MessageChannel` handshake and send the `init` frame,
1189
+ * - route `tools.*` calls to the binding table — concurrently, with DSH's
1190
+ * `maxParallelSubCalls` forwarding cap and `maxPendingCalls` admission control,
1191
+ * - collect logs / narration / phases and enforce the joint output budget,
1192
+ * - enforce the deadline, honour caller cancellation, and always tear the worker down.
1193
+ *
1194
+ * Everything the worker can influence is treated as untrusted input: every frame goes
1195
+ * through the protocol guards, is size-checked, and can only ever end the run.
1196
+ */
1197
+ function messageOf(error) {
1198
+ return error instanceof Error ? error.message : String(error);
1199
+ }
1200
+ /** Serialized byte size of a frame, the unit both the output and message budgets use. */
1201
+ function serializedBytes(value) {
1202
+ try {
1203
+ return Buffer.byteLength(JSON.stringify(value) ?? "", "utf8");
1204
+ } catch {
1205
+ return Number.POSITIVE_INFINITY;
1206
+ }
1207
+ }
1208
+ /**
1209
+ * Run one PTC program in a fresh worker and resolve with its outcome.
1210
+ *
1211
+ * Never rejects for program/ limit / cancellation failures — those are reported as
1212
+ * `outcome.error` so callers have one place to render from. It only throws on caller bugs
1213
+ * (invalid config overrides).
1214
+ */
1215
+ async function runPtcProgram(options) {
1216
+ const config = resolveConfig(options.config);
1217
+ const protocol = workerProtocolSpec();
1218
+ const env = createWorkerEnv();
1219
+ const runId = options.runId ?? randomUUID();
1220
+ const timeoutMs = effectiveTimeoutMs(options.timeoutMs, config);
1221
+ const logs = [];
1222
+ const narrations = [];
1223
+ const phases = [];
1224
+ if (options.signal?.aborted) return {
1225
+ logs,
1226
+ narrations,
1227
+ phases,
1228
+ error: {
1229
+ kind: PTC_ERROR_KIND.abort,
1230
+ message: "run cancelled before start"
1231
+ }
1232
+ };
1233
+ return await new Promise((resolve) => {
1234
+ const worker = new Worker(buildWorkerUrl(protocol), {
1235
+ name: `ptc-${options.surface}`,
1236
+ env,
1237
+ workerData: {
1238
+ runId,
1239
+ env
1240
+ },
1241
+ resourceLimits: {
1242
+ maxOldGenerationSizeMb: config.maxOldGenerationSizeMb,
1243
+ maxYoungGenerationSizeMb: config.maxYoungGenerationSizeMb
1244
+ }
1245
+ });
1246
+ const channel = new MessageChannel();
1247
+ const control = channel.port1;
1248
+ const workerPort = channel.port2;
1249
+ const bindingAbort = new AbortController();
1250
+ let settled = false;
1251
+ let cancelling;
1252
+ let pendingCalls = 0;
1253
+ let outputBytes = 0;
1254
+ let activeDispatches = 0;
1255
+ const dispatchWaiters = [];
1256
+ const runDepth = 0;
1257
+ let runTimer;
1258
+ let graceTimer;
1259
+ const images = [];
1260
+ /**
1261
+ * Hoist the images out of one successful binding result.
1262
+ *
1263
+ * DSH does this in its scheduler's commit step: a subtool result whose content carries an image
1264
+ * block has that content attached to the caller's context after the run, so the picture reaches
1265
+ * the model without travelling through the program's lossless-JSON return value (`dsh-tools`:
1266
+ * `exec.deferContext(createUserMessage(...))`). The host sees every binding result before it is
1267
+ * posted to the worker, so this is the same seam.
1268
+ *
1269
+ * Everything is hoisted: no count cap, no byte cap, no dedupe. How much context a run spends on
1270
+ * images is the program's call, and hiding a cap behind a warning would make this layer a
1271
+ * gatekeeper DSH does not have. pi's per-model resize (`inputLimits.images.resize`) still bounds
1272
+ * what a single attachment costs at the provider.
1273
+ */
1274
+ const hoistImages = (value) => {
1275
+ const content = value?.content;
1276
+ if (!Array.isArray(content)) return;
1277
+ for (const block of content) {
1278
+ if (block === null || typeof block !== "object") continue;
1279
+ const candidate = block;
1280
+ if (candidate.type !== "image") continue;
1281
+ const data = typeof candidate.data === "string" ? candidate.data : "";
1282
+ if (data.length === 0) continue;
1283
+ images.push({
1284
+ data,
1285
+ mimeType: typeof candidate.mimeType === "string" ? candidate.mimeType : "application/octet-stream"
1286
+ });
1287
+ }
1288
+ };
1289
+ const cancelMessage = (reason) => reason === "timeout" ? `run timed out after ${timeoutMs} ms` : "run cancelled";
1290
+ const finish = (outcome) => {
1291
+ if (settled) return;
1292
+ settled = true;
1293
+ if (runTimer) clearTimeout(runTimer);
1294
+ if (graceTimer) clearTimeout(graceTimer);
1295
+ options.signal?.removeEventListener("abort", onAbortSignal);
1296
+ bindingAbort.abort();
1297
+ control.close();
1298
+ worker.terminate();
1299
+ resolve(outcome);
1300
+ };
1301
+ const fail = (kind, message, stack) => {
1302
+ finish({
1303
+ logs,
1304
+ narrations,
1305
+ phases,
1306
+ error: stack === void 0 ? {
1307
+ kind,
1308
+ message
1309
+ } : {
1310
+ kind,
1311
+ message,
1312
+ stack
1313
+ }
1314
+ });
1315
+ };
1316
+ const sendControl = (frame) => {
1317
+ if (settled) return;
1318
+ if (!isPtcHostFrame(frame)) {
1319
+ fail(PTC_ERROR_KIND.protocol, "internal error: malformed host frame");
1320
+ return;
1321
+ }
1322
+ control.postMessage(frame);
1323
+ };
1324
+ const sendInit = () => {
1325
+ const frame = {
1326
+ kind: HOST_FRAME_KIND.init,
1327
+ runId,
1328
+ surface: options.surface,
1329
+ code: options.code,
1330
+ bindings: [...options.bindings.keys()],
1331
+ bindingCandidates: [...BUILTIN_BINDING_NAMES],
1332
+ maxItemsPerCall: config.maxItemsPerCall,
1333
+ maxPendingCalls: config.maxPendingCalls,
1334
+ ...options.args === void 0 ? {} : { args: options.args }
1335
+ };
1336
+ if (!isPtcHostFrame(frame)) {
1337
+ fail(PTC_ERROR_KIND.protocol, "internal error: malformed init frame");
1338
+ return;
1339
+ }
1340
+ const bytes = serializedBytes(frame);
1341
+ if (bytes > config.maxMessageBytes) {
1342
+ fail(PTC_ERROR_KIND.protocol, `init frame of ${bytes} bytes exceeds maxMessageBytes (${config.maxMessageBytes})`);
1343
+ return;
1344
+ }
1345
+ sendControl(frame);
1346
+ };
1347
+ const accountOutput = (bytes, source) => {
1348
+ outputBytes += bytes;
1349
+ if (outputBytes <= config.maxOutputBytes) return true;
1350
+ fail(PTC_ERROR_KIND.outputLimit, `${source} exceeded the output budget: logs + result reached ${outputBytes} bytes (maxOutputBytes=${config.maxOutputBytes}); ${logs.length} log line(s) retained`);
1351
+ return false;
1352
+ };
1353
+ const acquireDispatchSlot = async () => {
1354
+ if (activeDispatches < config.maxParallelSubCalls) {
1355
+ activeDispatches += 1;
1356
+ return;
1357
+ }
1358
+ await new Promise((slot) => {
1359
+ dispatchWaiters.push(slot);
1360
+ });
1361
+ };
1362
+ const releaseDispatchSlot = () => {
1363
+ const next = dispatchWaiters.shift();
1364
+ if (next) {
1365
+ next();
1366
+ return;
1367
+ }
1368
+ activeDispatches -= 1;
1369
+ };
1370
+ const handleCall = (frame) => {
1371
+ pendingCalls += 1;
1372
+ if (pendingCalls > config.maxPendingCalls) {
1373
+ fail(PTC_ERROR_KIND.protocol, `more than maxPendingCalls (${config.maxPendingCalls}) binding calls in flight`);
1374
+ return;
1375
+ }
1376
+ dispatchCall(frame).finally(() => {
1377
+ pendingCalls -= 1;
1378
+ });
1379
+ };
1380
+ const dispatchCall = async (frame) => {
1381
+ const binding = options.bindings.get(frame.tool);
1382
+ if (!binding) {
1383
+ postCallResult({
1384
+ kind: HOST_FRAME_KIND.callResult,
1385
+ callId: frame.callId,
1386
+ tool: frame.tool,
1387
+ ok: false,
1388
+ message: `no binding named "${frame.tool}" in this run; available bindings: ` + ([...options.bindings.keys()].join(", ") || "(none)")
1389
+ });
1390
+ return;
1391
+ }
1392
+ await acquireDispatchSlot();
1393
+ if (settled) {
1394
+ releaseDispatchSlot();
1395
+ return;
1396
+ }
1397
+ try {
1398
+ const value = await binding.execute(frame.args, {
1399
+ signal: bindingAbort.signal,
1400
+ callId: frame.callId,
1401
+ depth: runDepth,
1402
+ maxDispatchDepth: config.maxDispatchDepth
1403
+ });
1404
+ if (postCallResult({
1405
+ kind: HOST_FRAME_KIND.callResult,
1406
+ callId: frame.callId,
1407
+ tool: frame.tool,
1408
+ ok: true,
1409
+ value
1410
+ })) hoistImages(value);
1411
+ } catch (error) {
1412
+ postCallResult({
1413
+ kind: HOST_FRAME_KIND.callResult,
1414
+ callId: frame.callId,
1415
+ tool: frame.tool,
1416
+ ok: false,
1417
+ message: messageOf(error)
1418
+ });
1419
+ } finally {
1420
+ releaseDispatchSlot();
1421
+ }
1422
+ };
1423
+ /** `true` when the worker actually received the result (see the hoist at the call site). */
1424
+ const postCallResult = (frame) => {
1425
+ if (settled) return false;
1426
+ try {
1427
+ control.postMessage(frame);
1428
+ return true;
1429
+ } catch (error) {
1430
+ try {
1431
+ control.postMessage({
1432
+ kind: HOST_FRAME_KIND.callResult,
1433
+ callId: frame.callId,
1434
+ tool: frame.tool,
1435
+ ok: false,
1436
+ message: `binding result could not be transferred: ${messageOf(error)}`
1437
+ });
1438
+ } catch {
1439
+ fail(PTC_ERROR_KIND.protocol, "binding result is not transferable");
1440
+ }
1441
+ return false;
1442
+ }
1443
+ };
1444
+ const settleTerminal = (outcome) => {
1445
+ if (!cancelling) return outcome;
1446
+ return {
1447
+ logs,
1448
+ narrations,
1449
+ phases,
1450
+ error: {
1451
+ kind: cancelling === "timeout" ? PTC_ERROR_KIND.timeout : PTC_ERROR_KIND.abort,
1452
+ message: cancelMessage(cancelling)
1453
+ }
1454
+ };
1455
+ };
1456
+ const handleFrame = (frame) => {
1457
+ if (settled) return;
1458
+ if (!isPtcWorkerFrame(frame)) {
1459
+ fail(PTC_ERROR_KIND.protocol, "malformed worker frame");
1460
+ return;
1461
+ }
1462
+ const bytes = frame.kind === WORKER_FRAME_KIND.ready ? 0 : serializedBytes(frame);
1463
+ if (!Number.isFinite(bytes)) {
1464
+ fail(PTC_ERROR_KIND.protocol, "worker frame could not be serialized for accounting");
1465
+ return;
1466
+ }
1467
+ if (bytes > config.maxMessageBytes) {
1468
+ fail(PTC_ERROR_KIND.protocol, `control frame of ${bytes} bytes exceeds maxMessageBytes (${config.maxMessageBytes})`);
1469
+ return;
1470
+ }
1471
+ switch (frame.kind) {
1472
+ case WORKER_FRAME_KIND.ready:
1473
+ sendInit();
1474
+ return;
1475
+ case WORKER_FRAME_KIND.call:
1476
+ handleCall(frame);
1477
+ return;
1478
+ case WORKER_FRAME_KIND.log:
1479
+ if (accountOutput(bytes, "console output")) logs.push(frame.text);
1480
+ return;
1481
+ case WORKER_FRAME_KIND.narration:
1482
+ if (accountOutput(bytes, "workflow narration")) narrations.push(frame.message);
1483
+ return;
1484
+ case WORKER_FRAME_KIND.phase:
1485
+ if (accountOutput(bytes, "workflow phase")) phases.push(frame.title);
1486
+ return;
1487
+ case WORKER_FRAME_KIND.result: {
1488
+ if (!accountOutput(bytes, "completion value")) return;
1489
+ const base = {
1490
+ logs,
1491
+ narrations,
1492
+ phases,
1493
+ ...images.length > 0 ? { images } : {}
1494
+ };
1495
+ finish(settleTerminal(frame.value === void 0 ? base : {
1496
+ ...base,
1497
+ value: frame.value
1498
+ }));
1499
+ return;
1500
+ }
1501
+ case WORKER_FRAME_KIND.error:
1502
+ finish(settleTerminal({
1503
+ logs,
1504
+ narrations,
1505
+ phases,
1506
+ error: frame.error
1507
+ }));
1508
+ return;
1509
+ default: fail(PTC_ERROR_KIND.protocol, "unknown worker frame");
1510
+ }
1511
+ };
1512
+ function onAbortSignal() {
1513
+ beginCancel("abort");
1514
+ }
1515
+ function beginCancel(reason) {
1516
+ if (settled || cancelling) return;
1517
+ cancelling = reason;
1518
+ if (runTimer) {
1519
+ clearTimeout(runTimer);
1520
+ runTimer = void 0;
1521
+ }
1522
+ bindingAbort.abort();
1523
+ sendControl({
1524
+ kind: HOST_FRAME_KIND.cancel,
1525
+ reason
1526
+ });
1527
+ graceTimer = setTimeout(() => {
1528
+ fail(reason === "timeout" ? PTC_ERROR_KIND.timeout : PTC_ERROR_KIND.abort, cancelMessage(reason));
1529
+ }, config.graceMs);
1530
+ }
1531
+ worker.on("error", (error) => {
1532
+ fail(PTC_ERROR_KIND.workerExit, `worker failed: ${messageOf(error)}`);
1533
+ });
1534
+ worker.on("exit", (code) => {
1535
+ fail(PTC_ERROR_KIND.workerExit, `worker exited with code ${code} before the run completed`);
1536
+ });
1537
+ control.on("message", handleFrame);
1538
+ control.on("messageerror", () => {
1539
+ fail(PTC_ERROR_KIND.protocol, "worker sent a frame that could not be deserialized");
1540
+ });
1541
+ options.signal?.addEventListener("abort", onAbortSignal, { once: true });
1542
+ runTimer = setTimeout(() => {
1543
+ beginCancel("timeout");
1544
+ }, timeoutMs);
1545
+ const connectFrame = {
1546
+ kind: HOST_FRAME_KIND.connect,
1547
+ port: workerPort
1548
+ };
1549
+ if (!isPtcHostFrame(connectFrame)) fail(PTC_ERROR_KIND.protocol, "internal error: malformed connect frame");
1550
+ else worker.postMessage(connectFrame, [workerPort]);
1551
+ });
1552
+ }
1553
+ //#endregion
1554
+ //#region src/tools/text.ts
1555
+ /** Hard cap for one rendered line; longer lines are truncated with `…`. */
1556
+ const MAX_LINE_CHARS = 200;
1557
+ /** A value stays on one line while its inline form fits this; otherwise it renders as a block. */
1558
+ const INLINE_MAX_CHARS = 100;
1559
+ /** Indent applied per nesting level in block form. */
1560
+ const INDENT = " ";
1561
+ /**
1562
+ * ANSI escapes, in the two shapes that matter: OSC (\`ESC ] …\` to BEL, \`ESC \\\\` or C1 ST) and
1563
+ * CSI plus friends (introducer, optional intermediates, optional params, final byte).
1564
+ *
1565
+ * Built through the \`RegExp\` constructor from an escaped source so no control character appears
1566
+ * literally — the repo lints via oxlint, whose \`no-control-regex\` rule rejects that.
1567
+ */
1568
+ const ANSI_PATTERN = new RegExp(["(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))", "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]"].join("|"), "g");
1569
+ /** Drop ANSI escape sequences (colours, cursor moves, OSC hyperlinks). */
1570
+ function stripAnsi(value) {
1571
+ if (!value.includes(String.fromCharCode(27)) && !value.includes(String.fromCharCode(155))) return value;
1572
+ return value.replace(ANSI_PATTERN, "");
1573
+ }
1574
+ /**
1575
+ * Make arbitrary program output safe to hand the model.
1576
+ *
1577
+ * Same three steps as pi's built-ins: strip ANSI, remove `\r` (a progress bar's carriage
1578
+ * return is not a line break), then drop control characters other than `\n`/`\t` and the
1579
+ * Unicode format characters that break width math. Lone surrogates fall out of code-point
1580
+ * iteration for free.
1581
+ */
1582
+ function sanitizeText(value) {
1583
+ const stripped = stripAnsi(value).replace(/\r/g, "");
1584
+ if (stripped.length === 0) return stripped;
1585
+ let out = "";
1586
+ for (const char of stripped) {
1587
+ const code = char.codePointAt(0);
1588
+ if (code === void 0) continue;
1589
+ if (code === 10 || code === 9) {
1590
+ out += char;
1591
+ continue;
1592
+ }
1593
+ if (code <= 31) continue;
1594
+ if (code >= 65529 && code <= 65531) continue;
1595
+ out += char;
1596
+ }
1597
+ return out;
1598
+ }
1599
+ /** Object keys that read as identifiers in the summary style are left unquoted. */
1600
+ const BARE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
1601
+ function keyText(key) {
1602
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
1603
+ }
1604
+ /**
1605
+ * The inline form of a value, or `undefined` when it cannot be inlined.
1606
+ *
1607
+ * A string with a real newline is never inlined: keeping its line structure is the whole point
1608
+ * (see ADR-0012), and quoting it would turn one readable block back into `\n` escapes.
1609
+ */
1610
+ function inlineForm(value) {
1611
+ if (value === null) return "null";
1612
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1613
+ if (typeof value === "string") {
1614
+ const sanitized = sanitizeText(value);
1615
+ return sanitized.includes("\n") ? void 0 : JSON.stringify(sanitized);
1616
+ }
1617
+ if (Array.isArray(value)) {
1618
+ const items = [];
1619
+ for (const item of value) {
1620
+ const rendered = inlineForm(item);
1621
+ if (rendered === void 0) return void 0;
1622
+ items.push(rendered);
1623
+ }
1624
+ return `[${items.join(", ")}]`;
1625
+ }
1626
+ const keys = Object.keys(value);
1627
+ if (keys.length === 0) return "{}";
1628
+ const parts = [];
1629
+ for (const key of keys) {
1630
+ const rendered = inlineForm(value[key] ?? null);
1631
+ if (rendered === void 0) return void 0;
1632
+ parts.push(`${keyText(key)}: ${rendered}`);
1633
+ }
1634
+ return `{${parts.join(", ")}}`;
1635
+ }
1636
+ /** Inline rendering, but only while it stays short enough to read on one line. */
1637
+ function tryInline(value) {
1638
+ const rendered = inlineForm(value);
1639
+ if (rendered === void 0) return void 0;
1640
+ return rendered.length <= INLINE_MAX_CHARS ? rendered : void 0;
1641
+ }
1642
+ /** A non-container value on its own line (block form only meets these defensively). */
1643
+ function scalarText(value) {
1644
+ if (value === null) return "null";
1645
+ return typeof value === "string" ? sanitizeText(value) : String(value);
1646
+ }
1647
+ /** One key per line, braces kept, string values raw (real newlines preserved, indented). */
1648
+ function blockLines(value, indent) {
1649
+ if (value === null || typeof value !== "object") return [`${indent}${scalarText(value)}`];
1650
+ if (Array.isArray(value)) {
1651
+ if (value.length === 0) return [`${indent}[]`];
1652
+ const lines = [`${indent}[`];
1653
+ for (const item of value) {
1654
+ const inline = tryInline(item);
1655
+ if (inline !== void 0) {
1656
+ lines.push(`${indent}${INDENT}${inline}`);
1657
+ continue;
1658
+ }
1659
+ lines.push(...valueLines(item, indent + INDENT));
1660
+ }
1661
+ lines.push(`${indent}]`);
1662
+ return lines;
1663
+ }
1664
+ const keys = Object.keys(value);
1665
+ if (keys.length === 0) return [`${indent}{}`];
1666
+ const lines = [`${indent}{`];
1667
+ const inner = indent + INDENT;
1668
+ for (const key of keys) {
1669
+ const child = value[key] ?? null;
1670
+ const inline = tryInline(child);
1671
+ if (inline !== void 0) {
1672
+ lines.push(`${inner}${keyText(key)}: ${inline}`);
1673
+ continue;
1674
+ }
1675
+ if (typeof child === "string") {
1676
+ lines.push(`${inner}${keyText(key)}:`);
1677
+ for (const line of sanitizeText(child).split("\n")) lines.push(line.length === 0 ? "" : `${inner}${INDENT}${line}`);
1678
+ continue;
1679
+ }
1680
+ const nested = blockLines(child, inner);
1681
+ lines.push(`${inner}${keyText(key)}: ${(nested[0] ?? "").trimStart()}`.trimEnd(), ...nested.slice(1));
1682
+ }
1683
+ lines.push(`${indent}}`);
1684
+ return lines;
1685
+ }
1686
+ function valueLines(value, indent) {
1687
+ if (typeof value === "string") return sanitizeText(value).split("\n");
1688
+ if (value === null || typeof value !== "object") return [String(value)];
1689
+ return blockLines(value, indent);
1690
+ }
1691
+ /** Truncate every line that exceeds {@link MAX_LINE_CHARS}. */
1692
+ function capLines(text) {
1693
+ return text.split("\n").map((line) => line.length > 200 ? `${line.slice(0, 199)}…` : line).join("\n");
1694
+ }
1695
+ /**
1696
+ * Render a completion value for the model: strings verbatim, everything else as a compact
1697
+ * `{key: value}` summary or an indented block — never `JSON.stringify` on the whole value, whose
1698
+ * escaping destroys exactly the content a reader needs (newlines, quotes, non-ASCII spacing).
1699
+ */
1700
+ function renderModelValue(value) {
1701
+ if (typeof value === "string") return capLines(sanitizeText(value));
1702
+ if (value === null || typeof value !== "object") return String(value);
1703
+ const inline = tryInline(value);
1704
+ return capLines((inline !== void 0 ? [inline] : valueLines(value, "")).join("\n"));
1705
+ }
1706
+ //#endregion
1707
+ //#region src/tools/common.ts
1708
+ /**
1709
+ * Shared plumbing for the two model-facing PTC tools (`ptc_run_code`, `ptc_workflow`).
1710
+ *
1711
+ * Both tools are thin. They resolve the run's working directory, hand the program to
1712
+ * `runPtcProgram()` (T3), and turn the dispatcher's outcome into one of pi's two tool-result
1713
+ * shapes:
1714
+ *
1715
+ * - **success** — `content` carries one text block (logs, workflow narration, phases, then the
1716
+ * completion value) and `details` carries the same facts structurally for rendering and logs;
1717
+ * - **failure** — the tool *throws* (pi's convention: `AgentTool.execute` — "Throw on failure
1718
+ * instead of encoding errors in `content`"), with R1 §3's message shape
1719
+ * `code run failed (<kind>): <message>` plus a `Captured output:` block.
1720
+ *
1721
+ * The dispatcher never rejects for program failures — it reports them as `outcome.error` — so
1722
+ * "did the run fail" is one check in one place, shared by both tools.
1723
+ *
1724
+ * The text block is the model's copy, so it is cleaned and laid out for reading (`./text.ts`:
1725
+ * ANSI stripped, control characters dropped, strings with real newlines kept multi-line) while
1726
+ * `details` stays raw for the TUI. See ADR-0012.
1727
+ */
1728
+ /**
1729
+ * Binding names for one run: the built-ins this session actually has enabled (T7, #21).
1730
+ *
1731
+ * A PTC program must never reach further than the session it runs in — a session started
1732
+ * with `--tools read` or `--no-builtin-tools` must not be escapable through `tools.<name>`
1733
+ * calls. Names outside the built-in factory set are ignored: only tools this package can
1734
+ * build adapters for can be bound.
1735
+ */
1736
+ function resolveBindingNames(activeToolNames) {
1737
+ if (activeToolNames === void 0) return BUILTIN_BINDING_NAMES;
1738
+ const active = new Set(activeToolNames);
1739
+ return BUILTIN_BINDING_NAMES.filter((name) => active.has(name));
1740
+ }
1741
+ /**
1742
+ * One-line entry for the system prompt's "Available tools" section.
1743
+ *
1744
+ * Custom tools are omitted from that section unless they set this, which matters most in PTC mode:
1745
+ * there the two PTC surfaces are the *only* callable tools, so a prompt that lists no usable tool
1746
+ * would contradict the tool declarations. `promptGuidelines` cannot substitute for it — those
1747
+ * bullets land in the flat `Guidelines` section, which does not tell the model what it can call.
1748
+ */
1749
+ const PTC_RUN_CODE_SNIPPET = "Run a TypeScript program that composes pi's tools in one shot (tools.<name>(args)); only its return value and console.log come back";
1750
+ const PTC_WORKFLOW_SNIPPET = "Run a structured TypeScript workflow with named phases, narration (log/phase) and structured concurrency (parallel/pipeline)";
1751
+ /**
1752
+ * Guidelines are appended flat to the `Guidelines` section with no tool-name prefix, so each bullet
1753
+ * must name its tool explicitly (pi's docs call this out; "Use this tool when…" is ambiguous).
1754
+ * These are the normal-mode hints — in PTC mode the injected briefing supersedes them.
1755
+ */
1756
+ const PTC_TOOL_GUIDELINES = [
1757
+ "Image-bearing tool results inside a program (a `tools.read` on a PNG, say) are attached to you after the run — never return image data as the completion value.",
1758
+ "Use ptc_run_code when a task needs several tool calls whose intermediate output you do not need to see — gather it inside the program and return only the final value.",
1759
+ "Use ptc_workflow instead of ptc_run_code when the work has named phases and the user benefits from seeing progress narration."
1760
+ ];
1761
+ /** Tool name per worker surface — the names the model calls and reads in failure messages. */
1762
+ const SURFACE_TOOL_NAME = {
1763
+ run_code: "ptc_run_code",
1764
+ workflow: "ptc_workflow"
1765
+ };
1766
+ /**
1767
+ * Resolve the run's working directory from pi's tool execution context.
1768
+ *
1769
+ * Investigated against `@earendil-works/pi-coding-agent@0.86.1`: `execute`'s fifth parameter is
1770
+ * `ExtensionContext`, and the type *does* expose `cwd: string` — documented there as "Current
1771
+ * working directory" (`dist/core/extensions/types.d.ts`), the same value pi's own built-in tools
1772
+ * resolve relative paths against (`ToolRenderContext.cwd`, and the extension guide's
1773
+ * `resolve(ctx.cwd, params.path)` pattern). So the session cwd comes from pi, and this package
1774
+ * never has to guess from `process.cwd()`.
1775
+ *
1776
+ * The `process.cwd()` fallback stays for hand-built contexts (tests, or a future caller passing a
1777
+ * partial object); pi always supplies the field.
1778
+ */
1779
+ function resolveToolCwd(ctx) {
1780
+ const cwd = ctx?.cwd;
1781
+ return typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd();
1782
+ }
1783
+ /**
1784
+ * The captured-output lines R1 §3 appends when a run fails.
1785
+ *
1786
+ * Phases and narrations are prefixed because they are workflow bookkeeping rather than console
1787
+ * output; `ptc_run_code` has neither, so its block is exactly the `logs` join R1 describes.
1788
+ */
1789
+ function capturedOutputLines(outcome) {
1790
+ return [
1791
+ ...outcome.phases.map((title) => `[phase] ${sanitizeText(title)}`),
1792
+ ...outcome.narrations.map((message) => `[log] ${sanitizeText(message)}`),
1793
+ ...outcome.logs.map((line) => sanitizeText(line))
1794
+ ];
1795
+ }
1796
+ /**
1797
+ * Build the error a failed run is surfaced with (R1 §3's `CodeRunFailedError` message).
1798
+ *
1799
+ * The model must be able to fix its program from this message alone: the error kind and message
1800
+ * explain what broke, and the captured output shows how far the program got before it did. There
1801
+ * is no `sandbox` text and no escalation guidance — ADR-0007 ships no OS sandbox, so the only
1802
+ * failure classes are the protocol ones.
1803
+ */
1804
+ function codeRunFailedError(outcome) {
1805
+ const error = outcome.error;
1806
+ if (error === void 0) return /* @__PURE__ */ new Error("internal error: a successful PTC run was rendered as a failure");
1807
+ const captured = capturedOutputLines(outcome);
1808
+ const block = captured.length === 0 ? "" : `\nCaptured output:\n${captured.join("\n")}`;
1809
+ const failure = new Error(sanitizeText(`code run failed (${error.kind}): ${error.message}${block}`));
1810
+ failure.name = "CodeRunFailedError";
1811
+ return failure;
1812
+ }
1813
+ /**
1814
+ * Write the untruncated text block to a temp file and return its path.
1815
+ *
1816
+ * Mirrors what pi's own `bash` does with a long output (its `fullOutputPath`): the run is the only
1817
+ * place the text ever existed, so a file under the OS temp dir is the difference between "the rest is
1818
+ * gone" and "the rest is one `tools.read` away".
1819
+ */
1820
+ function writeFullOutput(text) {
1821
+ const filePath = join(tmpdir(), `pi-ptc-output-${randomUUID()}.txt`);
1822
+ writeFileSync(filePath, text, "utf8");
1823
+ return filePath;
1824
+ }
1825
+ /**
1826
+ * The `[Showing … Full output: path]` footer pi's built-ins use, worded for the same numbers.
1827
+ *
1828
+ * `truncatedBy` decides the wording: a line cut reports the line range, a byte cut also names the
1829
+ * ceiling, and a single oversized last line reports its own size — exactly what `bash` prints.
1830
+ */
1831
+ function truncationFooter(truncation, fullOutputPath) {
1832
+ const startLine = truncation.totalLines - truncation.outputLines + 1;
1833
+ const endLine = truncation.totalLines;
1834
+ if (truncation.lastLinePartial) return `[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine}. Full output: ${fullOutputPath}]`;
1835
+ if (truncation.truncatedBy === "lines") return `[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${fullOutputPath}]`;
1836
+ return `[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${fullOutputPath}]`;
1837
+ }
1838
+ /**
1839
+ * Render one successful outcome as pi's tool result.
1840
+ *
1841
+ * `content` is ordered the way a reader reconstructs the run: the phase roll-up, then workflow
1842
+ * narration, then console output, then the completion value, then warnings. Empty runs get R1's
1843
+ * placeholder (`(run_code completed with no output)`) so the model always sees a non-empty text
1844
+ * block — a tool result with nothing in it looks like a harness failure.
1845
+ *
1846
+ * `details` is deliberately the *uncleaned* copy: logs keep their ANSI so the TUI can still
1847
+ * colour them, and `result` stays structured for `render.ts`.
1848
+ */
1849
+ function renderToolResult(input) {
1850
+ const { outcome, surface } = input;
1851
+ const warnings = [...input.warnings ?? []];
1852
+ const images = outcome.images ?? [];
1853
+ const parts = [];
1854
+ if (outcome.phases.length > 0) parts.push(`Phases: ${outcome.phases.map((title) => sanitizeText(title)).join(" → ")}`);
1855
+ if (outcome.narrations.length > 0) parts.push(outcome.narrations.map((message) => sanitizeText(message)).join("\n"));
1856
+ if (outcome.logs.length > 0) parts.push(outcome.logs.map((line) => sanitizeText(line)).join("\n"));
1857
+ if (outcome.value !== void 0) parts.push(renderModelValue(outcome.value));
1858
+ for (const warning of warnings) parts.push(`Warning: ${sanitizeText(warning)}`);
1859
+ const built = parts.length > 0 ? parts.join("\n") : `(${SURFACE_TOOL_NAME[surface]} completed with no output)`;
1860
+ const truncation = truncateTail(built, {
1861
+ maxLines: DEFAULT_MAX_LINES,
1862
+ maxBytes: DEFAULT_MAX_BYTES
1863
+ });
1864
+ let fullOutputPath;
1865
+ let text = truncation.content;
1866
+ if (truncation.truncated) {
1867
+ fullOutputPath = writeFullOutput(built);
1868
+ text += `\n\n${truncationFooter(truncation, fullOutputPath)}`;
1869
+ }
1870
+ return {
1871
+ content: [{
1872
+ type: "text",
1873
+ text
1874
+ }, ...images.map((image) => ({
1875
+ type: "image",
1876
+ data: image.data,
1877
+ mimeType: image.mimeType
1878
+ }))],
1879
+ details: {
1880
+ surface,
1881
+ logs: [...outcome.logs],
1882
+ narrations: [...outcome.narrations],
1883
+ phases: [...outcome.phases],
1884
+ warnings,
1885
+ ...outcome.value === void 0 ? {} : { result: outcome.value },
1886
+ durationMs: input.durationMs,
1887
+ imageCount: images.length,
1888
+ ...fullOutputPath === void 0 ? {} : { fullOutputPath }
1889
+ }
1890
+ };
1891
+ }
1892
+ //#endregion
1893
+ //#region src/tools/render.ts
1894
+ /** Call-row label per surface; `ptc_workflow` gets its own so the two rows stay tellable apart. */
1895
+ const TOOL_TITLE = {
1896
+ run_code: "PTC",
1897
+ workflow: "PTC workflow"
1898
+ };
1899
+ /**
1900
+ * Tree-connector layout. The call row owns column 0–2 (`└─ `); everything below it sits at column 3.
1901
+ * Children are siblings of the call's content (the summary line `→ {hint}`), so a child row needs a
1902
+ * connector to distinguish itself from the summary — and a continuation prefix to distinguish its
1903
+ * own wrapped lines from the child's first line.
1904
+ *
1905
+ * - Root call row: `└─ PTC …`
1906
+ * - Root continuation: ` → {hint}` or ` failed: …` (summary; same column as children)
1907
+ * - First / middle child: ` ├─ code …`
1908
+ * - First / middle cont.: ` │ …`
1909
+ * - Last child: ` └─ image …`
1910
+ * - Last cont.: ` …` (no connector — same shape as a wrapped value line)
1911
+ *
1912
+ * `TREE_INDENT` (3 spaces) is the column children and root continuations share.
1913
+ */
1914
+ const TREE_ROOT = "└─ ";
1915
+ const TREE_ROOT_CONT = " ";
1916
+ const TREE_INDENT = " ";
1917
+ const TREE_FIRST = "├─ ";
1918
+ const TREE_LAST = "└─ ";
1919
+ const TREE_CONT_FIRST = "│ ";
1920
+ const TREE_CONT_LAST = " ";
1921
+ /**
1922
+ * Gutter width for child labels. `code` / `out` / `value` / `warn` / `image` are 3–5 chars; `phases`
1923
+ * is 6 — pad to 8 so the longest label gets two trailing spaces before its content.
1924
+ */
1925
+ const LABEL_WIDTH = 8;
1926
+ const MAX_CODE_LINES_EXPANDED = 3;
1927
+ const MAX_CODE_LINE_CHARS = 120;
1928
+ const MAX_LOG_LINES_EXPANDED = 12;
1929
+ const MAX_PHASES_EXPANDED = 8;
1930
+ const MAX_WARNINGS_EXPANDED = 4;
1931
+ const MAX_RESULT_HINT_CHARS = 60;
1932
+ const MAX_ERROR_CHARS = 120;
1933
+ /**
1934
+ * A `Component` that right-aligns one meta segment per line.
1935
+ *
1936
+ * Stateless: it holds already-styled strings and pads them at render time, so pi can re-render at a
1937
+ * new width (terminal resize) without any invalidation bookkeeping.
1938
+ */
1939
+ var PtcRow = class {
1940
+ lines;
1941
+ constructor(lines) {
1942
+ this.lines = lines;
1943
+ }
1944
+ /** Part of the `Component` contract; nothing is cached, so nothing has to be dropped. */
1945
+ invalidate() {}
1946
+ render(width) {
1947
+ const safeWidth = Math.max(1, Math.floor(width));
1948
+ return this.lines.map((line) => alignRow(line, safeWidth));
1949
+ }
1950
+ };
1951
+ /**
1952
+ * Lay out one row inside `width` columns.
1953
+ *
1954
+ * With no meta segment the line is simply truncated. With one, the meta is what must survive — a
1955
+ * count that has been cut in half (`• 19 outpu…`) tells the reader nothing — so the left side gives
1956
+ * up room first, and only a meta wider than the whole viewport is truncated itself.
1957
+ */
1958
+ function alignRow(line, width) {
1959
+ const { left, right } = line;
1960
+ if (right === void 0) return truncateToWidth(left, width, "…");
1961
+ const rightWidth = visibleWidth(right);
1962
+ if (rightWidth >= width) return truncateToWidth(right, width, "…");
1963
+ const leftText = truncateToWidth(left, Math.max(0, width - rightWidth - 1), "…");
1964
+ const pad = Math.max(1, width - rightWidth - visibleWidth(leftText));
1965
+ return leftText + " ".repeat(pad) + right;
1966
+ }
1967
+ /** Truncate `s` to `n` chars, appending `…` when the input was longer. */
1968
+ function truncateChars(s, n) {
1969
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
1970
+ }
1971
+ /** First non-blank line of a block of text, sanitized and capped. */
1972
+ function firstLine(value) {
1973
+ return truncateChars((sanitizeText(value).split("\n").find((candidate) => candidate.trim().length > 0) ?? "").trim(), MAX_ERROR_CHARS);
1974
+ }
1975
+ /** `n` rendered as `1.2s` / `850ms` (so users can tell short from long at a glance). */
1976
+ function formatDuration(ms) {
1977
+ if (ms < 1e3) return `${ms}ms`;
1978
+ return `${(ms / 1e3).toFixed(2).replace(/\.?0+$/, "")}s`;
1979
+ }
1980
+ /** `3 phases` / `1 phase` — singular and plural are both reachable from a real run. */
1981
+ function plural(count, noun) {
1982
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
1983
+ }
1984
+ /**
1985
+ * Pull the first line of code that is actually doing something — not a leading comment, blank
1986
+ * line, or import. Used as the call row's fallback when the model sent no description.
1987
+ */
1988
+ function firstMeaningfulCodeLine(code) {
1989
+ for (const raw of code.split("\n")) {
1990
+ const line = raw.trim();
1991
+ if (line.length === 0) continue;
1992
+ if (line.startsWith("//")) continue;
1993
+ if (line.startsWith("/*")) continue;
1994
+ if (line.startsWith("*")) continue;
1995
+ return truncateChars(line.replace(/\s*\/\/.*$/, ""), MAX_CODE_LINE_CHARS);
1996
+ }
1997
+ }
1998
+ /**
1999
+ * The completion value as a single line a human can read: the value itself while it stays short
2000
+ * and single-line, otherwise its shape (`{version, node}`, `Array(3)`).
2001
+ *
2002
+ * A multi-line string contributes its first non-blank line plus a `+N lines` tail, which is the
2003
+ * whole difference between one readable row and the escaped wall this replaces.
2004
+ */
2005
+ function resultHint(value) {
2006
+ if (value === void 0) return void 0;
2007
+ if (typeof value === "string") {
2008
+ const lines = sanitizeText(value).split("\n");
2009
+ const first = lines.find((line) => line.trim().length > 0)?.trim() ?? "";
2010
+ const extra = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
2011
+ if (first.length === 0 && extra.length === 0) return `""`;
2012
+ return truncateChars(first, MAX_RESULT_HINT_CHARS) + extra;
2013
+ }
2014
+ if (value === null || typeof value !== "object") return String(value);
2015
+ const inline = renderModelValue(value);
2016
+ if (!inline.includes("\n") && inline.length <= MAX_RESULT_HINT_CHARS) return inline;
2017
+ if (Array.isArray(value)) return `Array(${value.length})`;
2018
+ const keys = Object.keys(value);
2019
+ if (keys.length === 0) return "{}";
2020
+ return `{${keys.slice(0, 4).join(", ")}${keys.length > 4 ? `, +${keys.length - 4}` : ""}}`;
2021
+ }
2022
+ /**
2023
+ * Right-aligned meta: the run's countable facts, in the order a reader asks for them — how much
2024
+ * output, how long it took, how many phases (workflow), and anything that went wrong.
2025
+ */
2026
+ function metaText(details, theme) {
2027
+ if (details === void 0) return void 0;
2028
+ const segments = [];
2029
+ const outputLines = details.logs.length + details.narrations.length;
2030
+ if (outputLines > 0) segments.push(theme.fg("dim", plural(outputLines, "output line")));
2031
+ if (details.imageCount > 0) segments.push(theme.fg("toolOutput", plural(details.imageCount, "image")));
2032
+ if (details.surface === "workflow" && details.phases.length > 0) segments.push(theme.fg("dim", plural(details.phases.length, "phase")));
2033
+ if (details.warnings.length > 0) segments.push(theme.fg("warning", plural(details.warnings.length, "warning")));
2034
+ if (details.fullOutputPath !== void 0) segments.push(theme.fg("warning", "truncated"));
2035
+ segments.push(theme.fg("dim", formatDuration(details.durationMs)));
2036
+ return `${theme.fg("dim", "•")} ${segments.join(theme.fg("dim", " · "))}`;
2037
+ }
2038
+ /** Render one child block as `RowLine[]`, with `├─` / `│` / `└─` connectors decided by position. */
2039
+ function renderChildBlock(child, isLast, theme) {
2040
+ const firstPrefix = TREE_INDENT + (isLast ? TREE_LAST : TREE_FIRST);
2041
+ const contPrefix = TREE_INDENT + (isLast ? TREE_CONT_LAST : TREE_CONT_FIRST);
2042
+ const gutter = " ".repeat(LABEL_WIDTH);
2043
+ const rows = [];
2044
+ const first = child.lines[0] ?? "";
2045
+ rows.push({ left: `${firstPrefix}${child.label.padEnd(LABEL_WIDTH)}${theme.fg("dim", first)}` });
2046
+ for (let i = 1; i < child.lines.length; i++) rows.push({ left: `${contPrefix}${gutter}${theme.fg("dim", child.lines[i] ?? "")}` });
2047
+ if (child.more !== void 0 && child.more > 0) rows.push({ left: `${contPrefix}${gutter}…+${child.more} more lines` });
2048
+ return rows;
2049
+ }
2050
+ /** A JSON value is "expandable" when it is a non-empty object or array. */
2051
+ function isExpandableContainer(value) {
2052
+ if (value === null || typeof value !== "object") return false;
2053
+ if (Array.isArray(value)) return value.length > 0;
2054
+ return Object.keys(value).length > 0;
2055
+ }
2056
+ /** Object keys that read as identifiers are left unquoted; the rest get JSON quoting. */
2057
+ const TREE_BARE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2058
+ function treeFormatKey(key) {
2059
+ return TREE_BARE_KEY.test(key) ? key : JSON.stringify(key);
2060
+ }
2061
+ /** A scalar JSON value as a single readable token; strings are JSON-quoted, newlines folded. */
2062
+ function treeScalarPreview(value, maxChars) {
2063
+ if (value === null) return "null";
2064
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
2065
+ if (typeof value === "string") {
2066
+ const sanitized = sanitizeText(value);
2067
+ if (sanitized.length === 0) return "\"\"";
2068
+ if (sanitized.includes("\n")) {
2069
+ const head = truncateChars(sanitized.replace(/\n/g, " "), Math.max(2, maxChars - 5));
2070
+ return JSON.stringify(head) + "…";
2071
+ }
2072
+ if (sanitized.length + 2 <= maxChars) return JSON.stringify(sanitized);
2073
+ return JSON.stringify(truncateChars(sanitized, Math.max(2, maxChars - 5))) + "…";
2074
+ }
2075
+ return "?";
2076
+ }
2077
+ function treeIsScalarJson(value) {
2078
+ return value === null || typeof value !== "object";
2079
+ }
2080
+ /** Try to render a container as a one-liner bracket form ({k: v} / [v, v]); undefined when it does not fit or children are deep. */
2081
+ function treeInlinePreview(value, maxChars) {
2082
+ if (maxChars < 8) return void 0;
2083
+ if (Array.isArray(value)) {
2084
+ if (value.length === 0) return "[]";
2085
+ if (value.length > 5 || !value.every(treeIsScalarJson)) return void 0;
2086
+ const inline = "[" + value.map((item) => treeScalarPreview(item, Math.max(2, Math.floor(maxChars / 4)))).join(", ") + "]";
2087
+ return inline.length <= maxChars ? inline : void 0;
2088
+ }
2089
+ if (value === null || typeof value !== "object") return void 0;
2090
+ const keys = Object.keys(value);
2091
+ if (keys.length === 0) return "{}";
2092
+ if (keys.length > 5 || !Object.values(value).every(treeIsScalarJson)) return void 0;
2093
+ const inline = "{" + keys.map((key) => {
2094
+ const child = value[key] ?? null;
2095
+ return treeFormatKey(key) + ": " + treeScalarPreview(child, Math.max(2, Math.floor(maxChars / 4)));
2096
+ }).join(", ") + "}";
2097
+ return inline.length <= maxChars ? inline : void 0;
2098
+ }
2099
+ /**
2100
+ * Append one pre-prefixed tree row to out, recursing for containers. Each level passes the
2101
+ * continuation indent its children should use; the connector itself encodes "more siblings".
2102
+ */
2103
+ function treeAppendNode(value, label, parentPrefix, isLast, maxDepth, maxChildren, maxLineChars, depth, out) {
2104
+ const ownPrefix = parentPrefix + (isLast ? "└─ " : "├─ ");
2105
+ const continuation = parentPrefix + (isLast ? " " : "│ ");
2106
+ if (depth >= maxDepth) {
2107
+ out.push(treeTruncateIndent(ownPrefix + label + "…", maxLineChars));
2108
+ return;
2109
+ }
2110
+ if (Array.isArray(value) && value.length === 0) {
2111
+ out.push(treeTruncateIndent(ownPrefix + label + "[]", maxLineChars));
2112
+ return;
2113
+ }
2114
+ if (!Array.isArray(value) && value !== null && typeof value === "object" && Object.keys(value).length === 0) {
2115
+ out.push(treeTruncateIndent(ownPrefix + label + "{}", maxLineChars));
2116
+ return;
2117
+ }
2118
+ if (value === null || typeof value !== "object") {
2119
+ const budget = Math.max(0, maxLineChars - visibleWidth(ownPrefix) - label.length);
2120
+ out.push(treeTruncateIndent(ownPrefix + label + treeScalarPreview(value, budget), maxLineChars));
2121
+ return;
2122
+ }
2123
+ const inline = treeInlinePreview(value, Math.max(0, maxLineChars - visibleWidth(ownPrefix) - label.length));
2124
+ if (inline !== void 0) {
2125
+ out.push(treeTruncateIndent(ownPrefix + label + inline, maxLineChars));
2126
+ return;
2127
+ }
2128
+ const listLike = Array.isArray(value);
2129
+ const childCount = listLike ? value.length : Object.keys(value).length;
2130
+ let header;
2131
+ if (listLike) header = "Array(" + childCount + ")";
2132
+ else header = childCount > maxChildren ? "{" + maxChildren + " of " + childCount + "}" : "{" + childCount + " keys}";
2133
+ out.push(treeTruncateIndent(ownPrefix + label + header, maxLineChars));
2134
+ const limit = Math.min(maxChildren, childCount);
2135
+ if (listLike) for (let index = 0; index < limit; index += 1) {
2136
+ const isChildLast = index === limit - 1 && childCount <= limit;
2137
+ treeAppendNode(value[index] ?? null, "[" + index + "] ", continuation, isChildLast, maxDepth, maxChildren, maxLineChars, depth + 1, out);
2138
+ }
2139
+ else {
2140
+ const keys = Object.keys(value);
2141
+ for (let index = 0; index < limit; index += 1) {
2142
+ const isChildLast = index === limit - 1 && childCount <= limit;
2143
+ const key = keys[index];
2144
+ treeAppendNode(value[key] ?? null, treeFormatKey(key) + ": ", continuation, isChildLast, maxDepth, maxChildren, maxLineChars, depth + 1, out);
2145
+ }
2146
+ }
2147
+ if (childCount > limit) {
2148
+ const tail = listLike ? "items" : "keys";
2149
+ out.push(treeTruncateIndent(continuation + "└─ …+" + (childCount - limit) + " more " + tail, maxLineChars));
2150
+ }
2151
+ }
2152
+ /** Truncate a rendered row, preserving the leading tree-prefix indent (│/├/└ etc.). */
2153
+ function treeTruncateIndent(line, maxLineChars) {
2154
+ if (visibleWidth(line) <= maxLineChars) return line;
2155
+ const match = line.match(/^([\s│├└─]*)/);
2156
+ const indent = match && match[1] ? match[1] : "";
2157
+ const indentWidth = visibleWidth(indent);
2158
+ const budget = Math.max(0, maxLineChars - indentWidth - 1);
2159
+ let body = "";
2160
+ let used = 0;
2161
+ for (const ch of line.slice(indent.length)) {
2162
+ const w = visibleWidth(ch);
2163
+ if (used + w > budget) break;
2164
+ body += ch;
2165
+ used += w;
2166
+ }
2167
+ return indent + body + "…";
2168
+ }
2169
+ /**
2170
+ * Render a JSON value as an array of indented tree rows.
2171
+ *
2172
+ * Each row is a complete prefixed line ready to live under the call row's " " indent
2173
+ * (TREE_ROOT_CONT): root children start at "├─ " / "└─ ", deeper levels add their own
2174
+ * connectors on top of the continuation bar. Caller supplies the row's TREE_ROOT_CONT — a
2175
+ * row that starts with "├─ " lands at column 3, exactly where other call-row children sit.
2176
+ *
2177
+ * Empty / scalar values return a one-row preview; non-empty containers recurse.
2178
+ */
2179
+ function renderValueTree(value, options = {}) {
2180
+ const maxDepth = options.maxDepth ?? 4;
2181
+ const maxChildren = options.maxChildren ?? 6;
2182
+ const maxLineChars = options.maxLineChars ?? 120;
2183
+ const moreAfter = options.moreAfter === true;
2184
+ if (!isExpandableContainer(value)) {
2185
+ if (value !== null && typeof value === "object") return [Array.isArray(value) ? "[]" : "{}"];
2186
+ return [treeScalarPreview(value, maxLineChars)];
2187
+ }
2188
+ const out = [];
2189
+ if (Array.isArray(value)) {
2190
+ const total = value.length;
2191
+ const limit = Math.min(maxChildren, total);
2192
+ for (let index = 0; index < limit; index += 1) {
2193
+ const isLast = !moreAfter && index === limit - 1 && total <= limit;
2194
+ treeAppendNode(value[index] ?? null, "[" + index + "] ", "", isLast, maxDepth, maxChildren, maxLineChars, 0, out);
2195
+ }
2196
+ if (total > limit) out.push((moreAfter ? "├─ " : "└─ ") + "…+" + (total - limit) + " more items");
2197
+ return out;
2198
+ }
2199
+ const keys = Object.keys(value);
2200
+ const total = keys.length;
2201
+ const limit = Math.min(maxChildren, total);
2202
+ for (let index = 0; index < limit; index += 1) {
2203
+ const isLast = !moreAfter && index === limit - 1 && total <= limit;
2204
+ const key = keys[index];
2205
+ treeAppendNode(value[key] ?? null, treeFormatKey(key) + ": ", "", isLast, maxDepth, maxChildren, maxLineChars, 0, out);
2206
+ }
2207
+ if (total > limit) out.push((moreAfter ? "├─ " : "└─ ") + "…+" + (total - limit) + " more keys");
2208
+ return out;
2209
+ }
2210
+ /**
2211
+ * One-line tool-call header: the tree root, then the tool label, then the model's own description.
2212
+ *
2213
+ * The description is the only detail that gets to sit next to the label — the previous renderer
2214
+ * appended the first code line as well, which is what made the call row read as a paragraph rather
2215
+ * than a heading. The code is one `ctrl+e` away in the expanded view.
2216
+ */
2217
+ function renderPtcToolCall(args, theme, surface = "run_code") {
2218
+ const description = (typeof args.description === "string" && args.description.trim().length > 0 ? args.description.trim() : args.meta?.name) ?? "";
2219
+ const fallback = firstMeaningfulCodeLine(args.code ?? args.script ?? "");
2220
+ const detail = description.length > 0 ? description : fallback ?? "(no description)";
2221
+ const left = `${theme.fg("toolTitle", theme.bold(TOOL_TITLE[surface]))} ${theme.fg("accent", detail)}`;
2222
+ return new PtcRow([{ left: `${TREE_ROOT}${left}` }]);
2223
+ }
2224
+ /** Text body of a failed run — pi surfaces the thrown error in the first text block. */
2225
+ function errorText(result) {
2226
+ const text = result.content?.find((block) => block.type === "text" && (block.text ?? "").length > 0);
2227
+ return firstLine(text?.text ?? "") || "failed";
2228
+ }
2229
+ /**
2230
+ * The result area under the call row.
2231
+ *
2232
+ * One of four shapes, all hanging at column 3 so a column of PTC rows stays scannable:
2233
+ * - error: one line with the failure reason in the error colour.
2234
+ * - no completion value: one line, "done".
2235
+ * - scalar / empty container: one line, `→ <hint>` (or "done" for null).
2236
+ * - non-empty container: a tree of rows (recursive `├─/└─/│` connectors from
2237
+ * `renderValueTree`), with the right-aligned meta pinned to
2238
+ * the tree's first row. ADR-0013 §5.
2239
+ *
2240
+ * Each row returns its left-side text WITHOUT the `TREE_ROOT_CONT` prefix being in scope;
2241
+ * we prepend it here so the same output works for both surfaces.
2242
+ */
2243
+ function resultArea(result, isError, theme, moreAfter = false) {
2244
+ const right = metaText(result.details, theme);
2245
+ const attachRight = (row) => right === void 0 ? row : {
2246
+ ...row,
2247
+ right
2248
+ };
2249
+ if (isError) return [attachRight({ left: `${TREE_ROOT_CONT}${theme.fg("error", `failed: ${errorText(result)}`)}` })];
2250
+ const value = result.details?.result;
2251
+ if (value === void 0) return [attachRight({ left: `${TREE_ROOT_CONT}${theme.fg("muted", "done")}` })];
2252
+ if (isExpandableContainer(value)) return renderValueTree(value, {
2253
+ maxDepth: 4,
2254
+ maxChildren: 6,
2255
+ maxLineChars: 120,
2256
+ moreAfter
2257
+ }).map((line, index) => {
2258
+ const row = { left: `${TREE_ROOT_CONT}${line}` };
2259
+ return index === 0 && right !== void 0 ? {
2260
+ ...row,
2261
+ right
2262
+ } : row;
2263
+ });
2264
+ const hint = resultHint(value);
2265
+ if (hint === void 0) return [attachRight({ left: `${TREE_ROOT_CONT}${theme.fg("muted", "done")}` })];
2266
+ return [attachRight({ left: `${TREE_ROOT_CONT}${theme.fg("dim", `→ ${hint}`)}` })];
2267
+ }
2268
+ /**
2269
+ * Collapsed result: the result area only.
2270
+ *
2271
+ * A scalar row fits on one line; a container value expands into a tree (1+ lines). Right-aligned
2272
+ * meta (output lines / phases / warnings / duration) is pinned to the first row of the area.
2273
+ */
2274
+ function renderPtcToolResultCollapsed(result, isError, theme) {
2275
+ return new PtcRow(resultArea(result, isError, theme));
2276
+ }
2277
+ /**
2278
+ * Expanded view: the result area, then the run's children as labelled blocks.
2279
+ *
2280
+ * Each child block opens with a fixed-width gutter (`code`, `phases`, `log`, `out`, `warn`,
2281
+ * `image`); the `value` block is gone — for a scalar value the result area already shows the
2282
+ * hint, and for a container value the area shows the full tree (ADR-0013 §5). Children that
2283
+ * overflow cap themselves and report `+N more lines`; the view stays bounded.
2284
+ */
2285
+ function renderPtcToolResultExpanded(result, args, isError, theme) {
2286
+ if (isError) {
2287
+ const lines = resultArea(result, true, theme);
2288
+ const text = sanitizeText(result.content?.find((block) => block.type === "text")?.text ?? errorText(result));
2289
+ for (const line of text.split("\n").slice(0, MAX_LOG_LINES_EXPANDED)) lines.push({ left: `${TREE_ROOT_CONT}${theme.fg("error", line)}` });
2290
+ return new PtcRow(lines);
2291
+ }
2292
+ const details = result.details;
2293
+ const children = [];
2294
+ const code = args.code ?? args.script ?? "";
2295
+ if (code.length > 0) {
2296
+ const codeLines = code.split("\n").map((line) => truncateChars(line, MAX_CODE_LINE_CHARS));
2297
+ const shown = codeLines.slice(0, MAX_CODE_LINES_EXPANDED);
2298
+ children.push({
2299
+ label: "code",
2300
+ lines: shown,
2301
+ ...codeLines.length > shown.length ? { more: codeLines.length - shown.length } : {}
2302
+ });
2303
+ }
2304
+ if (details !== void 0 && details.surface === "workflow" && details.phases.length > 0) {
2305
+ const shown = details.phases.slice(0, MAX_PHASES_EXPANDED);
2306
+ const tail = details.phases.length > shown.length ? " …" : "";
2307
+ children.push({
2308
+ label: "phases",
2309
+ lines: [`${shown.join(" → ")}${tail}`]
2310
+ });
2311
+ }
2312
+ if (details !== void 0 && details.narrations.length > 0) {
2313
+ const shown = details.narrations.slice(0, MAX_LOG_LINES_EXPANDED);
2314
+ children.push({
2315
+ label: "log",
2316
+ lines: shown.map((message) => sanitizeText(message)),
2317
+ ...details.narrations.length > shown.length ? { more: details.narrations.length - shown.length } : {}
2318
+ });
2319
+ }
2320
+ if (details !== void 0 && details.logs.length > 0) {
2321
+ const shown = details.logs.slice(0, MAX_LOG_LINES_EXPANDED);
2322
+ children.push({
2323
+ label: "out",
2324
+ lines: shown.map((line) => sanitizeText(line)),
2325
+ ...details.logs.length > shown.length ? { more: details.logs.length - shown.length } : {}
2326
+ });
2327
+ }
2328
+ if (details !== void 0 && details.warnings.length > 0) {
2329
+ const shown = details.warnings.slice(0, MAX_WARNINGS_EXPANDED);
2330
+ children.push({
2331
+ label: "warn",
2332
+ lines: shown.map((warning) => sanitizeText(warning)),
2333
+ ...details.warnings.length > shown.length ? { more: details.warnings.length - shown.length } : {}
2334
+ });
2335
+ }
2336
+ if (details !== void 0 && details.imageCount > 0) {
2337
+ const desc = details.imageCount === 1 ? "1 image attached" : `${details.imageCount} images attached`;
2338
+ children.push({
2339
+ label: "image",
2340
+ lines: [desc]
2341
+ });
2342
+ }
2343
+ const lines = resultArea(result, false, theme, children.length > 0);
2344
+ for (let index = 0; index < children.length; index += 1) {
2345
+ const isLast = index === children.length - 1;
2346
+ lines.push(...renderChildBlock(children[index] ?? {
2347
+ label: "",
2348
+ lines: []
2349
+ }, isLast, theme));
2350
+ }
2351
+ return new PtcRow(lines);
2352
+ }
2353
+ //#endregion
2354
+ //#region src/tools/run-code.ts
2355
+ /**
2356
+ * `ptc_run_code` — the unstructured PTC surface.
2357
+ *
2358
+ * The model writes the body of an async function; inside it, pi's built-in tools are reachable as
2359
+ * `tools.<name>(args)` (all seven: read, bash, edit, write, grep, find, ls — ADR-0005's set), and
2360
+ * the program's return value plus `console.log` output are what come back. There are no helpers
2361
+ * on this surface: `log` / `phase` / `parallel` / `pipeline` belong to `ptc_workflow` (G1 #13 →
2362
+ * decision B; a call to a helper that does not exist is a plain `ReferenceError` through the
2363
+ * normal code-run error path).
2364
+ *
2365
+ * Scope notes, so this stays a faithful subset of DSH's `run_code`:
2366
+ * - DSH's `sandbox_permissions` / `justification` are deliberately absent — they exist to request
2367
+ * a wider sandbox from an approval pipeline this package does not have (ADR-0007 ships no OS
2368
+ * sandbox, and the map decision on #8 dropped the approval path).
2369
+ * - `timeoutMs: 0` does not disable the deadline; it falls back to `DEFAULT_CONFIG.timeoutMs`,
2370
+ * exactly as DSH's resolver does (R1 §3). The description names the default and the ceiling.
2371
+ */
2372
+ const DESCRIPTION$1 = [
2373
+ "Run a TypeScript program that composes pi's tools in one shot. Required arguments: `code` —",
2374
+ "the body of an async function (top-level `return` and `await` work; type annotations are",
2375
+ "advisory, the code runs type-stripped) — and `description`, a 5-10 word summary of what the",
2376
+ "program does.",
2377
+ "",
2378
+ "Inside the program, call this session's enabled built-in tools as `tools.<name>(args)` — e.g.",
2379
+ "`await tools.read({ path: \"src/index.ts\" })` or `await tools.bash({ command: \"npm test\" })`.",
2380
+ "The bound names mirror the session's active tools (a default session has `read`, `bash`, `edit`,",
2381
+ "`write`); calling a name that is not bound rejects with an error the program can catch, and",
2382
+ "independent calls may overlap under `Promise.all`.",
2383
+ "",
2384
+ "Only the program's return value and its `console.log` output come back. This surface has no",
2385
+ "helpers: `log` / `phase` / `parallel` / `pipeline` exist only in `ptc_workflow`.",
2386
+ "",
2387
+ "Image-bearing tool results inside the program (a `tools.read` on a PNG, say) are attached to you",
2388
+ "after the run, so never return image data as the completion value — that only spends your context",
2389
+ "on base64."
2390
+ ].join("\n");
2391
+ const PARAMETERS$1 = Type.Object({
2392
+ code: Type.String({ description: "The program: the body of an async TypeScript function." }),
2393
+ description: Type.String({ description: "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI)." }),
2394
+ timeoutMs: Type.Optional(Type.Number({ description: `Elapsed deadline in milliseconds for the whole run, including tool calls. Omit it (or pass 0) for the default of ${DEFAULT_CONFIG.timeoutMs / 1e3} s; anything above ${DEFAULT_CONFIG.maxTimeoutMs / 1e3} s is capped.` }))
2395
+ });
2396
+ /**
2397
+ * Build the `ptc_run_code` tool definition.
2398
+ *
2399
+ * Called once by the extension factory. Every run gets a fresh worker and a fresh binding table
2400
+ * built against the run's own cwd, so two concurrent calls cannot share state.
2401
+ */
2402
+ function createPtcRunCodeTool(options = {}) {
2403
+ return defineTool({
2404
+ name: "ptc_run_code",
2405
+ label: "PTC Run Code",
2406
+ description: DESCRIPTION$1,
2407
+ promptSnippet: PTC_RUN_CODE_SNIPPET,
2408
+ promptGuidelines: [...PTC_TOOL_GUIDELINES],
2409
+ parameters: PARAMETERS$1,
2410
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2411
+ const cwd = resolveToolCwd(ctx);
2412
+ const names = resolveBindingNames(options.getBindingSourceNames?.());
2413
+ const startedAt = Date.now();
2414
+ const outcome = await runPtcProgram({
2415
+ code: params.code,
2416
+ surface: "run_code",
2417
+ cwd,
2418
+ bindings: createBuiltinBindings({
2419
+ cwd,
2420
+ names
2421
+ }),
2422
+ ...params.timeoutMs === void 0 ? {} : { timeoutMs: params.timeoutMs },
2423
+ ...signal === void 0 ? {} : { signal },
2424
+ ...options.config === void 0 ? {} : { config: options.config }
2425
+ });
2426
+ if (outcome.error !== void 0) throw codeRunFailedError(outcome);
2427
+ return renderToolResult({
2428
+ outcome,
2429
+ surface: "run_code",
2430
+ durationMs: Date.now() - startedAt
2431
+ });
2432
+ },
2433
+ renderCall(args, theme) {
2434
+ return renderPtcToolCall(args, theme, "run_code");
2435
+ },
2436
+ renderResult(result, options, theme, context) {
2437
+ if (options.expanded) return renderPtcToolResultExpanded(result, context.args, context.isError, theme);
2438
+ return renderPtcToolResultCollapsed(result, context.isError, theme);
2439
+ }
2440
+ });
2441
+ }
2442
+ //#endregion
2443
+ //#region src/tools/workflow.ts
2444
+ /**
2445
+ * `ptc_workflow` — the structured PTC surface.
2446
+ *
2447
+ * Same worker, same bindings, same Node surface as `ptc_run_code`; what it adds is a plan
2448
+ * (`meta` with an ordered phase list), plain-JSON input (`args`, bound as the program's `args`
2449
+ * global) and the four workflow helpers: `log` / `phase` / `parallel` / `pipeline` (G1 #13 →
2450
+ * decision B — there is no `agent()`, not even a stub).
2451
+ *
2452
+ * Three decisions recorded here rather than re-litigated per call:
2453
+ * - **Language**: the same type-stripping pipeline as `ptc_run_code`. The worker compiles both
2454
+ * surfaces through one `compileProgram`, and the pipeline is type-*strip* only — it adds no
2455
+ * runtime semantics that a workflow could not tolerate. There is no JS-only mode because there
2456
+ * is no concrete reason for one (the old pi-ptc "JS-only" idea is explicitly not inherited).
2457
+ * - **Phase strictness**: warning, not error. A `phase(title)` outside `meta.phases` is a plan
2458
+ * drift — usually a typo or a forgotten declaration — but the run has already happened by the
2459
+ * time the titles are known, and failing then would discard a completed result over a cosmetic
2460
+ * mismatch. Each distinct unlisted title is reported once, as a `Warning:` line in `content`
2461
+ * and in `details.warnings`. When `meta.phases` is absent there is no declared plan to drift
2462
+ * from, so nothing is reported.
2463
+ * - **`args`**: validated as plain JSON before dispatch (see `validateWorkflowArgs`), because a
2464
+ * function/symbol/`undefined`/cycle would otherwise be silently dropped or mangled by the
2465
+ * structured clone on its way to the worker.
2466
+ */
2467
+ const DESCRIPTION = [
2468
+ "Run a structured TypeScript workflow: a named plan that reports phases and narration as it",
2469
+ "goes. `script` is the body of an async function, `meta` names it (`{ name, description, phases? }`,",
2470
+ "where `phases` is the ordered plan), and optional `args` is plain-JSON input bound to the",
2471
+ "program's `args` global.",
2472
+ "",
2473
+ "Helpers inside the script: `log(message)` narrates progress; `phase(title)` frames the workflow",
2474
+ "(titles outside `meta.phases` are reported as warnings); `parallel(thunks)` runs thunks",
2475
+ "concurrently, a failed item becoming `null`; `pipeline(items, ...stages)` chains stages per item",
2476
+ "with the same per-item `null` on failure. There is no `agent()` helper.",
2477
+ "",
2478
+ "Tools are reachable as `tools.<name>(args)` exactly as in `ptc_run_code`, and the bound names",
2479
+ "mirror the session's enabled tools. What comes back is the script's return value, its",
2480
+ "`log`/`phase` narration and its `console.log` output.",
2481
+ "",
2482
+ "Image-bearing tool results inside the script are attached to you after the run — never return",
2483
+ "image data as the script's value."
2484
+ ].join("\n");
2485
+ const PARAMETERS = Type.Object({
2486
+ meta: Type.Object({
2487
+ name: Type.String({ description: "Short workflow name, shown in the UI." }),
2488
+ description: Type.String({ description: "What this workflow does, in active voice." }),
2489
+ phases: Type.Optional(Type.Array(Type.Object({ name: Type.String({ description: "Phase title, matched against phase(title) calls." }) }), { description: "Ordered plan of the workflow's phases. phase() titles outside this list are reported as warnings." }))
2490
+ }, { description: "Workflow metadata: what this run is and which phases it declares." }),
2491
+ script: Type.String({ description: "The program: the body of an async TypeScript function." }),
2492
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Plain-JSON input bound to the program's `args` global. No functions, symbols, undefined values or cycles." }))
2493
+ });
2494
+ function describeValue(value) {
2495
+ if (value === null) return "null";
2496
+ if (Array.isArray(value)) return "an array";
2497
+ return `a ${typeof value}`;
2498
+ }
2499
+ /**
2500
+ * Reject anything that is not plain JSON, with a path-qualified reason.
2501
+ *
2502
+ * The rule is the worker's own result rule (`toJsonValue`) applied one direction earlier, so both
2503
+ * ends agree on what "plain JSON" means: objects with `Object.prototype` (or null), arrays,
2504
+ * strings, finite numbers, booleans and null. Class instances, functions, symbols, bigints,
2505
+ * non-finite numbers, circular references and `undefined` values are all rejected — `undefined`
2506
+ * because the ticket calls it out and because a structured clone would drop it silently, leaving
2507
+ * the script reading a key that is not there.
2508
+ */
2509
+ function validateWorkflowArgs(args) {
2510
+ if (args === void 0) return;
2511
+ if (typeof args !== "object" || args === null || Array.isArray(args)) throw new TypeError(`ptc_workflow args must be a plain JSON object, received ${describeValue(args)}`);
2512
+ for (const key of Object.keys(args)) {
2513
+ const problem = findJsonProblem(args[key], `args.${key}`, /* @__PURE__ */ new Set());
2514
+ if (problem !== void 0) throw new TypeError(`ptc_workflow args must be plain JSON: ${problem}`);
2515
+ }
2516
+ }
2517
+ /** Path-qualified reason a value cannot cross the wire as plain JSON, or `undefined` when it can. */
2518
+ function findJsonProblem(value, path, seen) {
2519
+ if (value === null || typeof value === "string" || typeof value === "boolean") return void 0;
2520
+ if (typeof value === "undefined") return `${path} is undefined`;
2521
+ if (typeof value === "number") return Number.isFinite(value) ? void 0 : `${path} is ${String(value)}, which is not representable as JSON`;
2522
+ if (typeof value !== "object") return `${path} is ${describeValue(value)}`;
2523
+ const container = value;
2524
+ if (seen.has(container)) return `${path} is a circular reference`;
2525
+ seen.add(container);
2526
+ try {
2527
+ if (Array.isArray(container)) {
2528
+ for (let index = 0; index < container.length; index += 1) {
2529
+ const problem = findJsonProblem(container[index], `${path}[${index}]`, seen);
2530
+ if (problem !== void 0) return problem;
2531
+ }
2532
+ return;
2533
+ }
2534
+ const prototype = Object.getPrototypeOf(container);
2535
+ if (prototype !== Object.prototype && prototype !== null) {
2536
+ const name = container.constructor?.name;
2537
+ return `${path} is a ${typeof name === "string" && name.length > 0 ? name : "non-plain object"}, not plain JSON`;
2538
+ }
2539
+ for (const key of Object.keys(container)) {
2540
+ const problem = findJsonProblem(container[key], `${path}.${key}`, seen);
2541
+ if (problem !== void 0) return problem;
2542
+ }
2543
+ return;
2544
+ } finally {
2545
+ seen.delete(container);
2546
+ }
2547
+ }
2548
+ /**
2549
+ * Collect the plan-drift warnings for one workflow run: distinct `phase()` titles the declared
2550
+ * `meta.phases` list does not mention, in first-seen order.
2551
+ */
2552
+ function unlistedPhaseWarnings(outcome, declared) {
2553
+ if (declared === void 0 || declared.length === 0) return [];
2554
+ const known = new Set(declared);
2555
+ const reported = /* @__PURE__ */ new Set();
2556
+ const warnings = [];
2557
+ for (const title of outcome.phases) {
2558
+ if (known.has(title) || reported.has(title)) continue;
2559
+ reported.add(title);
2560
+ warnings.push(`phase "${title}" is not listed in meta.phases (declared: ${[...known].join(", ")})`);
2561
+ }
2562
+ return warnings;
2563
+ }
2564
+ /**
2565
+ * Build the `ptc_workflow` tool definition.
2566
+ *
2567
+ * `args` is validated before `runPtcProgram` is called, so a malformed payload never spawns a
2568
+ * worker. Everything after dispatch is identical to `ptc_run_code`, plus the phase roll-up.
2569
+ */
2570
+ function createPtcWorkflowTool(options = {}) {
2571
+ return defineTool({
2572
+ name: "ptc_workflow",
2573
+ label: "PTC Workflow",
2574
+ description: DESCRIPTION,
2575
+ promptSnippet: PTC_WORKFLOW_SNIPPET,
2576
+ promptGuidelines: [...PTC_TOOL_GUIDELINES],
2577
+ parameters: PARAMETERS,
2578
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2579
+ validateWorkflowArgs(params.args);
2580
+ const cwd = resolveToolCwd(ctx);
2581
+ const names = resolveBindingNames(options.getBindingSourceNames?.());
2582
+ const startedAt = Date.now();
2583
+ const outcome = await runPtcProgram({
2584
+ code: params.script,
2585
+ surface: "workflow",
2586
+ cwd,
2587
+ bindings: createBuiltinBindings({
2588
+ cwd,
2589
+ names
2590
+ }),
2591
+ ...params.args === void 0 ? {} : { args: params.args },
2592
+ ...signal === void 0 ? {} : { signal },
2593
+ ...options.config === void 0 ? {} : { config: options.config }
2594
+ });
2595
+ if (outcome.error !== void 0) throw codeRunFailedError(outcome);
2596
+ const declared = params.meta.phases?.map((phase) => phase.name);
2597
+ return renderToolResult({
2598
+ outcome,
2599
+ surface: "workflow",
2600
+ warnings: unlistedPhaseWarnings(outcome, declared),
2601
+ durationMs: Date.now() - startedAt
2602
+ });
2603
+ },
2604
+ renderCall(args, theme) {
2605
+ return renderPtcToolCall(args, theme, "workflow");
2606
+ },
2607
+ renderResult(result, options, theme, context) {
2608
+ if (options.expanded) return renderPtcToolResultExpanded(result, context.args, context.isError, theme);
2609
+ return renderPtcToolResultCollapsed(result, context.isError, theme);
2610
+ }
2611
+ });
2612
+ }
2613
+ //#endregion
2614
+ //#region src/mode/ptc-mode.ts
2615
+ /**
2616
+ * PTC default mode — the session-level tool-restriction state machine.
2617
+ *
2618
+ * ## What "mode" means here
2619
+ *
2620
+ * While enabled, the session's visible tool loadout is narrowed so the model reaches
2621
+ * `read` / `bash` / `edit` / `write` / `grep` / `find` / `ls` only from *inside* a program
2622
+ * (`tools.<name>(args)`). That is DSH's PTC-preset shape, and it is what makes the mode visible
2623
+ * in the TUI: the transcript stops showing file-operation rows and shows PTC rows instead.
2624
+ *
2625
+ * The mode is decided per session (`session_start`), announced once, and always reversible.
2626
+ *
2627
+ * ## Why bindings need a base snapshot (the trap this module exists to avoid)
2628
+ *
2629
+ * `resolveBindingNames()` computes bindings as `BUILTIN_BINDING_NAMES ∩ pi.getActiveTools()`
2630
+ * (T7, ADR-0005 addendum). But `pi.getActiveTools()` reads the *live* loadout — the very set this
2631
+ * mode narrows. Hiding the built-ins therefore empties the binding table, and every
2632
+ * `tools.read(...)` fails with "not bound": the extension would neuter itself.
2633
+ *
2634
+ * The fix is a **base snapshot**. `base` is captured *before* the mode hides anything, and
2635
+ * bindings derive from `base` rather than the live loadout while the mode is on. T7's invariant
2636
+ * survives, because `base` is itself read from `pi.getActiveTools()`: a session launched with
2637
+ * `--tools read` has `base = ["read"]`, so bindings stay `["read"]`. The mode never widens access
2638
+ * beyond what the session was launched with — it only makes its **own** narrowing transparent to
2639
+ * the binding table.
2640
+ *
2641
+ * ## Fail-safe on external loadout changes
2642
+ *
2643
+ * Another extension can call `setActiveTools()` (pi's own `preset.ts` and `tools.ts` examples do).
2644
+ * `ourLoadout` records the exact array this mode wrote, so a mismatch means someone else owns the
2645
+ * loadout now. The mode then exits and restores `base` instead of fighting over it.
2646
+ *
2647
+ * ## Where the mode never runs
2648
+ *
2649
+ * Print / JSON / RPC sessions (`ctx.mode !== "tui"`) are left alone: forcing the shape on CI
2650
+ * scripts buys nothing and breaks them. A session that was *launched* with an explicit tool
2651
+ * restriction is left alone too — see `decideModeEntry`.
2652
+ */
2653
+ /** The two surfaces this package exposes. `/ptc on` needs at least one of them active. */
2654
+ const PTC_MODE_TOOL_NAMES = ["ptc_run_code", "ptc_workflow"];
2655
+ /**
2656
+ * Tools that must all be present for the **automatic** entry path to proceed.
2657
+ *
2658
+ * These four are pi's default session surface (`agent-session.js`: "["read", "bash", "edit",
2659
+ * "write"]"), so "all four present" means "this session was not narrowed". Comparing against
2660
+ * `BUILTIN_BINDING_NAMES` instead would be wrong: that list is the set of names that *can* be
2661
+ * bound, not what a default session has (`grep` / `find` / `ls` are bindable but off by default),
2662
+ * so requiring all seven would misread every ordinary session as restricted and never turn on.
2663
+ */
2664
+ const MODE_REQUIRED_TOOL_NAMES = [
2665
+ "read",
2666
+ "bash",
2667
+ "edit",
2668
+ "write"
2669
+ ];
2670
+ /** `customType` for the persisted mode entry (`pi.appendEntry`). */
2671
+ const PTC_MODE_ENTRY_TYPE = "ptc-mode";
2672
+ /** Footer status key (`ctx.ui.setStatus`). */
2673
+ const PTC_MODE_STATUS_KEY = "ptc-mode";
2674
+ /** Config file name, resolved against pi's agent dir (`~/.pi/agent/`). */
2675
+ const PTC_MODE_CONFIG_FILE = "ptc.json";
2676
+ /**
2677
+ * Which tools the mode hides while it is on.
2678
+ *
2679
+ * - `"builtins-only"` (default) — hide the seven built-in tools; tools contributed by *other*
2680
+ * extensions (`web_search`, `todo`, `subagent`, …) stay visible and directly callable. The
2681
+ * model is forced to program for file and shell work, which is the bulk of a coding session,
2682
+ * without losing capabilities this package cannot re-expose: extension tools have no bindings
2683
+ * (`pi.getAllTools()` returns metadata only — no `execute`), so hiding one makes it
2684
+ * unreachable for the whole session.
2685
+ * - `"all-but-ptc"` — hide everything except the two PTC surfaces. Closest to a strict reading of
2686
+ * DSH's preset, at the cost of making other extensions' tools unreachable until `/ptc off`.
2687
+ */
2688
+ const DEFAULT_HIDE_STRATEGY = "builtins-only";
2689
+ /** Fresh, disabled state. */
2690
+ function initialModeState() {
2691
+ return {
2692
+ enabled: false,
2693
+ base: void 0,
2694
+ ourLoadout: void 0
2695
+ };
2696
+ }
2697
+ /**
2698
+ * Read `defaultMode` from the agent-dir config file.
2699
+ *
2700
+ * Absent file → on (this package is default-on by design; see CONTEXT.md). A present file with a
2701
+ * non-boolean `defaultMode`, or unparseable JSON, is reported as `invalid` **and still defaults to
2702
+ * on** — the caller should surface the problem rather than silently changing behavior.
2703
+ */
2704
+ function readDefaultModeConfig(agentDir) {
2705
+ const path = join(agentDir, PTC_MODE_CONFIG_FILE);
2706
+ let raw;
2707
+ try {
2708
+ raw = readFileSync(path, "utf8");
2709
+ } catch {
2710
+ return {
2711
+ defaultMode: true,
2712
+ source: "default"
2713
+ };
2714
+ }
2715
+ let parsed;
2716
+ try {
2717
+ parsed = JSON.parse(raw);
2718
+ } catch (error) {
2719
+ return {
2720
+ defaultMode: true,
2721
+ source: "invalid",
2722
+ error: `${path} is not valid JSON (${error instanceof Error ? error.message : String(error)})`
2723
+ };
2724
+ }
2725
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
2726
+ defaultMode: true,
2727
+ source: "invalid",
2728
+ error: `${path} must contain a JSON object`
2729
+ };
2730
+ const value = parsed.defaultMode;
2731
+ if (value === void 0) return {
2732
+ defaultMode: true,
2733
+ source: "default"
2734
+ };
2735
+ if (typeof value !== "boolean") return {
2736
+ defaultMode: true,
2737
+ source: "invalid",
2738
+ error: `${path}: "defaultMode" must be a boolean, received ${typeof value}`
2739
+ };
2740
+ return {
2741
+ defaultMode: value,
2742
+ source: "file"
2743
+ };
2744
+ }
2745
+ /** Normalize to a de-duplicated name list, preserving order. */
2746
+ function uniqueNames(names) {
2747
+ return [...new Set(names)];
2748
+ }
2749
+ /** Order- and duplicate-insensitive set equality, for loadout comparison. */
2750
+ function sameToolSet(a, b) {
2751
+ if (a.length !== b.length) return false;
2752
+ const left = [...a].sort();
2753
+ const right = [...b].sort();
2754
+ return left.every((name, index) => name === right[index]);
2755
+ }
2756
+ /**
2757
+ * The loadout applied while the mode is on, given the session's current one.
2758
+ *
2759
+ * Always keeps the PTC surfaces; what else survives depends on the hide strategy (see
2760
+ * `DEFAULT_HIDE_STRATEGY`). Order follows `active`, so the visible list reads the way the session
2761
+ * was configured.
2762
+ */
2763
+ function modeLoadout(active, hide) {
2764
+ const isPtc = (name) => PTC_MODE_TOOL_NAMES.includes(name);
2765
+ if (hide === "all-but-ptc") return uniqueNames(active.filter(isPtc));
2766
+ const builtins = new Set(BUILTIN_BINDING_NAMES);
2767
+ return uniqueNames(active.filter((name) => isPtc(name) || !builtins.has(name)));
2768
+ }
2769
+ /**
2770
+ * Decide whether the mode turns on for this session.
2771
+ *
2772
+ * The policy, in order:
2773
+ * 1. **TUI only** — print / JSON / RPC sessions are never touched.
2774
+ * 2. **Config** — `{"defaultMode": false}` opts out; `/ptc on` overrides it.
2775
+ * 3. **PTC tools must exist** — if this session has them disabled, there is nothing to run.
2776
+ * 4. **Explicit restriction wins** — a session launched with `--tools` / `--exclude-tools` /
2777
+ * `--no-builtin-tools` that is missing any of `MODE_REQUIRED_TOOL_NAMES` (pi's default four)
2778
+ * stays as launched. Narrowing *further* would be the extension overriding a deliberate user
2779
+ * instruction, and the PTC surface would be degraded anyway (bindings = `BUILTIN ∩ base`).
2780
+ * `/ptc on` overrides this: the manual path enters with the restricted loadout as `base`, so
2781
+ * bindings stay inside the user's allowlist.
2782
+ */
2783
+ function decideModeEntry(input) {
2784
+ const { mode, defaultMode, active, manual } = input;
2785
+ if (mode !== "tui") return {
2786
+ enter: false,
2787
+ reason: "not-tui"
2788
+ };
2789
+ if (!defaultMode && !manual) return {
2790
+ enter: false,
2791
+ reason: "config-off"
2792
+ };
2793
+ if (!PTC_MODE_TOOL_NAMES.some((name) => active.includes(name))) return {
2794
+ enter: false,
2795
+ reason: "tools-unavailable"
2796
+ };
2797
+ if (!manual) {
2798
+ if (MODE_REQUIRED_TOOL_NAMES.filter((name) => !active.includes(name)).length > 0) return {
2799
+ enter: false,
2800
+ reason: "restricted-session"
2801
+ };
2802
+ }
2803
+ return {
2804
+ enter: true,
2805
+ base: uniqueNames(active),
2806
+ loadout: modeLoadout(active, input.hide ?? "builtins-only")
2807
+ };
2808
+ }
2809
+ /**
2810
+ * Tool names the binding table should be built from.
2811
+ *
2812
+ * While the mode is on this is the base snapshot (so the built-ins the mode just hid remain
2813
+ * callable from inside a program); otherwise it is simply the live loadout, i.e. T7's rule.
2814
+ */
2815
+ function bindingSource(state, active) {
2816
+ return state.enabled && state.base !== void 0 ? state.base : active;
2817
+ }
2818
+ /**
2819
+ * Whether the live loadout is no longer the one this mode wrote — i.e. another extension (or the
2820
+ * user) took ownership of the tool set. Always false while the mode is off.
2821
+ */
2822
+ function detectExternalLoadoutChange(state, active) {
2823
+ if (!state.enabled || state.ourLoadout === void 0) return false;
2824
+ return !sameToolSet(state.ourLoadout, active);
2825
+ }
2826
+ /**
2827
+ * Reconstruct the base loadout on `session_start`.
2828
+ *
2829
+ * Two shapes are possible:
2830
+ * - The session is still narrowed from a previous run of this mode (a `/reload`, or a resumed
2831
+ * session): the live loadout is a subset of the PTC tools and the persisted record says the mode
2832
+ * was on. The persisted `base` is then authoritative — but only to *undo our own hiding*.
2833
+ * - Otherwise the live loadout is whatever this pi process was launched with, and it wins. That is
2834
+ * what keeps a new `--tools …` choice from being overridden by an older session's snapshot.
2835
+ */
2836
+ function resolveBaseOnStart(persisted, active) {
2837
+ const looksNarrowedByUs = active.length > 0 && active.every((name) => PTC_MODE_TOOL_NAMES.includes(name));
2838
+ if (persisted?.enabled === true && looksNarrowedByUs && persisted.base !== void 0) return {
2839
+ base: persisted.base,
2840
+ restoreFirst: true
2841
+ };
2842
+ return {
2843
+ base: active,
2844
+ restoreFirst: false
2845
+ };
2846
+ }
2847
+ /**
2848
+ * Build the system-visible briefing for the mode.
2849
+ *
2850
+ * Generated from the *actual* binding list rather than hardcoded, because bindings vary by session
2851
+ * (`base` is whatever the session was launched with) and a stale list would have the model calling
2852
+ * names that are not bound.
2853
+ */
2854
+ function buildModeInstruction(bindings, hide) {
2855
+ const builtinNote = hide === "all-but-ptc" ? "Every built-in tool is hidden from you, and so are other extensions' tools." : "The built-in tools (read, bash, edit, write, grep, find, ls) are hidden from you.";
2856
+ const callable = bindings.map((name) => `tools.${name}(args)`);
2857
+ const examples = bindings.slice(0, 2).map((name) => name === "read" ? "await tools.read({ path: \"src/index.ts\" })" : name === "bash" ? "await tools.bash({ command: \"pnpm test\" })" : `await tools.${name}({ /* … */ })`).join("\n");
2858
+ return [
2859
+ "[PTC MODE ACTIVE]",
2860
+ "This session runs in PTC mode. " + builtinNote,
2861
+ "",
2862
+ "Work by writing one TypeScript program per task and running it:",
2863
+ " - ptc_run_code for a plain program (its return value and console.log come back to you)",
2864
+ " - ptc_workflow when the task has named phases and you want narration (log / phase /",
2865
+ " parallel / pipeline are available there)",
2866
+ "",
2867
+ `The program body is an async function. Available inside it: ${callable.join(", ")}.`,
2868
+ examples.length > 0 ? `Examples:\n${examples}` : "",
2869
+ "",
2870
+ "Batch a task's steps into ONE program instead of issuing many tool calls — gathering",
2871
+ "intermediate output yourself and returning only what matters is the point of this mode.",
2872
+ "Image-bearing tool results inside a program are attached to you after the run — never return",
2873
+ "base64 image data as your program's value.",
2874
+ "If the PTC surfaces cannot express what you need, say so and the user can run /ptc off."
2875
+ ].filter((line) => line.length > 0).join("\n");
2876
+ }
2877
+ //#endregion
2878
+ //#region src/mode/skills-section.ts
2879
+ /**
2880
+ * The system-prompt skills section, restored for PTC mode.
2881
+ *
2882
+ * pi advertises skills only when the session can actually open one:
2883
+ *
2884
+ * const skillFileReadTool = ["read", "bash"].find((tool) => selectedTools.includes(tool));
2885
+ * if (skillFileReadTool && skills.length > 0) promptSections.skills = ...
2886
+ * (pi-coding-agent: dist/core/system-prompt.js)
2887
+ *
2888
+ * PTC mode hides exactly those two tools, so that gate drops the section — and with it the model's
2889
+ * only way to learn that skills exist. Measured on real session files: sessions before
2890
+ * PTC-mode-by-default carried 43 skills in `SystemMessage.sections.skills`; PTC sessions carried
2891
+ * no `skills` section at all. See ADR-0011.
2892
+ *
2893
+ * The list body stays pi's own — `formatSkillsForPrompt` is a public export and its XML shape is
2894
+ * the agentskills.io spec, so re-deriving it here would only create drift. Only the loading
2895
+ * sentence changes: "Use the read tool" is false in a session where `read` is hidden, and the way
2896
+ * in is `tools.read` from inside a program.
2897
+ */
2898
+ /** The two tools pi accepts as "this session can read a skill file". */
2899
+ const SKILL_READING_TOOL_NAMES = ["read", "bash"];
2900
+ /** pi's sentence, which names a tool PTC mode hides. */
2901
+ const PI_LOAD_INSTRUCTION = "Use the read tool to load a skill's file when the task matches its description.";
2902
+ /** What replaces it: the same instruction, in the only call form this session has. */
2903
+ const PTC_SKILL_LOAD_INSTRUCTION = "Use tools.read({ path }) inside a ptc_run_code program to load a skill's file when the task matches its description.";
2904
+ /**
2905
+ * Would pi withhold the skills section for this loadout?
2906
+ *
2907
+ * Mirrors the gate rather than guessing: it is true exactly when neither `read` nor `bash` is
2908
+ * directly callable, which is the state the mode deliberately puts an ordinary session in.
2909
+ */
2910
+ function skillsSectionDropped(visibleTools) {
2911
+ return !SKILL_READING_TOOL_NAMES.some((name) => visibleTools.includes(name));
2912
+ }
2913
+ /**
2914
+ * Build the `skills` section body (pi wraps it in `<skills>…</skills>` itself).
2915
+ *
2916
+ * Returns `""` when nothing is advertisable — pi's formatter filters out skills marked
2917
+ * `disable-model-invocation`, which is the correct behaviour to inherit: those are
2918
+ * `/skill:name`-only by design.
2919
+ *
2920
+ * `format` is injectable so a test can drive the reworded-header branch without patching pi.
2921
+ */
2922
+ function buildPtcSkillsSection(skills, format = formatSkillsForPrompt) {
2923
+ const section = format([...skills], "read").trim();
2924
+ if (section.length === 0) return "";
2925
+ if (section.includes(PI_LOAD_INSTRUCTION)) return section.replace(PI_LOAD_INSTRUCTION, PTC_SKILL_LOAD_INSTRUCTION);
2926
+ return `${PTC_SKILL_LOAD_INSTRUCTION}\n\n${section}`;
2927
+ }
2928
+ //#endregion
2929
+ //#region src/index.ts
2930
+ /**
2931
+ * pi-ptc-subagents — DSH PTC mode (Programmable Tool Calling) for pi.
2932
+ *
2933
+ * This module is the extension entrypoint pi loads (`package.json` → `pi.extensions`).
2934
+ * The PTC machinery it exposes is complete and tested (T3): wire protocol, dispatcher,
2935
+ * bindings and the two worker surfaces. On top of it sit the two model-facing tools:
2936
+ *
2937
+ * - `ptc_run_code` — bindings + Node + `console.log`, program's return value is the result
2938
+ * - `ptc_workflow` — the same plus `log` / `phase` / `parallel` / `pipeline` and `args`
2939
+ *
2940
+ * There is no `agent()` helper on either surface (G1 #13 → decision B): calling it produces
2941
+ * a plain `ReferenceError` through the normal code-run error path.
2942
+ */
2943
+ /** Footer status label shown while the mode is on. */
2944
+ const MODE_STATUS_TEXT = "PTC";
2945
+ /**
2946
+ * Which tools the mode hides. The shipped extension always uses the default; it is a named
2947
+ * constant so a future settings surface (or a test) has one place to change it.
2948
+ */
2949
+ const MODE_HIDE_STRATEGY = DEFAULT_HIDE_STRATEGY;
2950
+ /**
2951
+ * What to tell the user when the mode turns on. Names what became unreachable, because that is the
2952
+ * part that surprises people — and the binding list, because that is the part they need in order
2953
+ * to know what a program can still do.
2954
+ */
2955
+ function describeEntry(base, hide) {
2956
+ return [
2957
+ `PTC mode on — ${hide === "all-but-ptc" ? "all other tools" : "built-in tools (now reachable only as tools.<name> inside a program)"} hidden.`,
2958
+ `Bindings available inside a program: ${resolveBindingNames(base).join(", ") || "(none)"}.`,
2959
+ "Run /ptc off to restore the normal tool set."
2960
+ ].join("\n");
2961
+ }
2962
+ function ptcSubagents(pi) {
2963
+ const mode = initialModeState();
2964
+ let briefingPending = false;
2965
+ /**
2966
+ * Bindings come from the mode's base snapshot while PTC mode is on, and from the live loadout
2967
+ * otherwise (T7, #21). See `src/mode/ptc-mode.ts` for why the snapshot is required: the mode
2968
+ * hides the built-ins, which would otherwise empty the binding table and make every
2969
+ * `tools.<name>(...)` call fail.
2970
+ */
2971
+ const getBindingSourceNames = () => bindingSource(mode, pi.getActiveTools());
2972
+ pi.registerTool(createPtcRunCodeTool({ getBindingSourceNames }));
2973
+ pi.registerTool(createPtcWorkflowTool({ getBindingSourceNames }));
2974
+ const paintStatus = (ctx) => {
2975
+ ctx.ui.setStatus(PTC_MODE_STATUS_KEY, mode.enabled ? ctx.ui.theme.fg("accent", MODE_STATUS_TEXT) : void 0);
2976
+ };
2977
+ const enterMode = (base, loadout, ctx, announcement) => {
2978
+ mode.enabled = true;
2979
+ mode.base = base;
2980
+ mode.ourLoadout = loadout;
2981
+ pi.setActiveTools([...loadout]);
2982
+ briefingPending = true;
2983
+ pi.appendEntry(PTC_MODE_ENTRY_TYPE, {
2984
+ enabled: true,
2985
+ base: [...base]
2986
+ });
2987
+ paintStatus(ctx);
2988
+ ctx.ui.notify(announcement, "info");
2989
+ };
2990
+ const exitMode = (ctx, opts) => {
2991
+ const base = mode.base;
2992
+ mode.enabled = false;
2993
+ mode.base = void 0;
2994
+ mode.ourLoadout = void 0;
2995
+ briefingPending = false;
2996
+ if (base !== void 0) pi.setActiveTools([...base]);
2997
+ pi.appendEntry(opts.customType, { enabled: false });
2998
+ paintStatus(ctx);
2999
+ if (opts.announce) ctx.ui.notify("PTC mode off — built-in tools are directly callable again.", "info");
3000
+ };
3001
+ /** Restore the persisted mode record, if this session has one. */
3002
+ const readPersistedMode = (ctx) => {
3003
+ const entries = ctx.sessionManager.getEntries();
3004
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
3005
+ const entry = entries[index];
3006
+ if (entry?.type !== "custom" || entry.customType !== "ptc-mode") continue;
3007
+ const data = entry.data;
3008
+ const base = Array.isArray(data?.base) ? data.base.filter((name) => typeof name === "string") : void 0;
3009
+ return {
3010
+ enabled: data?.enabled === true,
3011
+ ...base === void 0 ? {} : { base }
3012
+ };
3013
+ }
3014
+ };
3015
+ pi.registerCommand("ptc", {
3016
+ description: "Show or toggle PTC mode (built-in tools reachable only from inside a PTC program)",
3017
+ handler: async (args, ctx) => {
3018
+ const action = args.trim().toLowerCase();
3019
+ if (action === "off") {
3020
+ if (!mode.enabled) {
3021
+ ctx.ui.notify("PTC mode is already off.", "info");
3022
+ return;
3023
+ }
3024
+ exitMode(ctx, {
3025
+ announce: true,
3026
+ customType: PTC_MODE_ENTRY_TYPE
3027
+ });
3028
+ return;
3029
+ }
3030
+ if (action !== "on") {
3031
+ ctx.ui.notify(mode.enabled ? `PTC mode is ON — run /ptc off to restore built-in tools.\nBindings: ${resolveBindingNames(mode.base).join(", ") || "(none)"}` : "PTC mode is OFF — run /ptc on to enter it.", "info");
3032
+ return;
3033
+ }
3034
+ if (mode.enabled) {
3035
+ ctx.ui.notify("PTC mode is already on.", "info");
3036
+ return;
3037
+ }
3038
+ const decision = decideModeEntry({
3039
+ mode: ctx.mode,
3040
+ defaultMode: true,
3041
+ active: pi.getActiveTools(),
3042
+ manual: true,
3043
+ hide: MODE_HIDE_STRATEGY
3044
+ });
3045
+ if (!decision.enter) {
3046
+ ctx.ui.notify(decision.reason === "tools-unavailable" ? "Cannot enter PTC mode: ptc_run_code / ptc_workflow are not active in this session." : "Cannot enter PTC mode in this run mode.", "warning");
3047
+ return;
3048
+ }
3049
+ enterMode(decision.base, decision.loadout, ctx, describeEntry(decision.base, MODE_HIDE_STRATEGY));
3050
+ }
3051
+ });
3052
+ pi.on("session_start", async (_event, ctx) => {
3053
+ const config = readDefaultModeConfig(getAgentDir());
3054
+ if (config.error !== void 0) ctx.ui.notify(`pi-ptc-subagents: ${config.error}`, "warning");
3055
+ const persisted = readPersistedMode(ctx);
3056
+ const { base, restoreFirst } = resolveBaseOnStart(persisted, pi.getActiveTools());
3057
+ if (restoreFirst) pi.setActiveTools([...base]);
3058
+ const decision = decideModeEntry({
3059
+ mode: ctx.mode,
3060
+ defaultMode: config.defaultMode,
3061
+ active: base,
3062
+ manual: false,
3063
+ hide: MODE_HIDE_STRATEGY
3064
+ });
3065
+ const wantMode = persisted?.enabled ?? decision.enter;
3066
+ if (decision.enter && wantMode) {
3067
+ enterMode(base, decision.loadout, ctx, describeEntry(base, MODE_HIDE_STRATEGY));
3068
+ return;
3069
+ }
3070
+ paintStatus(ctx);
3071
+ if (!decision.enter && decision.reason !== "not-tui" && persisted === void 0) {
3072
+ if (decision.reason === "restricted-session") ctx.ui.notify("PTC mode skipped: this session was launched with an explicit tool restriction.", "info");
3073
+ }
3074
+ });
3075
+ /**
3076
+ * Put back the skills section pi withholds while the mode hides `read`/`bash` (ADR-0011).
3077
+ *
3078
+ * pi advertises skills only when the session can open a skill file at all (`read` or `bash`
3079
+ * among the selected tools), so a PTC session silently loses the whole `<available_skills>`
3080
+ * list: the model stops knowing skills exist. Writing `sections.skills` here is the seam pi
3081
+ * leaves open — custom sections are merged after its own, so this one wins.
3082
+ *
3083
+ * The same options object is reused across turns and sessions of a resume, so the injection is
3084
+ * undone the moment the mode stops hiding those tools: a `/ptc off` must not leave PTC-flavoured
3085
+ * loading instructions behind while `read` is directly callable again.
3086
+ */
3087
+ let skillsSectionInjected = false;
3088
+ const syncSkillsSection = (options, hidden) => {
3089
+ if (options === void 0) return;
3090
+ if (!mode.enabled || !hidden) {
3091
+ if (skillsSectionInjected) {
3092
+ delete options.sections.skills;
3093
+ skillsSectionInjected = false;
3094
+ }
3095
+ return;
3096
+ }
3097
+ const section = buildPtcSkillsSection(options.skills);
3098
+ if (section.length === 0) return;
3099
+ options.sections.skills = section;
3100
+ skillsSectionInjected = true;
3101
+ };
3102
+ pi.on("before_agent_start", async (event, ctx) => {
3103
+ const options = event.systemPromptOptions;
3104
+ syncSkillsSection(options, skillsSectionDropped(pi.getActiveTools()));
3105
+ if (!mode.enabled) return;
3106
+ if (detectExternalLoadoutChange(mode, pi.getActiveTools())) {
3107
+ exitMode(ctx, {
3108
+ announce: false,
3109
+ customType: PTC_MODE_ENTRY_TYPE
3110
+ });
3111
+ syncSkillsSection(options, skillsSectionDropped(pi.getActiveTools()));
3112
+ ctx.ui.notify("PTC mode off — another extension changed the active tool set.", "warning");
3113
+ return;
3114
+ }
3115
+ if (!briefingPending) return;
3116
+ briefingPending = false;
3117
+ return { message: {
3118
+ customType: "ptc-mode-briefing",
3119
+ content: buildModeInstruction(resolveBindingNames(mode.base), MODE_HIDE_STRATEGY),
3120
+ display: false
3121
+ } };
3122
+ });
3123
+ }
3124
+ //#endregion
3125
+ export { BUILTIN_BINDING_NAMES, DEFAULT_BINDING_NAMES, DEFAULT_CONFIG, DEFAULT_HIDE_STRATEGY, HOST_FRAME_KIND, MAX_LINE_CHARS, MODE_REQUIRED_TOOL_NAMES, PTC_ERROR_KIND, PTC_LOG_LEVEL, PTC_MODE_CONFIG_FILE, PTC_MODE_ENTRY_TYPE, PTC_MODE_STATUS_KEY, PTC_MODE_TOOL_NAMES, PTC_SKILL_LOAD_INSTRUCTION, SKILL_READING_TOOL_NAMES, WORKER_ENV_ALLOW_LIST, WORKER_FRAME_KIND, bindingSource, buildModeInstruction, buildPtcSkillsSection, createBuiltinBindings, createWorkerEnv, decideModeEntry, ptcSubagents as default, detectExternalLoadoutChange, effectiveTimeoutMs, initialModeState, modeLoadout, readDefaultModeConfig, renderModelValue, resolveBaseOnStart, resolveConfig, runPtcProgram, sameToolSet, sanitizeText, skillsSectionDropped, stripAnsi };
3126
+
3127
+ //# sourceMappingURL=index.js.map