pi-ptc-subagents 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -2
- package/dist/index.js +11 -11
- package/dist/worker.js +1 -1
- package/package.json +13 -13
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,41 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [5.0.1] - 2026-10-20
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- **pi 1.3.0 is now measured, not merely claimed.** The package declares
|
|
13
|
+
`@earendil-works/pi-coding-agent: ">=0.86.0"`, so it has always _claimed_ to work on every pi
|
|
14
|
+
release in that range — but 1.3.0, published on 2026-10-19, had never been measured. The
|
|
15
|
+
differential table's measured versions stopped at 1.2.0 and the compatibility matrix's version
|
|
16
|
+
list did not name it. pi 1.3.0 was installed on its own and the forty codemode-switch cases were
|
|
17
|
+
driven through **its own** `DefaultPackageManager.resolve()`: it answered identically to 1.2.0 on
|
|
18
|
+
all forty, and the static capability probe answered ✓ on all sixteen capability points. The
|
|
19
|
+
1.3.0 column is that measurement, not an inference from 1.2.0 being older. A user on pi 1.3.0
|
|
20
|
+
now has a version whose behaviour this package has actually observed rather than assumed.
|
|
21
|
+
- **The test toolchain moves to vitest 5, and the compatibility matrix can measure the version the
|
|
22
|
+
repository currently pins.** `vitest` 4.1.11 → 5.0.5, `@vitest/coverage-v8` 4.1.11 → 5.0.5,
|
|
23
|
+
`vite-plus` 0.3.3 → 1.3.0, `oxfmt` 0.70.0 → 0.73.0, `oxlint` 1.85.0 → 1.89.0, `@types/node`
|
|
24
|
+
22.20.4 → 26.6.5. The coverage provider and the test runner have to move together —
|
|
25
|
+
`@vitest/coverage-v8@5.0.5` declares `vitest: 5.0.5` as a peer, and the mismatched pair is what
|
|
26
|
+
produced 79 unhandled rejections (one per test file) in the upgrade's own CI. Separately,
|
|
27
|
+
`scripts/pi-compat-matrix.mjs` decided "this devDependency entry was not found" by asking
|
|
28
|
+
whether **replacing the version changed the text** — and replacing `1.3.0` with `1.3.0` does
|
|
29
|
+
not change the text, so the matrix could not measure the version the repository currently pins.
|
|
30
|
+
It asks whether the pattern matched now, and a test that _runs_ the function pins that.
|
|
31
|
+
- **The toolchain bump reformats 26 markdown files.** oxfmt 0.73 changed list-continuation
|
|
32
|
+
indentation and thematic-break fences. No prose changed. The files it touched carry a single
|
|
33
|
+
unpaired `---` rather than a YAML frontmatter block, so the site's frontmatter stripping never
|
|
34
|
+
matched them and does not match `***` either; the three files that do carry real frontmatter are
|
|
35
|
+
untouched.
|
|
36
|
+
|
|
37
|
+
### Fixed
|
|
38
|
+
|
|
39
|
+
- **Nothing in the published package's behaviour changed.** The runtime code, the tool
|
|
40
|
+
descriptions, the argument and result shapes and the declared peer range are all as 5.0.0
|
|
41
|
+
shipped them; this release carries development-side and documentation-side work only.
|
|
42
|
+
|
|
8
43
|
## [5.0.0] - 2026-10-19
|
|
9
44
|
|
|
10
45
|
### Added
|
|
@@ -518,7 +553,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
518
553
|
([ADR-0025](./docs/adr/0025-extension-surface-is-a-setting.md) §3 as amended).
|
|
519
554
|
|
|
520
555
|
**A pi older than 0.99.0 is unaffected.** `ToolExposure` does not exist there — `grep -r
|
|
521
|
-
exposure` over `pi-coding-agent@0.86.1`'s `dist/` returns nothing, and so does
|
|
556
|
+
exposure` over `pi-coding-agent@0.86.1`'s `dist/` returns nothing, and so does
|
|
522
557
|
`AgentSession._getCallableTools` — so the field is ignored and the tools are declared to the
|
|
523
558
|
model, which is correct: such a pi ships no `codemode`, resolves to `full` anyway, and has
|
|
524
559
|
nothing that could call a `codemode`-reach tool. Measured across 0.86.1 / 0.87.1 / 0.99.0 /
|
|
@@ -1130,7 +1165,7 @@ exposure` over `pi-coding-agent@0.86.1`'s `dist/` returns nothing, and so does
|
|
|
1130
1165
|
immediately instead of queueing.** The dispatcher used to read `maxParallelSubCalls`
|
|
1131
1166
|
(default 10) and FIFO-queue the overflow; per ADR-0016 §2 the N+1th concurrent
|
|
1132
1167
|
`pi.dispatch` now resolves at once with `{ status: "rejected", errorMessage:
|
|
1133
|
-
"dispatch concurrency limit reached" }`. The cap applies to `pi.dispatch` only and
|
|
1168
|
+
"dispatch concurrency limit reached" }`. The cap applies to `pi.dispatch` only and
|
|
1134
1169
|
has its own counter; builtin binding fan-out keeps DSH's `maxParallelSubCalls` (10)
|
|
1135
1170
|
FIFO-queueing semantics (ADR-0004), so in-flight builtin calls never consume
|
|
1136
1171
|
dispatch slots.
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./protocol-CfOgxz3u.js";import{DEFAULT_MAX_BYTES as s,DEFAULT_MAX_LINES as c,createBashTool as l,createEditTool as u,createFindTool as d,createGrepTool as f,createLsTool as p,createReadTool as m,createWriteTool as h,defineTool as g,formatSize as _,formatSkillsForPrompt as v,getAgentDir as y,truncateTail as b}from"@earendil-works/pi-coding-agent";import{Type as x}from"typebox";import{validateToolArguments as S}from"@earendil-works/pi-ai";import*as C from"node:fs";import{existsSync as w,readFileSync as T,realpathSync as E,statSync as D,writeFileSync as ee}from"node:fs";import*as te from"node:os";import{homedir as O,tmpdir as k}from"node:os";import*as A from"node:path";import{basename as ne,dirname as j,join as M,relative as N,resolve as P,sep as re}from"node:path";import{spawn as ie}from"node:child_process";import{randomBytes as ae,randomUUID as oe}from"node:crypto";import{ok as F}from"node:assert/strict";import{MessageChannel as se,Worker as ce}from"node:worker_threads";import le from"node:diagnostics_channel";import{fileURLToPath as ue,pathToFileURL as de}from"node:url";import{truncateToWidth as I,visibleWidth as L}from"@earendil-works/pi-tui";import{appendFile as fe,mkdir as pe,readFile as me,readdir as he,rename as ge,unlink as _e,writeFile as ve}from"node:fs/promises";import{minimatch as ye}from"minimatch";function R(e){return g(e)}const be=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`;function xe(e){let t=``,n=Math.max(0,Math.floor(e));for(let e=0;e<10;e++)t=(be[n%32]??`0`)+t,n=Math.floor(n/32);return t}function Se(e){let t=``,n=0,r=0;for(let i=0;i<e.length&&t.length<16;i++)for(n=n<<8|(e[i]??0),r+=8;r>=5&&t.length<16;)r-=5,t+=be[n>>>r&31];return t.padEnd(16,`0`)}function Ce(e){let t=new Uint8Array(e);for(let e=t.length-1;e>=0;e--){if((t[e]??0)<255)return t[e]=(t[e]??0)+1,t;t[e]=0}return t}function we(e){let t=e.randomBytes??(e=>new Uint8Array(ae(e))),n=-1,r=/* @__PURE__ */ new Uint8Array(10);return{next(){let i=Math.max(0,Math.floor(e.now())),a=i>n?i:n,o=a===n?Ce(r):t(10);return n=a,r=o,xe(a)+Se(o)}}}const Te=we({now:()=>Date.now()});function Ee(){return Te.next()}function De(e){let t=e.trim();if(t.length===0)return null;try{return JSON.parse(t)}catch{return null}}function Oe(e,t){if(e.pid===void 0)return!1;try{return e.kill(t),!0}catch{return!1}}function ke(e,t){if(e.eventWaiters.length>0){let n=e.eventWaiters.shift();n&&n(t)
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./protocol-CfOgxz3u.js";import{DEFAULT_MAX_BYTES as s,DEFAULT_MAX_LINES as c,createBashTool as l,createEditTool as u,createFindTool as d,createGrepTool as f,createLsTool as p,createReadTool as m,createWriteTool as h,defineTool as g,formatSize as _,formatSkillsForPrompt as v,getAgentDir as y,truncateTail as b}from"@earendil-works/pi-coding-agent";import{Type as x}from"typebox";import{validateToolArguments as S}from"@earendil-works/pi-ai";import*as C from"node:fs";import{existsSync as w,readFileSync as T,realpathSync as E,statSync as D,writeFileSync as ee}from"node:fs";import*as te from"node:os";import{homedir as O,tmpdir as k}from"node:os";import*as A from"node:path";import{basename as ne,dirname as j,join as M,relative as N,resolve as P,sep as re}from"node:path";import{spawn as ie}from"node:child_process";import{randomBytes as ae,randomUUID as oe}from"node:crypto";import{ok as F}from"node:assert/strict";import{MessageChannel as se,Worker as ce}from"node:worker_threads";import le from"node:diagnostics_channel";import{fileURLToPath as ue,pathToFileURL as de}from"node:url";import{truncateToWidth as I,visibleWidth as L}from"@earendil-works/pi-tui";import{appendFile as fe,mkdir as pe,readFile as me,readdir as he,rename as ge,unlink as _e,writeFile as ve}from"node:fs/promises";import{minimatch as ye}from"minimatch";function R(e){return g(e)}const be=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`;function xe(e){let t=``,n=Math.max(0,Math.floor(e));for(let e=0;e<10;e++)t=(be[n%32]??`0`)+t,n=Math.floor(n/32);return t}function Se(e){let t=``,n=0,r=0;for(let i=0;i<e.length&&t.length<16;i++)for(n=n<<8|(e[i]??0),r+=8;r>=5&&t.length<16;)r-=5,t+=be[n>>>r&31];return t.padEnd(16,`0`)}function Ce(e){let t=new Uint8Array(e);for(let e=t.length-1;e>=0;e--){if((t[e]??0)<255)return t[e]=(t[e]??0)+1,t;t[e]=0}return t}function we(e){let t=e.randomBytes??(e=>new Uint8Array(ae(e))),n=-1,r=/* @__PURE__ */ new Uint8Array(10);return{next(){let i=Math.max(0,Math.floor(e.now())),a=i>n?i:n,o=a===n?Ce(r):t(10);return n=a,r=o,xe(a)+Se(o)}}}const Te=we({now:()=>Date.now()});function Ee(){return Te.next()}function De(e){let t=e.trim();if(t.length===0)return null;try{return JSON.parse(t)}catch{return null}}function Oe(e,t){if(e.pid===void 0)return!1;try{return e.kill(t),!0}catch{return!1}}function ke(e,t){if(e.eventWaiters.length>0){let n=e.eventWaiters.shift();n&&n(t)}else e.events.push(t)}function Ae(e,t){if(e.exited)return;e.exited=!0,e.exitValue=t;for(let n of e.exitWaiters)n(t);e.exitWaiters=[];let n=e.eventWaiters;e.eventWaiters=[];for(let e of n)e(null);for(let t of e.stderrWaiters)t(e.stderr);e.stderrWaiters=[]}function je(e,t){let n=t.sessionDir===void 0?[...e]:e.filter(e=>e!==`--no-session`);return t.sessionDir!==void 0&&(n.push(`--session-dir`,t.sessionDir),t.sessionId!==void 0&&n.push(`--session-id`,t.sessionId),t.sessionName!==void 0&&n.push(`--name`,t.sessionName)),n}const Me={warn:e=>{console.warn(`[pi-ptc.lifecycle] `+e)}};function Ne(e){return e.length<=200?e:e.slice(0,200)+`…`}var Pe=class{#e;constructor(e={}){this.#e=e.logger??Me}spawn(e,t){if(e.length===0)throw TypeError(`RealChildProcessLifecycle.spawn: argv must include the command`);let n=je(e,t),r=n[0],i=n.slice(1),a=ie(r,i,{cwd:t.cwd,shell:!1,stdio:[`ignore`,`pipe`,`pipe`],env:t.env}),o={proc:a,events:[],eventWaiters:[],exited:!1,exitValue:null,stderrWaiters:[],exitWaiters:[],stderr:``,lineBuffer:``},s={id:Ee(),opaque:o},c=a.stdout;c&&c.on(`data`,e=>{o.lineBuffer+=e.toString(`utf-8`);let t=o.lineBuffer.indexOf(`
|
|
2
2
|
`);for(;t>=0;){let e=o.lineBuffer.slice(0,t);o.lineBuffer=o.lineBuffer.slice(t+1);let n=De(e);n?ke(o,n):e.trim().length>0&&this.#t(s,e),t=o.lineBuffer.indexOf(`
|
|
3
3
|
`)}});let l=a.stderr;return l&&l.on(`data`,e=>{o.stderr+=e.toString(`utf-8`)}),a.on(`close`,(e,t)=>{let n=o.lineBuffer.trim();if(n.length>0){let e=De(n);e?ke(o,e):this.#t(s,n),o.lineBuffer=``}Ae(o,{code:e,signal:t})}),a.on(`error`,e=>{o.stderr+=`[spawn-error] `+e.message+`
|
|
4
|
-
`,o.exited||Ae(o,{code:null,signal:null})}),s}kill(e,t){let n=e.opaque;Oe(n.proc,t)}events(e){let t=e.opaque;return{async*[Symbol.asyncIterator](){for(;;){if(t.events.length>0){let e=t.events.shift();e!==void 0&&(yield e);continue}if(t.exited)return;let e=await new Promise(e=>{t.eventWaiters.push(e)});if(e===null)return;yield e}}}}exit(e){let t=e.opaque;return t.exited&&t.exitValue?Promise.resolve(t.exitValue):new Promise(e=>{t.exitWaiters.push(e)})}stderr(e){let t=e.opaque;return t.exited?Promise.resolve(t.stderr):new Promise(e=>{t.stderrWaiters.push(e)})}#t(e,t){this.#e.warn(`child ${e.id}: dropped a non-JSON stdout line (${t.length} chars): `+Ne(t))}};const Fe=`ptc_child_report`,z=Object.freeze({timeoutMs:12e4,maxTimeoutMs:6e5,maxOutputBytes:67108864,maxMessageBytes:134217728,maxPendingCalls:128,maxParallelSubCalls:10,dispatchConcurrency:8,maxDispatchDepth:3,maxItemsPerCall:4096,graceMs:3e3,maxOldGenerationSizeMb:512,maxYoungGenerationSizeMb:64,poolSize:4,poolAcquireTimeoutMs:3e4,drainGraceMs:5e3}),Ie=Object.freeze([`PATH`,`PATHEXT`,`SYSTEMROOT`,`WINDIR`,`TEMP`,`TMP`]);function Le(e=process.env){let t={};for(let n of Ie){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}function Re(e={}){let t={...z};for(let n of Object.keys(z)){let r=e[n];if(r!==void 0){if(typeof r!=`number`||!Number.isFinite(r)||r<=0)throw TypeError(`invalid PTC config override for ${n}: ${String(r)}`);t[n]=r}}return t}function ze(e,t=z){return e===void 0||!Number.isFinite(e)||e<=0?t.timeoutMs:Math.min(e,t.maxTimeoutMs)}const Be={running:[`stopping`,`succeeded`,`failed`,`canceled`,`lost`],stopping:[`succeeded`,`failed`,`canceled`],succeeded:[],failed:[],canceled:[],lost:[]},Ve=/* @__PURE__ */ new Set([`succeeded`,`failed`,`canceled`,`lost`]),He=/* @__PURE__ */ new Set([`running`,`stopping`]);function Ue(e,t,n,r){if(n!==`canceled`&&n!==`succeeded`){if(t.childError!==void 0)return t.childError;if(t.stderrDiagnostic!==void 0)return t.stderrDiagnostic;if(t.exitCode===0&&!r)return`dispatch produced no final text`}}function We(e){return e===`running`||e===`stopping`||e===`succeeded`||e===`failed`||e===`canceled`||e===`lost`}function Ge(e){return typeof e==`string`&&e.length>0}const Ke=/* @__PURE__ */ new Set([`session_ended_while_running`,`user_killed_via_esc`,`lost_on_session_restart`]);function qe(e){return typeof e==`string`&&Ke.has(e)}function Je(e,t){return e.ownerPid===t.pid&&e.ownerBootMs===t.bootMs}function Ye(e){try{return process.kill(e,0),!0}catch(e){let t=e?.code;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}function Xe(e,t){let n=`task:${e}`;return t===`running`||t===`stopping`?`${n}:${t}`:`${n}:->${t}`}var Ze=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t.clock,this.#n=t.logger,this.#r=t.owner,this.#i=t.isPidAlive??Ye,this.#a=we({now:()=>this.#t()})}async transition(e,t){let n=await this.#h(()=>this.#c(e,t)),r=n.events[n.events.length-1];return r!==void 0&&this.#g(n.record,r,t.logger),n}onTransition(e){this.#o.add(e);let t=!0;return()=>{t&&(t=!1,this.#o.delete(e))}}async#c(e,t){switch(e.kind){case`spawn`:return this.#l(e,t);case`transition`:return this.#u(e,t);case`stop`:return this.#d(e,t);case`reconcile-lost`:return this.#p(e,t);case`resolve-exit`:return this.#f(e,t)}throw Error(`transition: unknown command kind ${String(e.kind)}`)}async get(e){return Ge(e)?await this.#e.loadTask(e):null}async query(e){let t=e.limit??100;if(!Number.isInteger(t)||t<0)throw Error(`query: limit must be a non-negative integer, got ${String(e.limit)}`);let n=e.orderBy??`createdAt-desc`,r=e.label===void 0?void 0:{label:e.label},i=[];for await(let t of this.#e.listTasks(r))(e.status===void 0||e.status.includes(t.status))&&i.push(t);return i.sort((e,t)=>n===`createdAt-asc`?e.createdAt-t.createdAt:t.createdAt-e.createdAt),i.slice(0,t)}async reconcileLostTasks(){let e=[];for await(let t of this.#e.listTasks())He.has(t.status)&&this.#_(t)&&e.push(t);let t=[];for(let n of e){let e=await this.transition({kind:`reconcile-lost`,taskId:n.id,reason:`lost_on_session_restart`},{clock:this.#t,callerId:this.#S(n),logger:this.#n});t.push(e.record)}return this.#n?.info(`reconcileLostTasks: marked ${t.length} task(s) lost`),t}async#l(e,t){let n=Math.max(0,Math.floor(t.clock())),r=e.handle;if(r==null)throw Error(`spawn: handle is required`);if(r.status!==`running`)throw Error(`spawn: handle.status must be "running", got ${String(r.status)}`);let i=Ge(r.taskId),a=i?r.taskId:this.#a.next();if(await this.#e.loadTask(a)!==null)throw Error(`spawn: task ${a} already exists (duplicate spawn)`);let o={...e.record,id:a,label:e.record.label.length>0?e.record.label:r.label,status:`running`,createdAt:n,startedAt:n,finishedAt:void 0,durationMs:void 0,transitionAt:n,parentTaskId:e.parentTaskId??e.record.parentTaskId};this.#r!==void 0&&(o.ownerPid=this.#r.pid,o.ownerBootMs=this.#r.bootMs),i||(r.taskId=a);let s=t.callerId,c=this.#x(a,s,`running`,n,o);return await this.#e.saveSubscription({subscriberId:s,taskId:a,cursor:c.eventId,status:`active`,createdAt:n}),await this.#e.appendEvents(s,[c]),await this.#e.saveTask(o),(t.logger??this.#n)?.info(`spawn: task ${a} (${o.label}) running for subscriber ${s}`),{record:o,events:[c],cursor:c.eventId}}async#u(e,t){if(!We(e.to))throw Error(`transition: unknown target state ${String(e.to)}`);let n=await this.#y(e.taskId);if(this.#v(n,e.to),e.to===`lost`&&!qe(e.reason))throw Error(`transition: to "lost" requires a LostReason (session_ended_while_running | user_killed_via_esc | lost_on_session_restart)`+(e.reason===void 0?``:`, got ${String(e.reason)}`));return this.#m(n,e.to,t,{reason:e.reason,stopReason:e.stopReason,errorMessage:e.errorMessage,exitCode:e.exitCode,outputRef:e.outputRef,outputBytes:e.outputBytes,outputPreview:e.outputPreview})}async#d(e,t){let n=await this.#y(e.taskId);return n.status===`stopping`?{record:n,events:[],cursor:(await this.#e.loadSubscription(t.callerId,n.id))?.cursor??n.id,fromStatus:n.status}:(this.#v(n,`stopping`),this.#m(n,`stopping`,t,{stopReason:e.reason}))}async#f(e,t){let n=await this.#y(e.taskId);if(n.status!==`running`&&n.status!==`stopping`)throw Error(`resolve-exit: task ${n.id} is terminal (${n.status}); the single terminal writer refuses to overwrite it`);let r=(e.outputBytes??0)>0,i=n.status===`stopping`?`canceled`:e.exitCode===0&&r?`succeeded`:`failed`;return this.#v(n,i),this.#m(n,i,t,{exitCode:e.exitCode,outputRef:e.outputRef,outputBytes:e.outputBytes,outputPreview:e.outputPreview,errorMessage:Ue(n,e,i,r),usage:e.usage,observedProvider:e.observedProvider,observedModel:e.observedModel,...i===`succeeded`?{report:e.report,reportChannel:e.reportChannel}:{}})}async#p(e,t){let n=await this.#y(e.taskId);if(!He.has(n.status))throw Error(`reconcile-lost: task ${n.id} is terminal (${n.status}); only running/stopping tasks can be reconciled`);return this.#m(n,`lost`,t,{errorMessage:e.reason})}async#m(e,t,n,r){let i=Math.max(0,Math.floor(n.clock())),a={...e,status:t,transitionAt:i};Ve.has(t)&&(a.finishedAt=i,a.durationMs=i-e.startedAt),r.stopReason!==void 0&&(a.stopReason=r.stopReason),r.errorMessage!==void 0&&(a.errorMessage=r.errorMessage),r.exitCode!==void 0&&(a.exitCode=r.exitCode),r.outputRef!==void 0&&(a.outputRef=r.outputRef),r.outputBytes!==void 0&&(a.outputBytes=r.outputBytes),r.outputPreview!==void 0&&(a.outputPreview=r.outputPreview),r.report!==void 0&&(a.report=r.report),r.reportChannel!==void 0&&(a.reportChannel=r.reportChannel),r.usage!==void 0&&(a.usage=r.usage),r.observedProvider!==void 0&&(a.observedProvider=r.observedProvider),r.observedModel!==void 0&&(a.observedModel=r.observedModel),r.reason!==void 0&&((t===`stopping`||t===`canceled`)&&a.stopReason===void 0&&(a.stopReason=r.reason),(t===`failed`||t===`lost`)&&a.errorMessage===void 0&&(a.errorMessage=r.reason));let o=n.callerId,s=this.#x(e.id,o,t,i,a);return await this.#b(o,e.id,i,s.eventId),await this.#e.appendEvents(o,[s]),await this.#e.saveTask(a),(n.logger??this.#n)?.info(`transition: task ${e.id} ${e.status} -> ${t} (subscriber ${o})`),{record:a,events:[s],cursor:s.eventId,fromStatus:e.status}}async#h(e){let t=this.#s.then(e,e);return this.#s=t.then(()=>void 0,()=>void 0),await t}#g(e,t,n){for(let r of this.#o)try{r(e,t)}catch(t){let r=t instanceof Error?t.message:String(t),i=`transition observer threw for task ${e.id}: ${r}`,a=n??this.#n;a===void 0?console.warn(`[task-registry] `+i):a.warn(i)}}#_(e){return e.ownerPid===void 0||!this.#i(e.ownerPid)}#v(e,t){let n=Be[e.status];if(!n.includes(t)){let r=n.length===0?`<terminal>`:n.join(`, `);throw Error(`illegal transition for task ${e.id}: ${e.status} -> ${t} (allowed from ${e.status}: ${r})`)}}async#y(e){if(!Ge(e))throw Error(`transition: taskId is required`);let t=await this.#e.loadTask(e);if(t===null)throw Error(`transition: unknown taskId ${e}`);return t}async#b(e,t,n,r){await this.#e.loadSubscription(e,t)===null&&(await this.#e.saveSubscription({subscriberId:e,taskId:t,cursor:r,status:`active`,createdAt:n}),this.#n?.warn(`subscription: auto-created for subscriber ${e} on task ${t} at cursor ${r}`))}#x(e,t,n,r,i){let a=i.outputBytes,o=a!==void 0&&a<=2048?i.outputPreview:void 0;return{eventId:this.#a.next(),subscriptionId:t,taskId:e,type:Xe(e,n),status:n,transitionAtMs:r,outputBytes:a,outputPreview:o}}#S(e){let t=e.spawnSource.callerId;return t.length>0?t:e.id}};function Qe(e,t){return new Ze(e,t)}function $e(e){return e.provider+`/`+e.id}function et(e){if(typeof e!=`object`||!e)return;let t=e.model;if(typeof t!=`object`||!t)return;let n=t.provider,r=t.id;if(tt(n)&&tt(r))return{provider:n,id:r}}function tt(e){if(typeof e!=`string`)return!1;let t=e.trim();return!(t.length===0||t.length>200||t!==e||/\s/.test(e)||/\p{Cc}/u.test(e)||e.startsWith(`-`))}const nt=/* @__PURE__ */ RegExp(`\x1B(?:\\[[0-?]*[ -/]*[@-~]|\\][^\x07]*(?:\x07|\x1B\\\\)?)`,`g`),rt=/[\p{Cc}\p{Cf}]/gu;function it(e){return e.replace(nt,``).replace(rt,``).trim()}function at(e,t){let n=t===void 0?``:it(t);if(n.length===0)return;let r=e===void 0?``:it(e),i=r.length===0?n:r+`/`+n;return i.length<=200?i:i.slice(0,200)}function ot(e){let t=e;if(t.provider===void 0&&t.model===void 0)return e;let{provider:n,model:r,...i}=t,a={...i};return a.observedProvider===void 0&&typeof n==`string`&&(a.observedProvider=n),a.observedModel===void 0&&typeof r==`string`&&(a.observedModel=r),a}function st(e,t){return e.eventId<t.eventId?-1:+(e.eventId>t.eventId)}function ct(e){for(let t=1;t<e.length;t++)if(st(e[t-1],e[t])>0)return!1;return!0}var lt=class e{#e;#t;#n;#r;constructor(){this.#e=/* @__PURE__ */ new Map,this.#t=/* @__PURE__ */ new Map,this.#n=/* @__PURE__ */ new Set,this.#r=/* @__PURE__ */ new Map}static#i(e,t){return`${e}-${t}`}#a(e){return this.#n.has(e)}async loadTask(e){let t=this.#e.get(e);return t===void 0?null:structuredClone(t)}async saveTask(e){F(e,`saveTask: record is required`),this.#e.set(e.id,structuredClone(e))}async deleteTask(e){if(!this.#e.has(e))throw Error(`deleteTask: unknown taskId ${e}`);this.#e.delete(e)}async*listTasks(e){for(let t of this.#e.values())(e?.status===void 0||t.status===e.status)&&(e?.label===void 0||t.label===e.label)&&(yield structuredClone(t))}async loadSubscription(t,n){let r=this.#t.get(e.#i(t,n));return r===void 0?null:structuredClone(r)}async saveSubscription(t){F(t,`saveSubscription: sub is required`);let n=e.#i(t.subscriberId,t.taskId);this.#t.set(n,structuredClone(t)),this.#n.add(t.subscriberId)}async appendEvents(e,t){if(!this.#a(e))throw Error(`appendEvents: unknown subscriptionId ${e}`);if(t.length===0)return;let n=this.#r.get(e)??[],r=ct(t)?[...t]:[...t].sort(st),i=n.length===0?void 0:n[n.length-1]?.eventId,a=r[0]?.eventId;if(i===void 0||a!==void 0&&i<=a){for(let e of r)n.push(structuredClone(e));this.#r.set(e,n);return}let o=[...n,...r.map(e=>structuredClone(e))];o.sort(st),this.#r.set(e,o)}async*loadEvents(e,t){if(!this.#a(e))throw Error(`loadEvents: unknown subscriptionId ${e}`);let n=this.#r.get(e)??[],r=0;if(t!==void 0){let e=0,i=n.length;for(;e<i;){let r=e+i>>>1;(n[r]?.eventId??``)<=t?e=r+1:i=r}r=e}for(let e=r;e<n.length;e++)yield structuredClone(n[e])}};const ut=new Pe;var dt=class{limit;#e;#t=/* @__PURE__ */ new Set;constructor(e){if(!Number.isInteger(e)||e<0)throw TypeError(`DispatchSlotCounter: limit must be a non-negative integer, got ${String(e)}`);this.limit=e,this.#e=0}get active(){return this.#e}tryAcquire(e){return e!==void 0&&this.#t.has(e)||this.#e>=this.limit?!1:(e!==void 0&&this.#t.add(e),this.#e+=1,!0)}release(e){if(e!==void 0){if(!this.#t.delete(e))return;--this.#e;return}this.#e>this.#t.size&&--this.#e}};const ft=new dt(z.dispatchConcurrency);let pt;function mt(e,t){return e.taskRegistry===void 0?(pt??=new Ze(new lt,{clock:t}),pt):e.taskRegistry}const ht={info:()=>void 0,warn:e=>{console.warn(`[pi.dispatch] `+e)}},gt=[`read`,`grep`,`find`,`ls`];function _t(e){return e===`strict`||e===`lenient`?e:void 0}function vt(e){return e==null||e===`strict`||e===`lenient`}function yt(e){return{text:``,status:`rejected`,started:!1,agentName:`unknown`,durationMs:0,exitCode:-1,reportChannel:`none`,errorMessage:`invalid readOnly value: `+(typeof e==`object`&&e?JSON.stringify(e):String(e))+` (readOnly accepts "strict" or "lenient"; null and undefined ask for no tier)`}}function bt(e,t){return t===void 0?e:{...e,readOnlyTier:t}}function xt(e,t){let n=typeof e==`string`?e.trim():``;return n.length===0?{why:void 0,suppressed:!1}:t?{why:n,suppressed:!1}:{why:void 0,suppressed:!0}}function St(e,t){return t?{...e,whySuppressed:!0}:e}const Ct=Object.freeze({name:``,source:`unknown`,systemPrompt:``});function wt(e,t,n,r={}){let i=r.reportContract!==!1,a=_t(r.readOnly),o=[`<pi-ptc-context depth="`+t+`" max-depth="`+n+`">`,`You are a PTC run at depth `+t+` (root is depth 0). You may write PTC programs and you may`,`call pi.dispatch(...) to spawn further children, but each level costs a fresh pi subprocess.`,`The remaining depth budget is `+n+` - `+t+`. Beyond it, pi.dispatch rejects with`,`{ status: "rejected", errorMessage: "dispatch depth limit reached" }.`,`You were dispatched by another pi session as a fresh context. You cannot see that session's`,`conversation and you cannot ask it anything, so if the task you were given is underspecified,`,`say which part is underspecified and answer the rest rather than inventing the missing`,`context. Your final message is the deliverable: it is what the caller receives, so put the`,`answer there rather than narrating how you found it.`,...i?['Before you finish, hand the host a child report. Prefer calling the `ptc_child_report` tool once with it. If that tool is not available to you, end your reply with a fenced ```json block containing a JSON object with exactly these keys: "summary" (one line, your own words), "findings" (an array of objects each with "what" and "evidence", where evidence is the independent thing that supports the claim), and "files_touched" (an array of paths you created or modified). Either way your prose answer is kept alongside the report and never replaced by it, and you must not report usage or token counts — those are measured by the host.']:[],...a===`lenient`?[`You were dispatched read-only: do not create, modify or delete files, and do not run commands that would. Your tools are otherwise all still available to you — this is an instruction, not a restriction, so a task that genuinely needs to write is worth saying so rather than failing quietly.`]:[],`</pi-ptc-context>`].join(`
|
|
4
|
+
`,o.exited||Ae(o,{code:null,signal:null})}),s}kill(e,t){let n=e.opaque;Oe(n.proc,t)}events(e){let t=e.opaque;return{async*[Symbol.asyncIterator](){for(;;){if(t.events.length>0){let e=t.events.shift();e!==void 0&&(yield e);continue}if(t.exited)return;let e=await new Promise(e=>{t.eventWaiters.push(e)});if(e===null)return;yield e}}}}exit(e){let t=e.opaque;return t.exited&&t.exitValue?Promise.resolve(t.exitValue):new Promise(e=>{t.exitWaiters.push(e)})}stderr(e){let t=e.opaque;return t.exited?Promise.resolve(t.stderr):new Promise(e=>{t.stderrWaiters.push(e)})}#t(e,t){this.#e.warn(`child ${e.id}: dropped a non-JSON stdout line (${t.length} chars): `+Ne(t))}};const Fe=`ptc_child_report`,z=Object.freeze({timeoutMs:12e4,maxTimeoutMs:6e5,maxOutputBytes:67108864,maxMessageBytes:134217728,maxPendingCalls:128,maxParallelSubCalls:10,dispatchConcurrency:8,maxDispatchDepth:3,maxItemsPerCall:4096,graceMs:3e3,maxOldGenerationSizeMb:512,maxYoungGenerationSizeMb:64,poolSize:4,poolAcquireTimeoutMs:3e4,drainGraceMs:5e3}),Ie=Object.freeze([`PATH`,`PATHEXT`,`SYSTEMROOT`,`WINDIR`,`TEMP`,`TMP`]);function Le(e=process.env){let t={};for(let n of Ie){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}function Re(e={}){let t={...z};for(let n of Object.keys(z)){let r=e[n];if(r!==void 0){if(typeof r!=`number`||!Number.isFinite(r)||r<=0)throw TypeError(`invalid PTC config override for ${n}: ${String(r)}`);t[n]=r}}return t}function ze(e,t=z){return e===void 0||!Number.isFinite(e)||e<=0?t.timeoutMs:Math.min(e,t.maxTimeoutMs)}const Be={running:[`stopping`,`succeeded`,`failed`,`canceled`,`lost`],stopping:[`succeeded`,`failed`,`canceled`],succeeded:[],failed:[],canceled:[],lost:[]},Ve=/* @__PURE__ */ new Set([`succeeded`,`failed`,`canceled`,`lost`]),He=/* @__PURE__ */ new Set([`running`,`stopping`]);function Ue(e,t,n,r){if(n!==`canceled`&&n!==`succeeded`){if(t.childError!==void 0)return t.childError;if(t.stderrDiagnostic!==void 0)return t.stderrDiagnostic;if(t.exitCode===0&&!r)return`dispatch produced no final text`}}function We(e){return e===`running`||e===`stopping`||e===`succeeded`||e===`failed`||e===`canceled`||e===`lost`}function Ge(e){return typeof e==`string`&&e.length>0}const Ke=/* @__PURE__ */ new Set([`session_ended_while_running`,`user_killed_via_esc`,`lost_on_session_restart`]);function qe(e){return typeof e==`string`&&Ke.has(e)}function Je(e,t){return e.ownerPid===t.pid&&e.ownerBootMs===t.bootMs}function Ye(e){try{return process.kill(e,0),!0}catch(e){let t=e?.code;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}function Xe(e,t){let n=`task:${e}`;return t===`running`||t===`stopping`?`${n}:${t}`:`${n}:->${t}`}var Ze=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t.clock,this.#n=t.logger,this.#r=t.owner,this.#i=t.isPidAlive??Ye,this.#a=we({now:()=>this.#t()})}async transition(e,t){let n=await this.#h(()=>this.#c(e,t)),r=n.events[n.events.length-1];return r!==void 0&&this.#g(n.record,r,t.logger),n}onTransition(e){this.#o.add(e);let t=!0;return()=>{t&&(t=!1,this.#o.delete(e))}}async#c(e,t){switch(e.kind){case`spawn`:return this.#l(e,t);case`transition`:return this.#u(e,t);case`stop`:return this.#d(e,t);case`reconcile-lost`:return this.#p(e,t);case`resolve-exit`:return this.#f(e,t)}throw Error(`transition: unknown command kind ${String(e.kind)}`)}async get(e){return Ge(e)?await this.#e.loadTask(e):null}async query(e){let t=e.limit??100;if(!Number.isInteger(t)||t<0)throw Error(`query: limit must be a non-negative integer, got ${String(e.limit)}`);let n=e.orderBy??`createdAt-desc`,r=e.label===void 0?void 0:{label:e.label},i=[];for await(let t of this.#e.listTasks(r))(e.status===void 0||e.status.includes(t.status))&&i.push(t);return i.sort((e,t)=>n===`createdAt-asc`?e.createdAt-t.createdAt:t.createdAt-e.createdAt),i.slice(0,t)}async reconcileLostTasks(){let e=[];for await(let t of this.#e.listTasks())He.has(t.status)&&this.#_(t)&&e.push(t);let t=[];for(let n of e){let e=await this.transition({kind:`reconcile-lost`,taskId:n.id,reason:`lost_on_session_restart`},{clock:this.#t,callerId:this.#S(n),logger:this.#n});t.push(e.record)}return this.#n?.info(`reconcileLostTasks: marked ${t.length} task(s) lost`),t}async#l(e,t){let n=Math.max(0,Math.floor(t.clock())),r=e.handle;if(r==null)throw Error(`spawn: handle is required`);if(r.status!==`running`)throw Error(`spawn: handle.status must be "running", got ${String(r.status)}`);let i=Ge(r.taskId),a=i?r.taskId:this.#a.next();if(await this.#e.loadTask(a)!==null)throw Error(`spawn: task ${a} already exists (duplicate spawn)`);let o={...e.record,id:a,label:e.record.label.length>0?e.record.label:r.label,status:`running`,createdAt:n,startedAt:n,finishedAt:void 0,durationMs:void 0,transitionAt:n,parentTaskId:e.parentTaskId??e.record.parentTaskId};this.#r!==void 0&&(o.ownerPid=this.#r.pid,o.ownerBootMs=this.#r.bootMs),i||(r.taskId=a);let s=t.callerId,c=this.#x(a,s,`running`,n,o);return await this.#e.saveSubscription({subscriberId:s,taskId:a,cursor:c.eventId,status:`active`,createdAt:n}),await this.#e.appendEvents(s,[c]),await this.#e.saveTask(o),(t.logger??this.#n)?.info(`spawn: task ${a} (${o.label}) running for subscriber ${s}`),{record:o,events:[c],cursor:c.eventId}}async#u(e,t){if(!We(e.to))throw Error(`transition: unknown target state ${String(e.to)}`);let n=await this.#y(e.taskId);if(this.#v(n,e.to),e.to===`lost`&&!qe(e.reason))throw Error(`transition: to "lost" requires a LostReason (session_ended_while_running | user_killed_via_esc | lost_on_session_restart)`+(e.reason===void 0?``:`, got ${String(e.reason)}`));return this.#m(n,e.to,t,{reason:e.reason,stopReason:e.stopReason,errorMessage:e.errorMessage,exitCode:e.exitCode,outputRef:e.outputRef,outputBytes:e.outputBytes,outputPreview:e.outputPreview})}async#d(e,t){let n=await this.#y(e.taskId);return n.status===`stopping`?{record:n,events:[],cursor:(await this.#e.loadSubscription(t.callerId,n.id))?.cursor??n.id,fromStatus:n.status}:(this.#v(n,`stopping`),this.#m(n,`stopping`,t,{stopReason:e.reason}))}async#f(e,t){let n=await this.#y(e.taskId);if(n.status!==`running`&&n.status!==`stopping`)throw Error(`resolve-exit: task ${n.id} is terminal (${n.status}); the single terminal writer refuses to overwrite it`);let r=(e.outputBytes??0)>0,i=n.status===`stopping`?`canceled`:e.exitCode===0&&r?`succeeded`:`failed`;return this.#v(n,i),this.#m(n,i,t,{exitCode:e.exitCode,outputRef:e.outputRef,outputBytes:e.outputBytes,outputPreview:e.outputPreview,errorMessage:Ue(n,e,i,r),usage:e.usage,observedProvider:e.observedProvider,observedModel:e.observedModel,...i===`succeeded`?{report:e.report,reportChannel:e.reportChannel}:{}})}async#p(e,t){let n=await this.#y(e.taskId);if(!He.has(n.status))throw Error(`reconcile-lost: task ${n.id} is terminal (${n.status}); only running/stopping tasks can be reconciled`);return this.#m(n,`lost`,t,{errorMessage:e.reason})}async#m(e,t,n,r){let i=Math.max(0,Math.floor(n.clock())),a={...e,status:t,transitionAt:i};Ve.has(t)&&(a.finishedAt=i,a.durationMs=i-e.startedAt),r.stopReason!==void 0&&(a.stopReason=r.stopReason),r.errorMessage!==void 0&&(a.errorMessage=r.errorMessage),r.exitCode!==void 0&&(a.exitCode=r.exitCode),r.outputRef!==void 0&&(a.outputRef=r.outputRef),r.outputBytes!==void 0&&(a.outputBytes=r.outputBytes),r.outputPreview!==void 0&&(a.outputPreview=r.outputPreview),r.report!==void 0&&(a.report=r.report),r.reportChannel!==void 0&&(a.reportChannel=r.reportChannel),r.usage!==void 0&&(a.usage=r.usage),r.observedProvider!==void 0&&(a.observedProvider=r.observedProvider),r.observedModel!==void 0&&(a.observedModel=r.observedModel),r.reason!==void 0&&((t===`stopping`||t===`canceled`)&&a.stopReason===void 0&&(a.stopReason=r.reason),(t===`failed`||t===`lost`)&&a.errorMessage===void 0&&(a.errorMessage=r.reason));let o=n.callerId,s=this.#x(e.id,o,t,i,a);return await this.#b(o,e.id,i,s.eventId),await this.#e.appendEvents(o,[s]),await this.#e.saveTask(a),(n.logger??this.#n)?.info(`transition: task ${e.id} ${e.status} -> ${t} (subscriber ${o})`),{record:a,events:[s],cursor:s.eventId,fromStatus:e.status}}async#h(e){let t=this.#s.then(e,e);return this.#s=t.then(()=>void 0,()=>void 0),await t}#g(e,t,n){for(let r of this.#o)try{r(e,t)}catch(t){let r=t instanceof Error?t.message:String(t),i=`transition observer threw for task ${e.id}: ${r}`,a=n??this.#n;a===void 0?console.warn(`[task-registry] `+i):a.warn(i)}}#_(e){return e.ownerPid===void 0||!this.#i(e.ownerPid)}#v(e,t){let n=Be[e.status];if(!n.includes(t)){let r=n.length===0?`<terminal>`:n.join(`, `);throw Error(`illegal transition for task ${e.id}: ${e.status} -> ${t} (allowed from ${e.status}: ${r})`)}}async#y(e){if(!Ge(e))throw Error(`transition: taskId is required`);let t=await this.#e.loadTask(e);if(t===null)throw Error(`transition: unknown taskId ${e}`);return t}async#b(e,t,n,r){await this.#e.loadSubscription(e,t)===null&&(await this.#e.saveSubscription({subscriberId:e,taskId:t,cursor:r,status:`active`,createdAt:n}),this.#n?.warn(`subscription: auto-created for subscriber ${e} on task ${t} at cursor ${r}`))}#x(e,t,n,r,i){let a=i.outputBytes,o=a!==void 0&&a<=2048?i.outputPreview:void 0;return{eventId:this.#a.next(),subscriptionId:t,taskId:e,type:Xe(e,n),status:n,transitionAtMs:r,outputBytes:a,outputPreview:o}}#S(e){let t=e.spawnSource.callerId;return t.length>0?t:e.id}};function Qe(e,t){return new Ze(e,t)}function $e(e){return e.provider+`/`+e.id}function et(e){if(typeof e!=`object`||!e)return;let t=e.model;if(typeof t!=`object`||!t)return;let n=t.provider,r=t.id;if(tt(n)&&tt(r))return{provider:n,id:r}}function tt(e){if(typeof e!=`string`)return!1;let t=e.trim();return!(t.length===0||t.length>200||t!==e||/\s/.test(e)||/\p{Cc}/u.test(e)||e.startsWith(`-`))}const nt=/* @__PURE__ */ RegExp(`\x1B(?:\\[[0-?]*[ -/]*[@-~]|\\][^\x07]*(?:\x07|\x1B\\\\)?)`,`g`),rt=/[\p{Cc}\p{Cf}]/gu;function it(e){return e.replace(nt,``).replace(rt,``).trim()}function at(e,t){let n=t===void 0?``:it(t);if(n.length===0)return;let r=e===void 0?``:it(e),i=r.length===0?n:r+`/`+n;return i.length<=200?i:i.slice(0,200)}function ot(e){let t=e;if(t.provider===void 0&&t.model===void 0)return e;let{provider:n,model:r,...i}=t,a={...i};return a.observedProvider===void 0&&typeof n==`string`&&(a.observedProvider=n),a.observedModel===void 0&&typeof r==`string`&&(a.observedModel=r),a}function st(e,t){return e.eventId<t.eventId?-1:+(e.eventId>t.eventId)}function ct(e){for(let t=1;t<e.length;t++)if(st(e[t-1],e[t])>0)return!1;return!0}var lt=class e{#e;#t;#n;#r;constructor(){this.#e=/* @__PURE__ */ new Map,this.#t=/* @__PURE__ */ new Map,this.#n=/* @__PURE__ */ new Set,this.#r=/* @__PURE__ */ new Map}static#i(e,t){return`${e}-${t}`}#a(e){return this.#n.has(e)}async loadTask(e){let t=this.#e.get(e);return t===void 0?null:structuredClone(t)}async saveTask(e){F(e,`saveTask: record is required`),this.#e.set(e.id,structuredClone(e))}async deleteTask(e){if(!this.#e.has(e))throw Error(`deleteTask: unknown taskId ${e}`);this.#e.delete(e)}async*listTasks(e){for(let t of this.#e.values())(e?.status===void 0||t.status===e.status)&&(e?.label===void 0||t.label===e.label)&&(yield structuredClone(t))}async loadSubscription(t,n){let r=this.#t.get(e.#i(t,n));return r===void 0?null:structuredClone(r)}async saveSubscription(t){F(t,`saveSubscription: sub is required`);let n=e.#i(t.subscriberId,t.taskId);this.#t.set(n,structuredClone(t)),this.#n.add(t.subscriberId)}async appendEvents(e,t){if(!this.#a(e))throw Error(`appendEvents: unknown subscriptionId ${e}`);if(t.length===0)return;let n=this.#r.get(e)??[],r=ct(t)?[...t]:[...t].sort(st),i=n.length===0?void 0:n[n.length-1]?.eventId,a=r[0]?.eventId;if(i===void 0||a!==void 0&&i<=a){for(let e of r)n.push(structuredClone(e));this.#r.set(e,n);return}let o=[...n,...r.map(e=>structuredClone(e))];o.sort(st),this.#r.set(e,o)}async*loadEvents(e,t){if(!this.#a(e))throw Error(`loadEvents: unknown subscriptionId ${e}`);let n=this.#r.get(e)??[],r=0;if(t!==void 0){let e=0,i=n.length;for(;e<i;){let r=e+i>>>1;(n[r]?.eventId??``)<=t?e=r+1:i=r}r=e}for(let e=r;e<n.length;e++)yield structuredClone(n[e])}};const ut=new Pe;var dt=class{limit;#e;#t=/* @__PURE__ */ new Set;constructor(e){if(!Number.isInteger(e)||e<0)throw TypeError(`DispatchSlotCounter: limit must be a non-negative integer, got ${String(e)}`);this.limit=e,this.#e=0}get active(){return this.#e}tryAcquire(e){return e!==void 0&&this.#t.has(e)||this.#e>=this.limit?!1:(e!==void 0&&this.#t.add(e),this.#e+=1,!0)}release(e){if(e!==void 0){if(!this.#t.delete(e))return;--this.#e}else this.#e>this.#t.size&&--this.#e}};const ft=new dt(z.dispatchConcurrency);let pt;function mt(e,t){return e.taskRegistry===void 0?(pt??=new Ze(new lt,{clock:t}),pt):e.taskRegistry}const ht={info:()=>void 0,warn:e=>{console.warn(`[pi.dispatch] `+e)}},gt=[`read`,`grep`,`find`,`ls`];function _t(e){return e===`strict`||e===`lenient`?e:void 0}function vt(e){return e==null||e===`strict`||e===`lenient`}function yt(e){return{text:``,status:`rejected`,started:!1,agentName:`unknown`,durationMs:0,exitCode:-1,reportChannel:`none`,errorMessage:`invalid readOnly value: `+(typeof e==`object`&&e?JSON.stringify(e):String(e))+` (readOnly accepts "strict" or "lenient"; null and undefined ask for no tier)`}}function bt(e,t){return t===void 0?e:{...e,readOnlyTier:t}}function xt(e,t){let n=typeof e==`string`?e.trim():``;return n.length===0?{why:void 0,suppressed:!1}:t?{why:n,suppressed:!1}:{why:void 0,suppressed:!0}}function St(e,t){return t?{...e,whySuppressed:!0}:e}const Ct=Object.freeze({name:``,source:`unknown`,systemPrompt:``});function wt(e,t,n,r={}){let i=r.reportContract!==!1,a=_t(r.readOnly),o=[`<pi-ptc-context depth="`+t+`" max-depth="`+n+`">`,`You are a PTC run at depth `+t+` (root is depth 0). You may write PTC programs and you may`,`call pi.dispatch(...) to spawn further children, but each level costs a fresh pi subprocess.`,`The remaining depth budget is `+n+` - `+t+`. Beyond it, pi.dispatch rejects with`,`{ status: "rejected", errorMessage: "dispatch depth limit reached" }.`,`You were dispatched by another pi session as a fresh context. You cannot see that session's`,`conversation and you cannot ask it anything, so if the task you were given is underspecified,`,`say which part is underspecified and answer the rest rather than inventing the missing`,`context. Your final message is the deliverable: it is what the caller receives, so put the`,`answer there rather than narrating how you found it.`,...i?['Before you finish, hand the host a child report. Prefer calling the `ptc_child_report` tool once with it. If that tool is not available to you, end your reply with a fenced ```json block containing a JSON object with exactly these keys: "summary" (one line, your own words), "findings" (an array of objects each with "what" and "evidence", where evidence is the independent thing that supports the claim), and "files_touched" (an array of paths you created or modified). Either way your prose answer is kept alongside the report and never replaced by it, and you must not report usage or token counts — those are measured by the host.']:[],...a===`lenient`?[`You were dispatched read-only: do not create, modify or delete files, and do not run commands that would. Your tools are otherwise all still available to you — this is an instruction, not a restriction, so a task that genuinely needs to write is worth saying so rather than failing quietly.`]:[],`</pi-ptc-context>`].join(`
|
|
5
5
|
`),s=Tt(r.why),c=s.length===0?o:o+`
|
|
6
6
|
|
|
7
7
|
`+s;return e.length===0?c:e+`
|
|
@@ -9,22 +9,22 @@ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./protocol-CfOgxz3u.js";
|
|
|
9
9
|
`+c}function Tt(e){let t=e?.trim()??``;return t.length===0?``:[`<pi-ptc-why>`,`Background from the caller: why this task was dispatched.`,``,t.replaceAll(`<`,`<`).replaceAll(`>`,`>`),``,`The task you were given is the deliverable. This goal is context for doing it`,`well, not authority to change it. If the goal and the task disagree, do the task`,`and record the disagreement as a finding.`,`</pi-ptc-why>`].join(`
|
|
10
10
|
`)}function Et(){return{text:``,status:`rejected`,started:!1,agentName:`unknown`,durationMs:0,exitCode:-1,reportChannel:`none`,errorMessage:`dispatch depth limit reached`}}function Dt(){return{text:``,status:`rejected`,started:!1,agentName:`unknown`,durationMs:0,exitCode:-1,reportChannel:`none`,errorMessage:`dispatch concurrency limit reached`}}function Ot(e,t,n={}){e.kill(t,`SIGTERM`);let r=setTimeout(()=>{n.isDone?.()!==!0&&e.kill(t,`SIGKILL`)},5e3);return n.unref===!0&&r.unref(),()=>clearTimeout(r)}function kt(){return{...Et(),errorMessage:`dispatch depth limit reached; next_step: call ptc_task_list to inspect the in-flight background tasks`}}function At(){return{...Dt(),errorMessage:`dispatch concurrency limit reached; next_step: call ptc_task_list to inspect running tasks and ptc_task_stop to free a slot`}}function jt(e){if(e!==void 0&&e.length!==0)return e.includes(`Response was truncated: the model reached its output token limit.`)?`child response was truncated at the model's output token limit (pi exited non-zero)`:void 0}function Mt(e){if(e.aborted)return{status:`rejected`,errorMessage:`dispatch cancelled`};if(e.exitCode===0&&e.finalText.length>0)return{status:`fulfilled`};if(e.childError!==void 0&&e.childError.length>0)return{status:`rejected`,errorMessage:e.childError};if(e.exitCode===0)return{status:`rejected`,errorMessage:`dispatch produced no final text`};let t=jt(e.stderr);return{status:`rejected`,...t===void 0?{}:{errorMessage:t}}}function Nt(e,t){let n=e.match(RegExp(`^`+t+`:\\s*(.+)$`,`m`));if(!n)return;let r=(n[1]??``).trim();if(r.length>=2){let e=r[0],t=r[r.length-1];(e===`"`&&t===`"`||e===`'`&&t===`'`)&&(r=r.slice(1,-1))}return r.length===0?void 0:r}function Pt(e,t){let n=e.match(RegExp(`^`+t+`:\\s*(.+)$`,`m`));if(!n)return;let r=(n[1]??``).trim();r.startsWith(`[`)&&r.endsWith(`]`)&&(r=r.slice(1,-1));let i=r.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return i.length===0?void 0:i}function Ft(e){let t=Nt(e,`childReport`);if(t!==void 0)return t.toLowerCase()!==`false`&&t.toLowerCase()!==`no`}function It(e){return e.childReport!==!1}function Lt(e){let t=e.match(/^\uFEFF?[ \t]*(?:\r?\n)?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/);if(!t)return null;let n=(t[1]??``).replace(/\r\n/g,`
|
|
11
11
|
`),r=(t[2]??``).replace(/\r\n/g,`
|
|
12
|
-
`),i=Nt(n,`name`);if(!i)return null;let a=Nt(n,`description`)??``,o=Nt(n,`model`)??``,s=Pt(n,`tools`),c=Ft(n),l={name:i,systemPrompt:r.trim()};return a!==void 0&&(l.description=a),o!==void 0&&(l.model=o),s!==void 0&&(l.tools=s),c!==void 0&&(l.childReport=c),l}function Rt(e){let t=e.replace(/^\uFEFF/,``).split(/\r?\n/).find(e=>e.trim().length>0);if(t===void 0)return!1;let n=t.trim();return n===`---`||/^name[ \t]*:/.test(n)}function zt(e){let{userDir:t,projectDir:n,userRoot:r,projectRoot:i}=Vt(e),a=[];(e.agentScope===`user`||e.agentScope===`both`)&&a.push({dir:t,boundary:r,source:`user`}),(e.agentScope===`project`||e.agentScope===`both`)&&a.push({dir:n,boundary:i,source:`project`});let o=/* @__PURE__ */ new Map,s=[];for(let{dir:e,boundary:t,source:n}of a){let r;try{r=C.readdirSync(e)}catch(n){Kt(e,t,n)||s.push(`pi.dispatch: cannot read agent directory ${e} (${Ht(n)}); the agents registered there are not listed`);continue}r.sort();for(let t of r){if(!t.endsWith(`.md`))continue;let r=A.join(e,t),i;try{i=C.readFileSync(r,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);s.push(`pi.dispatch: cannot read agent file ${r}: ${t}; skipping it`);continue}let a=Lt(i);if(!a){Rt(i)&&s.push(`pi.dispatch: agent file ${r} looks like an agent definition but its frontmatter did not parse (no usable \`name:\`); it is not listed and cannot be dispatched`);continue}let c=o.get(a.name);
|
|
12
|
+
`),i=Nt(n,`name`);if(!i)return null;let a=Nt(n,`description`)??``,o=Nt(n,`model`)??``,s=Pt(n,`tools`),c=Ft(n),l={name:i,systemPrompt:r.trim()};return a!==void 0&&(l.description=a),o!==void 0&&(l.model=o),s!==void 0&&(l.tools=s),c!==void 0&&(l.childReport=c),l}function Rt(e){let t=e.replace(/^\uFEFF/,``).split(/\r?\n/).find(e=>e.trim().length>0);if(t===void 0)return!1;let n=t.trim();return n===`---`||/^name[ \t]*:/.test(n)}function zt(e){let{userDir:t,projectDir:n,userRoot:r,projectRoot:i}=Vt(e),a=[];(e.agentScope===`user`||e.agentScope===`both`)&&a.push({dir:t,boundary:r,source:`user`}),(e.agentScope===`project`||e.agentScope===`both`)&&a.push({dir:n,boundary:i,source:`project`});let o=/* @__PURE__ */ new Map,s=[];for(let{dir:e,boundary:t,source:n}of a){let r;try{r=C.readdirSync(e)}catch(n){Kt(e,t,n)||s.push(`pi.dispatch: cannot read agent directory ${e} (${Ht(n)}); the agents registered there are not listed`);continue}r.sort();for(let t of r){if(!t.endsWith(`.md`))continue;let r=A.join(e,t),i;try{i=C.readFileSync(r,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);s.push(`pi.dispatch: cannot read agent file ${r}: ${t}; skipping it`);continue}let a=Lt(i);if(!a){Rt(i)&&s.push(`pi.dispatch: agent file ${r} looks like an agent definition but its frontmatter did not parse (no usable \`name:\`); it is not listed and cannot be dispatched`);continue}let c=o.get(a.name);c?c.source===n&&s.push(`pi.dispatch: agent name "${a.name}" is declared by both ${c.filePath} and ${r}; using ${c.filePath} and shadowing the other (#205)`):o.set(a.name,{name:a.name,description:(a.description??``).trim(),source:n,filePath:r,...a.model===void 0?{}:{model:a.model},...a.tools===void 0?{}:{tools:a.tools},...a.childReport===void 0?{}:{childReport:a.childReport},systemPrompt:a.systemPrompt})}}return{definitions:o,diagnostics:s}}function Bt(e,t,n,r){let{definitions:i}=zt({cwd:t,agentScope:n,homeDir:r?.homeDir}),a=i.get(e);if(a===void 0)return null;let o={name:a.name,source:a.source,systemPrompt:a.systemPrompt};return a.model!==void 0&&(o.model=a.model),a.tools!==void 0&&(o.tools=a.tools),a.childReport!==void 0&&(o.childReport=a.childReport),o}function Vt(e){let t=e.homeDir??te.homedir();return{userDir:A.join(t,`.pi`,`agent`,`agents`),projectDir:A.join(e.cwd,`.pi`,`agents`),userRoot:t,projectRoot:e.cwd}}function Ht(e){let t=e?.code;return typeof t==`string`?t:String(e)}function Ut(e){try{return!C.statSync(e).isDirectory()}catch{try{return C.lstatSync(e),!0}catch{return!1}}}function Wt(e,t){let n=A.resolve(e),r=A.resolve(t),i=e=>A.dirname(e),a=n,o=!1;for(let e=0;e<=8;e+=1){try{if(C.statSync(a).isDirectory()){o=!0;break}}catch{}if(a===r)break;let e=i(a);if(e===a)break;a=e}if(o){for(let e=n;e!==a&&e!==i(e);e=i(e))if(Gt(e))return!0;return!1}return a===r&&Gt(r)}function Gt(e){try{return C.lstatSync(e).isSymbolicLink()}catch{return!1}}function Kt(e,t,n){let r=Ht(n);return r!==`ENOENT`&&r!==`ENOTDIR`||Ut(e)?!1:!Wt(e,t)}function qt(e){let{definitions:t,diagnostics:n}=zt(e);for(let e of n)console.warn(e);return[...t.values()].map(e=>({name:e.name,description:e.description,source:e.source}))}function Jt(e){return qt(e).map(e=>e.name).sort()}function Yt(e){let t=qt(e),n="`agent` is optional: omit it for a fresh generalist pi with pi's own system prompt and its full toolset. Name a definition to NARROW the child instead.";if(t.length===0)return n+` None are registered here, so there is nothing to name.`;let r=t.map(e=>{let t=e.description.length>0?e.description:`(no description given)`;return`- ${e.name} (${e.source} scope): ${t}`});return n+"\nRegistered definitions — pass `agentScope` matching the scope shown, since it defaults "+`to "user" and does not see the others:
|
|
13
13
|
`+r.join(`
|
|
14
14
|
`)}function Xt(e){let{userDir:t,projectDir:n}=Vt(e),r=Jt(e);return`registered agents: ${r.length>0?`[`+r.join(`, `)+`]`:`(none)`} — agents load from ${t} (user scope) or ${n} (project scope); register one as an agent markdown file: frontmatter header (\`---\\nname: <agent-name>\\n---\`) followed by the system prompt body. the \`name:\` header IS the agent's name: naming the file after it is the convention, but the two are independent, so a definition is dispatchable under the name it declares even when the file is named otherwise`}function Zt(e){return{text:``,status:`rejected`,started:!1,agentName:``,durationMs:0,exitCode:1,reportChannel:`none`,errorMessage:`agent, when given, must be a non-empty string — omit it entirely to dispatch a generalist child; `+Xt(e)}}function Qt(e){return e!==void 0&&(typeof e!=`string`||e.trim().length===0)}function $t(e){return e===void 0}function en(e,t,n){if($t(e.agent))return{kind:`resolved`,agent:Ct};let r=Bt(e.agent,t,n);return r?{kind:`resolved`,agent:r}:{kind:`unknown`,name:e.agent}}function tn(e,t,n,r=0){return{text:``,status:`rejected`,started:!1,agentName:e,durationMs:r,exitCode:1,reportChannel:`none`,errorMessage:`unknown agent: `+e+` (agentScope=`+t+`, cwd=`+n+`). `+Xt({cwd:n,agentScope:t})}}function nn(e,t){if(_t(t)===`strict`)return It(e)?[...gt,Fe]:gt;let n=e.tools??[];if(!It(e))return n.length>0?n:void 0;if(n.length!==0)return n.includes(`ptc_child_report`)?n:[...n,Fe]}function rn(e,t,n,r){let i=[`--mode`,`json`,`-p`,`--no-session`],a=e.model||t.model||(r?$e(r):void 0);a&&i.push(`--model`,a);let o=e.thinkingLevel??`off`;i.push(`--thinking`,o);let s=nn(t,e.readOnly);return s!==void 0&&i.push(`--tools`,s.join(`,`)),i.push(`--append-system-prompt`,n),i.push(`Task: `+e.task),i}let an=on;async function on(e,t){let n=await C.promises.mkdtemp(A.join(te.tmpdir(),`pi-dispatch-`)),r=e.replace(/[^\w.-]+/g,`_`),i=A.join(n,`prompt-`+r+`.md`);return await C.promises.writeFile(i,t,{encoding:`utf-8`,mode:384}),{dir:n,filePath:i}}function sn(e){try{C.unlinkSync(e.filePath)}catch{}try{C.rmdirSync(e.dir)}catch{}}function cn(e){if(e.type!==`message_end`||e.message?.role!==`assistant`)return;let t=e.message.content;if(!Array.isArray(t))return;let n;for(let e of t)e&&e.type===`text`&&typeof e.text==`string`&&(n=e.text);return n}function ln(e,t){if(t.type!==`message_end`)return e;let n=t.message;if(n?.role!==`assistant`||n.usage===void 0)return e;let r=e??{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,turns:0};return r.input+=n.usage.input??0,r.output+=n.usage.output??0,r.cacheRead+=n.usage.cacheRead??0,r.cacheWrite+=n.usage.cacheWrite??0,r.cost+=n.usage.cost?.total??0,r.turns+=1,r}function un(e,t){if(t.type!==`message_end`||t.message?.role!==`assistant`)return e;let n=dn(t.message.provider)?t.message.provider:void 0,r=dn(t.message.model)?t.message.model:void 0;if(n===void 0&&r===void 0)return e;let i={...e};return n!==void 0&&(i.provider=n),r!==void 0&&(i.model=r),i}function dn(e){return typeof e==`string`&&e.length>0}function fn(e){let t=[],n;for(let r of e.split(`
|
|
15
|
-
`)){let e=r.trim();if(n===void 0){let t=/^(`{3,}|~{3,})(.*)$/.exec(e);t&&(n={marker:(t[1]??``)[0],info:(t[2]??``).trim(),body:[]})
|
|
15
|
+
`)){let e=r.trim();if(n===void 0){let t=/^(`{3,}|~{3,})(.*)$/.exec(e);t&&(n={marker:(t[1]??``)[0],info:(t[2]??``).trim(),body:[]})}else RegExp(`^`+n.marker+`{3,}\\s*$`).test(e)?(t.push({info:n.info,body:n.body.join(`
|
|
16
16
|
`)}),n=void 0):n.body.push(r)}return n!==void 0&&t.push({info:n.info,body:n.body.join(`
|
|
17
17
|
`)}),t}function pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mn(e){if(!pn(e))return;let{summary:t,findings:n,files_touched:r}=e;if(typeof t!=`string`||!Array.isArray(n))return;let i=[];for(let e of n){if(!pn(e)||typeof e.what!=`string`||typeof e.evidence!=`string`)return;i.push({what:e.what,evidence:e.evidence})}if(!Array.isArray(r))return;let a=[];for(let e of r){if(typeof e!=`string`)return;a.push(e)}return{summary:t,findings:i,files_touched:a}}function hn(e){let t=fn(e),n=t[t.length-1];if(n===void 0)return{reportChannel:`none`};let r;try{r=JSON.parse(n.body)}catch{return{reportChannel:`none`}}let i=mn(r);return i===void 0?{reportChannel:`none`}:{report:i,reportChannel:`prompt-json`}}function gn(e){if(e.type===`tool_execution_end`&&e.toolName===`ptc_child_report`&&e.isError!==!0)return mn(e.result?.structuredContent)}function _n(){return{prompt:{reportChannel:`none`},tool:void 0}}function vn(e,t){let n=gn(t);n!==void 0&&(e.tool=n)}function yn(e){return e.tool===void 0?e.prompt:{report:e.tool,reportChannel:`tool`}}function bn(e){if(e.type!==`message_end`||e.message?.role!==`assistant`)return;let t=e.message;if(t.stopReason!==`error`)return;let n=t.errorMessage;return typeof n==`string`&&n.trim().length>0?n.trim():`child reported stopReason: error`}async function xn(e,t,n,r){let i=xt(e.why,n.whyEnabled!==!1),a=e=>St(bt(e,r),i.suppressed),o=t.depth+1;if(o>t.maxDispatchDepth)return a(kt());if(Qt(e.agent))return a(Zt({cwd:e.cwd??t.cwd,agentScope:e.agentScope??`user`}));let s=Ee(),c=n.slots??ft;if(!c.tryAcquire(s))return a(At());let l=n.clock??(()=>Date.now()),u=n.logger??ht,d=e.cwd??t.cwd,f=e.agentScope??`user`,p=n.lifecycle??ut,m=t.callerId??`dispatch:`+String(t.callId),h=mt(n,l),g=n.outputStorage,_=en(e,d,f);if(_.kind===`unknown`)return c.release(s),a(tn(_.name,f,d));let v=_.agent,y,b;try{let n=e.label??e.task.slice(0,64),a=It(v),f=wt(v.systemPrompt,o,t.maxDispatchDepth,{reportContract:a,readOnly:e.readOnly,why:i.why}),_=await an(v.name,f);b=_;let x=rn(e,v,_.filePath,t.sessionModel),S={cwd:d,env:{...process.env,PI_PTC_DEPTH:String(o),PI_PTC_TASK_ID:s},promptFile:_.filePath};t.sessionDir!==void 0&&(S.sessionDir=t.sessionDir,S.sessionId=s,S.sessionName=`bgdispatch:`+s),y=p.spawn([`pi`,...x],S);let C=y,w={kind:`ptc-program`,callerId:m};await h.transition({kind:`spawn`,handle:{taskId:s,label:n,status:`running`},record:{label:n,agentName:v.name,depth:o,startedAt:Math.max(0,Math.floor(l())),finishedAt:void 0,durationMs:void 0,outputRef:void 0,outputBytes:void 0,outputPreview:void 0,stopReason:void 0,errorMessage:void 0,exitCode:void 0,spawnSource:w,parentTaskId:t.parentTaskId,...r===void 0?{}:{readOnlyTier:r},...i.suppressed?{whySuppressed:!0}:{}}},{clock:l,callerId:m,logger:u});let T=!1,E,D=h.onTransition((e,t)=>{e.id===s&&t.status===`stopping`&&(T||E!==void 0||(E=Ot(p,C,{isDone:()=>T,unref:!0})))});return(async()=>{let e=``,t,n,r=_n(),i;try{for await(let a of p.events(C)){vn(r,a);let o=cn(a);o!==void 0&&(e=o,r.prompt=hn(o)),i=ln(i,a),n=un(n,a);let s=bn(a);s!==void 0&&(t=s)}T=!0,E?.();let o=(await p.exit(C)).code??-1,c=await p.stderr(C),d=o===0?void 0:jt(c),f=Buffer.byteLength(e,`utf8`),_=f<=2048?e:void 0,v;if(g!==void 0)try{await g.writeOutput(s,e),v=g.outputRef(s)}catch(e){let t=e instanceof Error?e.message:String(e);u.warn(`background dispatch output persistence for task `+s+` failed: `+t)}let y=a?yn(r):{reportChannel:`opted-out`},b=await h.transition({kind:`resolve-exit`,taskId:s,exitCode:o,reportChannel:y.reportChannel,usage:i,observedProvider:n?.provider,observedModel:n?.model,...y.report===void 0?{}:{report:{...y.report,usage:{input:i?.input??0,output:i?.output??0,cost:i?.cost??0,turns:i?.turns??0}}},outputRef:v,outputBytes:f,outputPreview:_,childError:t,...d===void 0?{}:{stderrDiagnostic:d}},{clock:l,callerId:m,logger:u});b.record.status===`failed`&&b.record.errorMessage!==void 0&&u.warn(`background dispatch task `+s+` failed: `+b.record.errorMessage)}catch(t){let n=t instanceof Error?t.message:String(t);u.warn(`background dispatch pump for task `+s+` failed after `+String(e.length)+` chars of buffered output: `+n)}finally{D(),E?.(),sn(_),c.release(s)}})(),{taskId:s,label:n,status:`running`}}catch(e){let t=e instanceof Error?e.message:String(e);return y!==void 0&&Ot(p,y,{unref:!0}),b!==void 0&&sn(b),c.release(s),u.warn(`background dispatch failed for agent `+v.name+`: `+t),a({text:``,status:`rejected`,started:y!==void 0,agentName:v.name,durationMs:0,exitCode:-1,reportChannel:`none`,errorMessage:`background dispatch failed: `+t})}}async function Sn(e,t,n={}){let r=xt(e.why,n.whyEnabled!==!1),i=_t(e.readOnly),a=e=>St(bt(e,i),r.suppressed);if(!vt(e.readOnly))return a(yt(e.readOnly));if(e.background===!0)return await xn(e,t,n,i);let o=t.depth+1;if(o>t.maxDispatchDepth)return a(Et());let s=e.cwd??t.cwd,c=e.agentScope??`user`,l=Date.now();if(Qt(e.agent))return a(Zt({cwd:s,agentScope:c}));let u=n.slots??ft;if(!u.tryAcquire())return a(Dt());let d=en(e,s,c);if(d.kind===`unknown`)return u.release(),a(tn(d.name,c,s,Date.now()-l));let f=d.agent,p=It(f),m=wt(f.systemPrompt,o,t.maxDispatchDepth,{reportContract:p,readOnly:e.readOnly,why:r.why}),h,g=n.lifecycle??ut,_;try{h=await an(f.name,m),_=rn(e,f,h.filePath,t.sessionModel)}catch(e){throw u.release(),e}return await new Promise(e=>{let r=``,i,c=_n(),d=-1,m=``,v,y,b=!1,x,S,C=!1,w=(o,s,_=!0)=>{if(b)return;b=!0,u.release(),S!==void 0&&g.exit(S).catch(e=>{(n.logger??ht).warn(`exit() failed for a foreground child; the session live set may retain it: `+(e instanceof Error?e.message:String(e)))}),x?.(),t.signal&&t.signal.removeEventListener(`abort`,T),sn(h);let C=p?yn(c):{reportChannel:`opted-out`},w=a({text:r,status:o,started:_,agentName:f.name,durationMs:Date.now()-l,exitCode:d,reportChannel:C.reportChannel});C.report&&(w.report={...C.report,usage:{input:i?.input??0,output:i?.output??0,cost:i?.cost??0,turns:i?.turns??0}}),i&&(w.usage=i),y?.provider!==void 0&&(w.observedProvider=y.provider),y?.model!==void 0&&(w.observedModel=y.model),m.length>0&&(w.stderr=m),s&&(w.errorMessage=s),o===`rejected`&&_&&v!==void 0&&(n.logger??ht).warn(`foreground dispatch failed: `+v),e(w)},T=()=>{S&&!b&&(C=!0,x=Ot(g,S,{isDone:()=>b}))};try{S=g.spawn([`pi`,..._],{cwd:s,env:{...process.env,PI_PTC_DEPTH:String(o)},promptFile:h.filePath})}catch(e){w(`rejected`,`failed to spawn pi: `+(e instanceof Error?e.message:String(e)),!1);return}t.signal&&(t.signal.aborted?T():t.signal.addEventListener(`abort`,T,{once:!0})),(async()=>{if(!S)return;let e=S;try{for await(let t of g.events(e)){vn(c,t),y=un(y,t);let e=bn(t);if(e!==void 0&&(v=e),t.type===`message_end`&&t.message&&t.message.role===`assistant`){let e=t.message;if(i=ln(i,t),Array.isArray(e.content))for(let t of e.content)t&&t.type===`text`&&typeof t.text==`string`&&(r=t.text,c.prompt=hn(t.text))}}let t=await ut.exit(e);d=t.code??-1,m=await ut.stderr(e);let n=m.match(/^\[spawn-error\] (.+)$/m);if(n&&t.code===null&&t.signal===null){w(`rejected`,`failed to spawn pi: `+n[1],!1);return}let{status:a,errorMessage:o}=Mt({exitCode:d,finalText:r,aborted:C,stderr:m,childError:v});w(a,o)}catch(e){let t=e instanceof Error?e.message:String(e);w(`rejected`,`dispatch internal error: `+t)}})()})}const B=[`read`,`bash`,`edit`,`write`,`grep`,`find`,`ls`],V=`pi.dispatch`,Cn=[`bash`];function wn(e){return Cn.includes(e)}function Tn(e){if(e===void 0)return[];let t=new Set(e);for(let e of t)if(!wn(e))throw TypeError(`unknown PTC opt-in binding "${e}"; opt-in bindings: ${Cn.join(`, `)}`);return B.filter(e=>t.has(e))}const En=B.filter(e=>!wn(e)),Dn={read:m,bash:l,edit:u,write:h,grep:f,find:d,ls:p},On=x.Object({agent:x.Optional(x.String({minLength:1,description:`Optional. Name a registered agent definition to narrow the child, or omit it entirely for a fresh generalist pi with pi's own prompt and its full toolset. A name with no definition behind it is refused; an empty string is refused.`})),task:x.String({minLength:1}),why:x.Optional(x.String({description:`Why this dispatch slice exists, in your own words: the intent behind cutting this task out, not the whole conversation and not the user's original request. Pass it when the task involves judgment or trade-offs, so the child can resolve ambiguities the task text leaves open instead of inventing context. Omit it for a fully specified task.`})),cwd:x.Optional(x.String()),agentScope:x.Optional(x.Union([x.Literal(`user`),x.Literal(`project`),x.Literal(`both`)],{description:`Which agent directories to search: "user" (~/.pi/agent/agents, the default), "project" (<cwd>/.pi/agents), or "both". Defaults to "user", which cannot see project agents.`})),model:x.Optional(x.String({description:`Omit to inherit the caller session's current model (when this pi exposes one; otherwise pi's configured default applies); pass a model id (or let the agent definition pin one) to override.`})),thinkingLevel:x.Optional(x.String()),background:x.Optional(x.Boolean()),label:x.Optional(x.String()),readOnly:x.Optional(x.Union([x.Literal(`strict`),x.Literal(`lenient`)],{description:`Ask for a read-only child. "strict": its tools are narrowed to the read set, so it cannot write anything. "lenient": its tools are left exactly as they would have been and it is only told to work without modifying anything. Omit for today’s behaviour.`}))}),kn={name:V,description:`Dispatch a task to a registered pi agent as a child subprocess (foreground await or background task).`,parameters:On};function An(e){return _t(e?.readOnly)}function jn(e,t){return xt(e?.why,t).suppressed}function Mn(e,t){let n=t.trim();return n.length===0?`${e} reported a failure with no message`:`${e} failed: ${n.length<=2e3?n:`…${n.slice(-2e3)}`}`}function Nn(e){let t=new Set(Tn(e.optIns)),n=e.names??B.filter(e=>En.includes(e)||t.has(e)),r=e.includeDispatch??e.names===void 0,i=/* @__PURE__ */ new Map;for(let t of n){let n=Dn[t];if(!n)throw TypeError(`unknown PTC binding "${t}"; known bindings: ${B.join(`, `)}`);let r=n(e.cwd);i.set(t,{name:t,execute:async(e,t)=>{let n=`ptc:${t.callId}`,i={type:`toolCall`,id:n,name:r.name,arguments:e},a=S(r,i),o;try{o=await r.execute(n,a,t.signal,void 0)}catch(e){throw Error(Mn(r.name,e instanceof Error?e.message:String(e)))}if(o.isError===!0)throw Error(Mn(r.name,(o.content??[]).filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
18
|
-
`)));return{content:o.content,details:o.details===void 0?null:o.details}}})}return r&&i.set(V,{name:V,execute:async(t,n)=>{let r={type:`toolCall`,id:`ptc:${n.callId}`,name:V,arguments:t},i;try{i=S(kn,r)}catch(r){let i=typeof t==`object`&&t&&!Array.isArray(t)?t:void 0,a=i?.agent,o=i?.agentScope,s=jn(i,n.dispatchDeps?.whyEnabled!==!1);return Qt(a)?St(bt(Zt({cwd:e.cwd,agentScope:o===`user`||o===`project`||o===`both`?o:`user`}),An(i)),s):St(bt({text:``,status:`rejected`,started:!1,agentName:typeof a==`string`?a:``,durationMs:0,exitCode:1,reportChannel:`none`,errorMessage:r instanceof Error?r.message:String(r)},An(i)),s)}return Sn(i,{signal:n.signal,callId:n.callId,cwd:e.cwd,depth:n.depth,maxDispatchDepth:n.maxDispatchDepth,...n.callerId===void 0?{}:{callerId:n.callerId},...n.sessionDir===void 0?{}:{sessionDir:n.sessionDir},...n.parentTaskId===void 0?{}:{parentTaskId:n.parentTaskId},...n.sessionModel===void 0?{}:{sessionModel:n.sessionModel}},n.dispatchDeps)}}),i}function Pn(){let e=/* @__PURE__ */ new Map;return{recordStart(t,n,r){if(e.has(t))throw Error(`duplicate sub-call callId ${t}`);e.set(t,{callId:t,name:n,args:r,status:`running`,startMs:Date.now()})},recordEnd(t,n,r){let i=e.get(t);if(i===void 0)throw Error(`recordEnd on unknown callId ${t}`);return i.status=n,i.endMs=Date.now(),i.durationMs=i.endMs-i.startMs,n===`rejected`&&(i.durationMs=0),r?.errorMessage!==void 0&&(i.errorMessage=r.errorMessage),r?.resultSummary!==void 0&&(i.resultSummary=r.resultSummary),i},snapshot(){return[...e.values()].map(e=>({...e}))}}}function Fn(e){return{name:`ptc-${e.surface}`,env:e.env,workerData:e.runId===void 0?{env:e.env}:{runId:e.runId,env:e.env},resourceLimits:{maxOldGenerationSizeMb:e.limits.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:e.limits.maxYoungGenerationSizeMb}}}const In={acquireLatency:le.channel(`ptc:pool:acquire-latency`),resetTime:le.channel(`ptc:worker:reset-time`),imageBytes:le.channel(`ptc:image:hoist-bytes`)};function Ln(e,t){e.publish(t)}var Rn=class{#e;#t;#n;#r;#i;#a=[];#o=/* @__PURE__ */ new Set;#s=[];#c=/* @__PURE__ */ new WeakMap;#l=0;#u=0;#d=!1;constructor(e){if(typeof e.buildWorkerUrl!=`function`)throw TypeError(`WorkerPool: buildWorkerUrl must be a function`);if(e.size!==void 0&&(typeof e.size!=`number`||!Number.isFinite(e.size)||e.size<=0))throw TypeError(`WorkerPool: size must be a positive finite number, received ${String(e.size)}`);if(e.acquireTimeoutMs!==void 0&&(typeof e.acquireTimeoutMs!=`number`||!Number.isFinite(e.acquireTimeoutMs)||e.acquireTimeoutMs<=0))throw TypeError(`WorkerPool: acquireTimeoutMs must be a positive finite number, received ${String(e.acquireTimeoutMs)}`);if(e.drainGraceMs!==void 0&&(typeof e.drainGraceMs!=`number`||!Number.isFinite(e.drainGraceMs)||e.drainGraceMs<=0))throw TypeError(`WorkerPool: drainGraceMs must be a positive finite number, received ${String(e.drainGraceMs)}`);this.#e=e.buildWorkerUrl,this.#t=e.size??4,this.#n=e.acquireTimeoutMs??3e4,this.#r=e.drainGraceMs??5e3,this.#i=e.workerOptions}async acquire(){if(this.#d)throw Error(`pool has been drained and can no longer serve workers`);this.#l+=1;let e=Date.now(),t=this.#a.shift();for(;t!==void 0&&!this.#p(t);)t=this.#a.shift();if(t!==void 0)return this.#o.add(t),t.ref(),Ln(In.acquireLatency,{poolSize:this.#t,waiters:this.#s.length,durationMs:Date.now()-e}),t;if(this.#o.size<this.#t){let t=this.#f();return this.#o.add(t),Ln(In.acquireLatency,{poolSize:this.#t,waiters:this.#s.length,durationMs:Date.now()-e}),t}return this.#u+=1,await new Promise((t,n)=>{let r=setTimeout(()=>{let e=this.#s.findIndex(e=>e.timer===r);e>=0&&this.#s.splice(e,1),n(/* @__PURE__ */ Error(`pool acquire timed out after ${this.#n} ms`))},this.#n);this.#s.push({resolve:t,reject:n,timer:r,startedAt:e})})}release(e){if(!this.#o.delete(e)||!this.#p(e))return;this.#c.set(e,Date.now());let t=this.#s.shift();
|
|
19
|
-
`);return e===-1?t:t.slice(0,e)}}}}function Wn(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function Gn(e,t){let n=/* @__PURE__ */ new WeakSet,r=e=>{if(e!=null){if(e instanceof ArrayBuffer)
|
|
18
|
+
`)));return{content:o.content,details:o.details===void 0?null:o.details}}})}return r&&i.set(V,{name:V,execute:async(t,n)=>{let r={type:`toolCall`,id:`ptc:${n.callId}`,name:V,arguments:t},i;try{i=S(kn,r)}catch(r){let i=typeof t==`object`&&t&&!Array.isArray(t)?t:void 0,a=i?.agent,o=i?.agentScope,s=jn(i,n.dispatchDeps?.whyEnabled!==!1);return Qt(a)?St(bt(Zt({cwd:e.cwd,agentScope:o===`user`||o===`project`||o===`both`?o:`user`}),An(i)),s):St(bt({text:``,status:`rejected`,started:!1,agentName:typeof a==`string`?a:``,durationMs:0,exitCode:1,reportChannel:`none`,errorMessage:r instanceof Error?r.message:String(r)},An(i)),s)}return Sn(i,{signal:n.signal,callId:n.callId,cwd:e.cwd,depth:n.depth,maxDispatchDepth:n.maxDispatchDepth,...n.callerId===void 0?{}:{callerId:n.callerId},...n.sessionDir===void 0?{}:{sessionDir:n.sessionDir},...n.parentTaskId===void 0?{}:{parentTaskId:n.parentTaskId},...n.sessionModel===void 0?{}:{sessionModel:n.sessionModel}},n.dispatchDeps)}}),i}function Pn(){let e=/* @__PURE__ */ new Map;return{recordStart(t,n,r){if(e.has(t))throw Error(`duplicate sub-call callId ${t}`);e.set(t,{callId:t,name:n,args:r,status:`running`,startMs:Date.now()})},recordEnd(t,n,r){let i=e.get(t);if(i===void 0)throw Error(`recordEnd on unknown callId ${t}`);return i.status=n,i.endMs=Date.now(),i.durationMs=i.endMs-i.startMs,n===`rejected`&&(i.durationMs=0),r?.errorMessage!==void 0&&(i.errorMessage=r.errorMessage),r?.resultSummary!==void 0&&(i.resultSummary=r.resultSummary),i},snapshot(){return[...e.values()].map(e=>({...e}))}}}function Fn(e){return{name:`ptc-${e.surface}`,env:e.env,workerData:e.runId===void 0?{env:e.env}:{runId:e.runId,env:e.env},resourceLimits:{maxOldGenerationSizeMb:e.limits.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:e.limits.maxYoungGenerationSizeMb}}}const In={acquireLatency:le.channel(`ptc:pool:acquire-latency`),resetTime:le.channel(`ptc:worker:reset-time`),imageBytes:le.channel(`ptc:image:hoist-bytes`)};function Ln(e,t){e.publish(t)}var Rn=class{#e;#t;#n;#r;#i;#a=[];#o=/* @__PURE__ */ new Set;#s=[];#c=/* @__PURE__ */ new WeakMap;#l=0;#u=0;#d=!1;constructor(e){if(typeof e.buildWorkerUrl!=`function`)throw TypeError(`WorkerPool: buildWorkerUrl must be a function`);if(e.size!==void 0&&(typeof e.size!=`number`||!Number.isFinite(e.size)||e.size<=0))throw TypeError(`WorkerPool: size must be a positive finite number, received ${String(e.size)}`);if(e.acquireTimeoutMs!==void 0&&(typeof e.acquireTimeoutMs!=`number`||!Number.isFinite(e.acquireTimeoutMs)||e.acquireTimeoutMs<=0))throw TypeError(`WorkerPool: acquireTimeoutMs must be a positive finite number, received ${String(e.acquireTimeoutMs)}`);if(e.drainGraceMs!==void 0&&(typeof e.drainGraceMs!=`number`||!Number.isFinite(e.drainGraceMs)||e.drainGraceMs<=0))throw TypeError(`WorkerPool: drainGraceMs must be a positive finite number, received ${String(e.drainGraceMs)}`);this.#e=e.buildWorkerUrl,this.#t=e.size??4,this.#n=e.acquireTimeoutMs??3e4,this.#r=e.drainGraceMs??5e3,this.#i=e.workerOptions}async acquire(){if(this.#d)throw Error(`pool has been drained and can no longer serve workers`);this.#l+=1;let e=Date.now(),t=this.#a.shift();for(;t!==void 0&&!this.#p(t);)t=this.#a.shift();if(t!==void 0)return this.#o.add(t),t.ref(),Ln(In.acquireLatency,{poolSize:this.#t,waiters:this.#s.length,durationMs:Date.now()-e}),t;if(this.#o.size<this.#t){let t=this.#f();return this.#o.add(t),Ln(In.acquireLatency,{poolSize:this.#t,waiters:this.#s.length,durationMs:Date.now()-e}),t}return this.#u+=1,await new Promise((t,n)=>{let r=setTimeout(()=>{let e=this.#s.findIndex(e=>e.timer===r);e>=0&&this.#s.splice(e,1),n(/* @__PURE__ */ Error(`pool acquire timed out after ${this.#n} ms`))},this.#n);this.#s.push({resolve:t,reject:n,timer:r,startedAt:e})})}release(e){if(!this.#o.delete(e)||!this.#p(e))return;this.#c.set(e,Date.now());let t=this.#s.shift();t?(clearTimeout(t.timer),this.#o.add(e),Ln(In.acquireLatency,{poolSize:this.#t,waiters:this.#s.length,durationMs:Date.now()-t.startedAt}),t.resolve(e)):(this.#a.push(e),e.unref())}lastSettledAt(e){return this.#c.get(e)}async drain(){for(;this.#s.length>0;){let e=this.#s.shift();if(!e)break;clearTimeout(e.timer),e.reject(/* @__PURE__ */ Error(`pool drained before acquire could be satisfied`))}let e=Date.now()+this.#r;for(;this.#o.size>0&&Date.now()<e;)await new Promise(e=>setTimeout(e,5));let t=[...this.#a,...this.#o];this.#a.length=0,this.#o.clear(),await Promise.all(t.map(e=>e.terminate().catch(()=>void 0))),this.#d=!0}stats(){return{resident:this.#o.size+this.#a.length,inFlight:this.#o.size,waiters:this.#s.length,totalAcquires:this.#l,poolExhaustions:this.#u}}#f(){let e=new ce(this.#e(),this.#i);return e.once(`exit`,()=>{let t=this.#a.indexOf(e);t>=0?this.#a.splice(t,1):this.#o.delete(e)}),e}#p(e){return e.threadId!==-1}};function zn(e){Ln(In.imageBytes,{byteLength:e})}function Bn(e){Ln(In.resetTime,{durationMs:e})}function Vn(){let e=j(ue(import.meta.url)),t=[P(e,`worker.js`),P(e,`worker-entry.ts`)];for(let e of t)if(w(e))return de(e);throw Error(`worker entry not found; tried: ${t.join(`, `)}`)}function Hn(e){if(typeof e!=`object`||!e)return;let t=e;if(t.status!==`rejected`)return;let n=typeof t.errorMessage==`string`?t.errorMessage:t.started===!1?`dispatch refused`:`dispatch failed`;return{kind:t.started===!1?`refused`:`failed`,message:n}}function H(e){return e instanceof Error?e.message:String(e)}function Un(e){if(typeof e!=`object`||!e)return;let t=e.content;if(Array.isArray(t)&&t.length>0){let e=t[0];if(typeof e==`object`&&e){let t=e.text;if(typeof t==`string`&&t.length>0){let e=t.indexOf(`
|
|
19
|
+
`);return e===-1?t:t.slice(0,e)}}}}function Wn(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function Gn(e,t){let n=/* @__PURE__ */ new WeakSet,r=e=>{if(e!=null){if(e instanceof ArrayBuffer)t(e);else if(ArrayBuffer.isView(e))t(e);else if(typeof e==`object`&&!n.has(e)){if(n.add(e),Array.isArray(e))for(let t of e)r(t);else for(let t of Object.keys(e))r(e[t])}}};r(e)}function Kn(e){try{let t=Buffer.byteLength(JSON.stringify(e,(e,t)=>Wn(t)?null:t)??``,`utf8`),n=0;return Gn(e,e=>{n+=e.byteLength}),t+n}catch{return 1/0}}async function qn(e){let i=Re(e.config),s=Le(),c=e.runId??oe(),l=ze(e.timeoutMs,i),u=[],d=[],f=[];if(e.signal?.aborted)return{logs:u,narrations:d,phases:f,error:{kind:n.abort,message:`run cancelled before start`}};let p;try{p=e.pool?await e.pool.acquire():new ce(Vn(),Fn({surface:e.surface,env:s,limits:i,runId:c}))}catch(e){return{logs:u,narrations:d,phases:f,error:{kind:n.workerExit,message:`pool acquire failed: ${H(e)}`}}}return await new Promise(s=>{let m=new se,h=m.port1,g=m.port2,_=new AbortController,v=!1,y=Pn(),b=()=>{v||e.onSubCallChange?.(()=>y.snapshot())},x={recordStart(e,t,n){y.recordStart(e,t,n),b()},recordEnd(e,t,n){let r=y.recordEnd(e,t,n);return b(),r},snapshot:()=>y.snapshot()},S,C=!1,w=0,T=0,E=new dt(i.dispatchConcurrency),D=0,ee=[],te=e.depth??0,O,k,A=[],ne=e=>{let t=[],n=e?.content;if(!Array.isArray(n))return t;for(let e of n){if(typeof e!=`object`||!e)continue;let n=e;if(n.type!==`image`)continue;let r;typeof n.data==`string`&&n.data.length>0?r=n.data:n.bytes instanceof ArrayBuffer&&n.bytes.byteLength>0&&(r=Buffer.from(n.bytes).toString(`base64`)),r!==void 0&&t.push({data:r,mimeType:typeof n.mimeType==`string`?n.mimeType:`application/octet-stream`})}return t},j=e=>e===`timeout`?`run timed out after ${l} ms`:`run cancelled`,M=e=>e===`timeout`?n.timeout:n.abort,N=t=>{if(v)return;v=!0,O&&clearTimeout(O),k&&clearTimeout(k),e.signal?.removeEventListener(`abort`,L),_.abort(),h.close(),e.pool?e.pool.release(p):p.terminate();let n=x.snapshot();s(n.length>0?{...t,subCalls:n}:t)},P=(e,t,n)=>{N({logs:u,narrations:d,phases:f,error:n===void 0?{kind:e,message:t}:{kind:e,message:t,stack:n}})},re=e=>{v||(r(e)?h.postMessage(e):P(n.protocol,`internal error: malformed host frame`))},ie=()=>{let t={kind:o.init,runId:c,surface:e.surface,code:e.code,bindings:[...e.bindings.keys()],bindingCandidates:[...B],maxItemsPerCall:i.maxItemsPerCall,maxPendingCalls:i.maxPendingCalls,...e.args===void 0?{}:{args:e.args}};if(!r(t)){P(n.protocol,`internal error: malformed init frame`);return}let a=Kn(t);a>i.maxMessageBytes?P(n.protocol,`init frame of ${a} bytes exceeds maxMessageBytes (${i.maxMessageBytes})`):re(t)},ae=(e,t)=>(T+=e,T<=i.maxOutputBytes||(P(n.outputLimit,`${t} exceeded the output budget: logs + result reached ${T} bytes (maxOutputBytes=${i.maxOutputBytes}); ${u.length} log line(s) retained`),!1)),oe=async()=>{D<i.maxParallelSubCalls?D+=1:await new Promise(e=>{ee.push(e)})},F=()=>{let e=ee.shift();e?e():--D},ce=e=>{x.recordStart(e.callId,e.tool,e.args),w+=1,w>i.maxPendingCalls?(x.recordEnd(e.callId,`error`,{errorMessage:`more than maxPendingCalls (${i.maxPendingCalls}) binding calls in flight`}),P(n.protocol,`more than maxPendingCalls (${i.maxPendingCalls}) binding calls in flight`)):le(e).finally(()=>{--w})},le=async t=>{let r=e.bindings.get(t.tool);if(!r){x.recordEnd(t.callId,`error`,{errorMessage:`no binding named "${t.tool}" in this run; available bindings: `+([...e.bindings.keys()].join(`, `)||`(none)`)}),ue({kind:o.callResult,callId:t.callId,tool:t.tool,ok:!1,message:`no binding named "${t.tool}" in this run; available bindings: `+([...e.bindings.keys()].join(`, `)||`(none)`)});return}let a=t.tool===V;if(!a&&(await oe(),v))x.recordEnd(t.callId,`cancelled`,{errorMessage:`run settled before binding started`}),F();else try{let s=await r.execute(t.args,{signal:_.signal,callId:t.callId,depth:te,maxDispatchDepth:i.maxDispatchDepth,callerId:c,...e.parentTaskId===void 0?{}:{parentTaskId:e.parentTaskId},...e.sessionDir===void 0?{}:{sessionDir:e.sessionDir},...e.sessionModel===void 0?{}:{sessionModel:e.sessionModel},dispatchDeps:{...e.dispatchDeps,slots:e.dispatchDeps?.slots??E}}),l=ne(s),u={kind:o.callResult,callId:t.callId,tool:t.tool,ok:!0,value:s},d=Kn(u);if(d>i.maxMessageBytes){x.recordEnd(t.callId,`error`,{errorMessage:`callResult frame of ${d} bytes exceeds maxMessageBytes (${i.maxMessageBytes})`}),P(n.protocol,`callResult frame of ${d} bytes exceeds maxMessageBytes (${i.maxMessageBytes})`);return}if(ue(u))for(let e of l)A.push(e),zn(Buffer.byteLength(e.data,`base64`));if(_.signal.aborted)x.recordEnd(t.callId,`cancelled`,{errorMessage:`binding aborted by run cancellation`});else{let e=a?Hn(s):void 0;e===void 0?x.recordEnd(t.callId,`ok`,{resultSummary:Un(s)}):x.recordEnd(t.callId,e.kind===`refused`?`rejected`:`error`,{errorMessage:e.message})}}catch(e){_.signal.aborted?x.recordEnd(t.callId,`cancelled`,{errorMessage:H(e)}):x.recordEnd(t.callId,`error`,{errorMessage:H(e)}),ue({kind:o.callResult,callId:t.callId,tool:t.tool,ok:!1,message:H(e)})}finally{a||F()}},ue=e=>{if(v)return!1;try{return h.postMessage(e),!0}catch(t){try{h.postMessage({kind:o.callResult,callId:e.callId,tool:e.tool,ok:!1,message:`binding result could not be transferred: ${H(t)}`})}catch{P(n.protocol,`binding result is not transferable`)}return!1}},de=e=>S?{logs:u,narrations:d,phases:f,error:{kind:M(S),message:j(S)}}:e,I=r=>{if(v)return;if(!a(r)){P(n.protocol,`malformed worker frame`);return}let o=r.kind===t.ready?0:Kn(r);if(!Number.isFinite(o))P(n.protocol,`worker frame could not be serialized for accounting`);else if(o>i.maxMessageBytes)P(n.protocol,`control frame of ${o} bytes exceeds maxMessageBytes (${i.maxMessageBytes})`);else switch(r.kind){case t.ready:if(e.pool){let t=e.pool.lastSettledAt(p);t!==void 0&&Bn(Date.now()-t)}if(!C&&(C=!0,S)){fe(S);return}ie();return;case t.call:ce(r);return;case t.log:ae(o,`console output`)&&u.push(r.text);return;case t.narration:ae(o,`workflow narration`)&&d.push(r.message);return;case t.phase:ae(o,`workflow phase`)&&f.push(r.title);return;case t.result:{if(!ae(o,`completion value`))return;let e={logs:u,narrations:d,phases:f,...A.length>0?{images:A}:{}};N(de(r.value===void 0?e:{...e,value:r.value}));return}case t.error:N(de({logs:u,narrations:d,phases:f,error:r.error}));return;default:P(n.protocol,`unknown worker frame`)}};function L(){pe(`abort`)}let fe=e=>{k&&clearTimeout(k),k=setTimeout(()=>{P(M(e),j(e))},i.graceMs)};function pe(e){v||(S?P(M(S),j(S)):(S=e,_.abort(),re({kind:o.cancel,reason:e}),fe(e)))}p.on(`error`,e=>{P(n.workerExit,`worker failed: ${H(e)}`)}),p.on(`exit`,e=>{P(n.workerExit,`worker exited with code ${e} before the run completed`)}),h.on(`message`,I),h.on(`messageerror`,()=>{P(n.protocol,`worker sent a frame that could not be deserialized`)}),e.signal?.addEventListener(`abort`,L,{once:!0}),O=setTimeout(()=>{pe(`timeout`)},l);let me={kind:o.connect,port:g};r(me)?p.postMessage(me,[g]):P(n.protocol,`internal error: malformed connect frame`)})}const Jn=["Return value: every `tools.<name>(args)` call above resolves to `{ content, details }`.","`content` is an ARRAY of content blocks, never a string, so a text result is","`result.content[0].text`; `details` is that tool's own detail object or `null`, never","`undefined`. No binding result has a `files`, `output`, `matches` or `entries` field:","`bash`, `grep`, `find` and `ls` hand back ONE text block of newline-separated rows that","you split yourself, and the empty answer is a sentinel string (`No matches found`,","`No files found matching pattern`, `(empty directory)`) rather than an empty list.","A failing call REJECTS with `ToolCallError` instead of resolving, so wrap the call in","`try`/`catch` (or `Promise.allSettled`): a path that is not there, a builtin this run did not",`bind. A name that is not a builtin is simply not a function.`],Yn=/* @__PURE__ */ new Map([[`bash`,"`bash` rejects on a non-zero exit rather than resolving with its output."],[`write`,"`write` always reports `details: null`."],[`edit`,"`edit` always reports a `details` object carrying `diff` and `patch`."],[V,'`tools["pi.dispatch"]` is the exception: it resolves to `{ text, status, ... }` with no `content` and never throws, so read `status`.']]),Xn=[Jn.join(`
|
|
20
20
|
`),`Exceptions: `+[...Yn.values()].join(` `)].join(`
|
|
21
|
-
`),Zn=`pi-ptc-output-`;function Qn(e,t=Zn){let n=M(k(),`${t}${oe()}.txt`);return ee(n,e,`utf8`),n}function $n(e,t){let n=e.totalLines-e.outputLines+1,r=e.totalLines;return e.lastLinePartial?`[Showing last ${_(e.outputBytes)} of line ${r}. Full output: ${t}]`:e.truncatedBy===`lines`?`[Showing lines ${n}-${r} of ${e.totalLines}. Full output: ${t}]`:`[Showing lines ${n}-${r} of ${e.totalLines} (${_(s)} limit). Full output: ${t}]`}function er(e,t=Zn,n={}){let r=b(e,{maxLines:c,maxBytes:s});if(!r.truncated)return{text:e,truncated:!1};let i=Qn(n.fullText??e,t);return{text:`${r.content}\n\n${$n(r,i)}`,truncated:!0,fullPath:i}}const tr=200,nr=new RegExp([`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`].join(`|`),`g`);function rr(e){return!e.includes(`\x1B`)&&!e.includes(``)?e:e.replace(nr,``)}function U(e){let t=rr(e).replace(/\r/g,``);if(t.length===0)return t;let n=``;for(let e of t){let t=e.codePointAt(0);
|
|
22
|
-
`)?void 0:JSON.stringify(t)}if(Array.isArray(e)){let t=[];for(let n of e){let e=or(n);if(e===void 0)return;t.push(e)}return`[${t.join(`, `)}]`}let t=Object.keys(e);if(t.length===0)return`{}`;let n=[];for(let r of t){let t=or(e[r]??null);if(t===void 0)return;n.push(`${ar(r)}: ${t}`)}return`{${n.join(`, `)}}`}function sr(e){let t=or(e);if(t!==void 0)return t.length<=100?t:void 0}function cr(e){return e===null?`null`:typeof e==`string`?U(e):String(e)}function lr(e,t){if(typeof e!=`object`||!e)return[`${t}${cr(e)}`];if(Array.isArray(e)){if(e.length===0)return[`${t}[]`];let n=[`${t}[`];for(let r of e){let e=sr(r);
|
|
21
|
+
`),Zn=`pi-ptc-output-`;function Qn(e,t=Zn){let n=M(k(),`${t}${oe()}.txt`);return ee(n,e,`utf8`),n}function $n(e,t){let n=e.totalLines-e.outputLines+1,r=e.totalLines;return e.lastLinePartial?`[Showing last ${_(e.outputBytes)} of line ${r}. Full output: ${t}]`:e.truncatedBy===`lines`?`[Showing lines ${n}-${r} of ${e.totalLines}. Full output: ${t}]`:`[Showing lines ${n}-${r} of ${e.totalLines} (${_(s)} limit). Full output: ${t}]`}function er(e,t=Zn,n={}){let r=b(e,{maxLines:c,maxBytes:s});if(!r.truncated)return{text:e,truncated:!1};let i=Qn(n.fullText??e,t);return{text:`${r.content}\n\n${$n(r,i)}`,truncated:!0,fullPath:i}}const tr=200,nr=new RegExp([`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`].join(`|`),`g`);function rr(e){return!e.includes(`\x1B`)&&!e.includes(``)?e:e.replace(nr,``)}function U(e){let t=rr(e).replace(/\r/g,``);if(t.length===0)return t;let n=``;for(let e of t){let t=e.codePointAt(0);t!==void 0&&(t===10||t===9?n+=e:t<=31||t>=65529&&t<=65531||(n+=e))}return n}const ir=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ar(e){return ir.test(e)?e:JSON.stringify(e)}function or(e){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`string`){let t=U(e);return t.includes(`
|
|
22
|
+
`)?void 0:JSON.stringify(t)}if(Array.isArray(e)){let t=[];for(let n of e){let e=or(n);if(e===void 0)return;t.push(e)}return`[${t.join(`, `)}]`}let t=Object.keys(e);if(t.length===0)return`{}`;let n=[];for(let r of t){let t=or(e[r]??null);if(t===void 0)return;n.push(`${ar(r)}: ${t}`)}return`{${n.join(`, `)}}`}function sr(e){let t=or(e);if(t!==void 0)return t.length<=100?t:void 0}function cr(e){return e===null?`null`:typeof e==`string`?U(e):String(e)}function lr(e,t){if(typeof e!=`object`||!e)return[`${t}${cr(e)}`];if(Array.isArray(e)){if(e.length===0)return[`${t}[]`];let n=[`${t}[`];for(let r of e){let e=sr(r);e===void 0?n.push(...ur(r,t+` `)):n.push(`${t} ${e}`)}return n.push(`${t}]`),n}let n=Object.keys(e);if(n.length===0)return[`${t}{}`];let r=[`${t}{`],i=t+` `;for(let t of n){let n=e[t]??null,a=sr(n);if(a!==void 0){r.push(`${i}${ar(t)}: ${a}`);continue}if(typeof n==`string`){r.push(`${i}${ar(t)}:`);for(let e of U(n).split(`
|
|
23
23
|
`))r.push(e.length===0?``:`${i} ${e}`);continue}let o=lr(n,i);r.push(`${i}${ar(t)}: ${(o[0]??``).trimStart()}`.trimEnd(),...o.slice(1))}return r.push(`${t}}`),r}function ur(e,t){return typeof e==`string`?U(e).split(`
|
|
24
24
|
`):typeof e!=`object`||!e?[String(e)]:lr(e,t)}function dr(e){return e.split(`
|
|
25
25
|
`).map(e=>e.length>200?`${e.slice(0,199)}…`:e).join(`
|
|
26
26
|
`)}function fr(e){if(typeof e==`string`)return dr(U(e));if(typeof e!=`object`||!e)return String(e);let t=sr(e);return dr((t===void 0?ur(e,``):[t]).join(`
|
|
27
|
-
`))}function pr(e=process.env){let t=e.PI_PTC_DEPTH;return t===void 0||!/^\d+$/.test(t)?0:Number.parseInt(t,10)}function mr(e=process.env){let t=e.PI_PTC_TASK_ID;if(t!==void 0&&/^[0-9A-HJKMNP-TV-Z]{26}$/.test(t))return t}function W(e,t){let n=e===void 0?void 0:new Set(e),r=new Set(Tn(t));return B.filter(e=>(n===void 0||n.has(e))&&(En.includes(e)||r.has(e)))}const hr=["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.",`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.`,`Use ptc_workflow instead of ptc_run_code when the work has named phases and the user benefits from seeing progress narration.`],gr="A `codemode` script cannot call the parallel binding directly: `pi.dispatch` is never in that script's own tool table, on any surface. A script reaches it by calling `ptc_run_code` or `ptc_workflow` and using the binding inside the program.",_r={run_code:`ptc_run_code`,workflow:`ptc_workflow`};function vr(e){let t=e?.cwd;return typeof t==`string`&&t.length>0?t:process.cwd()}function yr(e){let{surface:t,startedAt:n,onUpdate:r}=e;if(r===void 0)return{update:()=>{},cancel:()=>{}};let i=0,a,o,s=()=>{if(o===void 0)return;let e=o;o=void 0,i=Date.now(),r({content:[],details:{surface:t,logs:[],narrations:[],phases:[],warnings:[],durationMs:Date.now()-n,imageCount:0,subCalls:e()}})};return{update(e){o=e;let t=100-(Date.now()-i);
|
|
27
|
+
`))}function pr(e=process.env){let t=e.PI_PTC_DEPTH;return t===void 0||!/^\d+$/.test(t)?0:Number.parseInt(t,10)}function mr(e=process.env){let t=e.PI_PTC_TASK_ID;if(t!==void 0&&/^[0-9A-HJKMNP-TV-Z]{26}$/.test(t))return t}function W(e,t){let n=e===void 0?void 0:new Set(e),r=new Set(Tn(t));return B.filter(e=>(n===void 0||n.has(e))&&(En.includes(e)||r.has(e)))}const hr=["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.",`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.`,`Use ptc_workflow instead of ptc_run_code when the work has named phases and the user benefits from seeing progress narration.`],gr="A `codemode` script cannot call the parallel binding directly: `pi.dispatch` is never in that script's own tool table, on any surface. A script reaches it by calling `ptc_run_code` or `ptc_workflow` and using the binding inside the program.",_r={run_code:`ptc_run_code`,workflow:`ptc_workflow`};function vr(e){let t=e?.cwd;return typeof t==`string`&&t.length>0?t:process.cwd()}function yr(e){let{surface:t,startedAt:n,onUpdate:r}=e;if(r===void 0)return{update:()=>{},cancel:()=>{}};let i=0,a,o,s=()=>{if(o===void 0)return;let e=o;o=void 0,i=Date.now(),r({content:[],details:{surface:t,logs:[],narrations:[],phases:[],warnings:[],durationMs:Date.now()-n,imageCount:0,subCalls:e()}})};return{update(e){o=e;let t=100-(Date.now()-i);t<=0?(a!==void 0&&(clearTimeout(a),a=void 0),s()):a??=setTimeout(()=>{a=void 0,s()},t)},cancel(){a!==void 0&&(clearTimeout(a),a=void 0),o=void 0}}}function br(e){return[...e.phases.map(e=>`[phase] ${U(e)}`),...e.narrations.map(e=>`[log] ${U(e)}`),...e.logs.map(e=>U(e))]}function xr(e){let t=e.error;if(t===void 0)return/* @__PURE__ */ Error(`internal error: a successful PTC run was rendered as a failure`);let n=br(e),r=n.length===0?``:`\nCaptured output:\n${n.join(`
|
|
28
28
|
`)}`,i=Error(U(`code run failed (${t.kind}): ${t.message}${r}`));return i.name=`CodeRunFailedError`,i}function Sr(e){let{outcome:t,surface:n}=e,r=[...e.warnings??[]],i=t.images??[],a=[];t.phases.length>0&&a.push(`Phases: ${t.phases.map(e=>U(e)).join(` → `)}`),t.narrations.length>0&&a.push(t.narrations.map(e=>U(e)).join(`
|
|
29
29
|
`)),t.logs.length>0&&a.push(t.logs.map(e=>U(e)).join(`
|
|
30
30
|
`)),t.value!==void 0&&a.push(fr(t.value));for(let e of r)a.push(`Warning: ${U(e)}`);let o=er(a.length>0?a.join(`
|
|
@@ -54,7 +54,7 @@ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./protocol-CfOgxz3u.js";
|
|
|
54
54
|
`)){let t=r.trim();if(t.length===0)continue;let i;try{i=JSON.parse(t)}catch(t){throw Error(`FileTaskStorage: corrupt event JSON in `+e+`: `+Da(t))}if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`FileTaskStorage: corrupt event JSON in `+e+`: expected a JSON object`);n.push(i)}return n}async#o(e,t){await this.#t.mkdir(j(e),{recursive:!0});let n=e+`.tmp-`+oe();await this.#t.writeFile(n,JSON.stringify(t,null,2),{encoding:`utf8`}),await this.#t.rename(n,e)}async#s(e){try{return await this.#t.readdir(e)}catch(e){if(Ea(e))return[];throw e}}async#c(e){try{return await this.#t.readFile(e,{encoding:`utf8`}),!0}catch(e){if(Ea(e))return!1;throw e}}#l(){return M(this.#e,`tasks`)}#u(){return M(this.#e,`subscriptions`)}#d(){return M(this.#e,`events`)}#f(e){return M(this.#l(),e+`.json`)}#p(e,t){return M(this.#u(),e+`-`+t+`.json`)}#m(e,t){return M(this.#d(),e+`-`+t+`.jsonl`)}};function Aa(e,t){return new ka(e,t)}const ja=/* @__PURE__ */ new Set([`succeeded`,`failed`,`canceled`,`lost`]),Ma=/* @__PURE__ */ new Set([`running`,`stopping`]),Na=2**53-1,Pa={info:()=>void 0,warn:e=>{console.warn(`[pi-ptc.background] `+e)}};function J(e){return e instanceof Error?e.message:String(e)}function Fa(e){return e===void 0||e.length===0?`<in-memory>`:e}function Ia(e){let t=e.spawnSource.callerId;return t.length>0?t:e.id}var La=class{#e;#t=/* @__PURE__ */ new Map;constructor(e){this.#e=e}setCurrent(e){this.#e=e}async transition(e,t){let n=e.kind===`spawn`?this.#e:this.#t.get(e.taskId)??this.#e,r=await n.transition(e,t);return e.kind===`spawn`&&this.#t.set(r.record.id,n),r}query(e){return this.#e.query(e)}get(e){return this.#e.get(e)}onTransition(e){return this.#e.onTransition(e)}reconcileLostTasks(){return this.#e.reconcileLostTasks()}},Ra=class{#e;constructor(e){this.#e=e}setCurrent(e){this.#e=e}readOutput(e){return this.#e.readOutput(e)}writeOutput(e,t){return this.#e.writeOutput(e,t)}outputRef(e){return this.#e.outputRef(e)}},za=class{#e;#t=[];constructor(e){this.#e=e}setCurrent(e){this.#e=e;for(let t of this.#t)e.onIdleWake(t)}current(){return this.#e}subscribe(e,t,n){return this.#e.subscribe(e,t,n)}drainPending(e,t){return this.#e.drainPending(e,t)}acknowledgeEvents(e,t,n){return this.#e.acknowledgeEvents(e,t,n)}onIdleWake(e){this.#t.push(e),this.#e.onIdleWake(e)}pendingCount(e,t){return this.#e.pendingCount(e,t)}notifyIdle(e,t){return this.#e.notifyIdle(e,t)}},Ba=class{#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Map;constructor(e){this.#e=e}isLive(e){return this.#t.has(e)}trackReapCancel(e,t){this.#n.set(e,t)}spawn(e,t){let n=this.#e.spawn(e,t);return this.#t.add(n),n}kill(e,t){this.#e.kill(e,t)}events(e){return this.#e.events(e)}async exit(e){try{return await this.#e.exit(e)}finally{this.#t.delete(e);let t=this.#n.get(e);t!==void 0&&(this.#n.delete(e),t())}}stderr(e){return this.#e.stderr(e)}liveHandles(){return[...this.#t]}},Va=class{registry;outputStorage;pipeline;slots;lifecycle;dispatchDeps;clock;#e;#t;#n;#r;#i;#a=!1;constructor(e){this.clock=e.clock??(()=>Date.now()),this.#e=e.logger??Pa,this.#r=e.owner??{pid:process.pid,bootMs:this.clock()},this.#i=e.isPidAlive??Ye,this.#t=e.createStorage??(e=>e===void 0||e.length===0?new lt:Aa(e)),this.#n=e.createOutputStorage??(e=>e===void 0||e.length===0?new ki:new ji(e));let t=(e.createInitialStorage??(()=>new lt))(),n=Qe(t,{clock:this.clock,logger:this.#e,owner:this.#r,isPidAlive:this.#i}),r=new wa(t,{now:this.clock,logger:this.#e});this.registry=new La(n),this.outputStorage=new Ra(new ki),this.pipeline=new za(r),this.lifecycle=new Ba((e.createLifecycle??(()=>new Pe({logger:this.#e})))()),this.slots=new dt(e.concurrency??z.dispatchConcurrency),this.dispatchDeps={taskRegistry:this.registry,lifecycle:this.lifecycle,slots:this.slots,outputStorage:this.outputStorage,clock:this.clock,logger:this.#e,...e.whyEnabled===void 0?{}:{whyEnabled:e.whyEnabled}},this.registry.onTransition(this.#o)}#o=(e,t)=>{this.#a||ja.has(e.status)&&this.pipeline.notifyIdle(t.subscriptionId,e.id).catch(t=>{this.#e.warn(`terminal notification wake for task `+e.id+` failed: `+J(t))})};async bindSession(e,t){let n,r;try{n=this.#t(e),r=this.#n(e)}catch(n){return this.#s(`background runtime: session storage for `+Fa(e)+` is unavailable: `+J(n),t),[]}let i=Qe(n,{clock:this.clock,logger:this.#e,owner:this.#r,isPidAlive:this.#i}),a=new wa(n,{now:this.clock,logger:this.#e});this.registry.setCurrent(i),this.outputStorage.setCurrent(r),this.pipeline.setCurrent(a),this.#a=!1;try{return await i.reconcileLostTasks()}catch(e){return this.#s(`background runtime: startup reconcile failed; stale running tasks were not all marked lost (reconcile is not per-record tolerant yet): `+J(e),t),[]}finally{this.registry.onTransition(this.#o)}}async drainNotifications(e){let t;try{t=await this.registry.query({limit:Na})}catch(t){return this.#e.warn(`drainNotifications: could not list tasks for subscriber `+e+`: `+J(t)),{items:[],acks:[]}}let n=[],r=[],i=this.pipeline.current();for(let a of t){if(a.spawnSource.callerId!==e)continue;let t;try{t=await i.drainPending(e,a.id)}catch(t){this.#e.warn(`drainNotifications: task `+a.id+` for subscriber `+e+`: `+J(t));continue}for(let e of t)n.push({event:e,record:a});let o=t[t.length-1];o!==void 0&&r.push({subscriberId:e,taskId:a.id,cursor:o.eventId,sink:i})}return{items:n,acks:r}}async acknowledgeNotifications(e){for(let t of e)try{await t.sink.acknowledgeEvents(t.subscriberId,t.taskId,t.cursor)}catch(e){this.#e.warn(`acknowledgeNotifications: could not acknowledge task `+t.taskId+`: `+J(e))}}async shutdown(e){if(this.#a)return[];this.#a=!0;let t;try{t=await this.registry.query({limit:Na})}catch(e){this.#e.warn(`shutdown: could not list tasks: `+J(e)),t=[]}let n=[];for(let r of t)if(Ma.has(r.status)&&Je(r,this.#r))try{let t=await this.registry.transition({kind:`reconcile-lost`,taskId:r.id,reason:e},{clock:this.clock,callerId:Ia(r),logger:this.#e});n.push(t.record)}catch(e){this.#e.warn(`shutdown: could not mark task `+r.id+` lost: `+J(e))}for(let e of this.lifecycle.liveHandles()){let t=Ot(this.lifecycle,e,{isDone:()=>!this.lifecycle.isLive(e),unref:!0});this.lifecycle.trackReapCancel(e,t)}for(let e of n)this.slots.release(e.id);return n}#s(e,t){if(this.#e.warn(e),t!==void 0)try{t(e)}catch(e){this.#e.warn(`bindSession reporter threw: `+J(e))}}};function Ha(e={}){return new Va(e)}const Ua=/* @__PURE__ */ new Set([`succeeded`,`failed`,`lost`]);function Wa(e){return Ua.has(e.status)}function Ga(e,t){if(e.length===0)return``;let n=e.map(Ja).join(`
|
|
55
55
|
`);return`${`<bg-task-notifications batch-id="${Y(t.batchId)}" delivered-at-ms="${t.deliveredAtMs}">`}\n${n}\n</bg-task-notifications>`}function Ka(e,t=102400){let n=[],r=[],i=0,a=t-Xa;for(let t of e){let e=Ya(t);r.length>0&&i+1+e>a&&(n.push(r),r=[],i=0),r.length>0&&(i+=1),r.push(t),i+=e}return r.length>0&&n.push(r),n}function qa(e){let t=Array.from(e);return t.length<=1024?e:t.slice(0,1023).join(``)+`…`}function Ja(e){let{event:t,record:n}=e,r=t.outputBytes??n.outputBytes,i=r??0,a=t.outputPreview??n.outputPreview,o=[` <bg-task-notification`,` id="${Y(t.type)}"`,` task-id="${Y(t.taskId)}"`,` subscription-id="${Y(t.subscriptionId)}"`,` status="${Y(t.status)}"`,` label="${Y(n.label)}"`,` agent-name="${Y(n.agentName)}"`,` depth="${n.depth}"`,` duration-ms="${n.durationMs??0}"`,` transition-at-ms="${t.transitionAtMs}">`,` <output-bytes>${i}</output-bytes>`];return n.errorMessage!==void 0&&o.push(` <error-message>${Y(qa(n.errorMessage))}</error-message>`),n.reportChannel!==void 0&&o.push(` <report-channel>${Y(n.reportChannel)}</report-channel>`),n.outputRef!==void 0&&o.push(` <output-ref>${Y(n.outputRef)}</output-ref>`),r!==void 0&&r<=2048&&a!==void 0&&o.push(` <output-preview>${Y(a)}</output-preview>`),o.push(` </bg-task-notification>`),o.join(`
|
|
56
56
|
`)}function Y(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`"`,`"`).replaceAll(` `,`	`).replaceAll(`
|
|
57
|
-
`,` `).replaceAll(`\r`,` `)}function Ya(e){return Buffer.byteLength(Ja(e),`utf8`)}const Xa=Buffer.byteLength(`<bg-task-notifications batch-id="${`0`.repeat(26)}" delivered-at-ms="${`9`.repeat(13)}">\n\n</bg-task-notifications>`,`utf8`),Za=[`ptc_run_code`,`ptc_workflow`],Qa=[`read`,`bash`,`edit`,`write`],$a=`ptc-mode`,eo=`ptc-mode`,to=`ptc.json`,no=`builtins-only`;function ro(){return{enabled:!1,base:void 0,ourLoadout:void 0}}function io(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{defaultMode:!0,source:`default`}}let r;try{r=JSON.parse(n)}catch(e){return{defaultMode:!0,source:`invalid`,error:`${t} is not valid JSON (${e instanceof Error?e.message:String(e)})`}}if(typeof r!=`object`||!r||Array.isArray(r))return{defaultMode:!0,source:`invalid`,error:`${t} must contain a JSON object`};let i=r.defaultMode;return i===void 0?{defaultMode:!0,source:`default`}:typeof i==`boolean`?{defaultMode:i,source:`file`}:{defaultMode:!0,source:`invalid`,error:`${t}: "defaultMode" must be a boolean, received ${typeof i}`}}function ao(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{whyEnabled:!0,source:`default`}}let r;try{r=JSON.parse(n)}catch{return{whyEnabled:!0,source:`default`}}if(typeof r!=`object`||!r||Array.isArray(r))return{whyEnabled:!0,source:`default`};let i=r.whyEnabled;return i===void 0?{whyEnabled:!0,source:`default`}:typeof i==`boolean`?{whyEnabled:i,source:`file`}:{whyEnabled:!0,source:`invalid`,error:`${t}: "whyEnabled" must be a boolean, received ${typeof i}`}}function oo(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{optInBindings:[],source:`default`}}let r;try{r=JSON.parse(n)}catch{return{optInBindings:[],source:`default`}}if(typeof r!=`object`||!r||Array.isArray(r))return{optInBindings:[],source:`default`};let i=r.optInBindings;if(i===void 0)return{optInBindings:[],source:`default`};if(!Array.isArray(i))return{optInBindings:[],source:`invalid`,error:`${t}: "optInBindings" must be an array of binding names, received ${typeof i}`};let a=i.find(e=>typeof e!=`string`);if(a!==void 0)return{optInBindings:[],source:`invalid`,error:`${t}: "optInBindings" entries must be strings, received ${typeof a}`};try{return{optInBindings:Tn(i),source:`file`}}catch(e){return{optInBindings:[],source:`invalid`,error:`${t}: ${e instanceof Error?e.message:String(e)}`}}}const X=`builtin:codemode`;function Z(e){return e.split(re).join(`/`)}function so(e){return e===`~`?O():e.startsWith(`~/`)?M(O(),e.slice(2)):e.startsWith(`file://`)?ue(e):e}function co(e){return Z(so(e.startsWith(`./`)||e.startsWith(`.\\`)?e.slice(2):e))}function lo(e,t,n){let r=Z(N(n,e)),i=ne(e),a=Z(e);return t.some(e=>{let t=Z(so(e));return ye(r,t)||ye(i,t)||ye(a,t)})}function uo(e,t,n){if(t.length===0)return!1;let r=Z(N(n,e)),i=Z(e);return t.some(e=>{let t=co(e);return t===r||t===i})}function fo(e){let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n[0];(e===`+`||e===`-`||e===`!`)&&t.push({sign:e,target:n.slice(1)})}return t}function po(e,t){if(!Array.isArray(e))return;let n;for(let{sign:r,target:i}of fo(e)){let e=r!==`-`&&r!==`!`;(r===`+`||r===`-`?uo(X,[i],t):lo(X,[i],t))&&(n=e?`enabled`:`disabled`)}return n}function mo(e,t){if(!Array.isArray(e))return;let n=fo(e),r=e=>n.filter(t=>t.sign===e).map(e=>e.target),i=r(`!`),a=r(`+`),o=r(`-`),s;return lo(X,i,t)&&(s=`disabled`),uo(X,a,t)&&(s=`enabled`),uo(X,o,t)&&(s=`disabled`),s}function ho(e){for(let t=0;t<e.length;t+=1){let n=e[t];if((n===`-e`||n===`--extension`)&&e[t+1]===X)return!0}return!1}function go(e){let t;try{t=T(e,`utf8`)}catch{return{value:void 0}}try{let n=JSON.parse(t);return typeof n!=`object`||!n||Array.isArray(n)?{value:void 0,error:`${e} must contain a JSON object`}:{value:n}}catch(t){return{value:void 0,error:`${e} is not valid JSON (${t instanceof Error?t.message:String(t)})`}}}function _o(e,t,n,r={project:process.cwd(),user:process.cwd()}){let i=e.slice(1);if(ho(i))return{switch:`enabled`,source:`cli`};if(i.some(e=>e===`-ne`||e===`--no-extensions`))return{switch:`disabled`,source:`cli`};let a=t?.extensions,o=po(a,r.project);if(o!==void 0)return{switch:o,source:`project`};let s=n?.extensions,c=mo(s,r.user);return c===void 0?{switch:`absent`,source:`default`}:{switch:c,source:`user`}}function vo(e,t,n=process.argv){let r=go(M(t,`.pi`,`settings.json`)),i=go(M(e,`settings.json`)),a=_o(n,r.value,i.value,{project:M(t,`.pi`),user:e}),o=r.error??i.error;return o===void 0?a:{...a,source:`invalid`,error:o}}function yo(e){return{activation:e.includes(`codemode`)?`active`:`inactive`,source:`loadout`}}function bo(e,t,n){return No(yo(n),Mo(e,t))}const xo=[`codemode`,`deferred`,`direct`,`hidden`],So={"codemode-deferred":`codemode`},Co=/^[A-Za-z0-9_-]+$/;function wo(e){return typeof e==`string`?So[e]??e:e}function To(e){return typeof e==`string`&&xo.includes(e)}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eo(e){return Q(e)&&Object.values(e).every(e=>typeof e==`string`)}function Do(e){return URL.canParse(e)?/^https?:$/.test(new URL(e).protocol):!1}function Oo(e,t){if(!Co.test(e)||!Q(t))return;let n=wo(t.exposure),r=Q(t.toolExposure)?Object.fromEntries(Object.entries(t.toolExposure).map(([e,t])=>[e,wo(t)])):t.toolExposure;if(n!==void 0&&!To(n)||r!==void 0&&(!Q(r)||!Object.values(r).every(e=>To(e)))||t.enabled!==void 0&&typeof t.enabled!=`boolean`||t.description!==void 0&&typeof t.description!=`string`||t.timeout!==void 0&&(typeof t.timeout!=`number`||!(t.timeout>0))||t.type===`sse`)return;let i={enabled:t.enabled,exposure:n,toolExposure:r},a=t.type;if(typeof t.url==`string`&&(a===void 0||a===`http`||a===`streamable-http`))return!Do(t.url)||t.headers!==void 0&&!Eo(t.headers)?void 0:i;if(typeof t.command==`string`&&(a===void 0||a===`stdio`))return t.args!==void 0&&!(Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`))||t.env!==void 0&&!Eo(t.env)||t.cwd!==void 0&&typeof t.cwd!=`string`?void 0:i}function ko(e,t){e.error=e.error===void 0?t:`${e.error}; ${t}`}function Ao(e,t,n,r,i){if(t===void 0){n!==void 0&&ko(i,n);return}let a;try{a=JSON.parse(t)}catch(t){ko(i,`${e} is not valid JSON (${t instanceof Error?t.message:String(t)})`);return}if(!Q(a)||a.mcpServers!==void 0&&!Q(a.mcpServers))
|
|
57
|
+
`,` `).replaceAll(`\r`,` `)}function Ya(e){return Buffer.byteLength(Ja(e),`utf8`)}const Xa=Buffer.byteLength(`<bg-task-notifications batch-id="${`0`.repeat(26)}" delivered-at-ms="${`9`.repeat(13)}">\n\n</bg-task-notifications>`,`utf8`),Za=[`ptc_run_code`,`ptc_workflow`],Qa=[`read`,`bash`,`edit`,`write`],$a=`ptc-mode`,eo=`ptc-mode`,to=`ptc.json`,no=`builtins-only`;function ro(){return{enabled:!1,base:void 0,ourLoadout:void 0}}function io(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{defaultMode:!0,source:`default`}}let r;try{r=JSON.parse(n)}catch(e){return{defaultMode:!0,source:`invalid`,error:`${t} is not valid JSON (${e instanceof Error?e.message:String(e)})`}}if(typeof r!=`object`||!r||Array.isArray(r))return{defaultMode:!0,source:`invalid`,error:`${t} must contain a JSON object`};let i=r.defaultMode;return i===void 0?{defaultMode:!0,source:`default`}:typeof i==`boolean`?{defaultMode:i,source:`file`}:{defaultMode:!0,source:`invalid`,error:`${t}: "defaultMode" must be a boolean, received ${typeof i}`}}function ao(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{whyEnabled:!0,source:`default`}}let r;try{r=JSON.parse(n)}catch{return{whyEnabled:!0,source:`default`}}if(typeof r!=`object`||!r||Array.isArray(r))return{whyEnabled:!0,source:`default`};let i=r.whyEnabled;return i===void 0?{whyEnabled:!0,source:`default`}:typeof i==`boolean`?{whyEnabled:i,source:`file`}:{whyEnabled:!0,source:`invalid`,error:`${t}: "whyEnabled" must be a boolean, received ${typeof i}`}}function oo(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return{optInBindings:[],source:`default`}}let r;try{r=JSON.parse(n)}catch{return{optInBindings:[],source:`default`}}if(typeof r!=`object`||!r||Array.isArray(r))return{optInBindings:[],source:`default`};let i=r.optInBindings;if(i===void 0)return{optInBindings:[],source:`default`};if(!Array.isArray(i))return{optInBindings:[],source:`invalid`,error:`${t}: "optInBindings" must be an array of binding names, received ${typeof i}`};let a=i.find(e=>typeof e!=`string`);if(a!==void 0)return{optInBindings:[],source:`invalid`,error:`${t}: "optInBindings" entries must be strings, received ${typeof a}`};try{return{optInBindings:Tn(i),source:`file`}}catch(e){return{optInBindings:[],source:`invalid`,error:`${t}: ${e instanceof Error?e.message:String(e)}`}}}const X=`builtin:codemode`;function Z(e){return e.split(re).join(`/`)}function so(e){return e===`~`?O():e.startsWith(`~/`)?M(O(),e.slice(2)):e.startsWith(`file://`)?ue(e):e}function co(e){return Z(so(e.startsWith(`./`)||e.startsWith(`.\\`)?e.slice(2):e))}function lo(e,t,n){let r=Z(N(n,e)),i=ne(e),a=Z(e);return t.some(e=>{let t=Z(so(e));return ye(r,t)||ye(i,t)||ye(a,t)})}function uo(e,t,n){if(t.length===0)return!1;let r=Z(N(n,e)),i=Z(e);return t.some(e=>{let t=co(e);return t===r||t===i})}function fo(e){let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n[0];(e===`+`||e===`-`||e===`!`)&&t.push({sign:e,target:n.slice(1)})}return t}function po(e,t){if(!Array.isArray(e))return;let n;for(let{sign:r,target:i}of fo(e)){let e=r!==`-`&&r!==`!`;(r===`+`||r===`-`?uo(X,[i],t):lo(X,[i],t))&&(n=e?`enabled`:`disabled`)}return n}function mo(e,t){if(!Array.isArray(e))return;let n=fo(e),r=e=>n.filter(t=>t.sign===e).map(e=>e.target),i=r(`!`),a=r(`+`),o=r(`-`),s;return lo(X,i,t)&&(s=`disabled`),uo(X,a,t)&&(s=`enabled`),uo(X,o,t)&&(s=`disabled`),s}function ho(e){for(let t=0;t<e.length;t+=1){let n=e[t];if((n===`-e`||n===`--extension`)&&e[t+1]===X)return!0}return!1}function go(e){let t;try{t=T(e,`utf8`)}catch{return{value:void 0}}try{let n=JSON.parse(t);return typeof n!=`object`||!n||Array.isArray(n)?{value:void 0,error:`${e} must contain a JSON object`}:{value:n}}catch(t){return{value:void 0,error:`${e} is not valid JSON (${t instanceof Error?t.message:String(t)})`}}}function _o(e,t,n,r={project:process.cwd(),user:process.cwd()}){let i=e.slice(1);if(ho(i))return{switch:`enabled`,source:`cli`};if(i.some(e=>e===`-ne`||e===`--no-extensions`))return{switch:`disabled`,source:`cli`};let a=t?.extensions,o=po(a,r.project);if(o!==void 0)return{switch:o,source:`project`};let s=n?.extensions,c=mo(s,r.user);return c===void 0?{switch:`absent`,source:`default`}:{switch:c,source:`user`}}function vo(e,t,n=process.argv){let r=go(M(t,`.pi`,`settings.json`)),i=go(M(e,`settings.json`)),a=_o(n,r.value,i.value,{project:M(t,`.pi`),user:e}),o=r.error??i.error;return o===void 0?a:{...a,source:`invalid`,error:o}}function yo(e){return{activation:e.includes(`codemode`)?`active`:`inactive`,source:`loadout`}}function bo(e,t,n){return No(yo(n),Mo(e,t))}const xo=[`codemode`,`deferred`,`direct`,`hidden`],So={"codemode-deferred":`codemode`},Co=/^[A-Za-z0-9_-]+$/;function wo(e){return typeof e==`string`?So[e]??e:e}function To(e){return typeof e==`string`&&xo.includes(e)}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eo(e){return Q(e)&&Object.values(e).every(e=>typeof e==`string`)}function Do(e){return URL.canParse(e)?/^https?:$/.test(new URL(e).protocol):!1}function Oo(e,t){if(!Co.test(e)||!Q(t))return;let n=wo(t.exposure),r=Q(t.toolExposure)?Object.fromEntries(Object.entries(t.toolExposure).map(([e,t])=>[e,wo(t)])):t.toolExposure;if(n!==void 0&&!To(n)||r!==void 0&&(!Q(r)||!Object.values(r).every(e=>To(e)))||t.enabled!==void 0&&typeof t.enabled!=`boolean`||t.description!==void 0&&typeof t.description!=`string`||t.timeout!==void 0&&(typeof t.timeout!=`number`||!(t.timeout>0))||t.type===`sse`)return;let i={enabled:t.enabled,exposure:n,toolExposure:r},a=t.type;if(typeof t.url==`string`&&(a===void 0||a===`http`||a===`streamable-http`))return!Do(t.url)||t.headers!==void 0&&!Eo(t.headers)?void 0:i;if(typeof t.command==`string`&&(a===void 0||a===`stdio`))return t.args!==void 0&&!(Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`))||t.env!==void 0&&!Eo(t.env)||t.cwd!==void 0&&typeof t.cwd!=`string`?void 0:i}function ko(e,t){e.error=e.error===void 0?t:`${e.error}; ${t}`}function Ao(e,t,n,r,i){if(t===void 0){n!==void 0&&ko(i,n);return}let a;try{a=JSON.parse(t)}catch(t){ko(i,`${e} is not valid JSON (${t instanceof Error?t.message:String(t)})`);return}if(!Q(a)||a.mcpServers!==void 0&&!Q(a.mcpServers))ko(i,`${e} must contain a JSON object with an "mcpServers" object`);else{typeof a.autoEnableCodemode==`boolean`?i.autoEnableCodemode=a.autoEnableCodemode:a.autoEnableCodemode!==void 0&&ko(i,`${e}: autoEnableCodemode must be a boolean`);for(let[e,t]of Object.entries(a.mcpServers??{})){let n=Oo(e,t);if(n===void 0||r===`project`&&Q(t)&&`url`in t&&t.auth)continue;let a=`mcp__${e.replace(/-/g,`_`)}`;[...i.servers.entries()].some(([t,n])=>t!==e&&n.namespace===a)||i.servers.set(e,{namespace:a,server:n})}}}function jo(e,t){let n={autoEnableCodemode:void 0,servers:/* @__PURE__ */ new Map,error:void 0};Ao(e.path,e.raw,e.readError,`global`,n),Ao(t.path,t.raw,t.readError,`project`,n);let r=[...n.servers.values()].some(({server:e})=>e.enabled!==!1&&(/* @__PURE__ */ new Set([e.exposure??`codemode`,...Object.values(e.toolExposure??{})])).has(`codemode`));return{autoEnablesCodemode:n.autoEnableCodemode!==!1&&r,...n.error===void 0?{}:{error:n.error}}}function Mo(e,t){let n=e=>{try{return{path:e,raw:T(e,`utf8`)}}catch(t){return t.code===`ENOENT`?{path:e,raw:void 0}:{path:e,raw:void 0,readError:`${e} could not be read (${t instanceof Error?t.message:String(t)})`}}};return jo(n(M(e,`mcp.json`)),n(M(t,`.pi`,`mcp.json`)))}function No(e,t){let n=t.error===void 0?e:{...e,mcpError:t.error};return e.activation===`active`||!t.autoEnablesCodemode?n:{...e,activation:`active`,source:`mcp`,...t.error===void 0?{}:{mcpError:t.error}}}function Po(e,t,n){return!e.present||t===`disabled`||n!==`active`?`full`:`subagents`}function Fo(e=process.argv){let t=e[1];if(t===void 0||t===``)return{present:!1,how:`no-entry`};let n;try{n=E(t)}catch{return{present:!1,how:`unresolvable-entry`}}let r=j(n);for(let e of Io){let t=M(r,...e);try{if(D(t).isDirectory())return{present:!0,how:`found`}}catch{}}return{present:!1,how:`not-found`}}const Io=[[`..`,`extensions`,`codemode`],[`..`,`..`,`extensions`,`codemode`],[`extensions`,`codemode`]];function Lo(e,t,n,r,i,a=process.cwd()){let o=n??Fo(),s=r??vo(e,a),c=i??bo(e,a,t);return{surfaceMode:Po(o,s.switch,c.activation),codemode:o,codemodeSwitch:s,codemodeActivation:c}}function Ro(e){let t=M(e,to),n;try{n=T(t,`utf8`)}catch{return}let r;try{r=JSON.parse(n)}catch{return}if(typeof r!=`object`||!r||Array.isArray(r))return;let i=r.surfaceMode;return i===void 0?void 0:{path:t,value:i}}function zo(e){return[...new Set(e)]}function Bo(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function Vo(e,t){let n=e=>Za.includes(e);if(t===`all-but-ptc`)return zo(e.filter(n));let r=new Set(B);return zo(e.filter(e=>n(e)||!r.has(e)))}function Ho(e){let{mode:t,defaultMode:n,active:r,manual:i}=e;return t===`tui`?!n&&!i?{enter:!1,reason:`config-off`}:Za.some(e=>r.includes(e))?!i&&Qa.filter(e=>!r.includes(e)).length>0?{enter:!1,reason:`restricted-session`}:{enter:!0,base:zo(r),loadout:Vo(r,e.hide??`builtins-only`)}:{enter:!1,reason:`tools-unavailable`}:{enter:!1,reason:`not-tui`}}function Uo(e,t){return e.enabled&&e.base!==void 0?e.base:t}function Wo(e,t){return!e.enabled||e.ourLoadout===void 0?!1:!Bo(e.ourLoadout,t)}function Go(e,t){let n=t.length>0&&t.every(e=>Za.includes(e));return e?.enabled===!0&&n&&e.base!==void 0?{base:e.base,restoreFirst:!0}:{base:t,restoreFirst:!1}}function Ko(e,t){let n=t===`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.`,r=e.map(e=>`tools.${e}(args)`),i=e.slice(0,2).map(e=>e===`read`?`await tools.read({ path: "src/index.ts" })`:e===`bash`?`await tools.bash({ command: "pnpm test" })`:`await tools.${e}({ /* … */ })`).join(`
|
|
58
58
|
`);return[`[PTC MODE ACTIVE]`,`This session runs in PTC mode. `+n,``,`Work by writing one TypeScript program per task and running it:`,` - ptc_run_code for a plain program (its return value and console.log come back to you)`,` - ptc_workflow when the task has named phases and you want narration (log / phase /`,` parallel / pipeline are available there)`,``,`The program body is an async function. Available inside it: ${r.join(`, `)}, plus the`,'parallel binding `tools["pi.dispatch"](args)` — always bound, and its dot name needs string',"indexing (`tools.pi.dispatch` does not exist). The run's actual bound names are on the","`ptcBindings` global, so a program never has to guess what is bound this run.",i.length>0?`Examples:\n${i}`:``,``,`Batch a task's steps into ONE program instead of issuing many tool calls — gathering`,`intermediate output yourself and returning only what matters is the point of this mode.`,`Image-bearing tool results inside a program are attached to you after the run — never return`,`base64 image data as your program's value.`,`If the PTC surfaces cannot express what you need, say so and the user can run /ptc off.`].filter(e=>e.length>0).join(`
|
|
59
59
|
`)}const qo=[`read`,`bash`],Jo=`Use the read tool to load a skill's file when the task matches its description.`,Yo=`Use tools.read({ path }) inside a ptc_run_code program to load a skill's file when the task matches its description.`;function Xo(e){return!qo.some(t=>e.includes(t))}function Zo(e,t=v){let n=t([...e],`read`).trim();return n.length===0?``:n.includes(Jo)?n.replace(Jo,Yo):`${Yo}\n\n${n}`}const Qo=x.Object({task_id:x.Optional(x.String({description:`Id of the background task to poll with ptc_task_output. Present ONLY for a background call; absent once the call has already finished.`})),status:x.String({description:`"background" when this call returned a handle to poll, otherwise the dispatcher's own outcome status ("fulfilled").`}),report_channel:x.String({description:'Which channel delivered the child report: "prompt-json" (a fenced JSON block on the child\'s final message), "tool" (the child called the report tool), "none" (no report arrived — either the child did not comply with the contract, or this is a background handle that has not finished), or "opted-out" (the agent\'s frontmatter set `childReport: false`, so it was never asked). ALWAYS present, so an absent `report` key is never ambiguous — "none" and "opted-out" are different claims about the child.'}),exit_code:x.Optional(x.Number({description:`The child's exit code. Present ONLY for a call that already finished.`})),read_only_tier:x.Optional(x.String({description:`The read-only tier the dispatch resolved to: "strict" or "lenient" (ADR-0041). Absent when no tier was asked for, so an absent key means "no tier" rather than "tier unknown".`})),why_suppressed:x.Optional(x.Boolean({description:"`true` when you passed a `why` and this session's `whyEnabled` switch was off, so the child's prompt carried no <pi-ptc-why> block (ADR-0043). ABSENT means no `why` was passed — that is the distinction the key exists to make. The child was never told your reason; it did not ignore one. A background call returns a handle and does not carry this key; read it from `ptc_task_output` instead."})),report:x.Optional(x.Object({summary:x.String({description:`One line, in the child's own words, of what it concluded.`}),findings:x.Array(x.Object({what:x.String({description:`The claim this finding makes.`}),evidence:x.String({description:`The independent thing that supports the claim.`})})),files_touched:x.Array(x.String({description:`A path the child created or modified.`})),usage:x.Object({input:x.Number({description:`Input tokens, counted by the host.`}),output:x.Number({description:`Output tokens, counted by the host.`}),cost:x.Number({description:`Total cost, counted by the host.`}),turns:x.Number({description:`Assistant turns, counted by the host.`})})})),usage:x.Optional(x.Object({input:x.Number({description:`Input tokens, counted by the host.`}),output:x.Number({description:`Output tokens, counted by the host.`}),cost:x.Number({description:`Total cost, counted by the host.`}),turns:x.Number({description:`Assistant turns, counted by the host.`})},{description:"The host's own count for this child: the same four fields `report.usage` carries, projected from the `DispatchResult.usage` accumulator (ADR-0032, issue #199). ABSENT for a background handle, which has measured nothing yet, and for a child that emitted no usage block. Present on every settled call REGARDLESS of `report_channel`, so a child that reported nothing still accounts for what it cost — the text render states the same four numbers on its `usage` row."}))});function $o(e){let t=e.taskId;return typeof t==`string`?t:void 0}function es(e){let t=e.errorMessage??`the child failed without an error message`,n=[e.started?`child ran`:`harness declined to start`,`exit=`+String(e.exitCode),`turns=`+String(e.usage?.turns??0),`reportChannel=`+e.reportChannel],r=at(e.observedProvider,e.observedModel);r!==void 0&&n.push(`model=`+r);let i=t+` (`+n.join(`, `)+`)`;return i.length<=800?i:`…`+i.slice(-799)}function ts(e){return R({name:`ptc_subagent`,label:`PTC Subagent`,description:["Start a fresh pi agent as a child process: it gets its own context and tools, and it cannot see or change this session except through what it returns. Omit `model` and the child inherits this session's current model (when this pi exposes one; otherwise it falls back to pi's configured default); pass `model`, or let its agent definition pin one, to override that. Use it for work that would otherwise flood this context: a survey, a second opinion, or a task that can run while you do something else.","`agent` is optional — omit it and the child is a fresh generalist pi, with pi's own system prompt and pi's full toolset. Name one to narrow the child instead: an agent is a markdown file in ~/.pi/agent/agents/ for your machine, or <project>/.pi/agents/ for one project, and naming one can restrict the child's tools, pin its model, or append a role. A name with no definition behind it is refused; the refusal lists what IS registered and how to write one.",Yt({cwd:e.cwd,agentScope:e.agentRosterScope??`both`,...e.homeDir===void 0?{}:{homeDir:e.homeDir}})].join(`
|
|
60
60
|
`),promptSnippet:`Start a fresh pi agent as a child process (foreground or background)`,promptGuidelines:[`Prefer one subagent over many tool calls when the work is a question with an answer rather than a fact you can look up, or when the raw output would be larger than the answer.`],parameters:On,outputSchema:Qo,async execute(t,n,r,i,a){let o=et(a),s=await Sn(n,{callId:0,cwd:n.cwd??e.cwd,depth:e.depth,maxDispatchDepth:e.maxDispatchDepth,...e.parentTaskId===void 0?{}:{parentTaskId:e.parentTaskId},...o===void 0?{}:{sessionModel:o}},e.getDispatchDeps?.()??{}),c=$o(s),l=c===void 0?{taskId:void 0,status:s.status,exitCode:s.exitCode}:{taskId:c,status:`background`,exitCode:void 0};if(c!==void 0){let e=_t(n.readOnly),t={task_id:c,status:l.status,report_channel:`none`,...e===void 0?{}:{read_only_tier:e}};return{content:[{type:`text`,text:[`Started background task `+c,wr(e)].filter(e=>e.length>0).join(`
|
|
@@ -63,5 +63,5 @@ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./protocol-CfOgxz3u.js";
|
|
|
63
63
|
|
|
64
64
|
`)}],details:l,structuredContent:m}},renderCall(t,n,r){let i=r?.state,a;return i===void 0?a=e.getSessionModel?.():(i.inheritedSessionModel===void 0&&(i.inheritedSessionModel=e.getSessionModel?.()??null),a=i.inheritedSessionModel??void 0),ui(t,n,{...r?.invalidate===void 0?{}:{requestInvalidate:r.invalidate},...r?.isPartial===void 0?{}:{isPartial:r.isPartial},...r?.state===void 0?{}:{state:r.state},...r?.expanded===!0?{expanded:!0}:{},...a===void 0?{}:{sessionModel:a}})}})}function ns(e){return e.length<=200?e:`…`+e.slice(-199)}const rs=x.Object({summary:x.String({description:`One line, in your own words, of what you concluded.`}),findings:x.Array(x.Object({what:x.String({description:`The claim this finding makes.`}),evidence:x.String({description:`The independent thing that supports the claim — what you read, ran or checked. Not the claim restated.`})})),files_touched:x.Array(x.String({description:`A path you created or modified. Empty if you touched nothing.`}))}),is=[`Hand the host a child report: what you did in this run, in the shape it can read without parsing English.`,`Call it once, at the end. The exact shape is stated in your instructions, which also tell you what to do if this tool is unavailable to you.`,`Evidence is the point of a finding. Put in the independent thing you read, ran or checked — the claim restated is not evidence, and a finding with none is worse than no finding.`,`files_touched lists only paths you actually created or modified; leave it empty rather than guessing.`,`Your prose answer is kept alongside this report and is never replaced by it, so still answer in words.`,`Do not report usage or token counts — those are measured by the host, and anything you send under them is discarded.`].join(`
|
|
65
65
|
`);function as(e){return R({name:Fe,label:`Child Report`,description:is,promptSnippet:`Hand the host a child report when you finish`,promptGuidelines:[`Call ptc_child_report once before you finish, even when the answer is "I changed nothing": a child that reports an empty result is a different thing from a child that never reported, and only the first one says so.`],parameters:rs,outputSchema:rs,defaultActive:e,renderCall(e,t){let n=e,r=typeof n?.summary==`string`?n.summary:``;return new q([{left:t.fg(`toolTitle`,t.bold(`Child report`))+(r===``?``:` `+t.fg(`dim`,ns(r)))}])},renderResult(){return new q([{left:`child report recorded`}])},async execute(e,t){let n={summary:t.summary,findings:t.findings.map(e=>({what:e.what,evidence:e.evidence})),files_touched:[...t.files_touched]};return{content:[{type:`text`,text:`child report recorded (`+String(n.findings.length)+` findings)`}],details:void 0,structuredContent:n}}})}const $=no;function os(e,t,n){return[`PTC mode on — ${t===`all-but-ptc`?`all other tools`:`built-in tools (now reachable only as tools.<name> inside a program)`} hidden.`,`Bindings available inside a program: ${W(e,n).join(`, `)||`(none)`}.`,`Run /ptc off to restore the normal tool set.`].join(`
|
|
66
|
-
`)}function ss(e,t={}){let n=ro(),r,i,a=!1,o=new Sa,s=()=>Uo(n,e.getActiveTools()),c=oo(y()),l=c.optInBindings,u=()=>l,d=ao(y()),f=pr(),p=mr(),m=t.backgroundRuntime??Ha({concurrency:Re({}).dispatchConcurrency,whyEnabled:d.whyEnabled}),h=!1,g=e=>{console.warn(`[pi-ptc.background] `+e)},_=t=>{if(t.length!==0){if(h){e.sendMessage({customType:`bg-task-notification`,content:t,display:!1},{deliverAs:`steer`});return}e.sendUserMessage(t)}},v=async e=>{let{items:t,acks:n}=await m.drainNotifications(e),r=t.filter(e=>Wa(e.record));for(let e of Ka(r))_(Ga(e,{batchId:Ee(),deliveredAtMs:m.clock()}));await m.acknowledgeNotifications(n)},b=async()=>{let e=await m.registry.query({limit:2**53-1}),t=/* @__PURE__ */ new Set;for(let n of e){let e=n.spawnSource.callerId;e.length>0&&t.add(e)}return[...t]},x=async()=>{for(let e of await b())await v(e)},S=async e=>{let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.spawnSource.callerId;e.length>0&&t.add(e)}for(let e of t)await v(e)};m.pipeline.onIdleWake(e=>{v(e).catch(e=>{g(`notification delivery failed: `+(e instanceof Error?e.message:String(e)))})});function C(t){if(t.surfaceMode===`full`||t.surfaceMode===`subagents`){let n=t.surfaceMode===`full`?`direct`:`codemode`;e.registerTool(Si({getBindingSourceNames:s,getOptInBindings:u,getPool:()=>o.get(`run_code`),depth:f,exposure:n,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps})),e.registerTool(Oi({getBindingSourceNames:s,getOptInBindings:u,getPool:()=>o.get(`workflow`),depth:f,exposure:n,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps}))}t.surfaceMode===`subagents`&&e.registerTool(ts({cwd:process.cwd(),depth:f,maxDispatchDepth:z.maxDispatchDepth,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps,getSessionModel:()=>i})),e.registerTool(ua(m.registry)),e.registerTool(va(m.registry,m.outputStorage)),e.registerTool(xa(m.registry,m.lifecycle,{clock:m.clock})),e.registerTool(as(f>0))}let w=!1,T=t=>{w||r.codemodeActivation.activation===`inactive`&&e.getActiveTools().includes(`codemode`)&&(w=!0,t.ui.notify(`pi-ptc-subagents: pi's codemode is active in this session, but nothing this package reads predicted it — no tool list names it and no readable mcp.json auto-enables it — so the surface defaulted to full, and your model is being offered two orchestration tools. pi activates codemode at runtime in ways no settings file records (its MCP extension is one). Run pi with codemode active (-t codemode, or add it to defaultTools) to get the subagents surface instead.`,`warning`))};e.on(`turn_start`,async(e,t)=>{i=et(t),h=!0,T(t)}),e.on(`agent_settled`,async()=>{h=!1;try{await x()}catch(e){g(`agent_settled delivery failed: `+(e instanceof Error?e.message:String(e)))}}),e.on(`turn_end`,async()=>{let e=o;o=new Sa,await e.drain()});let E=e=>{let t=[];n.enabled&&t.push(e.ui.theme.fg(`accent`,`PTC`)),e.ui.setStatus(eo,t.length>0?t.join(` `):void 0)},D=(t,r,i,o)=>{n.enabled=!0,n.base=t,n.ourLoadout=r,e.setActiveTools([...r]),a=!0,e.appendEntry($a,{enabled:!0,base:[...t]}),E(i),i.ui.notify(o,`info`)},ee=(t,r)=>{let i=n.base;n.enabled=!1,n.base=void 0,n.ourLoadout=void 0,a=!1,i!==void 0&&e.setActiveTools([...i]),e.appendEntry(r.customType,{enabled:!1}),E(t),r.announce&&t.ui.notify(`PTC mode off — built-in tools are directly callable again.`,`info`)},te=e=>{let t=e.sessionManager.getEntries();for(let e=t.length-1;e>=0;--e){let n=t[e];if(n?.type!==`custom`||n.customType!==`ptc-mode`)continue;let r=n.data,i=Array.isArray(r?.base)?r.base.filter(e=>typeof e==`string`):void 0;return{enabled:r?.enabled===!0,...i===void 0?{}:{base:i}}}};e.registerCommand(`ptc`,{description:`Show or toggle PTC mode`,handler:async(t,r)=>{let i=t.trim().toLowerCase();if(i===`why`||i.startsWith(`why `))return N(i.slice(4),r);if(i===`off`){if(!n.enabled){r.ui.notify(`PTC mode is already off.`,`info`);return}ee(r,{announce:!0,customType:$a});return}if(i!==`on`){r.ui.notify(n.enabled?`PTC mode is ON — run /ptc off to restore built-in tools.\nBindings: ${W(n.base,l).join(`, `)||`(none)`}`:`PTC mode is OFF — run /ptc on to enter it.`,`info`);return}if(n.enabled){r.ui.notify(`PTC mode is already on.`,`info`);return}let a=Ho({mode:r.mode,defaultMode:!0,active:e.getActiveTools(),manual:!0,hide:$});if(!a.enter){r.ui.notify(a.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`);return}D(a.base,a.loadout,r,os(a.base,$,l))}}),e.on(`session_start`,async(n,a)=>{i=et(a),r=Lo(y(),e.getActiveTools(),t.codemode,t.codemodeSwitch,t.codemodeActivation),C(r),h=!1;let o=await m.bindSession(a.sessionManager?.getSessionDir?.(),e=>a.ui.notify(e,`warning`));try{await S(o)}catch(e){g(`startup reconcile delivery failed: `+(e instanceof Error?e.message:String(e)))}let s=io(y());s.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${s.error}`,`warning`),d.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${d.error}. That key was ignored rather than acted on, so it cannot have switched the dispatch \`why\` block off — \`/ptc why\` is what decides that, and \`/ptc why\` on its own reports the value in force and where it came from.`,`warning`),c.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${c.error}. No opt-in binding was granted, so the PTC surface stays narrowed. Opt-in bindings: ${Cn.join(`, `)}.`,`warning`);let u=Ro(y());u!==void 0&&a.ui.notify(`pi-ptc-subagents: `+u.path+` still has a "surfaceMode" key (`+JSON.stringify(u.value)+"), and it is no longer read: the surface is detected from what pi is, and no key pins it. To keep this package out of your sessions entirely, turn it off in pi -- run `pi config` and disable this package's extensions there (its `extensions` entry set to [] stops pi loading it at all). To silence this notice, delete the key.",`warning`);let f=r.codemode;f.present||a.ui.notify(`pi-ptc-subagents: the codemode probe reported `+f.how+`, so the surface is full. That is the safe direction, not an error.`,`info`),r.codemodeSwitch?.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${r.codemodeSwitch.error}`,`warning`),r.codemodeActivation?.mcpError!==void 0&&a.ui.notify(`pi-ptc-subagents: ${r.codemodeActivation.mcpError}`,`warning`);{let t=e.getAllTools().some(e=>e.name===`codemode`);!f.present&&t&&a.ui.notify(`pi-ptc-subagents: this session registers pi's codemode, but the probe did not find it (`+f.how+`), so the surface defaulted to full, and your model is being offered two orchestration tools. Enable codemode for real (-t codemode) to get the subagents surface instead.`,`warning`),f.present&&!t&&a.ui.notify(`pi-ptc-subagents: the codemode probe found pi's codemode on disk, but this session does not register it (--no-extensions), so the surface is `+JSON.stringify(r.surfaceMode)+(r.surfaceMode===`subagents`?` with no orchestrator: ptc_run_code and ptc_workflow are reachable only from codemode, and this session has none. Launch with codemode active (pi -t codemode), or turn this package off with pi config.`:`.`),`warning`)}if(r.surfaceMode===`subagents`&&!e.getActiveTools().includes(`codemode`)){let t=e.getActiveTools();t.includes(`ptc_run_code`)||t.includes(`ptc_workflow`)||a.ui.notify(`pi-ptc-subagents: the detected surface is subagents, but codemode is not active in this session, so there is no orchestration tool. Add codemode to your pi tool list (the --tools flag or the default tools setting), or turn this package off with pi config.`,`warning`)}T(a);let p=te(a),{base:_,restoreFirst:v}=Go(p,e.getActiveTools());v&&e.setActiveTools([..._]);let b=Ho({mode:a.mode,defaultMode:s.defaultMode,active:_,manual:!1,hide:$}),x=p?.enabled??b.enter;if(ne(a),b.enter&&x){D(_,b.loadout,a,os(_,$,l));return}E(a),!b.enter&&b.reason!==`not-tui`&&p===void 0&&b.reason===`restricted-session`&&a.ui.notify(`PTC mode skipped: this session was launched with an explicit tool restriction.`,`info`)}),e.on(`session_shutdown`,async()=>{h=!1;try{await m.shutdown(`session_ended_while_running`)}catch(e){g(`session shutdown failed: `+(e instanceof Error?e.message:String(e)))}});let O=!1,k=(e,t)=>{if(e===void 0)return;if(!n.enabled||!t){O&&=(delete e.sections.skills,!1);return}let r=Zo(e.skills);r.length!==0&&(e.sections.skills=r,O=!0)};e.on(`before_agent_start`,async(t,r)=>{let i=t.systemPromptOptions;if(k(i,Xo(e.getActiveTools())),n.enabled){if(Wo(n,e.getActiveTools())){ee(r,{announce:!1,customType:$a}),k(i,Xo(e.getActiveTools())),r.ui.notify(`PTC mode off — another extension changed the active tool set.`,`warning`);return}if(a)return a=!1,{message:{customType:`ptc-mode-briefing`,content:Ko(W(n.base,l),$),display:!1}}}});let A;function ne(e){let t=j(e);t!==void 0&&(A=t.enabled,m.dispatchDeps.whyEnabled=t.enabled)}function j(e){let t=e.sessionManager.getEntries();for(let e=t.length-1;e>=0;--e){let n=t[e];if(n?.type!==`custom`||n.customType!==`ptc-why`)continue;let r=n.data?.enabled;if(typeof r==`boolean`)return{enabled:r}}}function M(e,t){return[`The dispatch \`why\` block is ${e?`ON`:`OFF`}`,t===`session`?`(set by this session)`:`(set by ptc.json)`,e?`-- a dispatched child receives your reason. Run /ptc why off to stop handing it over.`:`-- a dispatched child does not receive your reason. Run /ptc why on to hand it over.`].join(` `)}function N(t,n){let r=t.trim().toLowerCase(),i=A??d.whyEnabled,a=A===void 0?`config`:`session`;if(r===``){n.ui.notify(M(i,a),`info`);return}if(r!==`on`&&r!==`off`){n.ui.notify(`/ptc why takes "on" or "off", or nothing at all to report the current value -- not "${t.trim()}". Nothing changed.`,`warning`);return}let o=r===`on`;if(i===o){n.ui.notify(M(o,a),`info`);return}A=o,m.dispatchDeps.whyEnabled=o,e.appendEntry(cs,{enabled:o}),n.ui.notify(M(o,`session`),`info`)}}const cs=`ptc-why`;export{B as BUILTIN_BINDING_NAMES,En as DEFAULT_BINDING_NAMES,z as DEFAULT_CONFIG,no as DEFAULT_HIDE_STRATEGY,o as HOST_FRAME_KIND,tr as MAX_LINE_CHARS,Qa as MODE_REQUIRED_TOOL_NAMES,Cn as OPT_IN_BINDING_NAMES,n as PTC_ERROR_KIND,i as PTC_LOG_LEVEL,to as PTC_MODE_CONFIG_FILE,$a as PTC_MODE_ENTRY_TYPE,eo as PTC_MODE_STATUS_KEY,Za as PTC_MODE_TOOL_NAMES,Yo as PTC_SKILL_LOAD_INSTRUCTION,cs as PTC_WHY_ENTRY_TYPE,qo as SKILL_READING_TOOL_NAMES,Sa as TurnPools,Ie as WORKER_ENV_ALLOW_LIST,t as WORKER_FRAME_KIND,Rn as WorkerPool,Uo as bindingSource,Ko as buildModeInstruction,Zo as buildPtcSkillsSection,Nn as createBuiltinBindings,Le as createWorkerEnv,Ho as decideModeEntry,ss as default,Wo as detectExternalLoadoutChange,Lo as detectSurfaceMode,Po as detectedSurfaceMode,ze as effectiveTimeoutMs,ro as initialModeState,wn as isOptInBindingName,Vo as modeLoadout,Fo as probeCodemodePresence,vo as readCodemodeSwitch,io as readDefaultModeConfig,Ro as readLegacySurfaceKey,oo as readOptInBindingsConfig,ao as readWhyEnabledConfig,fr as renderModelValue,Go as resolveBaseOnStart,yo as resolveCodemodeActivation,_o as resolveCodemodeSwitch,Re as resolveConfig,Tn as resolveOptInBindingNames,qn as runPtcProgram,Bo as sameToolSet,U as sanitizeText,Xo as skillsSectionDropped,rr as stripAnsi};
|
|
66
|
+
`)}function ss(e,t={}){let n=ro(),r,i,a=!1,o=new Sa,s=()=>Uo(n,e.getActiveTools()),c=oo(y()),l=c.optInBindings,u=()=>l,d=ao(y()),f=pr(),p=mr(),m=t.backgroundRuntime??Ha({concurrency:Re({}).dispatchConcurrency,whyEnabled:d.whyEnabled}),h=!1,g=e=>{console.warn(`[pi-ptc.background] `+e)},_=t=>{t.length!==0&&(h?e.sendMessage({customType:`bg-task-notification`,content:t,display:!1},{deliverAs:`steer`}):e.sendUserMessage(t))},v=async e=>{let{items:t,acks:n}=await m.drainNotifications(e),r=t.filter(e=>Wa(e.record));for(let e of Ka(r))_(Ga(e,{batchId:Ee(),deliveredAtMs:m.clock()}));await m.acknowledgeNotifications(n)},b=async()=>{let e=await m.registry.query({limit:2**53-1}),t=/* @__PURE__ */ new Set;for(let n of e){let e=n.spawnSource.callerId;e.length>0&&t.add(e)}return[...t]},x=async()=>{for(let e of await b())await v(e)},S=async e=>{let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.spawnSource.callerId;e.length>0&&t.add(e)}for(let e of t)await v(e)};m.pipeline.onIdleWake(e=>{v(e).catch(e=>{g(`notification delivery failed: `+(e instanceof Error?e.message:String(e)))})});function C(t){if(t.surfaceMode===`full`||t.surfaceMode===`subagents`){let n=t.surfaceMode===`full`?`direct`:`codemode`;e.registerTool(Si({getBindingSourceNames:s,getOptInBindings:u,getPool:()=>o.get(`run_code`),depth:f,exposure:n,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps})),e.registerTool(Oi({getBindingSourceNames:s,getOptInBindings:u,getPool:()=>o.get(`workflow`),depth:f,exposure:n,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps}))}t.surfaceMode===`subagents`&&e.registerTool(ts({cwd:process.cwd(),depth:f,maxDispatchDepth:z.maxDispatchDepth,...p===void 0?{}:{parentTaskId:p},getDispatchDeps:()=>m.dispatchDeps,getSessionModel:()=>i})),e.registerTool(ua(m.registry)),e.registerTool(va(m.registry,m.outputStorage)),e.registerTool(xa(m.registry,m.lifecycle,{clock:m.clock})),e.registerTool(as(f>0))}let w=!1,T=t=>{w||r.codemodeActivation.activation===`inactive`&&e.getActiveTools().includes(`codemode`)&&(w=!0,t.ui.notify(`pi-ptc-subagents: pi's codemode is active in this session, but nothing this package reads predicted it — no tool list names it and no readable mcp.json auto-enables it — so the surface defaulted to full, and your model is being offered two orchestration tools. pi activates codemode at runtime in ways no settings file records (its MCP extension is one). Run pi with codemode active (-t codemode, or add it to defaultTools) to get the subagents surface instead.`,`warning`))};e.on(`turn_start`,async(e,t)=>{i=et(t),h=!0,T(t)}),e.on(`agent_settled`,async()=>{h=!1;try{await x()}catch(e){g(`agent_settled delivery failed: `+(e instanceof Error?e.message:String(e)))}}),e.on(`turn_end`,async()=>{let e=o;o=new Sa,await e.drain()});let E=e=>{let t=[];n.enabled&&t.push(e.ui.theme.fg(`accent`,`PTC`)),e.ui.setStatus(eo,t.length>0?t.join(` `):void 0)},D=(t,r,i,o)=>{n.enabled=!0,n.base=t,n.ourLoadout=r,e.setActiveTools([...r]),a=!0,e.appendEntry($a,{enabled:!0,base:[...t]}),E(i),i.ui.notify(o,`info`)},ee=(t,r)=>{let i=n.base;n.enabled=!1,n.base=void 0,n.ourLoadout=void 0,a=!1,i!==void 0&&e.setActiveTools([...i]),e.appendEntry(r.customType,{enabled:!1}),E(t),r.announce&&t.ui.notify(`PTC mode off — built-in tools are directly callable again.`,`info`)},te=e=>{let t=e.sessionManager.getEntries();for(let e=t.length-1;e>=0;--e){let n=t[e];if(n?.type!==`custom`||n.customType!==`ptc-mode`)continue;let r=n.data,i=Array.isArray(r?.base)?r.base.filter(e=>typeof e==`string`):void 0;return{enabled:r?.enabled===!0,...i===void 0?{}:{base:i}}}};e.registerCommand(`ptc`,{description:`Show or toggle PTC mode`,handler:async(t,r)=>{let i=t.trim().toLowerCase();if(i===`why`||i.startsWith(`why `))return N(i.slice(4),r);if(i===`off`){if(!n.enabled){r.ui.notify(`PTC mode is already off.`,`info`);return}ee(r,{announce:!0,customType:$a});return}if(i!==`on`){r.ui.notify(n.enabled?`PTC mode is ON — run /ptc off to restore built-in tools.\nBindings: ${W(n.base,l).join(`, `)||`(none)`}`:`PTC mode is OFF — run /ptc on to enter it.`,`info`);return}if(n.enabled){r.ui.notify(`PTC mode is already on.`,`info`);return}let a=Ho({mode:r.mode,defaultMode:!0,active:e.getActiveTools(),manual:!0,hide:$});a.enter?D(a.base,a.loadout,r,os(a.base,$,l)):r.ui.notify(a.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`)}}),e.on(`session_start`,async(n,a)=>{i=et(a),r=Lo(y(),e.getActiveTools(),t.codemode,t.codemodeSwitch,t.codemodeActivation),C(r),h=!1;let o=await m.bindSession(a.sessionManager?.getSessionDir?.(),e=>a.ui.notify(e,`warning`));try{await S(o)}catch(e){g(`startup reconcile delivery failed: `+(e instanceof Error?e.message:String(e)))}let s=io(y());s.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${s.error}`,`warning`),d.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${d.error}. That key was ignored rather than acted on, so it cannot have switched the dispatch \`why\` block off — \`/ptc why\` is what decides that, and \`/ptc why\` on its own reports the value in force and where it came from.`,`warning`),c.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${c.error}. No opt-in binding was granted, so the PTC surface stays narrowed. Opt-in bindings: ${Cn.join(`, `)}.`,`warning`);let u=Ro(y());u!==void 0&&a.ui.notify(`pi-ptc-subagents: `+u.path+` still has a "surfaceMode" key (`+JSON.stringify(u.value)+"), and it is no longer read: the surface is detected from what pi is, and no key pins it. To keep this package out of your sessions entirely, turn it off in pi -- run `pi config` and disable this package's extensions there (its `extensions` entry set to [] stops pi loading it at all). To silence this notice, delete the key.",`warning`);let f=r.codemode;f.present||a.ui.notify(`pi-ptc-subagents: the codemode probe reported `+f.how+`, so the surface is full. That is the safe direction, not an error.`,`info`),r.codemodeSwitch?.error!==void 0&&a.ui.notify(`pi-ptc-subagents: ${r.codemodeSwitch.error}`,`warning`),r.codemodeActivation?.mcpError!==void 0&&a.ui.notify(`pi-ptc-subagents: ${r.codemodeActivation.mcpError}`,`warning`);{let t=e.getAllTools().some(e=>e.name===`codemode`);!f.present&&t&&a.ui.notify(`pi-ptc-subagents: this session registers pi's codemode, but the probe did not find it (`+f.how+`), so the surface defaulted to full, and your model is being offered two orchestration tools. Enable codemode for real (-t codemode) to get the subagents surface instead.`,`warning`),f.present&&!t&&a.ui.notify(`pi-ptc-subagents: the codemode probe found pi's codemode on disk, but this session does not register it (--no-extensions), so the surface is `+JSON.stringify(r.surfaceMode)+(r.surfaceMode===`subagents`?` with no orchestrator: ptc_run_code and ptc_workflow are reachable only from codemode, and this session has none. Launch with codemode active (pi -t codemode), or turn this package off with pi config.`:`.`),`warning`)}if(r.surfaceMode===`subagents`&&!e.getActiveTools().includes(`codemode`)){let t=e.getActiveTools();t.includes(`ptc_run_code`)||t.includes(`ptc_workflow`)||a.ui.notify(`pi-ptc-subagents: the detected surface is subagents, but codemode is not active in this session, so there is no orchestration tool. Add codemode to your pi tool list (the --tools flag or the default tools setting), or turn this package off with pi config.`,`warning`)}T(a);let p=te(a),{base:_,restoreFirst:v}=Go(p,e.getActiveTools());v&&e.setActiveTools([..._]);let b=Ho({mode:a.mode,defaultMode:s.defaultMode,active:_,manual:!1,hide:$}),x=p?.enabled??b.enter;ne(a),b.enter&&x?D(_,b.loadout,a,os(_,$,l)):(E(a),!b.enter&&b.reason!==`not-tui`&&p===void 0&&b.reason===`restricted-session`&&a.ui.notify(`PTC mode skipped: this session was launched with an explicit tool restriction.`,`info`))}),e.on(`session_shutdown`,async()=>{h=!1;try{await m.shutdown(`session_ended_while_running`)}catch(e){g(`session shutdown failed: `+(e instanceof Error?e.message:String(e)))}});let O=!1,k=(e,t)=>{if(e===void 0)return;if(!n.enabled||!t){O&&=(delete e.sections.skills,!1);return}let r=Zo(e.skills);r.length!==0&&(e.sections.skills=r,O=!0)};e.on(`before_agent_start`,async(t,r)=>{let i=t.systemPromptOptions;if(k(i,Xo(e.getActiveTools())),n.enabled){if(Wo(n,e.getActiveTools()))ee(r,{announce:!1,customType:$a}),k(i,Xo(e.getActiveTools())),r.ui.notify(`PTC mode off — another extension changed the active tool set.`,`warning`);else if(a)return a=!1,{message:{customType:`ptc-mode-briefing`,content:Ko(W(n.base,l),$),display:!1}}}});let A;function ne(e){let t=j(e);t!==void 0&&(A=t.enabled,m.dispatchDeps.whyEnabled=t.enabled)}function j(e){let t=e.sessionManager.getEntries();for(let e=t.length-1;e>=0;--e){let n=t[e];if(n?.type!==`custom`||n.customType!==`ptc-why`)continue;let r=n.data?.enabled;if(typeof r==`boolean`)return{enabled:r}}}function M(e,t){return[`The dispatch \`why\` block is ${e?`ON`:`OFF`}`,t===`session`?`(set by this session)`:`(set by ptc.json)`,e?`-- a dispatched child receives your reason. Run /ptc why off to stop handing it over.`:`-- a dispatched child does not receive your reason. Run /ptc why on to hand it over.`].join(` `)}function N(t,n){let r=t.trim().toLowerCase(),i=A??d.whyEnabled,a=A===void 0?`config`:`session`;if(r===``){n.ui.notify(M(i,a),`info`);return}if(r!==`on`&&r!==`off`){n.ui.notify(`/ptc why takes "on" or "off", or nothing at all to report the current value -- not "${t.trim()}". Nothing changed.`,`warning`);return}let o=r===`on`;i===o?n.ui.notify(M(o,a),`info`):(A=o,m.dispatchDeps.whyEnabled=o,e.appendEntry(cs,{enabled:o}),n.ui.notify(M(o,`session`),`info`))}}const cs=`ptc-why`;export{B as BUILTIN_BINDING_NAMES,En as DEFAULT_BINDING_NAMES,z as DEFAULT_CONFIG,no as DEFAULT_HIDE_STRATEGY,o as HOST_FRAME_KIND,tr as MAX_LINE_CHARS,Qa as MODE_REQUIRED_TOOL_NAMES,Cn as OPT_IN_BINDING_NAMES,n as PTC_ERROR_KIND,i as PTC_LOG_LEVEL,to as PTC_MODE_CONFIG_FILE,$a as PTC_MODE_ENTRY_TYPE,eo as PTC_MODE_STATUS_KEY,Za as PTC_MODE_TOOL_NAMES,Yo as PTC_SKILL_LOAD_INSTRUCTION,cs as PTC_WHY_ENTRY_TYPE,qo as SKILL_READING_TOOL_NAMES,Sa as TurnPools,Ie as WORKER_ENV_ALLOW_LIST,t as WORKER_FRAME_KIND,Rn as WorkerPool,Uo as bindingSource,Ko as buildModeInstruction,Zo as buildPtcSkillsSection,Nn as createBuiltinBindings,Le as createWorkerEnv,Ho as decideModeEntry,ss as default,Wo as detectExternalLoadoutChange,Lo as detectSurfaceMode,Po as detectedSurfaceMode,ze as effectiveTimeoutMs,ro as initialModeState,wn as isOptInBindingName,Vo as modeLoadout,Fo as probeCodemodePresence,vo as readCodemodeSwitch,io as readDefaultModeConfig,Ro as readLegacySurfaceKey,oo as readOptInBindingsConfig,ao as readWhyEnabledConfig,fr as renderModelValue,Go as resolveBaseOnStart,yo as resolveCodemodeActivation,_o as resolveCodemodeSwitch,Re as resolveConfig,Tn as resolveOptInBindingNames,qn as runPtcProgram,Bo as sameToolSet,U as sanitizeText,Xo as skillsSectionDropped,rr as stripAnsi};
|
|
67
67
|
//# sourceMappingURL=index.js.map
|
package/dist/worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{a as e,c as t}from"./protocol-CfOgxz3u.js";import{stripTypeScriptTypes as n}from"node:module";import{parentPort as r,workerData as i}from"node:worker_threads";import{inspect as a}from"node:util";function o(t){let n=t.protocol.hostFrame,r=t.protocol.workerFrame,i=t.protocol.logLevel,a=t.protocol.errorKind,o=`__ptcProgram`,s=`CREATED`,c=0,l,u,d=1,f=0,p=1/0,m=[],h=/* @__PURE__ */ new Map,g,_=()=>globalThis;class v extends Error{toolName;constructor(e,t){super(t),this.name=`ToolCallError`,this.toolName=e}}let y=e=>e instanceof Error?e.message:String(e),b=e=>{if(!(e instanceof Error)||typeof e.stack!=`string`)return;let t=e.stack.split(`
|
|
2
2
|
`),n=[t[0]??``];for(let e of t.slice(1))if(n.push(e),n.length>=6)break;return n.join(`
|
|
3
|
-
`)},x=(e,t=l)=>{if(!t)return!1;try{return t.postMessage(e),!0}catch{return!1}},S=(e,t,n)=>{x({kind:r.log,level:e,text:t},n)},C=(e,t,n,i)=>{x(n===void 0?{kind:r.error,error:{kind:e,message:t}}:{kind:r.error,error:{kind:e,message:t,stack:n}},i)},w=e=>{let t=/* @__PURE__ */ Error(e===`timeout`?`PTC run timed out`:`PTC run was cancelled`);return t.name=`AbortError`,t},T=()=>{let e=/* @__PURE__ */ Error(`the PTC control channel closed before the call completed`);return e.name=`AbortError`,e},E=async()=>{
|
|
3
|
+
`)},x=(e,t=l)=>{if(!t)return!1;try{return t.postMessage(e),!0}catch{return!1}},S=(e,t,n)=>{x({kind:r.log,level:e,text:t},n)},C=(e,t,n,i)=>{x(n===void 0?{kind:r.error,error:{kind:e,message:t}}:{kind:r.error,error:{kind:e,message:t,stack:n}},i)},w=e=>{let t=/* @__PURE__ */ Error(e===`timeout`?`PTC run timed out`:`PTC run was cancelled`);return t.name=`AbortError`,t},T=()=>{let e=/* @__PURE__ */ Error(`the PTC control channel closed before the call completed`);return e.name=`AbortError`,e},E=async()=>{f<p?f+=1:await new Promise((e,t)=>{m.push({resolve:e,reject:t})})},D=()=>{let e=m.shift();e?e.resolve():--f},O=e=>{for(;m.length>0;){let t=m.shift();t&&t.reject(e)}},k=e=>{O(e);for(let[t,n]of h)h.delete(t),n.reject(e)},A=()=>{let e=t.workerData;if(typeof e!=`object`||!e)return;let n=e.env;if(typeof n!=`object`||!n||Array.isArray(n))return;let r=n;for(let e of Object.keys(process.env))e in r||delete process.env[e];for(let e of Object.keys(r)){let t=r[e];typeof t==`string`&&(process.env[e]=t)}},j=t=>{let n=/* @__PURE__ */ new Set,r=(t,i)=>{if(t===null)return{ok:!0,value:null};if(typeof t==`string`||typeof t==`boolean`)return{ok:!0,value:t};if(t===void 0)return{ok:!0,value:void 0};if(typeof t==`number`)return Number.isFinite(t)?{ok:!0,value:t}:{ok:!1,reason:`${i} is ${String(t)}, which is not representable as JSON`};if(typeof t!=`object`)return{ok:!1,reason:`${i} is ${e(t)}; results must be lossless JSON`};if(Array.isArray(t)){if(n.has(t))return{ok:!1,reason:`${i} is a circular reference`};n.add(t);let e=[];for(let n=0;n<t.length;n+=1){let a=r(t[n],`${i}[${n}]`);if(!a.ok)return a;e.push(a.value===void 0?null:a.value)}return n.delete(t),{ok:!0,value:e}}let a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null){let e=t.constructor;return{ok:!1,reason:`${i} is a ${e&&typeof e.name==`string`&&e.name.length>0?e.name:`an object`}; results must be plain JSON objects`}}if(n.has(t))return{ok:!1,reason:`${i} is a circular reference`};n.add(t);let o={};for(let e of Object.keys(t)){let n=r(t[e],`${i}.${e}`);if(!n.ok)return n;n.value!==void 0&&(o[e]=n.value)}return n.delete(t),{ok:!0,value:o}};return r(t,`result`)},M=e=>e.map(e=>typeof e==`string`?e:t.inspect(e,{depth:4,breakLength:1/0,colors:!1})).join(` `),N=e=>{let t=t=>(...n)=>{S(t,M(n),e)};_().console={log:t(i.log),info:t(i.info),warn:t(i.warn),error:t(i.error),debug:t(i.debug)}},P=()=>{typeof process.removeAllListeners==`function`&&typeof process.on==`function`&&(process.removeAllListeners(`warning`),process.on(`warning`,e=>{let t=typeof e==`object`&&e?e:void 0,n=t&&typeof t.name==`string`?t.name:`Warning`;if(n===`ExperimentalWarning`)return;let r=t&&typeof t.message==`string`?t.message:String(e);S(i.warn,`${n}: ${r}`)}))},F=e=>{let n=`async function ${o}() {\n${e}\n}`,r=n;try{r=t.stripTypes(n,{mode:`strip`})}catch{r=n}return Function(`${r}\nreturn ${o}();`)},I=async(e,t,n)=>{try{let t;try{t=F(e)}catch(e){C(a.exception,`program failed to compile: ${y(e)}`,b(e),n);return}try{let e=await t(),i=j(e);if(!i.ok){C(a.invalidOutput,i.reason,void 0,n);return}x(i.value===void 0?{kind:r.result}:{kind:r.result,value:i.value},n)}catch(e){C(u??a.exception,y(e),b(e),n)}}finally{await W(t,n)}},L=(e,t)=>async n=>{if(u)throw w(u);await E();try{if(u)throw w(u);let i=d;d+=1;let a=new Promise((e,t)=>{h.set(i,{resolve:e,reject:t})});if(!x({kind:r.call,callId:i,tool:e,args:n},t))throw h.delete(i),new v(e,`${e}() could not be called: the arguments are not transferable or the run has ended`);return await a}finally{D()}},R=e=>{let t=e.callId;if(typeof t!=`number`)return;let n=h.get(t);n&&(h.delete(t),e.ok===!0?n.resolve(e.value):n.reject(new v(typeof e.tool==`string`?e.tool:`unknown`,typeof e.message==`string`?e.message:`binding call failed`)))},z=e=>{u=e,k(w(e))},B=(e,t)=>{u=void 0;let n=w(e);C(e,n.message,void 0,t)},V=(e,t,n)=>{if(t>n)throw RangeError(`${e}() received ${t} items, exceeding maxItemsPerCall (${n})`)},H=(t,n,i)=>{let a=_();a.args=t===void 0?null:t,a.log=t=>{if(typeof t!=`string`)throw TypeError(`log(message) expects a string, received ${e(t)}`);x({kind:r.narration,message:t},i)},a.phase=t=>{if(typeof t!=`string`)throw TypeError(`phase(title) expects a string, received ${e(t)}`);x({kind:r.phase,title:t},i)},a.parallel=async t=>{if(!Array.isArray(t))throw TypeError(`parallel(thunks) expects an array of functions, received ${e(t)}`);V(`parallel`,t.length,n);for(let n=0;n<t.length;n+=1)if(typeof t[n]!=`function`)throw TypeError(`parallel(thunks) expects functions; item ${n} is ${e(t[n])}`);return await Promise.all(t.map(async e=>{try{return await e()}catch{return null}}))},a.pipeline=async(t,...r)=>{if(!Array.isArray(t))throw TypeError(`pipeline(items, ...stages) expects an array of items, received ${e(t)}`);if(V(`pipeline`,t.length,n),r.length===0)throw TypeError(`pipeline(items, ...stages) requires at least one stage function`);for(let t=0;t<r.length;t+=1)if(typeof r[t]!=`function`)throw TypeError(`pipeline(items, ...stages) expects stage functions; stage ${t} is ${e(r[t])}`);let i=r;return await Promise.all(t.map(async(e,t)=>{try{let n=e;for(let r of i)n=await r(n,e,t);return n}catch{return null}}))}},U=()=>{if(!g)return;let e=_();for(let t of Object.keys(e))g.has(t)||delete e[t];for(let[t,n]of g){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||r.writable!==!1)try{e[t]=n}catch{}}},W=async(e,t)=>{s===`RUNNING`&&e===c&&(k(T()),f=0,u=void 0,d=1,h.clear(),U(),A(),s=`READY`,x({kind:r.ready},t))},G=(e,t,n)=>{U(),u=void 0,f=0,h.clear(),A(),N(n),p=typeof e.maxPendingCalls==`number`&&Number.isFinite(e.maxPendingCalls)&&e.maxPendingCalls>0?e.maxPendingCalls:1/0;let r={},i=Array.isArray(e.bindings)?e.bindings.filter(e=>typeof e==`string`):[];for(let e of i)r[e]=L(e,n);let a=i.join(`, `)||`(none)`,o=Array.isArray(e.bindingCandidates)?e.bindingCandidates:[];for(let e of o)typeof e!=`string`||r[e]||(r[e]=async()=>{throw new v(e,`no binding named "${e}" in this run; available bindings: ${a}`)});if(_().tools=r,_().ptcBindings=Object.freeze([...i]),e.surface===`workflow`){let t=typeof e.maxItemsPerCall==`number`?e.maxItemsPerCall:0;H(e.args,t,n)}I(typeof e.code==`string`?e.code:``,t,n)},K=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e;if(r.kind===n.init){if(s!==`READY`)return;c+=1;let e=c;s=`RUNNING`,G(r,e,t)}else if(r.kind===n.callResult)R(r);else if(r.kind===n.cancel){let e=r.reason===`timeout`?`timeout`:`abort`;if(s===`READY`){B(e,t);return}z(e)}};s=`BOOTING`,t.parentPort.on(`message`,e=>{if(typeof e!=`object`||!e)return;let t=e;if(t.kind!==n.connect)return;let i=t.port;if(typeof i!=`object`||!i||typeof i.on!=`function`)return;let a=i;l=a,a.on(`message`,e=>{K(e,a)}),a.on(`close`,()=>{l===a&&k(T())}),P();let o=g===void 0;if(o&&(g=new Map(Object.entries(_()))),s=`READY`,u!==void 0){if(o){B(u,a);return}u=void 0}x({kind:r.ready},a)})}o({parentPort:r,workerData:i,inspect:a,stripTypes:n,protocol:t()});export{};
|
|
4
4
|
//# sourceMappingURL=worker.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-ptc-subagents",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.1",
|
|
4
4
|
"description": "Programmable tool calling (PTC) and subagent fan-out for pi — the model writes JS/TS programs that call pi's tools, or fans out to a fresh pi subprocess per subagent task",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
@@ -52,20 +52,20 @@
|
|
|
52
52
|
"minimatch": "^10.2.6"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
-
"@earendil-works/pi-ai": "^1.
|
|
56
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
57
|
-
"@earendil-works/pi-tui": "^1.
|
|
58
|
-
"@types/node": "^
|
|
59
|
-
"@vitest/coverage-v8": "
|
|
60
|
-
"oxfmt": "^0.
|
|
61
|
-
"oxlint": "^1.
|
|
62
|
-
"oxlint-tsgolint": "^7.0.
|
|
63
|
-
"rolldown": "^1.2.
|
|
64
|
-
"rolldown-plugin-dts": "^0.28.
|
|
55
|
+
"@earendil-works/pi-ai": "^1.3.0",
|
|
56
|
+
"@earendil-works/pi-coding-agent": "^1.3.0",
|
|
57
|
+
"@earendil-works/pi-tui": "^1.3.0",
|
|
58
|
+
"@types/node": "^26.6.5",
|
|
59
|
+
"@vitest/coverage-v8": "5.0.5",
|
|
60
|
+
"oxfmt": "^0.73.0",
|
|
61
|
+
"oxlint": "^1.88.0",
|
|
62
|
+
"oxlint-tsgolint": "^7.0.2004",
|
|
63
|
+
"rolldown": "^1.2.14",
|
|
64
|
+
"rolldown-plugin-dts": "^0.28.8",
|
|
65
65
|
"typebox": "^1.3.34",
|
|
66
66
|
"typescript": "^7.0.2",
|
|
67
|
-
"vite-plus": "
|
|
68
|
-
"vitest": "^
|
|
67
|
+
"vite-plus": "1.3.0",
|
|
68
|
+
"vitest": "^5.0.5"
|
|
69
69
|
},
|
|
70
70
|
"peerDependencies": {
|
|
71
71
|
"@earendil-works/pi-ai": "*",
|