pi-ptc-subagents 7.8.0 → 7.9.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 CHANGED
@@ -5,6 +5,42 @@ 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
+ ## [7.9.1] - 2026-11-02
9
+
10
+ ### Fixed
11
+
12
+ - **The plugin now hears about a new release within minutes, not hours**
13
+ (ADR-0023): the version check cached GitHub's "latest release" for 6 hours, and
14
+ the first check after installing the plugin is the one that opens that window —
15
+ so every release published inside it was silently swallowed (measured on
16
+ 2026-11-02: 7.8.0 and 7.9.0 were both missed, the user saw the releases on
17
+ GitHub and heard nothing from the plugin). The cache window is now 15 minutes,
18
+ and two new probes pin it: no request to GitHub inside the window, a fresh
19
+ request once it expires.
20
+
21
+ ## [7.9.0] - 2026-11-02
22
+
23
+ ### Changed
24
+
25
+ - **The published package no longer bundles typebox** (ADR-0026): the extension
26
+ builds its tool schemas with typebox, which dragged 245 typebox modules into the
27
+ bundle. pi's extension loader resolves `typebox` to its own copy (the same
28
+ version, 1.3.27), so the bundler now treats it as external: `dist/index.js` went
29
+ from 101,999 B to 61,052 B and the tarball from 72.2 kB to 60.2 kB — no new
30
+ dependency, nothing extra to install.
31
+
32
+ ### Fixed
33
+
34
+ - **The upgrade notice is no longer swallowed by the surface breadcrumb** (pi
35
+ extension): pi's TUI has a single status slot, so a later notification replaces
36
+ an earlier one — the upgrade reminder was pushed out by the `surface=…` line.
37
+ It now goes out as the last notification of `session_start`.
38
+ - **A version with nothing to say no longer burns its own reminder**: the seen
39
+ version was written before checking whether there was a section to show, so the
40
+ reminder for that version was lost for good.
41
+ - The display layer's build now clears its output directory first (rolldown never
42
+ does), so a renamed chunk can no longer linger as a dead file in the tree.
43
+
8
44
  ## [7.8.0] - 2026-11-02
9
45
 
10
46
  ### Changed
package/dist/index.js CHANGED
@@ -1,8 +1,6 @@
1
- import{i as e,n as t,r as n}from"./ptc-engine.js";import"./ptc/index.js";import*as r from"@earendil-works/pi-coding-agent";import{getAgentDir as i}from"@earendil-works/pi-coding-agent";import{existsSync as a,mkdirSync as o,readFileSync as s,readdirSync as c,renameSync as l,rmSync as u,statSync as d,writeFileSync as f}from"node:fs";import{dirname as ee,join as p}from"node:path";import{execSync as te,spawn as m}from"node:child_process";import{randomUUID as ne}from"node:crypto";import{mkdir as h,open as re,readFile as g,readdir as ie,rename as ae,writeFile as oe}from"node:fs/promises";import{gunzipSync as se,gzip as ce}from"node:zlib";import{promisify as le}from"node:util";import{fileURLToPath as ue}from"node:url";import{tmpdir as de}from"node:os";import{Box as fe,Text as pe}from"@earendil-works/pi-tui";const me={assign:0,create:0,clone:0,discard:0,update:0};function he(e){return Array.isArray(e)}function ge(e){return v(typeof e,`bigint`)}function _e(e){return v(typeof e,`boolean`)}function ve(e){return v(e,null)}function ye(e){return Number.isFinite(e)}function be(e){return _(e)&&!he(e)}function _(e){return v(typeof e,`object`)&&!ve(e)}function xe(e){return v(typeof e,`string`)}function v(e,t){return e===t}function Se(e,t){return e>t}function Ce(e,t){return e<t}function we(e){if(!_(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return!ve(t)&&v(typeof t.constructor,`function`)&&!(v(t.constructor,globalThis.Object)||v(t.constructor.name,`Object`))}function y(e,t,n){return v(e.length,0)?n():t(e[0],e.slice(1))}function Te(e){return v(e,`__proto__`)||v(e,`constructor`)||v(e,`prototype`)}function b(e,t){return Te(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function x(e){return Object.getOwnPropertyNames(e)}function Ee(e){return Object.getOwnPropertySymbols(e)}function De(e){return Object.values(e)}function Oe(e){return globalThis.ArrayBuffer.isView(e)}function ke(e){return e instanceof globalThis.RegExp}function Ae(e){return e instanceof globalThis.Set}function je(e){return e instanceof globalThis.Map}const Me={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Ne(){return Me}function Pe(e){return Ne().immutableTypes?Object.freeze(e):e}function S(e,t){return me.assign+=1,Pe({...e,...t})}function Fe(e){return e}function Ie(e){return b(e,`~kind`)||b(e,`~unsafe`)}function Le(e){let t={};for(let n of x(e)){if(Te(n))continue;let r=Object.getOwnPropertyDescriptor(e,n);r.value=Ge(r.value),v(r.enumerable,!0)?t[n]=r.value:Object.defineProperty(t,n,r)}return t}function Re(e){let t={};for(let n of x(e))Te(n)||(t[n]=Ge(e[n]));for(let n of Ee(e))t[n]=Ge(e[n]);return t}function ze(e){return we(e)?Fe(e):Ie(e)?Le(e):Re(e)}function Be(e){return e.map(e=>Ge(e))}function Ve(e){return e.slice()}function He(e){return new RegExp(e.source,e.flags)}function Ue(e){return new Map(Ge([...e.entries()]))}function We(e){return new Set(Ge([...e.values()]))}function Ge(e){return Oe(e)?Ve(e):ke(e)?He(e):je(e)?Ue(e):Ae(e)?We(e):he(e)?Be(e):_(e)?ze(e):e}function Ke(e){return me.clone+=1,Ge(e)}function qe(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Je(e,t){return{...e,...t}}function C(e,t,n={}){me.create+=1;let r=Je(t,n);return Pe(Ne().enumerableKind?Je(r,e):qe(r,e))}function Ye(e,t){me.discard+=1;let n={};for(let r of x(e)){if(t.includes(r))continue;let i=Object.getOwnPropertyDescriptor(e,r);i.value=Ke(i.value),Object.defineProperty(n,r,i)}return Pe(n)}function w(e,t,n){me.update+=1;let r=Ne(),i=Ke(e);for(let e of Object.keys(t))Object.defineProperty(i,e,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[e]});for(let e of Object.keys(n))Object.defineProperty(i,e,{configurable:!0,enumerable:!0,writable:!0,value:n[e]});return Pe(i)}function T(e,t){return _(e)&&b(e,`~kind`)&&v(e[`~kind`],t)}function Xe(e){return _(e)}function E(e,t,n){return C({"~kind":`Deferred`},{type:`deferred`,action:e,parameters:t,options:n},{})}function Ze(e){return T(e,`Deferred`)}function Qe(e){return w(e,{"~readonly":!0},{})}function $e(e,t){return w(Qe(e),{},t)}function et(e,t,n,r){return $e(Q(e,t,n),r)}function tt(e){return w(e,{"~optional":!0},{})}function nt(e,t){return w(tt(e),{},t)}function rt(e,t,n,r){return nt(Q(e,t,n),r)}function it(e,t){return C({"~kind":`Array`},{type:`array`,items:e},t)}function D(e){return T(e,`Array`)}function at(e){return Ye(e,[`~kind`,`type`,`items`])}function ot(e,t,n={}){return C({"~kind":`Constructor`},{type:`constructor`,parameters:e,instanceType:t},n)}function st(e){return T(e,`Constructor`)}function ct(e){return Ye(e,[`~kind`,`type`,`parameters`,`instanceType`])}function lt(e,t,n={}){return C({"~kind":`Function`},{type:`function`,parameters:e,returnType:t},n)}function ut(e){return T(e,`Function`)}function dt(e){return Ye(e,[`~kind`,`type`,`parameters`,`returnType`])}function ft(e,t){return C({"~kind":`Ref`},{$ref:e},t)}function pt(e){return T(e,`Ref`)}function mt(e,t){return C({"~kind":`Generic`},{type:`generic`,parameters:e,expression:t})}function ht(e){return T(e,`Generic`)}function gt(e){return C({"~kind":`Any`},{},e)}function O(e){return T(e,`Any`)}function k(e){return C({"~kind":`Never`},{not:{}},e)}function _t(e){return T(e,`Never`)}function vt(e,t={}){return nt(e,t)}function A(e){return vt(e)}function yt(e){return Xe(e)&&b(e,`~optional`)}function bt(e){return x(e).filter(t=>!yt(e[t]))}function xt(e){return x(e)}function St(e){return De(e)}function j(e,t={}){let n=bt(e);return C({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}function M(e){return T(e,`Object`)}function Ct(e){return Ye(e,[`~kind`,`type`,`properties`,`required`])}function wt(e){return C({"~kind":`Unknown`},{},e)}function N(e){return T(e,`Unknown`)}function Tt(e,t,n){return C({"~kind":`Cyclic`},{$defs:x(e).reduce((t,n)=>({...t,[n]:w(e[n],{},{$id:n})}),{}),$ref:t},n)}function Et(e){return T(e,`Cyclic`)}function Dt(e){return be(e)&&b(e,`~unsafe`)&&ve(e[`~unsafe`])}function P(e){return T(e,`Infer`)}function Ot(e,t,n,r={}){return C({"~kind":`Dependent`},{if:e,then:t,else:n},r)}function kt(e){return T(e,`Dependent`)}function At(e){return Ye(e,[`~kind`,`if`,`then`,`else`])}function jt(e){return T(e,`Enum`)}function Mt(e,t={}){return C({"~kind":`Intersect`},{allOf:e},t)}function F(e){return T(e,`Intersect`)}function Nt(e){return Ye(e,[`~kind`,`allOf`])}function Pt(){throw Error(`Unreachable`)}var Ft;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(Ft||={}),Array.from({length:256}).map((e,t)=>BigInt(t));const It=/* @__PURE__ */ new Float64Array(1);new DataView(It.buffer),new Uint8Array(It.buffer),new TextEncoder;function Lt(e){return Xe(e)&&b(e,`~immutable`)}function Rt(e,t={}){return $e(e,t)}function zt(e){return Xe(e)&&b(e,`~readonly`)}function Bt(e){return C({"~kind":`BigInt`},{type:`bigint`},e)}function Vt(e){return T(e,`BigInt`)}function Ht(e){return C({"~kind":`Boolean`},{type:`boolean`},e)}function Ut(e){return T(e,`Boolean`)}const Wt=`-?(?:0|[1-9][0-9]*)`;function Gt(e){return C({"~kind":`Integer`},{type:`integer`},e)}function Kt(e){return T(e,`Integer`)}var qt=class extends Error{constructor(e){super(`Invalid Literal value`),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function Jt(e){return ge(e)?`bigint`:_e(e)?`boolean`:ye(e)?`number`:xe(e)?`string`:(()=>{throw new qt(e)})()}function I(e,t){return C({"~kind":`Literal`},{type:Jt(e),const:e},t)}function Yt(e){return ge(e)||_e(e)||ye(e)||xe(e)}function Xt(e){return L(e)&&ye(e.const)}function Zt(e){return L(e)&&xe(e.const)}function L(e){return T(e,`Literal`)}function Qt(e){return C({"~kind":`Null`},{type:`null`},e)}function $t(e){return T(e,`Null`)}const en=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function R(e){return C({"~kind":`Number`},{type:`number`},e)}function tn(e){return T(e,`Number`)}function nn(e){return C({"~kind":`Symbol`},{type:`symbol`},e)}function rn(e){return T(e,`Symbol`)}function z(e){return C({"~kind":`String`},{type:`string`},e)}function an(e){return T(e,`String`)}function B(e,t={}){return C({"~kind":`Union`},{anyOf:e},t)}function V(e){return T(e,`Union`)}function on(e){return Ye(e,[`~kind`,`anyOf`])}function sn(e){let t=ji(e);return v(t.length,2)?t[0]:[]}function cn(e){return!0}function ln(e){return y(e,(e,t)=>dn(e)?ln(t):!1,()=>!0)}function un(e){return!v(e.length,0)&&ln(e)}function dn(e){return V(e)?un(e.anyOf):L(e)?cn(e.const):!1}function fn(e){return un(e)}function pn(e){return C({"~kind":`TemplateLiteral`},{type:`string`,pattern:e},{})}function mn(e,t,n=[]){return y(e,(e,r)=>mn(r,t,[...n,`${e}${t}`]),()=>n)}function hn(e,t){return v(e.length,0)?[`${t}`]:mn(e,t)}function gn(e,t,n=[]){return y(t,(t,r)=>gn(e,r,[...n,..._n(e,t)]),()=>n)}function _n(e,t){return V(t)?gn(e,t.anyOf):L(t)?hn(e,t.const):Pt()}function vn(e,t){return y(t,(t,n)=>vn(_n(e,t),n),()=>e)}function yn(e){return e.map(e=>I(e))}function bn(e){return B(yn(vn([],e)))}function xn(e){return v(e.length,0)?Pt():v(e.length,1)&&L(e[0])?e[0]:bn(e)}function Sn(e){let t=sn(e);return v(t.length,0)?z():fn(t)?xn(t):pn(e)}function Cn(e){let t=Sn(e);return Qi(t)?z():t}function wn(e,t){return C({"~kind":`Record`},{type:`object`,patternProperties:{[e]:t}})}function Tn(e){return wn(kr,e)}function En(e){return j({true:e,false:e})}function Dn(e,t={}){let[n,r,i]=[e,e.length,!1];return C({"~kind":`Tuple`},{type:`array`,additionalItems:i,items:n,minItems:r},t)}function H(e){return T(e,`Tuple`)}function On(e){return Ye(e,[`~kind`,`type`,`items`,`minItems`,`additionalItems`])}function kn(e){return Ye(e,[`~readonly`])}function An(e,t){return w(kn(e),{},t)}function jn(e,t,n,r){return An(Q(e,t,n),r)}function Mn(e,t={}){return An(e,t)}function Nn(e){return Ye(e,[`~optional`])}function Pn(e,t){return w(Nn(e),{},t)}function Fn(e,t,n,r){return Pn(Q(e,t,n),r)}function In(e,t={}){return Pn(e,t)}function Ln(e){return e.reduceRight((e,t,n)=>({[n]:t,...e}),{})}function Rn(e){return j(Ln(e.items))}function zn(e){return M(e)||H(e)}function Bn(e,t){return zt(e)?!!zt(t):!1}function Vn(e,t){return yt(e)?!!yt(t):!1}function Hn(e,t){let n=Bn(e,t),r=Vn(e,t),i=Mn(In(U([e,t])));return n&&r?Rt(vt(i)):n&&!r?Rt(i):!n&&r?vt(i):i}function Un(e,t,n){return n in e?n in t?Hn(e[n],t[n]):e[n]:n in t?t[n]:k()}function Wn(e,t){return[.../* @__PURE__ */ new Set([...x(e),...x(t)])].reduce((n,r)=>({...n,[r]:Un(e,t,r)}),{})}function Gn(e){return M(e)?e.properties:H(e)?Ln(e.items):{}}function Kn(e,t){return j(Wn(Gn(e),Gn(t)))}function qn(e,t){let n=Zo(e,t);return v(n,2)?e:v(n,3)||v(n,0)?t:k()}function Jn(e,t){let n=zn(e),r=zn(t);return n&&r?Kn(e,t):n&&!r?e:!n&&r?t:qn(e,t)}function Yn(e,t){return _t(e)||O(e)?e:N(e)||_t(t)||O(t)?t:N(t)?e:Jn(e,t)}function Xn(e,t){return V(e)||V(t)}function Zn(e,t){let n=cr(e),r=cr(t);return Xn(n,r)?U([n,r]):Yn(n,r)}function Qn(e,t,n=[]){return y(t,(t,r)=>Qn(e,r,[...n,Zn(t,e)]),()=>v(n.length,0)?[e]:n)}function $n(e,t,n=[]){return y(e,(e,r)=>$n(r,t,[...n,...er([e],t)]),()=>n)}function er(e,t=[]){return y(e,(e,n)=>V(e)?er(n,$n(e.anyOf,t)):er(n,Qn(e,t)),()=>t)}function tr(e,t){return q(Xo({},e,t))?[]:[e]}function nr(e,t,n=[]){return y(e,(e,r)=>nr(r,t,[...n,...tr(e,t)]),()=>n)}function rr(e,t){let n=cr(e);return sr(nr(V(n)?n.anyOf:[n],t))}function ir(e,t,n){return sr([U([e,t]),rr(n,e)])}function ar(e,t=[]){return y(e,(e,n)=>ar(n,[...t,I(e)]),()=>sr(t))}function U(e){return sr(ts(er(e)))}function or(e){return cr(Cn(e))}function sr(e){return lr(ts(e))}function cr(e){return kt(e)?ir(e.if,e.then,e.else):jt(e)?ar(e.enum):F(e)?U(e.allOf):Qi(e)?or(e.pattern):V(e)?sr(e.anyOf):e}function lr(e){return v(e.length,1)?e[0]:v(e.length,0)?k():B(e)}function ur(e,t){return wr(ar(e),t)}function dr(e,t){return wn(Dr,t)}function fr(e,t){return wr(U(e),t)}function pr(e,t){return xe(e)||ye(e)?j({[e]:t}):v(e,!1)?j({false:t}):v(e,!0)?j({true:t}):j({})}function mr(e,t){return wn(Or,t)}function hr(e,t){return b(e,`pattern`)&&(xe(e.pattern)||e.pattern instanceof RegExp)?wn(e.pattern.toString(),t):wn(kr,t)}function gr(e,t){return fn(sn(e))?wr(or(e),t):wn(e,t)}function _r(e){return V(e)?vr(e.anyOf):[e]}function vr(e,t=[]){return y(e,(e,n)=>vr(n,[...t,..._r(e)]),()=>t)}function yr(e){return e.some(e=>an(e)||tn(e)||Kt(e))}function br(e,t){return v(yr(e),!0)?wn(kr,t):void 0}function xr(e,t){return e.reduce((e,n)=>L(n)&&(xe(n.const)||ye(n.const))?{...e,[n.const]:t}:e,{})}function Sr(e,t){return j(xr(e,t))}function Cr(e,t){let n=vr(e),r=br(n,t);return Xe(r)?r:Sr(n,t)}function wr(e,t){return O(e)?Tn(t):Ut(e)?En(t):jt(e)?ur(e.enum,t):Kt(e)?dr(e,t):F(e)?fr(e.allOf,t):L(e)?pr(e.const,t):tn(e)?mr(e,t):V(e)?Cr(e.anyOf,t):an(e)?hr(e,t):Qi(e)?gr(e.pattern,t):j({})}function Tr(e,t,n){return Z([e])?w(wr(e,t),{},n):Ar(e,t,n)}function Er(e,t,n,r,i){return Tr(Q(e,t,n),Q(e,t,r),i)}const Dr=`^${Wt}$`,Or=`^${en}$`,kr=`^.*$`;function Ar(e,t,n={}){return E(`Record`,[e,t],n)}function jr(e,t,n={}){return Tr(e,t,n)}function Mr(e,t){return wn(e,t)}function Nr(e){return v(e,kr)?z():v(e,Dr)?Gt():v(e,Or)?R():Sn(e)}function Pr(e){return x(e.patternProperties)[0]}function Fr(e){return Nr(Pr(e))}function Ir(e){return e.patternProperties[Pr(e)]}function Lr(e){return T(e,`Record`)}function Rr(e){return C({"~kind":`Rest`},{type:`rest`,items:e},{})}function zr(e){return T(e,`Rest`)}function Br(e){return T(e,`This`)}function Vr(e){return C({"~kind":`Undefined`},{type:`undefined`},e)}function Hr(e){return T(e,`Undefined`)}function Ur(e){return T(e,`Void`)}function Wr(e){return Bt()}function Gr(e){return z()}function Kr(e){return R()}function qr(e){return Gt()}function Jr(e){return k()}function Yr(e){return I(e)}function Xr(e){return e}function Zr(e){return B(e[1])}function Qr(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function $r(e){return[e[0],...e[1]]}function ei(e){return e}function ti(e){return e[1]}function ni(e){return v(e.length,2)}function ri(e,t,n){return ni(e)?t(e[0],e[1]):n()}function ii(e,t){return v(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function ai(e,t){for(let n=0;n<e.length;n++){let r=ii(e[n],t);if(ni(r))return r}return[]}function oi(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}const si=[...oi(97,122),...oi(65,90)],ci=[`0`,...oi(49,57)];function li(e){let t=e.indexOf(`*/`);return v(t,-1)?``:e.slice(t+2)}function ui(e){let t=e.indexOf(`
2
- `);return v(t,-1)?``:e.slice(t)}function di(e){return e.replace(/^[ \t\r\f\v]+/,``)}function fi(e){let t=di(e);return t.startsWith(`/*`)?fi(li(t.slice(2))):t.startsWith(`//`)?fi(ui(t.slice(2))):t}function pi(e){let t=e.trimStart();return t.startsWith(`/*`)?pi(li(t.slice(2))):t.startsWith(`//`)?pi(ui(t.slice(2))):t}[...ci];function mi(e,t){return ai([e],t)}function hi(e,t){return v(e,``)?[``,t]:e.startsWith(`
3
- `)?mi(e,fi(t)):e.startsWith(` `)?mi(e,t):mi(e,pi(t))}[...si,...ci],[...ci];function gi(e){return v(e,``)?[]:[e.slice(0,1),e.slice(1)]}function _i(e,t){return y(e,(e,n)=>t.startsWith(e)?!0:_i(n,t),()=>!1)}function vi(e,t,n=``){return ri(gi(t),(r,i)=>_i(e,t)?[n,t]:vi(e,i,`${n}${r}`),()=>[])}function yi(e,t){return ri(vi(e,t),(e,t)=>v(e,``)?[]:[e,t],()=>[])}const W=(e,t,n=()=>[])=>e.length===2?t(e):n(),bi=e=>W(hi(`-?(?:0|[1-9][0-9]*)n`,e),([e,t])=>[Wr(e),t]),xi=e=>W(hi(`.*`,e),([e,t])=>[Gr(e),t]),Si=e=>W(hi(`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,e),([e,t])=>[Kr(e),t]),Ci=e=>W(hi(`-?(?:0|[1-9][0-9]*)`,e),([e,t])=>[qr(e),t]),wi=e=>W(hi(`(?!)`,e),([e,t])=>[Jr(e),t]),Ti=e=>W(yi([`-?(?:0|[1-9][0-9]*)n`,`.*`,`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`,`-?(?:0|[1-9][0-9]*)`,`(?!)`,`(`,`)`,`$`,`|`],e),([e,t])=>[Yr(e),t]),Ei=e=>W(W(bi(e),([e,t])=>[e,t],()=>W(xi(e),([e,t])=>[e,t],()=>W(Si(e),([e,t])=>[e,t],()=>W(Ci(e),([e,t])=>[e,t],()=>W(wi(e),([e,t])=>[e,t],()=>W(Di(e),([e,t])=>[e,t],()=>W(Ti(e),([e,t])=>[e,t],()=>[]))))))),([e,t])=>[Xr(e),t]),Di=e=>W(W(hi(`(`,e),([e,t])=>W(Ai(t),([t,n])=>W(hi(`)`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[Zr(e),t]),Oi=e=>W(W(W(ki(e),([e,t])=>W(hi(`|`,t),([t,n])=>W(Oi(n),([n,r])=>[[e,t,n],r]))),([e,t])=>[e,t],()=>W(W(ki(e),([e,t])=>[[e],t]),([e,t])=>[e,t],()=>W([[],e],([e,t])=>[e,t],()=>[]))),([e,t])=>[Qr(e),t]),ki=e=>W(W(Ei(e),([e,t])=>W(Ai(t),([t,n])=>[[e,t],n])),([e,t])=>[$r(e),t]),Ai=e=>W(W(Oi(e),([e,t])=>[e,t],()=>W(ki(e),([e,t])=>[e,t],()=>[])),([e,t])=>[ei(e),t]),ji=e=>W(W(hi(`^`,e),([e,t])=>W(Ai(t),([t,n])=>W(hi(`$`,n),([n,r])=>[[e,t,n],r]))),([e,t])=>[ti(e),t]);function Mi(e){return e.join(`|`)}function Ni(e){return e.slice(1,e.length-1)}function Pi(e,t,n){return Gi(t,`${n}${e}`)}function Fi(e,t){return Gi(e,`${t}-?(?:0|[1-9][0-9]*)n`)}function Ii(e,t){return Gi(e,`${t}${Wt}`)}function Li(e,t){return Gi(e,`${t}${en}`)}function Ri(e,t){return Wi(B([I(`false`),I(`true`)]),e,t)}function zi(e,t){return Gi(e,`${t}.*`)}function Bi(e,t,n){return Gi(t,`${n}${Ni(e)}`)}function Vi(e,t,n){return Wi(Ji(e,{}),t,n)}function Hi(e,t,n){return Wi(ar(e),t,n)}function Ui(e,t,n,r=[]){return y(e,(e,i)=>Ui(i,t,n,[...r,Wi(e,[],``)]),()=>Gi(t,`${n}(${Mi(r)})`))}function Wi(e,t,n){return jt(e)?Hi(e.enum,t,n):Kt(e)?Ii(t,n):L(e)?Pi(e.const,t,n):Vt(e)?Fi(t,n):Ut(e)?Ri(t,n):tn(e)?Li(t,n):an(e)?zi(t,n):Qi(e)?Bi(e.pattern,t,n):Zi(e)?Vi(e.parameters[0],t,n):V(e)?Ui(e.anyOf,t,n):`(?!)`}function Gi(e,t){return y(e,(e,n)=>Wi(e,n,t),()=>t)}function Ki(e){return`^${Gi(e,``)}$`}function qi(e){return pn(Ki(e))}function Ji(e,t){return Z(e)?w(qi(e),{},t):Xi(e,t)}function Yi(e,t,n,r){return Ji(id(e,t,n),r)}function Xi(e,t={}){return E(`TemplateLiteral`,[e],t)}function Zi(e){return Xe(e)&&b(e,`action`)&&v(e.action,`TemplateLiteral`)}function Qi(e){return T(e,`TemplateLiteral`)}function $i(e){return C({"~kind":`ExtendsUnion`},{inferred:e})}function ea(e){return _(e)&&b(e,`~kind`)&&b(e,`inferred`)&&v(e[`~kind`],`ExtendsUnion`)&&_(e.inferred)}function G(e){return C({"~kind":`ExtendsTrue`},{inferred:e})}function ta(e){return _(e)&&b(e,`~kind`)&&b(e,`inferred`)&&v(e[`~kind`],`ExtendsTrue`)&&_(e.inferred)}function K(){return C({"~kind":`ExtendsFalse`},{})}function na(e){return _(e)&&b(e,`~kind`)&&v(e[`~kind`],`ExtendsFalse`)}function q(e){return ea(e)||ta(e)}function J(e,t,n){return q(e)?t(e.inferred):n()}function ra(e,t,n,r){return J(X(e,n,r),r=>G(S(S(e,r),{[t]:n})),()=>K())}function ia(e,t){return G(e)}function aa(e,t,n,r,i){return J(X(e,t,n),e=>J(X(e,t,r),e=>G(e),()=>K()),()=>J(X(e,t,i),e=>G(e),()=>K()))}function oa(e,t,n){return X(e,t,ar(n))}function sa(e,t,n){return y(n,(n,r)=>J(X(e,t,n),e=>sa(e,t,r),()=>K()),()=>G(e))}function ca(e,t,n){return X(e,t,or(n))}function la(e,t,n){return y(n,(n,r)=>J(X(e,t,n),e=>G(e),()=>la(e,t,r)),()=>K())}function Y(e,t,n){return O(n)?ia(e,t):kt(n)?aa(e,t,n.if,n.then,n.else):jt(n)?oa(e,t,n.enum):P(n)?ra(e,n.name,t,n.extends):F(n)?sa(e,t,n.allOf):Qi(n)?ca(e,t,n.pattern):V(n)?la(e,t,n.anyOf):N(n)?G(e):K()}function ua(e,t,n){return P(n)?Y(e,t,n):O(n)||N(n)?G(e):$i(e)}function da(e,t){let n=Lt(e),r=Lt(t);return n&&r||!n&&r?!0:!(n&&!r)}function fa(e,t,n,r){return D(r)?da(t,r)?X(e,n,r.items):K():Y(e,t,r)}function pa(e,t,n){return Vt(n)?G(e):Y(e,t,n)}function ma(e,t,n){return Ut(n)?G(e):Y(e,t,n)}function ha(e,t,n,r,i){let a=P(r)?t:r,o=P(r)?r:t,s=yt(t),c=yt(r);return!s&&c?K():J(X(e,a,o),e=>va(e,n,i),()=>K())}function ga(e,t,n,r){return y(r,(r,i)=>ha(e,t,n,r,i),()=>yt(t)?G(e):K())}function _a(e,t,n){return y(t,(t,r)=>ga(e,t,r,n),()=>G(e))}function va(e,t,n){return _a(e,t,n)}function ya(e,t,n){return Ur(n)?G(e):X(e,t,n)}function ba(e,t,n,r){return O(r)||N(r)?G(e):st(r)?J(va(e,t,r.parameters),e=>ya(e,n,r.instanceType),()=>K()):K()}function xa(e,t,n,r,i){return J(X(e,t,i),()=>X(e,n,i),()=>X(e,r,i))}function Sa(e,t,n){return X(e,ar(t),n)}function Ca(e,t,n,r){return O(r)||N(r)?G(e):ut(r)?J(va(e,t,r.parameters),e=>ya(e,n,r.returnType),()=>K()):K()}function wa(e,t,n){return Kt(n)||tn(n)?G(e):Y(e,t,n)}function Ta(e,t,n){return X(e,U(t),n)}function Ea(e,t,n){return t===n?G(e):K()}function Da(e,t,n){return L(n)?Ea(e,t,n.const):Vt(n)?G(e):Y(e,I(t),n)}function Oa(e,t,n){return L(n)?Ea(e,t,n.const):Ut(n)?G(e):Y(e,I(t),n)}function ka(e,t,n){return L(n)?Ea(e,t,n.const):tn(n)?G(e):Y(e,I(t),n)}function Aa(e,t,n){return L(n)?Ea(e,t,n.const):an(n)?G(e):Y(e,I(t),n)}function ja(e,t,n){return ge(t.const)?Da(e,t.const,n):_e(t.const)?Oa(e,t.const,n):ye(t.const)?ka(e,t.const,n):xe(t.const)?Aa(e,t.const,n):Pt()}function Ma(e,t,n){return P(n)?Y(e,t,n):G(e)}function Na(e,t,n){return $t(n)?G(e):Y(e,t,n)}function Pa(e,t,n){return tn(n)?G(e):Y(e,t,n)}function Fa(e,t,n){return yt(t)?yt(n)?G(e):K():G(e)}function Ia(e,t,n){return P(n)&&_t(n.extends)?K():J(X(e,t,n),e=>Fa(e,t,n),()=>K())}function La(e,t){return e.reduce((e,n)=>n in t&&q(t[n])?{...e,...t[n].inferred}:Pt(),{})}function Ra(e,t,n){let r={};for(let i of x(n))r[i]=i in t?Ia({},t[i],n[i]):yt(n[i])?P(n[i])?G(S(e,{[n[i].name]:n[i].extends})):G(e):K();let i=De(r).every(e=>q(e)),a=i?La(x(r),r):{};return i?G(a):K()}function za(e,t,n){let r=Ra(e,t,n);return q(r)?G(S(e,r.inferred)):K()}function Ba(e,t,n){return za(e,t,n)}function Va(e,t){return x(t).reduce((n,r)=>({...n,[r]:b(e,r)?V(n[r])?B([...n[r].anyOf,t[r]]):B([e[r],t[r]]):t[r]}),e)}function Ha(e,t,n,r){return y(t,(t,i)=>J(X({},e[t],n),t=>Ha(e,i,n,Va(r,t)),()=>K()),()=>G(r))}function Ua(e,t,n,r){return Ha(t,x(t),r,e)}function Wa(e,t,n){return Lr(n)?Ua(e,t,Pr(n),Ir(n)):M(n)?Ba(e,t,n.properties):Y(e,j(t),n)}function Ga(e,t){return v(x(t).length,0)?G(e):K()}function Ka(e,t,n,r,i){return X(e,n,i)}function qa(e,t,n,r){return Lr(r)?Ka(e,Nr(t),n,Nr(Pr(r)),Ir(r)):M(r)?Ga(e,r.properties):O(r)||N(r)?G(e):K()}function Ja(e,t,n){return an(n)?G(e):Y(e,t,n)}function Ya(e,t,n){return rn(n)?G(e):Y(e,t,n)}function Xa(e,t,n){return X(e,or(t),n)}function Za(e,t){return C({"~kind":`Inferrable`},{name:e,type:t},{})}function Qa(e){return _(e)&&b(e,`~kind`)&&b(e,`name`)&&b(e,`type`)&&v(e[`~kind`],`Inferrable`)&&xe(e.name)&&_(e.type)}function $a(e){return zr(e)?P(e.items)?D(e.items.extends)?Za(e.items.name,e.items.extends.items):N(e.items.extends)?Za(e.items.name,e.items.extends):void 0:Pt():void 0}function eo(e){return P(e)?Za(e.name,e.extends):void 0}function to(e,t,n=[]){return y(e,(e,r)=>J(X({},e,t),()=>to(r,t,[...n,e]),()=>void 0),()=>n)}function no(e,t,n,r){let i=to(n,r);return he(i)?G(S(e,{[t]:Dn(i)})):K()}function ro(e,t,n,r){let i=to(n,r);return he(i)?G(S(e,{[t]:B(i)})):K()}function io(e){return[...e].reverse()}function ao(e,t){return t?io(e):e}function oo(e){let t=e.length>0?e[0]:void 0;return Xe(Xe(t)?$a(t):void 0)}function so(e,t,n,r,i,a){return J(X(e,n,i),e=>uo(e,t,r,a),()=>K())}function co(e,t,n,r,i){let a=$a(r);return Qa(a)?no(e,a.name,ao(n,t),a.type):y(n,(n,a)=>so(e,t,n,a,r,i),()=>K())}function lo(e,t,n,r){return y(r,(r,i)=>co(e,t,n,r,i),()=>v(n.length,0)?G(e):K())}function uo(e,t,n,r){return lo(e,t,n,r)}function fo(e,t,n){let r=rd(e,td([],[]),n),i=oo(r);return uo(e,i,ao(t,i),ao(r,i))}function po(e,t,n){let r=eo(n);return Qa(r)?ro(e,r.name,t,r.type):y(t,(t,r)=>J(X(e,t,n),e=>po(e,r,n),()=>K()),()=>G(e))}function mo(e,t,n){let r=rd(e,td([],[]),t);return H(n)?fo(e,r,n.items):D(n)?po(e,r,n.items):Y(e,Dn(r),n)}function ho(e,t,n){return Ur(n)||Hr(n)?G(e):Y(e,t,n)}function go(e,t,n){return y(n,(n,r)=>J(X(e,t,n),e=>G(e),()=>go(e,t,r)),()=>K())}function _o(e,t,n){return y(t,(t,r)=>J(go(e,t,n),e=>_o(e,r,n),()=>K()),()=>G(e))}function vo(e,t,n){let r=eo(n);return Qa(r)?ro(e,r.name,t,r.type):V(n)?_o(e,t,n.anyOf):_o(e,t,[n])}function yo(e,t,n){return P(n)?Y(e,t,n):O(n)||N(n)?G(e):K()}function bo(e,t,n){return Ur(n)?G(e):Y(e,t,n)}function X(e,t,n){return O(t)?ua(e,t,n):D(t)?fa(e,t,t.items,n):Vt(t)?pa(e,t,n):Ut(t)?ma(e,t,n):st(t)?ba(e,t.parameters,t.instanceType,n):kt(t)?xa(e,t.if,t.then,t.else,n):jt(t)?Sa(e,t.enum,n):ut(t)?Ca(e,t.parameters,t.returnType,n):Kt(t)?wa(e,t,n):F(t)?Ta(e,t.allOf,n):L(t)?ja(e,t,n):_t(t)?Ma(e,t,n):$t(t)?Na(e,t,n):tn(t)?Pa(e,t,n):M(t)?Wa(e,t.properties,n):Lr(t)?qa(e,Pr(t),Ir(t),n):an(t)?Ja(e,t,n):rn(t)?Ya(e,t,n):Qi(t)?Xa(e,t.pattern,n):H(t)?mo(e,t.items,n):Hr(t)?ho(e,t,n):V(t)?vo(e,t.anyOf,n):N(t)?yo(e,t,n):Ur(t)?bo(e,t,n):K()}function xo(e,t){return U([...e,j(t)])}function So(e,t,n){return Z(e)?w(xo(e,t),{},n):wo(e,t,n)}function Co(e,t,n,r,i){return So(id(e,t,n),nd(e,t,r),i)}function wo(e,t,n={}){return E(`Interface`,[e,t],n)}function To(e){return Xe(e)&&b(e,`action`)&&v(e.action,`Interface`)}function Eo(e,t,n){return e.includes(n)?!0:ko([...e,n],t,t[n])}function Do(e,t,n){return Oo(e,t,St(n))}function Oo(e,t,n){return y(n,(n,r)=>ko(e,t,n)?!0:Oo(e,t,r),()=>!1)}function ko(e,t,n){return pt(n)?Eo(e,t,n.$ref):D(n)?ko(e,t,n.items):st(n)?Oo(e,t,[...n.parameters,n.instanceType]):ut(n)?Oo(e,t,[...n.parameters,n.returnType]):To(n)?Do(e,t,n.parameters[1]):F(n)?Oo(e,t,n.allOf):M(n)?Do(e,t,n.properties):V(n)?Oo(e,t,n.anyOf):H(n)?Oo(e,t,n.items):Lr(n)?ko(e,t,Ir(n)):!1}function Ao(e,t,n){return ko(e,t,n)}function jo(e,t){return t.reduce((t,n)=>Ao([n],e,e[n])?[...t,n]:t,[])}function Mo(e){return jo(e,xt(e))}function No(e,t,n){return n.includes(t)?n:t in e?Io(e,e[t],[...n,t]):Pt()}function Po(e,t,n){return Fo(e,St(t),n)}function Fo(e,t,n){return t.reduce((t,n)=>Io(e,n,t),n)}function Io(e,t,n){return pt(t)?No(e,t.$ref,n):D(t)?Io(e,t.items,n):st(t)?Fo(e,[...t.parameters,t.instanceType],n):ut(t)?Fo(e,[...t.parameters,t.returnType],n):To(t)?Po(e,t.parameters[1],n):F(t)?Fo(e,t.allOf,n):M(t)?Po(e,t.properties,n):V(t)?Fo(e,t.anyOf,n):H(t)?Fo(e,t.items,n):Lr(t)?Io(e,Ir(t),n):n}function Lo(e,t,n){return Io(e,n,[t])}function Ro(e){return gt()}function zo(e){return x(e).reduce((t,n)=>({...t,[n]:Vo(e[n])}),{})}function Bo(e){return e.reduce((e,t)=>[...e,Vo(t)],[])}function Vo(e){return pt(e)?Ro(e.$ref):D(e)?it(Vo(e.items),at(e)):st(e)?ot(Bo(e.parameters),Vo(e.instanceType)):ut(e)?lt(Bo(e.parameters),Vo(e.returnType)):F(e)?Mt(Bo(e.allOf)):M(e)?j(zo(e.properties)):Lr(e)?jr(Fr(e),Vo(Ir(e))):V(e)?B(Bo(e.anyOf)):H(e)?Dn(Bo(e.items)):e}function Ho(e,t){return t in e?Vo(e[t]):wt()}function Uo(e){return Ho(e.$defs,e.$ref)}function Wo(e,t,n){let r=id(e,td([],[]),t),i=nd({},td([],[]),n);return U([...r,j(i)])}function Go(e,t){return x(e).filter(e=>t.includes(e)).reduce((t,n)=>{let r=e[n],i=To(r)?Wo(e,r.parameters[0],r.parameters[1]):r;return{...t,[n]:i}},{})}function Ko(e,t,n){return Tt(Go(e,Lo(e,t,n)),t)}function qo(e,t){return t in e?pt(e[t])?qo(e,e[t].$ref):e[t]:k()}function Jo(e,t){return qo(e,t)}function Yo(e){return Et(e)?Uo(e):Dt(e)?wt():e}function Xo(e,t,n){return X(e,Yo(t),Yo(n))}function Zo(e,t){let n=[Xo({},e,t),Xo({},t,e)];return q(n[0])&&q(n[1])?0:q(n[0])&&na(n[1])?2:na(n[0])&&q(n[1])?3:1}function Qo(e,t,n=[],r=t){return y(t,(t,i)=>{let a=Zo(e,t);return v(a,2)||v(a,0)?r:v(a,1)?Qo(e,i,[...n,t],r):Qo(e,i,n,r)},()=>[...n,e])}function $o(e,t,n){let r=cr(e);return O(r)||N(r)?[r]:_t(r)?es(t,n):M(r)?es(t,[...n,r]):es(t,Qo(r,n))}function es(e,t=[]){return y(e,(e,n)=>$o(e,n,t),()=>t)}function ts(e){return vr(es(e))}function ns(e,t){return w(cr(e),{},t)}function rs(e,t,n,r){return ns(Q(e,t,n),r)}function is(e,t=[]){return Ze(e)&&v(e.action,`Conditional`)?pt(e.parameters[0])?is(e.parameters[2],is(e.parameters[3],[...t,e.parameters[0].$ref])):is(e.parameters[2],is(e.parameters[3],t)):Ze(e)&&v(e.action,`Mapped`)&&Ze(e.parameters[1])&&v(e.parameters[1].action,`KeyOf`)&&pt(e.parameters[1].parameters[0])?[...t,e.parameters[1].parameters[0].$ref]:t}function as(e,t){return e.reduce((e,n)=>[...e,t.includes(n.name)],[])}function os(e,t,n=[]){return y(e,(e,r)=>y(t,(t,i)=>os(r,i,[...n,[t,e]]),()=>n),()=>n)}function ss(e){return Qi(e)?or(e.pattern):jt(e)?ar(e.enum):e}function cs(e){let t=ss(e);return V(t)?[...t.anyOf]:[t]}function ls(e,t){return e.reduce((e,n)=>[...e,[...n,t]],[])}function us(e,t){return t.reduce((t,n)=>[...t,...ls(e,n)],[])}function ds(e){return e.reduce((e,t)=>v(t[0],!0)?us(e,cs(t[1])):us(e,[t[1]]),[[]])}function fs(e,t,n){let r=os(t,as(e,is(n)));return Ze(n)&&v(n.action,`Conditional`)||Ze(n)&&v(n.action,`Mapped`)?ds(r):[t]}function ps(){return[`(not-resolvable)`,k()]}function ms(){return[`(not-generic)`,k()]}function hs(e,t,n){return[e,mt(t,n)]}function gs(e,t,n){return t in e?_s(e,t,e[t],n):ps()}function _s(e,t,n,r){return ht(n)?hs(t,n.parameters,n.expression):pt(n)?gs(e,n.$ref,r):ms()}function vs(e,t,n){return _s(e,`(anonymous)`,t,n)}function ys(e,t,n){if(P(t)||Is(t)||q(Xo({},t,n)))return;let r={parameter:e,expect:n,actual:t};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:r})}function bs(e,t,n,r,i){let a=Q(e,t,i);return ys(n,a,r),S(e,{[n]:a})}function xs(e,t,n,r,i){let a=Q(e,t,n.extends),o=Q(e,t,n.equals);return y(i,(i,o)=>Ss(bs(e,t,n.name,a,i),t,r,o),()=>Ss(bs(e,t,n.name,a,o),t,r,[]))}function Ss(e,t,n,r){return y(n,(n,i)=>xs(e,t,n,i,r),()=>e)}function Cs(e,t,n,r){return Ss(e,t,n,r)}let ws=0,Ts=0;function Es(){if(!Ce(Ts,Ne().maxInstantiationCount))throw Error(`Type instantiation is excessively deep and possibly infinite`)}function Ds(){Es(),Ts++,ws++}function Os(){ws--,v(ws,0)&&(Ts=0)}function ks(e){return Se(e.callstack.length,0)?e.callstack[e.callstack.length-1]:``}function As(e,t){return v(ks(e),t)}function js(e,t,n,r,i,a){Ds();try{let o=Cs(e,t,r,a),s=Q(o,td([...t.callstack,n.$ref],t.visited),i);return Q(o,td([],[]),s)}finally{Os()}}function Ms(e,t,n,r,i,a){return a.reduce((a,o)=>{let s=js(e,t,n,r,i,o);return[...a,s]},[])}function Ns(e,t,n,r,i,a){let o=Ms(e,t,n,r,i,fs(r,a,i));return v(o.length,1)?o[0]:sr(o)}function Ps(e,t,n,r){let i=id(e,t,r),a=vs(e,n,r),o=a[0],s=a[1];return ht(s)?As(t,o)?Fs(ft(o),i):Ns(e,t,ft(o),s.parameters,s.expression,i):Fs(n,i)}function Fs(e,t){return C({"~kind":`Call`},{type:`call`,target:e,arguments:t},{})}function Is(e){return T(e,`Call`)}function Ls(e){return Ye(e,[`~immutable`])}function Rs(e,t){return w(Ls(e),{},t)}function zs(e,t,n,r){return Rs(Q(e,t,n),r)}function Bs(e,t){return e(t)}function Vs(e,t){return xe(t)?I(Bs(e,t)):I(t)}function Hs(e,t){return Ws(e,or(t))}function Us(e,t){return B(t.map(t=>Ws(e,t)))}function Ws(e,t){return L(t)?Vs(e,t.const):Qi(t)?Hs(e,t.pattern):V(t)?Us(e,t.anyOf):t}function Gs(e,t={}){return E(`Capitalize`,[e],t)}function Ks(e,t={}){return E(`Lowercase`,[e],t)}function qs(e,t={}){return E(`Uncapitalize`,[e],t)}function Js(e,t={}){return E(`Uppercase`,[e],t)}const Ys=e=>e[0].toUpperCase()+e.slice(1),Xs=e=>e.toLowerCase(),Zs=e=>e[0].toLowerCase()+e.slice(1),Qs=e=>e.toUpperCase();function $s(e,t){return Z([e])?w(Ws(Ys,e),{},t):Gs(e,t)}function ec(e,t){return Z([e])?w(Ws(Xs,e),{},t):Ks(e,t)}function tc(e,t){return Z([e])?w(Ws(Zs,e),{},t):qs(e,t)}function nc(e,t){return Z([e])?w(Ws(Qs,e),{},t):Js(e,t)}function rc(e,t,n,r){return $s(Q(e,t,n),r)}function ic(e,t,n,r){return ec(Q(e,t,n),r)}function ac(e,t,n,r){return tc(Q(e,t,n),r)}function oc(e,t,n,r){return nc(Q(e,t,n),r)}function sc(e,t,n,r,i={}){return E(`Conditional`,[e,t,n,r],i)}function cc(e,t,n,r,i,a){let o=Xo(e,n,r);return ea(o)?B([Q(o.inferred,t,i),Q(e,t,a)]):ta(o)?Q(o.inferred,t,i):Q(e,t,a)}function lc(e,t,n,r,i,a,o){return Z([n,r])?w(cc(e,t,n,r,i,a),{},o):sc(n,r,i,a,o)}function uc(e,t,n,r,i,a,o){return lc(e,t,Q(e,t,n),Q(e,t,r),i,a,o)}function dc(e,t={}){return E(`ConstructorParameters`,[e],t)}function fc(e){let t=st(e)?e.parameters:[];return Dn(rd({},td([],[]),t))}function pc(e,t){return Z([e])?w(fc(e),{},t):dc(e,t)}function mc(e,t,n,r){return pc(Q(e,t,n),r)}function hc(e,t,n={}){return E(`Exclude`,[e,t],n)}function gc(e,t,n){return Z([e,t])?w(rr(e,t),{},n):hc(e,t,n)}function _c(e,t,n,r,i){return gc(Q(e,t,n),Q(e,t,r),i)}function vc(e,t,n={}){return E(`Extract`,[e,t],n)}function yc(e,t){return q(Xo({},e,t))?[e]:[]}function bc(e,t,n=[]){return y(e,(e,r)=>bc(r,t,[...n,...yc(e,t)]),()=>n)}function xc(e,t){let n=cr(e);return sr(bc(V(n)?n.anyOf:[n],t))}function Sc(e,t,n){return Z([e,t])?w(xc(e,t),{},n):vc(e,t,n)}function Cc(e,t,n,r,i){return Sc(Q(e,t,n),Q(e,t,r),i)}function wc(e,t,n={}){return E(`Index`,[e,t],n)}function Tc(e,t){return Pc(Jo(e,t))}function Ec(e,t,n){return Pc(ir(e,t,n))}function Dc(e,t){let n=x(e).filter(e=>!b(t,e)),r=x(t).filter(t=>!b(e,t)),i=x(e).filter(e=>b(t,e)),a=n.reduce((t,n)=>({...t,[n]:e[n]}),{}),o=r.reduce((e,n)=>({...e,[n]:t[n]}),{}),s=i.reduce((n,r)=>({...n,[r]:U([e[r],t[r]])}),{});return S(S(a,o),s)}function Oc(e){return e.reduce((e,t)=>Dc(e,Pc(t)),{})}function kc(e){return e}function Ac(e){return Pc(Rn(Dn(e)))}function jc(e,t){return x(e).filter(e=>e in t).reduce((n,r)=>({...n,[r]:sr([e[r],t[r]])}),{})}function Mc(e,t){return y(e,(e,n)=>Mc(n,jc(t,Pc(e))),()=>t)}function Nc(e){return y(e,(e,t)=>Mc(t,Pc(e)),()=>Pt())}function Pc(e){return Et(e)?Tc(e.$defs,e.$ref):kt(e)?Ec(e.if,e.then,e.else):F(e)?Oc(e.allOf):V(e)?Nc(e.anyOf):H(e)?Ac(e.items):M(e)?kc(e.properties):{}}function Fc(e){return j(Pc(e))}const Ic=/* @__PURE__ */ RegExp(`^(?:0|[1-9][0-9]*)$`);function Lc(e){let t=`${e}`;return Ic.test(t)?parseInt(t):e}function Rc(e){return I(Lc(e))}function zc(e){return e.map(e=>Bc(e))}function Bc(e){return F(e)?Mt(zc(e.allOf)):V(e)?B(zc(e.anyOf)):L(e)?Rc(e.const):e}function Vc(e,t){return q(Xo({},Bc(t),R()))?e:L(t)&&v(t.const,`length`)?R():k()}function Hc(e,t){return Yc(Jo(e,t))}function Uc(e,t,n){return Yc(ir(e,t,n))}function Wc(e){return Yc(ar(e))}function Gc(e){return Yc(U(e))}function Kc(e){return[`${e}`]}function qc(e){return Yc(or(e))}function Jc(e){return e.reduce((e,t)=>[...e,...Yc(t)],[])}function Yc(e){return Et(e)?Hc(e.$defs,e.$ref):kt(e)?Uc(e.if,e.then,e.else):jt(e)?Wc(e.enum):F(e)?Gc(e.allOf):L(e)?Kc(e.const):Qi(e)?qc(e.pattern):V(e)?Jc(e.anyOf):[]}function Xc(e){return Yc(e)}function Zc(e,t){return t.map(t=>Qc(e,t))}function Qc(e,t){return D(t)?it(Qc(e,t.items)):st(t)?ot(Zc(e,t.parameters),Qc(e,t.instanceType)):ut(t)?lt(Zc(e,t.parameters),Qc(e,t.returnType)):H(t)?Dn(Zc(e,t.items)):V(t)?B(Zc(e,t.anyOf)):F(t)?Mt(Zc(e,t.allOf)):Br(t)?j(e):t}function $c(e,t){return Qc(e,t)}function el(e,t){return $c(e,t in e?e[t]:k())}function tl(e,t){return t.reduce((t,n)=>[...t,el(e,n)],[])}function nl(e,t){return sr(tl(e,Xc(t)))}const rl=new RegExp(Dr);function il(e){return e.filter(e=>rl.test(e))}function al(e){return sr(tl(e,il(xt(e))))}function ol(e,t){return tn(t)?al(e):nl(e,t)}function sl(e){return I(Lc(e))}function cl(e){return e.map(e=>ll(e))}function ll(e){return F(e)?Mt(cl(e.allOf)):V(e)?B(cl(e.anyOf)):L(e)?sl(e.const):e}function ul(e,t){return e.reduceRight((e,n,r)=>q(Xo({},I(r),t))?[n,...e]:e,[])}function dl(e,t){return lr(ul(e,ll(t)))}function fl(e){return lr(e)}function pl(e,t){return L(t)&&v(t.const,`length`)?I(e.length):tn(t)||Kt(t)?fl(e):dl(e,t)}function ml(e,t){return D(e)?Vc(e.items,t):M(e)?ol(e.properties,t):H(e)?pl(e.items,t):k()}function hl(e){return Et(e)||kt(e)||F(e)||V(e)?Fc(e):e}function gl(e,t,n){return Z([e,t])?w(ml(hl(e),t),{},n):wc(e,t,n)}function _l(e,t,n,r,i){return gl(Q(e,t,n),Q(e,t,r),i)}function vl(e,t={}){return E(`InstanceType`,[e],t)}function yl(e){return st(e)?e.instanceType:k()}function bl(e,t){return Z([e])?w(yl(e),{},t):vl(e,t)}function xl(e,t,n,r={}){return bl(Q(e,t,n),r)}function Sl(e,t={}){return E(`KeyOf`,[e],t)}function Cl(){return B([R(),z(),nn()])}function wl(e){return R()}function Tl(e){return e.reduce((e,t)=>Yt(t)?[...e,I(Lc(t))]:Pt(),[])}function El(e){return lr(Tl(x(e)))}function Dl(e){return Fr(e)}function Ol(e){return lr(e.map((e,t)=>I(t)))}function kl(e){return O(e)?Cl():D(e)?wl(e.items):M(e)?El(e.properties):Lr(e)?Dl(e):H(e)?Ol(e.items):k()}function Al(e){return Et(e)||kt(e)||F(e)||V(e)?Fc(e):e}function jl(e,t){return Z([e])?w(kl(Al(e)),{},t):Sl(e,t)}function Ml(e,t,n,r){return jl(Q(e,t,n),r)}function Nl(e,t,n,r,i={}){return E(`Mapped`,[e,t,n,r],i)}function Pl(e){return Rl(or(e))}function Fl(e){return e.reduce((e,t)=>[...e,...Rl(t)],[])}function Il(e){return Rl(ar(e))}function Ll(e){return ye(e)?[I(`${e}`)]:[I(e)]}function Rl(e){return jt(e)?Il(e.enum):L(e)?Ll(e.const):Qi(e)?Pl(e.pattern):V(e)?Fl(e.anyOf):[e]}function zl(e){return Rl(e)}function Bl(e){return Qi(e)?or(e.pattern):e}function Vl(e,t,n,r,i,a){let o=S(e,{[n.name]:r}),s=Bl(Q(o,t,i)),c=Q(o,t,a);return Xt(s)||Zt(s)?{[s.const]:c}:{}}function Hl(e,t,n,r,i,a){return r.reduce((r,o)=>[...r,Vl(e,t,n,o,i,a)],[])}function Ul(e){return e.reduce((e,t)=>[...e,j(t)],[])}function Wl(e,t,n,r,i,a){return U(Ul(Hl(e,t,n,zl(r),i,a)))}function Gl(e,t,n,r,i,a,o){return Z([r])?w(Wl(e,t,n,r,i,a),{},o):Nl(n,r,i,a,o)}function Kl(e,t,n,r,i,a,o){return Gl(e,t,n,Q(e,t,r),i,a,o)}function ql(e,t,n){let r=S(e,t);return x(t).filter(e=>n.includes(e)).reduce((e,n)=>({...e,[n]:Ko(r,n,t[n])}),{})}function Jl(e,t,n){let r=S(e,t);return x(t).filter(e=>!n.includes(e)).reduce((e,n)=>({...e,[n]:Q(r,td([],[]),t[n])}),{})}function Yl(e,t,n){let r=Mo(t),i=ql(e,t,r),a=Jl(e,t,r);return w({...i,...a},{},n)}function Xl(e,t,n,r){return Yl(e,n,r)}function Zl(e,t={}){return E(`NonNullable`,[e],t)}function Ql(e){return gc(e,B([Qt(),Vr()]),{})}function $l(e,t){return Z([e])?w(Ql(e),{},t):Zl(e,t)}function eu(e,t,n,r){return $l(Q(e,t,n),r)}function tu(e,t,n={}){return E(`Omit`,[e,t],n)}function nu(e){let t=Fc(e);return M(t)?t.properties:Pt()}function ru(e,t){return x(e).reduce((n,r)=>t.includes(r)?n:{...n,[r]:e[r]},{})}function iu(e,t){return j(ru(nu(e),Xc(t)))}function au(e,t,n){return Z([e,t])?w(iu(e,t),{},n):tu(e,t,n)}function ou(e,t,n,r,i){return au(Q(e,t,n),Q(e,t,r),i)}function su(e,t={}){return E(`Parameters`,[e],t)}function cu(e){let t=ut(e)?e.parameters:[];return Dn(rd({},td([],[]),t))}function lu(e,t){return Z([e])?w(cu(e),{},t):su(e,t)}function uu(e,t,n,r){return lu(Q(e,t,n),r)}function du(e,t={}){return E(`Partial`,[e],t)}function fu(e,t){let n=_u(Jo(e,t));return Tt(S(e,{[t]:n}),t)}function pu(e,t,n){return _u(ir(e,t,n))}function mu(e){return _u(U(e))}function hu(e){return B(e.map(e=>_u(e)))}function gu(e){return j(x(e).reduce((t,n)=>({...t,[n]:vt(e[n])}),{}))}function _u(e){return Et(e)?fu(e.$defs,e.$ref):kt(e)?pu(e.if,e.then,e.else):F(e)?mu(e.allOf):V(e)?hu(e.anyOf):M(e)?gu(e.properties):j({})}function vu(e,t){return Z([e])?w(_u(e),{},t):du(e,t)}function yu(e,t,n,r){return vu(Q(e,t,n),r)}function bu(e,t,n={}){return E(`Pick`,[e,t],n)}function xu(e,t){return x(e).reduce((n,r)=>t.includes(r)?S(n,{[r]:e[r]}):n,{})}function Su(e,t){return j(xu(nu(e),Xc(t)))}function Cu(e,t,n){return Z([e,t])?w(Su(e,t),{},n):bu(e,t,n)}function wu(e,t,n,r,i){return Cu(Q(e,t,n),Q(e,t,r),i)}function Tu(e,t={}){return E(`ReadonlyObject`,[e],t)}function Eu(e){return dd(it(e))}function Du(e,t){let n=Nu(Jo(e,t));return Tt(S(e,{[t]:n}),t)}function Ou(e,t,n){return Nu(ir(e,t,n))}function ku(e){return Nu(U(e))}function Au(e){return j(x(e).reduce((t,n)=>({...t,[n]:Rt(e[n])}),{}))}function ju(e){return dd(Dn(e))}function Mu(e){return B(e.map(e=>Nu(e)))}function Nu(e){return D(e)?Eu(e.items):Et(e)?Du(e.$defs,e.$ref):kt(e)?Ou(e.if,e.then,e.else):F(e)?ku(e.allOf):M(e)?Au(e.properties):H(e)?ju(e.items):V(e)?Mu(e.anyOf):e}function Pu(e,t){return Z([e])?w(Nu(e),{},t):Tu(e)}function Fu(e,t,n,r){return Pu(Q(e,t,n),r)}function Iu(e,t,n,r){return t.visited.includes(r)?n:r in e?Q(e,td(t.callstack,[...t.visited,r]),e[r]):n}function Lu(e,t){let n=Hu(Jo(e,t));return Tt(S(e,{[t]:n}),t)}function Ru(e,t,n){return Hu(ir(e,t,n))}function zu(e){return Hu(U(e))}function Bu(e){return B(e.map(e=>Hu(e)))}function Vu(e){return j(x(e).reduce((t,n)=>({...t,[n]:In(e[n])}),{}))}function Hu(e){return Et(e)?Lu(e.$defs,e.$ref):kt(e)?Ru(e.if,e.then,e.else):F(e)?zu(e.allOf):V(e)?Bu(e.anyOf):M(e)?Vu(e.properties):j({})}function Uu(e,t={}){return E(`Required`,[e],t)}function Wu(e,t){return Z([e])?w(Hu(e),{},t):Uu(e,t)}function Gu(e,t,n,r){return Wu(Q(e,t,n),r)}function Ku(e,t={}){return E(`ReturnType`,[e],t)}function qu(e){return ut(e)?e.returnType:k()}function Ju(e,t){return Z([e])?w(qu(e),{},t):Ku(e,t)}function Yu(e,t,n,r={}){return Ju(Q(e,t,n),r)}function Xu(e,t){return E(`With`,[e,t],{})}function Zu(e,t){return Z([e])?w(e,{},t):Xu(e,t)}function Qu(e,t,n,r){return Zu(Q(e,t,n),r)}function $u(e){return zr(e)?H(e.items)?ed(e.items.items):P(e.items)||pt(e.items)?[e]:[k()]:[e]}function ed(e){return e.reduce((e,t)=>[...e,...$u(t)],[])}function td(e,t){return{callstack:e,visited:t}}function Z(e){return y(e,(e,t)=>!pt(e)&&Z(t),()=>!0)}function nd(e,t,n){return x(n).reduce((r,i)=>({...r,[i]:Q(e,t,n[i])}),{})}function rd(e,t,n){return ed(id(e,t,n))}function id(e,t,n){return n.map(n=>Q(e,t,n))}function ad(e,t){let n=yt(e)?nt(t,{}):t,r=zt(e)?$e(n,{}):n;return Lt(e)?ld(r,{}):r}function od(e,t,n,r,i){return v(n,`AddImmutable`)?ud(e,t,r[0],i):v(n,`RemoveImmutable`)?zs(e,t,r[0],i):v(n,`AddReadonly`)?et(e,t,r[0],i):v(n,`RemoveReadonly`)?jn(e,t,r[0],i):v(n,`AddOptional`)?rt(e,t,r[0],i):v(n,`RemoveOptional`)?Fn(e,t,r[0],i):v(n,`Capitalize`)?rc(e,t,r[0],i):v(n,`Conditional`)?uc(e,t,r[0],r[1],r[2],r[3],i):v(n,`ConstructorParameters`)?mc(e,t,r[0],i):v(n,`Evaluate`)?rs(e,t,r[0],i):v(n,`Exclude`)?_c(e,t,r[0],r[1],i):v(n,`Extract`)?Cc(e,t,r[0],r[1],i):v(n,`Index`)?_l(e,t,r[0],r[1],i):v(n,`InstanceType`)?xl(e,t,r[0],i):v(n,`Interface`)?Co(e,t,r[0],r[1],i):v(n,`KeyOf`)?Ml(e,t,r[0],i):v(n,`Lowercase`)?ic(e,t,r[0],i):v(n,`Mapped`)?Kl(e,t,r[0],r[1],r[2],r[3],i):v(n,`Module`)?Xl(e,t,r[0],i):v(n,`NonNullable`)?eu(e,t,r[0],i):v(n,`Pick`)?wu(e,t,r[0],r[1],i):v(n,`Parameters`)?uu(e,t,r[0],i):v(n,`Partial`)?yu(e,t,r[0],i):v(n,`Omit`)?ou(e,t,r[0],r[1],i):v(n,`ReadonlyObject`)?Fu(e,t,r[0],i):v(n,`Record`)?Er(e,t,r[0],r[1],i):v(n,`Required`)?Gu(e,t,r[0],i):v(n,`ReturnType`)?Yu(e,t,r[0],i):v(n,`TemplateLiteral`)?Yi(e,t,r[0],i):v(n,`Uncapitalize`)?ac(e,t,r[0],i):v(n,`Uppercase`)?oc(e,t,r[0],i):v(n,`With`)?Qu(e,t,r[0],r[1]):E(n,r,i)}function sd(e,t,n){return ad(n,pt(n)?Iu(e,t,n,n.$ref):D(n)?it(Q(e,t,n.items),at(n)):Is(n)?Ps(e,t,n.target,n.arguments):st(n)?ot(id(e,t,n.parameters),Q(e,t,n.instanceType),ct(n)):ut(n)?lt(id(e,t,n.parameters),Q(e,t,n.returnType),dt(n)):kt(n)?Ot(Q(e,t,n.if),Q(e,t,n.then),Q(e,t,n.else),At(n)):F(n)?Mt(id(e,t,n.allOf),Nt(n)):M(n)?j(nd(e,t,n.properties),Ct(n)):Lr(n)?Mr(Pr(n),Q(e,t,Ir(n))):zr(n)?Rr(Q(e,t,n.items)):H(n)?Dn(rd(e,t,n.items),On(n)):V(n)?B(id(e,t,n.anyOf),on(n)):n)}function Q(e,t,n){return Ze(n)?od(e,t,n.action,n.parameters,n.options):sd(e,t,n)}function cd(e){return w(e,{"~immutable":!0},{})}function ld(e,t){return w(cd(e),{},t)}function ud(e,t,n,r){return ld(Q(e,t,n),r)}function dd(e,t={}){return ld(e,t)}const fd=[`succeeded`,`failed`,`canceled`,`lost`],pd=[`queued`,`running`,`stopping`,`succeeded`,`failed`,`canceled`,`lost`];function md(e){return fd.includes(e)}const hd={queued:[`running`,`canceled`,`lost`],running:[`stopping`,`succeeded`,`failed`,`lost`],stopping:[`canceled`,`failed`,`lost`],succeeded:[],failed:[],canceled:[],lost:[]};var gd=class{#e=/* @__PURE__ */ new Map;#t=Promise.resolve();#n;constructor(e){this.#n=e?[e]:[]}subscribe(e){this.#n.push(e)}#r(e,t){for(let n of this.#n)n(e,t)}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}evictTerminal(e){let t=[];for(let e of this.#e.values())md(e.status)&&t.push(e);t.sort((e,t)=>(e.finishedAt??0)-(t.finishedAt??0)||(e.id<t.id?-1:+(e.id>t.id)));let n=t.slice(0,Math.max(0,t.length-e));for(let e of n)this.#e.delete(e.id);return n.map(e=>e.id)}submit(e){let t=this.#t.then(()=>this.#i(e));return this.#t=t.then(()=>void 0,()=>void 0),t}#i(e){switch(e.kind){case`spawn`:if(this.#e.has(e.record.id))throw Error(`duplicate task id ${e.record.id}`);return this.#e.set(e.record.id,e.record),this.#r(e.record,null),{record:e.record,fromStatus:null,changed:!0};case`transition`:return this.#o(e.id,e.to,{});case`stop`:return this.#o(e.id,`stopping`,{stopReason:e.reason});case`cancel-queued`:{let t=this.#a(e.id);return t.status===`queued`?this.#o(e.id,`canceled`,{stopReason:e.reason}):{record:t,fromStatus:t.status,changed:!1}}case`resolve-exit`:{let t=this.#a(e.id);return t.status===`stopping`?this.#o(e.id,`canceled`,{}):t.status===`running`?this.#o(e.id,e.exitCode===0?`succeeded`:`failed`,{}):{record:t,fromStatus:t.status,changed:!1}}case`reconcile-lost`:return this.#o(e.id,`lost`,{stopReason:e.reason});case`attach-report`:{let t=this.#a(e.id);if(md(t.status))return{record:t,fromStatus:t.status,changed:!1};let n={...t,report:e.report,reportChannel:e.channel,delivery:e.delivery??t.delivery};return this.#e.set(e.id,n),this.#r(n,t),{record:n,fromStatus:t.status,changed:!0}}case`attach-output`:{let t=this.#a(e.id);if(md(t.status))return{record:t,fromStatus:t.status,changed:!1};let n={...t,outputPath:e.outputPath,outputTruncated:e.truncated??!1};return this.#e.set(e.id,n),this.#r(n,t),{record:n,fromStatus:t.status,changed:!0}}}}#a(e){let t=this.#e.get(e);if(!t)throw Error(`unknown task id ${e}`);return t}#o(e,t,n){let r=this.#a(e);if(md(r.status))return{record:r,fromStatus:r.status,changed:!1};if(!hd[r.status].includes(t))throw Error(`illegal transition ${r.status} → ${t}`);let i={...r,...n,status:t,startedAt:t===`running`?Date.now():r.startedAt,finishedAt:md(t)?Date.now():r.finishedAt};return this.#e.set(e,i),this.#r(i,r),{record:i,fromStatus:r.status,changed:!0}}};function _d(){return ne()}var vd=class{#e;#t=/* @__PURE__ */ new Set;#n=[];constructor(e=8){this.#e=e}get queuedCount(){return this.#n.length}acquire(e){return this.#t.has(e)?Promise.resolve(`granted`):this.#t.size<this.#e?(this.#t.add(e),Promise.resolve(`granted`)):new Promise(t=>{this.#n.push({taskId:e,resolve:t})})}release(e){this.#t.delete(e);let t=this.#n.shift();return t?(this.#t.add(t.taskId),t.resolve(`granted`),t.taskId):null}releaseWithoutPromotion(e){this.#t.delete(e)}holders(){return[...this.#t]}cancelQueued(e){let t=this.#n.findIndex(t=>t.taskId===e);if(t<0)return!1;let[n]=this.#n.splice(t,1);return n.resolve(`withdrawn`),!0}drainWaiters(){let e=this.#n.splice(0);for(let t of e)t.resolve(`withdrawn`);return e.map(e=>e.taskId)}};const yd=e=>({status:`rejected`,errorMessage:e}),bd=e=>e.readOnly!==void 0&&e.readOnly!==`strict`&&e.readOnly!==`lenient`?yd(`invalid readOnly value: ${String(e.readOnly)}(可用 strict / lenient,不 coerce)`):null,xd=e=>()=>e()?null:yd(`dispatch is disabled(/ptc off):不再收新的派发,在飞任务不受影响`),Sd=e=>()=>e()?yd(`session is ending:这次派发不被接受`):null,Cd=(e,t)=>()=>e()+1>t?yd(`dispatch depth limit reached(max ${t})`):null,wd=e=>e.agent!==void 0&&!/^[\w-]+$/.test(e.agent)?yd(`agent name must match [A-Za-z0-9_-]+(省略 agent = 通用孩子)`):null,Td=e=>typeof e.task!=`string`||e.task.trim()===``?yd(`task 必须是非空字符串`):e.task.trimStart().startsWith(`-`)?yd(`task 不能以 - 开头:pi 会把它当命令行选项`):null,Ed=e=>t=>t.agent===void 0||e(t.agent)?null:yd(`unknown agent: ${t.agent}(agentScope 目录里没有这个定义)`);function Dd(e){return!e.includes(`/`)&&!e.includes(`\\`)&&!e.includes(`..`)}function Od(e,t){let n=0;for(;Buffer.byteLength(e.slice(n),`utf8`)>t&&n<e.length;){let t=e.slice(n);for(n+=Math.max(1,Math.floor(t.length/2));n<e.length&&(e.charCodeAt(n)&56320)==56320;)n++}let r=e.slice(n),i=r.indexOf(`
4
- `);return i>=0?r.slice(i+1):r}var kd=class{#e=/* @__PURE__ */ new Map;async write(e,t){return this.#e.set(e,t),`memory://${e}`}async read(e){return this.#e.get(e)}async size(e){let t=this.#e.get(e);return t===void 0?void 0:Buffer.byteLength(t,`utf8`)}async readTail(e,t){let n=this.#e.get(e);return n===void 0?void 0:Od(n,t)}},Ad=class{#e;constructor(e){this.#e=e}async write(e,t){if(!Dd(e))throw Error(`invalid task id: ${e}`);let n=p(this.#e,`tasks`,e);o(n,{recursive:!0});let r=p(n,`output.log`);return f(r,t,`utf8`),r}async read(e){if(!Dd(e))return;let t=p(this.#e,`tasks`,e,`output.log`);return a(t)?s(t,`utf8`):void 0}async size(e){if(!Dd(e))return;let t=p(this.#e,`tasks`,e,`output.log`);return a(t)?d(t).size:void 0}async readTail(e,t){if(!Dd(e))return;let n=p(this.#e,`tasks`,e,`output.log`);if(!a(n))return;let r=await re(n,`r`);try{let{size:e}=await r.stat();if(e<=t)return s(n,`utf8`);let i=Buffer.alloc(Math.min(e,t+8));await r.read(i,0,i.length,e-i.length);let a=new TextDecoder(`utf-8`,{fatal:!1}).decode(i),o=a.indexOf(`
5
- `);return o>=0&&(a=a.slice(o+1)),a}finally{await r.close()}}};function jd(e){let t=[...e.matchAll(/```(?:json)?[ \t]*\n([\s\S]*?)```/g)];for(let e=t.length-1;e>=0;e--){let n=t[e][1].trim();if(n.startsWith(`{`))try{let e=JSON.parse(n);if(typeof e.summary==`string`&&e.summary.length>0)return{report:Md(e),channel:`prompt-json`}}catch{}}return{report:null,channel:`none`}}function Md(e){return{summary:e.summary,findings:Array.isArray(e.findings)?e.findings.filter(e=>typeof e?.what==`string`):void 0,files_touched:Array.isArray(e.files_touched)?e.files_touched.filter(e=>typeof e==`string`):void 0,usage:e.usage&&typeof e.usage==`object`?e.usage:void 0}}function Nd(e,t=process.env){let n=m(e[0],e.slice(1),{env:t,stdio:[`ignore`,`pipe`,`pipe`]}),r=``;n.stderr.on(`data`,e=>{r=(r+String(e)).slice(-65536)});let i=null,a,o=e=>{i===null&&(i=e,a?.(e,r))};return n.on(`error`,e=>{r=`${r}spawn error: ${e.message}\n`.slice(-65536),o(-1)}),n.on(`close`,e=>o(e??-1)),{pid:n.pid??0,onOutput:e=>n.stdout.on(`data`,t=>e(String(t))),onExit:e=>{a=e,i!==null&&e(i,r)},kill:e=>{n.kill(e)}}}function Pd(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Fd(e){if(!e)return!1;let[t=`0`,n=`0`]=e.trim().replace(/^v/,``).split(`.`),r=Number.parseInt(t,10),i=Number.parseInt(n,10);return Number.isNaN(r)||Number.isNaN(i)?!1:r>1||r===1&&i>=1}function Id(e,t){let n=[`pi`,`-p`,`--no-session`,`--mode`,`json`,`--append-system-prompt`,[`<pi-ptc-context>`,`你是被派发的子代理:看不到父会话,你的最终消息就是交付物(depth ${t.depth})。`,e.why?`<pi-ptc-why>${Pd(e.why)}</pi-ptc-why>`:``,e.childReport===!1?``:`<child-report-contract>
1
+ import{i as e,n as t,r as n}from"./ptc-engine.js";import"./ptc/index.js";import*as r from"@earendil-works/pi-coding-agent";import{getAgentDir as i}from"@earendil-works/pi-coding-agent";import{existsSync as a,mkdirSync as o,readFileSync as s,readdirSync as c,renameSync as l,rmSync as u,statSync as d,writeFileSync as f}from"node:fs";import{dirname as p,join as m}from"node:path";import{execSync as h,spawn as g}from"node:child_process";import{Type as _}from"typebox";import{randomUUID as v}from"node:crypto";import{mkdir as y,open as b,readFile as x,readdir as S,rename as C,writeFile as w}from"node:fs/promises";import{gunzipSync as T,gzip as E}from"node:zlib";import{promisify as ee}from"node:util";import{fileURLToPath as D}from"node:url";import{tmpdir as O}from"node:os";import{Box as k,Text as A}from"@earendil-works/pi-tui";const j=[`succeeded`,`failed`,`canceled`,`lost`],te=[`queued`,`running`,`stopping`,`succeeded`,`failed`,`canceled`,`lost`];function M(e){return j.includes(e)}const ne={queued:[`running`,`canceled`,`lost`],running:[`stopping`,`succeeded`,`failed`,`lost`],stopping:[`canceled`,`failed`,`lost`],succeeded:[],failed:[],canceled:[],lost:[]};var re=class{#e=/* @__PURE__ */ new Map;#t=Promise.resolve();#n;constructor(e){this.#n=e?[e]:[]}subscribe(e){this.#n.push(e)}#r(e,t){for(let n of this.#n)n(e,t)}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}evictTerminal(e){let t=[];for(let e of this.#e.values())M(e.status)&&t.push(e);t.sort((e,t)=>(e.finishedAt??0)-(t.finishedAt??0)||(e.id<t.id?-1:+(e.id>t.id)));let n=t.slice(0,Math.max(0,t.length-e));for(let e of n)this.#e.delete(e.id);return n.map(e=>e.id)}submit(e){let t=this.#t.then(()=>this.#i(e));return this.#t=t.then(()=>void 0,()=>void 0),t}#i(e){switch(e.kind){case`spawn`:if(this.#e.has(e.record.id))throw Error(`duplicate task id ${e.record.id}`);return this.#e.set(e.record.id,e.record),this.#r(e.record,null),{record:e.record,fromStatus:null,changed:!0};case`transition`:return this.#o(e.id,e.to,{});case`stop`:return this.#o(e.id,`stopping`,{stopReason:e.reason});case`cancel-queued`:{let t=this.#a(e.id);return t.status===`queued`?this.#o(e.id,`canceled`,{stopReason:e.reason}):{record:t,fromStatus:t.status,changed:!1}}case`resolve-exit`:{let t=this.#a(e.id);return t.status===`stopping`?this.#o(e.id,`canceled`,{}):t.status===`running`?this.#o(e.id,e.exitCode===0?`succeeded`:`failed`,{}):{record:t,fromStatus:t.status,changed:!1}}case`reconcile-lost`:return this.#o(e.id,`lost`,{stopReason:e.reason});case`attach-report`:{let t=this.#a(e.id);if(M(t.status))return{record:t,fromStatus:t.status,changed:!1};let n={...t,report:e.report,reportChannel:e.channel,delivery:e.delivery??t.delivery};return this.#e.set(e.id,n),this.#r(n,t),{record:n,fromStatus:t.status,changed:!0}}case`attach-output`:{let t=this.#a(e.id);if(M(t.status))return{record:t,fromStatus:t.status,changed:!1};let n={...t,outputPath:e.outputPath,outputTruncated:e.truncated??!1};return this.#e.set(e.id,n),this.#r(n,t),{record:n,fromStatus:t.status,changed:!0}}}}#a(e){let t=this.#e.get(e);if(!t)throw Error(`unknown task id ${e}`);return t}#o(e,t,n){let r=this.#a(e);if(M(r.status))return{record:r,fromStatus:r.status,changed:!1};if(!ne[r.status].includes(t))throw Error(`illegal transition ${r.status} → ${t}`);let i={...r,...n,status:t,startedAt:t===`running`?Date.now():r.startedAt,finishedAt:M(t)?Date.now():r.finishedAt};return this.#e.set(e,i),this.#r(i,r),{record:i,fromStatus:r.status,changed:!0}}};function ie(){return v()}var ae=class{#e;#t=/* @__PURE__ */ new Set;#n=[];constructor(e=8){this.#e=e}get queuedCount(){return this.#n.length}acquire(e){return this.#t.has(e)?Promise.resolve(`granted`):this.#t.size<this.#e?(this.#t.add(e),Promise.resolve(`granted`)):new Promise(t=>{this.#n.push({taskId:e,resolve:t})})}release(e){this.#t.delete(e);let t=this.#n.shift();return t?(this.#t.add(t.taskId),t.resolve(`granted`),t.taskId):null}releaseWithoutPromotion(e){this.#t.delete(e)}holders(){return[...this.#t]}cancelQueued(e){let t=this.#n.findIndex(t=>t.taskId===e);if(t<0)return!1;let[n]=this.#n.splice(t,1);return n.resolve(`withdrawn`),!0}drainWaiters(){let e=this.#n.splice(0);for(let t of e)t.resolve(`withdrawn`);return e.map(e=>e.taskId)}};const N=e=>({status:`rejected`,errorMessage:e}),oe=e=>e.readOnly!==void 0&&e.readOnly!==`strict`&&e.readOnly!==`lenient`?N(`invalid readOnly value: ${String(e.readOnly)}(可用 strict / lenient,不 coerce)`):null,se=e=>()=>e()?null:N(`dispatch is disabled(/ptc off):不再收新的派发,在飞任务不受影响`),ce=e=>()=>e()?N(`session is ending:这次派发不被接受`):null,le=(e,t)=>()=>e()+1>t?N(`dispatch depth limit reached(max ${t})`):null,ue=e=>e.agent!==void 0&&!/^[\w-]+$/.test(e.agent)?N(`agent name must match [A-Za-z0-9_-]+(省略 agent = 通用孩子)`):null,de=e=>typeof e.task!=`string`||e.task.trim()===``?N(`task 必须是非空字符串`):e.task.trimStart().startsWith(`-`)?N(`task 不能以 - 开头:pi 会把它当命令行选项`):null,fe=e=>t=>t.agent===void 0||e(t.agent)?null:N(`unknown agent: ${t.agent}(agentScope 目录里没有这个定义)`);function P(e){return!e.includes(`/`)&&!e.includes(`\\`)&&!e.includes(`..`)}function pe(e,t){let n=0;for(;Buffer.byteLength(e.slice(n),`utf8`)>t&&n<e.length;){let t=e.slice(n);for(n+=Math.max(1,Math.floor(t.length/2));n<e.length&&(e.charCodeAt(n)&56320)==56320;)n++}let r=e.slice(n),i=r.indexOf(`
2
+ `);return i>=0?r.slice(i+1):r}var me=class{#e=/* @__PURE__ */ new Map;async write(e,t){return this.#e.set(e,t),`memory://${e}`}async read(e){return this.#e.get(e)}async size(e){let t=this.#e.get(e);return t===void 0?void 0:Buffer.byteLength(t,`utf8`)}async readTail(e,t){let n=this.#e.get(e);return n===void 0?void 0:pe(n,t)}},he=class{#e;constructor(e){this.#e=e}async write(e,t){if(!P(e))throw Error(`invalid task id: ${e}`);let n=m(this.#e,`tasks`,e);o(n,{recursive:!0});let r=m(n,`output.log`);return f(r,t,`utf8`),r}async read(e){if(!P(e))return;let t=m(this.#e,`tasks`,e,`output.log`);return a(t)?s(t,`utf8`):void 0}async size(e){if(!P(e))return;let t=m(this.#e,`tasks`,e,`output.log`);return a(t)?d(t).size:void 0}async readTail(e,t){if(!P(e))return;let n=m(this.#e,`tasks`,e,`output.log`);if(!a(n))return;let r=await b(n,`r`);try{let{size:e}=await r.stat();if(e<=t)return s(n,`utf8`);let i=Buffer.alloc(Math.min(e,t+8));await r.read(i,0,i.length,e-i.length);let a=new TextDecoder(`utf-8`,{fatal:!1}).decode(i),o=a.indexOf(`
3
+ `);return o>=0&&(a=a.slice(o+1)),a}finally{await r.close()}}};function ge(e){let t=[...e.matchAll(/```(?:json)?[ \t]*\n([\s\S]*?)```/g)];for(let e=t.length-1;e>=0;e--){let n=t[e][1].trim();if(n.startsWith(`{`))try{let e=JSON.parse(n);if(typeof e.summary==`string`&&e.summary.length>0)return{report:_e(e),channel:`prompt-json`}}catch{}}return{report:null,channel:`none`}}function _e(e){return{summary:e.summary,findings:Array.isArray(e.findings)?e.findings.filter(e=>typeof e?.what==`string`):void 0,files_touched:Array.isArray(e.files_touched)?e.files_touched.filter(e=>typeof e==`string`):void 0,usage:e.usage&&typeof e.usage==`object`?e.usage:void 0}}function ve(e,t=process.env){let n=g(e[0],e.slice(1),{env:t,stdio:[`ignore`,`pipe`,`pipe`]}),r=``;n.stderr.on(`data`,e=>{r=(r+String(e)).slice(-65536)});let i=null,a,o=e=>{i===null&&(i=e,a?.(e,r))};return n.on(`error`,e=>{r=`${r}spawn error: ${e.message}\n`.slice(-65536),o(-1)}),n.on(`close`,e=>o(e??-1)),{pid:n.pid??0,onOutput:e=>n.stdout.on(`data`,t=>e(String(t))),onExit:e=>{a=e,i!==null&&e(i,r)},kill:e=>{n.kill(e)}}}function ye(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function be(e){if(!e)return!1;let[t=`0`,n=`0`]=e.trim().replace(/^v/,``).split(`.`),r=Number.parseInt(t,10),i=Number.parseInt(n,10);return Number.isNaN(r)||Number.isNaN(i)?!1:r>1||r===1&&i>=1}function xe(e,t){let n=[`pi`,`-p`,`--no-session`,`--mode`,`json`,`--append-system-prompt`,[`<pi-ptc-context>`,`你是被派发的子代理:看不到父会话,你的最终消息就是交付物(depth ${t.depth})。`,e.why?`<pi-ptc-why>${ye(e.why)}</pi-ptc-why>`:``,e.childReport===!1?``:`<child-report-contract>
6
4
  Before finishing, deliver a child report — preferably by calling the ptc_child_report tool (its schema fixes the shape); if that tool is not available, put a fenced JSON block at the very end of your final message:
7
5
  \`\`\`json
8
6
  { "summary": "one sentence conclusion", "findings": [{ "what": "claim", "evidence": "where it comes from" }], "files_touched": ["relative/path"], "usage": { "input": 0, "output": 0, "cost": 0, "turns": 0 } }
@@ -10,33 +8,33 @@ Before finishing, deliver a child report — preferably by calling the ptc_child
10
8
  Rules: the report is a SUMMARY — it is NOT the deliverable. The deliverable is your prose answer, in exactly the format the task asked for; never hide the deliverable inside the JSON block. "summary" is one sentence of conclusion. "findings" carries load-bearing evidence only; never recap content you merely read. Do NOT write report/summary .md files — your final message is what the parent reads.
11
9
  findings/files_touched/usage may be omitted when empty.
12
10
  </child-report-contract>`,`</pi-ptc-context>`].filter(Boolean).join(`
13
- `)];n.push(`--no-extensions`,`--no-skills`),e.projectContext===`none`&&n.push(`--no-context-files`),Fd(t.piVersion)&&n.push(`--no-mcp`);let r=e.model??e.agentModel??t.sessionModel,i=e.thinkingLevel??e.agentThinkingLevel;r&&n.push(`--model`,i?`${r}:${i}`:r);let a=e.searchEnabled?[`read`,`grep`,`find`,`ls`,`web_ds_search`]:[`read`,`grep`,`find`,`ls`];return e.readOnly===`strict`?n.push(`--tools`,a.join(`,`)):e.agentTools&&e.agentTools.length>0&&n.push(`--tools`,e.agentTools.join(`,`)),n.push(e.task),n}function Ld(e,t){let n;try{n=s(e,`utf8`)}catch{return null}let r={name:t,path:e,childReport:!0},i=n.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!i)return r;for(let e of i[1].split(/\r?\n/)){let t=e.match(/^(\w[\w-]*)\s*:\s*(.+)$/);if(!t)continue;let n=t[1],i=t[2];n===`childReport`&&(r.childReport=i!==`false`&&i!==`no`),n===`tools`&&(r.tools=i.split(`,`).map(e=>e.trim())),n===`model`&&(r.model=i),(n===`thinkingLevel`||n===`thinking_level`)&&(r.thinkingLevel=i)}return r}function Rd(e,t=`both`){return t===`user`?[e.userDir]:t===`project`?[e.projectDir]:[e.projectDir,e.userDir]}function zd(e,t,n=`both`){if(!/^[\w-]+$/.test(e))return null;for(let r of Rd(t,n)){let t=p(r,`${e}.md`);if(a(t))return Ld(t,e)}return null}function Bd(e){let t=``,n=null,r=null,i=null,a=null,o={},s=[],c=0;for(let l of e.split(`
11
+ `)];n.push(`--no-extensions`,`--no-skills`),e.projectContext===`none`&&n.push(`--no-context-files`),be(t.piVersion)&&n.push(`--no-mcp`);let r=e.model??e.agentModel??t.sessionModel,i=e.thinkingLevel??e.agentThinkingLevel;r&&n.push(`--model`,i?`${r}:${i}`:r);let a=e.searchEnabled?[`read`,`grep`,`find`,`ls`,`web_ds_search`]:[`read`,`grep`,`find`,`ls`];return e.readOnly===`strict`?n.push(`--tools`,a.join(`,`)):e.agentTools&&e.agentTools.length>0&&n.push(`--tools`,e.agentTools.join(`,`)),n.push(e.task),n}function Se(e,t){let n;try{n=s(e,`utf8`)}catch{return null}let r={name:t,path:e,childReport:!0},i=n.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!i)return r;for(let e of i[1].split(/\r?\n/)){let t=e.match(/^(\w[\w-]*)\s*:\s*(.+)$/);if(!t)continue;let n=t[1],i=t[2];n===`childReport`&&(r.childReport=i!==`false`&&i!==`no`),n===`tools`&&(r.tools=i.split(`,`).map(e=>e.trim())),n===`model`&&(r.model=i),(n===`thinkingLevel`||n===`thinking_level`)&&(r.thinkingLevel=i)}return r}function Ce(e,t=`both`){return t===`user`?[e.userDir]:t===`project`?[e.projectDir]:[e.projectDir,e.userDir]}function we(e,t,n=`both`){if(!/^[\w-]+$/.test(e))return null;for(let r of Ce(t,n)){let t=m(r,`${e}.md`);if(a(t))return Se(t,e)}return null}function F(e){let t=``,n=null,r=null,i=null,a=null,o={},s=[],c=0;for(let l of e.split(`
14
12
  `)){let e=l.trim();if(!e.startsWith(`{`))continue;let u;try{u=JSON.parse(e)}catch{continue}if(u.type===`tool_execution_start`){let e=typeof u.toolName==`string`?u.toolName:`unknown`;o[e]=(o[e]??0)+1;let t=u.args?.path;typeof t==`string`&&t&&!s.includes(t)&&s.length<20&&s.push(t);continue}if(u.type===`tool_execution_end`){(u.isError===!0||u.result?.isError===!0)&&c++;continue}if(u.type!==`message_end`||!u.message)continue;let d=u.message;if(d.role===`assistant`&&(typeof d.model==`string`&&(i=d.model),typeof d.provider==`string`&&(a=d.provider),t=(Array.isArray(d.content)?d.content:[]).filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
15
- `),d.usage)){let e=typeof d.usage.cost==`number`?d.usage.cost:d.usage.cost?.total;r={input:d.usage.input,output:d.usage.output,...d.usage.cacheRead===void 0?{}:{cacheRead:d.usage.cacheRead},...d.usage.cacheWrite===void 0?{}:{cacheWrite:d.usage.cacheWrite},...e===void 0?{}:{cost:e}}}if(d.role===`toolResult`&&d.toolName===`ptc_child_report`){let e=d.structuredContent??d.details?.report??d.details;e&&typeof e.summary==`string`&&(n=e)}}return{text:t,toolReport:n,observedUsage:r,observedModel:i,observedProvider:a,delivery:{tools:o,paths:s,errors:c,textChars:t.length}}}var Vd=class{#e=[];#t=/* @__PURE__ */ new Set;#n=!1;attach(e){this.#n||(this.#n=!0,e.subscribe((e,t)=>{t?.status!==e.status&&Hd(e.status)&&(this.#t.has(e.id)?this.#t.delete(e.id):this.#e.push({taskId:e.id,label:e.label,status:e.status,stopReason:e.stopReason,at:e.finishedAt??Date.now()}))}))}markAwaited(e){this.#t.add(e)}pendingCount(){return this.#e.length}drain(){let e=[],t=[],n=0;for(let r of this.#e.splice(0)){let i=Buffer.byteLength(JSON.stringify(r),`utf8`);t.length>0&&n+i>102400&&(e.push(t),t=[],n=0),t.push(r),n+=i}return t.length>0&&e.push(t),e}};function Hd(e){return e===`succeeded`||e===`failed`||e===`canceled`||e===`lost`}var Ud=class{#e=``;#t;#n=0;#r;constructor(e=Date.now){this.#r=e,this.#t=e()}push(e){this.#t=this.#r(),this.#e+=e;let t=this.#e.indexOf(`
13
+ `),d.usage)){let e=typeof d.usage.cost==`number`?d.usage.cost:d.usage.cost?.total;r={input:d.usage.input,output:d.usage.output,...d.usage.cacheRead===void 0?{}:{cacheRead:d.usage.cacheRead},...d.usage.cacheWrite===void 0?{}:{cacheWrite:d.usage.cacheWrite},...e===void 0?{}:{cost:e}}}if(d.role===`toolResult`&&d.toolName===`ptc_child_report`){let e=d.structuredContent??d.details?.report??d.details;e&&typeof e.summary==`string`&&(n=e)}}return{text:t,toolReport:n,observedUsage:r,observedModel:i,observedProvider:a,delivery:{tools:o,paths:s,errors:c,textChars:t.length}}}var Te=class{#e=[];#t=/* @__PURE__ */ new Set;#n=!1;attach(e){this.#n||(this.#n=!0,e.subscribe((e,t)=>{t?.status!==e.status&&Ee(e.status)&&(this.#t.has(e.id)?this.#t.delete(e.id):this.#e.push({taskId:e.id,label:e.label,status:e.status,stopReason:e.stopReason,at:e.finishedAt??Date.now()}))}))}markAwaited(e){this.#t.add(e)}pendingCount(){return this.#e.length}drain(){let e=[],t=[],n=0;for(let r of this.#e.splice(0)){let i=Buffer.byteLength(JSON.stringify(r),`utf8`);t.length>0&&n+i>102400&&(e.push(t),t=[],n=0),t.push(r),n+=i}return t.length>0&&e.push(t),e}};function Ee(e){return e===`succeeded`||e===`failed`||e===`canceled`||e===`lost`}var De=class{#e=``;#t;#n=0;#r;constructor(e=Date.now){this.#r=e,this.#t=e()}push(e){this.#t=this.#r(),this.#e+=e;let t=this.#e.indexOf(`
16
14
  `);for(;t>=0;)this.#i(this.#e.slice(0,t)),this.#e=this.#e.slice(t+1),t=this.#e.indexOf(`
17
- `)}isStalled(e,t){return this.#n>0?!1:e-this.#t>=t}#i(e){let t=e.trim();if(!t.includes(`"tool_execution_start"`)&&!t.includes(`"tool_execution_end"`))return;let n;try{n=JSON.parse(t)}catch{return}n.type===`tool_execution_start`?this.#n++:n.type===`tool_execution_end`&&(this.#n=Math.max(0,this.#n-1))}};const Wd=le(ce);function Gd(e){return new Promise(t=>{if(e.aborted)return t();e.addEventListener(`abort`,()=>t(),{once:!0})})}function Kd(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}var qd=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b=Promise.resolve();#x=/* @__PURE__ */ new Map;#S=!1;#C=!1;constructor(e){this.#e=e.registry,this.#t=e.slots??new vd,this.#n=e.output??new kd,this.#r=e.spawnChild??((e,t)=>Nd(e,t)),this.#i=e.gates??[],this.#a=e.buildArgv??((e,t)=>Id(e,t)),this.#o=e.resolveAgent??(()=>null),this.#s=e.childExtensionPath,this.#c=e.searchEnabled??!1,this.#u={pid:process.pid,bootMs:Date.now()},this.#h=e.storageDir,this.#g=e.terminalRecordKeep??500,this.#_=e.archiveEnabled??!0,this.#v=e.archiveTtlDays??30,this.#y=e.stallMs??3e5,this.#l=e.storageDir?this.#j(e.storageDir):Promise.resolve(),this.#d=e.stopGraceMs??5e3;let t=e.whyEnabled;this.#f=typeof t==`function`?t:t===!1?()=>!1:()=>!0,this.#p=e.notifications,this.#m=e.context??{depth:0}}dispatch(e){return this.#l.then(()=>this.#w(e))}async#w(e){if(this.#C)return yd(`session is ending:拆卸中不再收新的派发`);for(let t of this.#i){let n=t(e);if(n)return Promise.resolve(n)}let t=this.#f(),n=!t&&e.why!==void 0,r={...e,why:t?e.why:void 0},i=r.agent===void 0?null:this.#o(r.agent,r.agentScope),a={childReport:i?.childReport??!0,agentTools:i?.tools,agentModel:i?.model,agentThinkingLevel:i?.thinkingLevel},o=_d();return this.#e.submit({kind:`spawn`,record:{id:o,status:`queued`,task:r.task,label:r.label,whySuppressed:n,ownerPid:this.#u.pid,ownerBootMs:this.#u.bootMs,sessionId:this.#m.sessionId}}).then(async()=>{if(r.wait){this.#p?.markAwaited(o);let e=this.#t.acquire(o),t=r.signal?await Promise.race([e,Gd(r.signal).then(()=>`aborted`)]):await e;return t===`aborted`?(this.#t.cancelQueued(o),await this.#e.submit({kind:`cancel-queued`,id:o,reason:`caller aborted`}),yd(`任务在排队中被调用方撤回(前台 abort,决策 17)`)):t===`withdrawn`?(await this.#e.submit({kind:`cancel-queued`,id:o,reason:`withdrawn while waiting`}),yd(`任务在排队中被抽掉`)):this.#E(o,r,n,a)}return this.#T(o,r,n,a),{taskId:o,label:r.label,status:`queued`,whySuppressed:n}})}async#T(e,t,n=!1,r={childReport:!0}){await this.#t.acquire(e)===`withdrawn`?await this.#e.submit({kind:`cancel-queued`,id:e,reason:`withdrawn`}):this.#E(e,t,n,r)}async#E(e,t,n=!1,r={childReport:!0}){try{return await this.#D(e,t,n,r)}catch{return await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:-1}).catch(()=>void 0),this.#O(e),this.#k(e,t,n,`任务内部错误(见日志)`,`rejected`)}}async#D(e,t,n=!1,r={childReport:!0}){if(!(await this.#e.submit({kind:`transition`,id:e,to:`running`})).changed)return this.#O(e),this.#k(e,t,n,`任务在启动前已取消`,`canceled`);if(this.#C)return await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:-1}).catch(()=>void 0),this.#O(e),this.#k(e,t,n,`会话拆卸发生在启动前`,`rejected`);let i=this.#a({...t,taskId:e,searchEnabled:this.#c,...r},this.#m);this.#s&&i.push(`-e`,this.#s);let a={...process.env,PI_PTC_DEPTH:String(this.#m.depth+1),PI_PTC_TASK_ID:e},o=this.#r(i,a);this.#x.set(e,o);let s=typeof t.timeoutMs==`number`&&t.timeoutMs>0?t.timeoutMs:void 0,c=s?setTimeout(()=>{this.stop(e,`timeout after ${s}ms`)},s):void 0;c?.unref();let l=new Ud,u=this.#y>0?this.#y:void 0,d=u?setInterval(()=>{l.isStalled(Date.now(),u)&&this.stop(e,`stalled: no activity for ${u}ms`)},Math.min(1e3,u)):void 0;d?.unref();let f=``,ee=!1;o.onOutput(e=>{l.push(e),f+=e,f.length>16777216&&(f=f.slice(-16777216),ee=!0)});let p=await new Promise(e=>{o.onExit(t=>e(t))});c&&clearTimeout(c),d&&clearInterval(d),this.#x.delete(e);let te=await this.#n.write(e,f),m=Bd(f),ne=m.text||f,h,re;if(!r.childReport)re=`opted-out`;else if(m.toolReport)h=m.toolReport,re=`tool`;else{let e=jd(ne);h=e.report??void 0,re=e.channel}let g=h?.usage,ie=!g||!g.input&&!g.output&&!g.cost;h&&ie&&m.observedUsage&&(h={...h,usage:m.observedUsage}),await this.#e.submit({kind:`attach-report`,id:e,report:h,channel:re,delivery:m.delivery}),await this.#e.submit({kind:`attach-output`,id:e,outputPath:te,truncated:ee});let ae=await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:p});this.#O(e),this.#N(this.#g,`runtime`);let oe=ae.record.status===`succeeded`?`fulfilled`:ae.record.status===`canceled`?`canceled`:`rejected`,se=ae.record.startedAt??0,ce=ae.record.finishedAt??0;return{status:oe,taskId:e,label:t.label,text:ne,exitCode:p,started:!0,agentName:t.agent??`generalist`,durationMs:se&&ce?ce-se:0,usage:h?.usage??m.observedUsage??void 0,observedModel:m.observedModel??void 0,observedProvider:m.observedProvider??void 0,errorMessage:oe===`fulfilled`?void 0:ae.record.stopReason??`exit code ${p}`,readOnlyTier:t.readOnly??`lenient`,outputPath:te,whySuppressed:n,report:h??void 0,reportChannel:re,delivery:m.delivery,outputTruncated:ee}}async stop(e,t){let n=await this.#e.submit({kind:`cancel-queued`,id:e,reason:t});if(n.changed){this.#t.cancelQueued(e);return}if(n.record.status!==`running`)return;await this.#e.submit({kind:`stop`,id:e,reason:t});let r=this.#x.get(e);r&&(r.kill(`SIGTERM`),setTimeout(()=>{this.#x.has(e)&&r.kill(`SIGKILL`)},this.#d).unref())}#O(e){this.#C?this.#t.releaseWithoutPromotion(e):this.#t.release(e)}#k(e,t,n,r,i){return{status:i,taskId:e,label:t.label,text:``,exitCode:-1,started:!1,agentName:t.agent??`generalist`,durationMs:0,errorMessage:r,readOnlyTier:t.readOnly??`lenient`,outputPath:``,whySuppressed:n,reportChannel:`none`,outputTruncated:!1}}isEnding(){return this.#S}readOutput(e){return this.#n.read(e).then(t=>t??this.#A(e))}outputSize(e){return this.#n.size(e).then(t=>{if(t!==void 0)return t;let n=this.#A(e);return n===void 0?void 0:Buffer.byteLength(n,`utf8`)})}readOutputTail(e,t){return this.#n.readTail(e,t).then(n=>{if(n!==void 0)return n;let r=this.#A(e);return r===void 0?void 0:r.slice(-t)})}readArchivedRecord(e){let t=this.#h?p(this.#h,`archive`,`${e}.json.gz`):null;if(!t||!a(t))return Promise.resolve(void 0);try{let e=JSON.parse(se(s(t)).toString(`utf8`));return Promise.resolve({...e,archived:!0})}catch{return Promise.resolve(void 0)}}async readArchivedRecords(){let e=this.#h?p(this.#h,`archive`):null;if(!e||!a(e))return[];let t=[];for(let n of await ie(e))if(n.endsWith(`.json.gz`))try{let r=JSON.parse(se(await g(p(e,n))).toString(`utf8`));r&&typeof r.id==`string`&&t.push({...r,archived:!0})}catch{}return t}#A(e){let t=this.#h?p(this.#h,`archive`,`${e}.output.gz`):null;if(t&&a(t))try{return se(s(t)).toString(`utf8`)}catch{return}}async#j(e){let t=p(e,`records`);if(a(t)){for(let e of c(t))if(e.endsWith(`.json`))try{let n=JSON.parse(s(p(t,e),`utf8`));n&&typeof n.id==`string`&&await this.#e.submit({kind:`spawn`,record:n}).catch(()=>void 0)}catch{}}this.#e.subscribe(t=>this.#M(e,t));for(let e of this.#e.list())md(e.status)||e.ownerPid!==void 0&&Kd(e.ownerPid)||await this.#e.submit({kind:`reconcile-lost`,id:e.id,reason:`lost_on_session_restart`}).catch(()=>void 0);this.#N(this.#g,`boot`),this.#L()}async#M(e,t){try{let n=p(e,`records`);o(n,{recursive:!0});let r=p(n,`${t.id}.json`),i=`${r}.tmp`;f(i,JSON.stringify(t,null,2),`utf8`),l(i,r)}catch{}}#N(e,t){let n=this.#e.evictTerminal(e);if(this.#h&&n.length!==0){if(t===`boot`||!this.#_)for(let e of n)this.#P(e);else for(let e of n)this.#F(e)}}#P(e){try{u(p(this.#h,`records`,`${e}.json`)),u(p(this.#h,`tasks`,e),{recursive:!0,force:!0})}catch{}}#F(e){this.#b=this.#b.then(()=>new Promise(t=>{setImmediate(()=>void this.#I(e).then(t,t))})).catch(()=>void 0)}async#I(e){let t=this.#h,n=JSON.parse(s(p(t,`records`,`${e}.json`),`utf8`)),r=await Wd(Buffer.from(JSON.stringify({...n,archivedAt:Date.now()}))),i=p(t,`archive`);await h(i,{recursive:!0}),await oe(p(i,`${e}.json.gz.tmp`),r),await ae(p(i,`${e}.json.gz.tmp`),p(i,`${e}.json.gz`));let o=p(t,`tasks`,e,`output.log`);if(a(o)){let t=await Wd(await g(o));await oe(p(i,`${e}.output.gz.tmp`),t),await ae(p(i,`${e}.output.gz.tmp`),p(i,`${e}.output.gz`))}this.#P(e)}#L(){let e=this.#h;if(!e||!this.#_)return;let t=p(e,`archive`);if(!a(t))return;let n=this.#v*864e5,r=Date.now(),i=0;for(let e of c(t)){if(i>=500)break;if(e.endsWith(`.gz`))try{r-d(p(t,e)).mtimeMs>n&&(u(p(t,e)),i++)}catch{}}}async shutdown(){this.#S=!0,this.#C=!0;let e=this.#t.drainWaiters();for(let t of e)await this.#e.submit({kind:`cancel-queued`,id:t,reason:`session shutdown`});for(let[e,t]of this.#x)this.#e.get(e)?.status===`running`&&(await this.#e.submit({kind:`stop`,id:e,reason:`session ended`}),t.kill(`SIGTERM`));await this.#b.catch(()=>void 0)}};const Jd={MAX_LOG_LINES_EXPANDED:12,VALUE_TREE_MAX_DEPTH:4,VALUE_TREE_MAX_CHILDREN:6,VALUE_TREE_MAX_LINE_CHARS:120},Yd=/\x1B\[[0-9:;<=>?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;function Xd(e){return e.replace(Yd,``)}function Zd(e){return Xd(e.replace(/\r/g,``))}const Qd=Jd.VALUE_TREE_MAX_LINE_CHARS;function $d(e,t=Qd){if(e.length<=t)return e;let n=t;for(;n>0&&(e.charCodeAt(n)&64512)==56320;)n--;return`${e.slice(0,n)}…`}function ef(e,t=0,n=/* @__PURE__ */ new WeakSet){let r=` `.repeat(t);if(t>=Jd.VALUE_TREE_MAX_DEPTH)return`…`;if(typeof e==`string`)return t===0?e:JSON.stringify(e);if(e===null||typeof e==`number`||typeof e==`boolean`)return String(e);if(nf(e))return`(无完成值)`;if(typeof e==`object`&&e){if(n.has(e))return`[Circular]`;n.add(e)}if(Array.isArray(e)){let i=e.slice(0,Jd.VALUE_TREE_MAX_CHILDREN),a=e.length-i.length,o=`[${i.map(e=>JSON.stringify(e)).join(`, `)}]`,s=e.length===0?`[]`:a===0&&i.every(e=>tf(e))&&o.length<=Qd?o:`[\n${i.map(e=>$d(`${r} ${ef(e,t+1,n)}`)).join(`,
18
- `)}${a>0?`,\n${r} …(余 ${a} 项)`:``}\n${r}]`;return n.delete(e),s}if(typeof e==`object`&&e){let i=Object.entries(e),a=i.slice(0,Jd.VALUE_TREE_MAX_CHILDREN),o=i.length-a.length,s=`{ ${a.map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)} }`,c=i.length===0?`{}`:o===0&&a.every(([,e])=>tf(e))&&s.length<=Qd?s:`{\n${a.map(([e,i])=>$d(`${r} ${e}: ${ef(i,t+1,n)}`)).join(`,
19
- `)}${o>0?`,\n${r} …(余 ${o} 项)`:``}\n${r}}`;return n.delete(e),c}return String(e)}function tf(e){return e===null||[`string`,`number`,`boolean`].includes(typeof e)}function nf(e){return typeof e==`object`&&!!e&&e.$void===!0}const rf=`pi-ptc-output-`;let af=!1;function of(){af=!0;let e;try{e=c(de())}catch{return}for(let t of e)if(t.startsWith(rf))try{let e=p(de(),t);Date.now()-d(e).mtimeMs>864e5&&u(e,{force:!0})}catch{}}function sf(e){let t=e.split(`
15
+ `)}isStalled(e,t){return this.#n>0?!1:e-this.#t>=t}#i(e){let t=e.trim();if(!t.includes(`"tool_execution_start"`)&&!t.includes(`"tool_execution_end"`))return;let n;try{n=JSON.parse(t)}catch{return}n.type===`tool_execution_start`?this.#n++:n.type===`tool_execution_end`&&(this.#n=Math.max(0,this.#n-1))}};const Oe=ee(E);function ke(e){return new Promise(t=>{if(e.aborted)return t();e.addEventListener(`abort`,()=>t(),{once:!0})})}function Ae(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}var je=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b=Promise.resolve();#x=/* @__PURE__ */ new Map;#S=!1;#C=!1;constructor(e){this.#e=e.registry,this.#t=e.slots??new ae,this.#n=e.output??new me,this.#r=e.spawnChild??((e,t)=>ve(e,t)),this.#i=e.gates??[],this.#a=e.buildArgv??((e,t)=>xe(e,t)),this.#o=e.resolveAgent??(()=>null),this.#s=e.childExtensionPath,this.#c=e.searchEnabled??!1,this.#u={pid:process.pid,bootMs:Date.now()},this.#h=e.storageDir,this.#g=e.terminalRecordKeep??500,this.#_=e.archiveEnabled??!0,this.#v=e.archiveTtlDays??30,this.#y=e.stallMs??3e5,this.#l=e.storageDir?this.#j(e.storageDir):Promise.resolve(),this.#d=e.stopGraceMs??5e3;let t=e.whyEnabled;this.#f=typeof t==`function`?t:t===!1?()=>!1:()=>!0,this.#p=e.notifications,this.#m=e.context??{depth:0}}dispatch(e){return this.#l.then(()=>this.#w(e))}async#w(e){if(this.#C)return N(`session is ending:拆卸中不再收新的派发`);for(let t of this.#i){let n=t(e);if(n)return Promise.resolve(n)}let t=this.#f(),n=!t&&e.why!==void 0,r={...e,why:t?e.why:void 0},i=r.agent===void 0?null:this.#o(r.agent,r.agentScope),a={childReport:i?.childReport??!0,agentTools:i?.tools,agentModel:i?.model,agentThinkingLevel:i?.thinkingLevel},o=ie();return this.#e.submit({kind:`spawn`,record:{id:o,status:`queued`,task:r.task,label:r.label,whySuppressed:n,ownerPid:this.#u.pid,ownerBootMs:this.#u.bootMs,sessionId:this.#m.sessionId}}).then(async()=>{if(r.wait){this.#p?.markAwaited(o);let e=this.#t.acquire(o),t=r.signal?await Promise.race([e,ke(r.signal).then(()=>`aborted`)]):await e;return t===`aborted`?(this.#t.cancelQueued(o),await this.#e.submit({kind:`cancel-queued`,id:o,reason:`caller aborted`}),N(`任务在排队中被调用方撤回(前台 abort,决策 17)`)):t===`withdrawn`?(await this.#e.submit({kind:`cancel-queued`,id:o,reason:`withdrawn while waiting`}),N(`任务在排队中被抽掉`)):this.#E(o,r,n,a)}return this.#T(o,r,n,a),{taskId:o,label:r.label,status:`queued`,whySuppressed:n}})}async#T(e,t,n=!1,r={childReport:!0}){await this.#t.acquire(e)===`withdrawn`?await this.#e.submit({kind:`cancel-queued`,id:e,reason:`withdrawn`}):this.#E(e,t,n,r)}async#E(e,t,n=!1,r={childReport:!0}){try{return await this.#D(e,t,n,r)}catch{return await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:-1}).catch(()=>void 0),this.#O(e),this.#k(e,t,n,`任务内部错误(见日志)`,`rejected`)}}async#D(e,t,n=!1,r={childReport:!0}){if(!(await this.#e.submit({kind:`transition`,id:e,to:`running`})).changed)return this.#O(e),this.#k(e,t,n,`任务在启动前已取消`,`canceled`);if(this.#C)return await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:-1}).catch(()=>void 0),this.#O(e),this.#k(e,t,n,`会话拆卸发生在启动前`,`rejected`);let i=this.#a({...t,taskId:e,searchEnabled:this.#c,...r},this.#m);this.#s&&i.push(`-e`,this.#s);let a={...process.env,PI_PTC_DEPTH:String(this.#m.depth+1),PI_PTC_TASK_ID:e},o=this.#r(i,a);this.#x.set(e,o);let s=typeof t.timeoutMs==`number`&&t.timeoutMs>0?t.timeoutMs:void 0,c=s?setTimeout(()=>{this.stop(e,`timeout after ${s}ms`)},s):void 0;c?.unref();let l=new De,u=this.#y>0?this.#y:void 0,d=u?setInterval(()=>{l.isStalled(Date.now(),u)&&this.stop(e,`stalled: no activity for ${u}ms`)},Math.min(1e3,u)):void 0;d?.unref();let f=``,p=!1;o.onOutput(e=>{l.push(e),f+=e,f.length>16777216&&(f=f.slice(-16777216),p=!0)});let m=await new Promise(e=>{o.onExit(t=>e(t))});c&&clearTimeout(c),d&&clearInterval(d),this.#x.delete(e);let h=await this.#n.write(e,f),g=F(f),_=g.text||f,v,y;if(!r.childReport)y=`opted-out`;else if(g.toolReport)v=g.toolReport,y=`tool`;else{let e=ge(_);v=e.report??void 0,y=e.channel}let b=v?.usage,x=!b||!b.input&&!b.output&&!b.cost;v&&x&&g.observedUsage&&(v={...v,usage:g.observedUsage}),await this.#e.submit({kind:`attach-report`,id:e,report:v,channel:y,delivery:g.delivery}),await this.#e.submit({kind:`attach-output`,id:e,outputPath:h,truncated:p});let S=await this.#e.submit({kind:`resolve-exit`,id:e,exitCode:m});this.#O(e),this.#N(this.#g,`runtime`);let C=S.record.status===`succeeded`?`fulfilled`:S.record.status===`canceled`?`canceled`:`rejected`,w=S.record.startedAt??0,T=S.record.finishedAt??0;return{status:C,taskId:e,label:t.label,text:_,exitCode:m,started:!0,agentName:t.agent??`generalist`,durationMs:w&&T?T-w:0,usage:v?.usage??g.observedUsage??void 0,observedModel:g.observedModel??void 0,observedProvider:g.observedProvider??void 0,errorMessage:C===`fulfilled`?void 0:S.record.stopReason??`exit code ${m}`,readOnlyTier:t.readOnly??`lenient`,outputPath:h,whySuppressed:n,report:v??void 0,reportChannel:y,delivery:g.delivery,outputTruncated:p}}async stop(e,t){let n=await this.#e.submit({kind:`cancel-queued`,id:e,reason:t});if(n.changed){this.#t.cancelQueued(e);return}if(n.record.status!==`running`)return;await this.#e.submit({kind:`stop`,id:e,reason:t});let r=this.#x.get(e);r&&(r.kill(`SIGTERM`),setTimeout(()=>{this.#x.has(e)&&r.kill(`SIGKILL`)},this.#d).unref())}#O(e){this.#C?this.#t.releaseWithoutPromotion(e):this.#t.release(e)}#k(e,t,n,r,i){return{status:i,taskId:e,label:t.label,text:``,exitCode:-1,started:!1,agentName:t.agent??`generalist`,durationMs:0,errorMessage:r,readOnlyTier:t.readOnly??`lenient`,outputPath:``,whySuppressed:n,reportChannel:`none`,outputTruncated:!1}}isEnding(){return this.#S}readOutput(e){return this.#n.read(e).then(t=>t??this.#A(e))}outputSize(e){return this.#n.size(e).then(t=>{if(t!==void 0)return t;let n=this.#A(e);return n===void 0?void 0:Buffer.byteLength(n,`utf8`)})}readOutputTail(e,t){return this.#n.readTail(e,t).then(n=>{if(n!==void 0)return n;let r=this.#A(e);return r===void 0?void 0:r.slice(-t)})}readArchivedRecord(e){let t=this.#h?m(this.#h,`archive`,`${e}.json.gz`):null;if(!t||!a(t))return Promise.resolve(void 0);try{let e=JSON.parse(T(s(t)).toString(`utf8`));return Promise.resolve({...e,archived:!0})}catch{return Promise.resolve(void 0)}}async readArchivedRecords(){let e=this.#h?m(this.#h,`archive`):null;if(!e||!a(e))return[];let t=[];for(let n of await S(e))if(n.endsWith(`.json.gz`))try{let r=JSON.parse(T(await x(m(e,n))).toString(`utf8`));r&&typeof r.id==`string`&&t.push({...r,archived:!0})}catch{}return t}#A(e){let t=this.#h?m(this.#h,`archive`,`${e}.output.gz`):null;if(t&&a(t))try{return T(s(t)).toString(`utf8`)}catch{return}}async#j(e){let t=m(e,`records`);if(a(t)){for(let e of c(t))if(e.endsWith(`.json`))try{let n=JSON.parse(s(m(t,e),`utf8`));n&&typeof n.id==`string`&&await this.#e.submit({kind:`spawn`,record:n}).catch(()=>void 0)}catch{}}this.#e.subscribe(t=>this.#M(e,t));for(let e of this.#e.list())M(e.status)||e.ownerPid!==void 0&&Ae(e.ownerPid)||await this.#e.submit({kind:`reconcile-lost`,id:e.id,reason:`lost_on_session_restart`}).catch(()=>void 0);this.#N(this.#g,`boot`),this.#L()}async#M(e,t){try{let n=m(e,`records`);o(n,{recursive:!0});let r=m(n,`${t.id}.json`),i=`${r}.tmp`;f(i,JSON.stringify(t,null,2),`utf8`),l(i,r)}catch{}}#N(e,t){let n=this.#e.evictTerminal(e);if(this.#h&&n.length!==0){if(t===`boot`||!this.#_)for(let e of n)this.#P(e);else for(let e of n)this.#F(e)}}#P(e){try{u(m(this.#h,`records`,`${e}.json`)),u(m(this.#h,`tasks`,e),{recursive:!0,force:!0})}catch{}}#F(e){this.#b=this.#b.then(()=>new Promise(t=>{setImmediate(()=>void this.#I(e).then(t,t))})).catch(()=>void 0)}async#I(e){let t=this.#h,n=JSON.parse(s(m(t,`records`,`${e}.json`),`utf8`)),r=await Oe(Buffer.from(JSON.stringify({...n,archivedAt:Date.now()}))),i=m(t,`archive`);await y(i,{recursive:!0}),await w(m(i,`${e}.json.gz.tmp`),r),await C(m(i,`${e}.json.gz.tmp`),m(i,`${e}.json.gz`));let o=m(t,`tasks`,e,`output.log`);if(a(o)){let t=await Oe(await x(o));await w(m(i,`${e}.output.gz.tmp`),t),await C(m(i,`${e}.output.gz.tmp`),m(i,`${e}.output.gz`))}this.#P(e)}#L(){let e=this.#h;if(!e||!this.#_)return;let t=m(e,`archive`);if(!a(t))return;let n=this.#v*864e5,r=Date.now(),i=0;for(let e of c(t)){if(i>=500)break;if(e.endsWith(`.gz`))try{r-d(m(t,e)).mtimeMs>n&&(u(m(t,e)),i++)}catch{}}}async shutdown(){this.#S=!0,this.#C=!0;let e=this.#t.drainWaiters();for(let t of e)await this.#e.submit({kind:`cancel-queued`,id:t,reason:`session shutdown`});for(let[e,t]of this.#x)this.#e.get(e)?.status===`running`&&(await this.#e.submit({kind:`stop`,id:e,reason:`session ended`}),t.kill(`SIGTERM`));await this.#b.catch(()=>void 0)}};const I={MAX_LOG_LINES_EXPANDED:12,VALUE_TREE_MAX_DEPTH:4,VALUE_TREE_MAX_CHILDREN:6,VALUE_TREE_MAX_LINE_CHARS:120},Me=/\x1B\[[0-9:;<=>?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;function Ne(e){return e.replace(Me,``)}function L(e){return Ne(e.replace(/\r/g,``))}const R=I.VALUE_TREE_MAX_LINE_CHARS;function z(e,t=R){if(e.length<=t)return e;let n=t;for(;n>0&&(e.charCodeAt(n)&64512)==56320;)n--;return`${e.slice(0,n)}…`}function B(e,t=0,n=/* @__PURE__ */ new WeakSet){let r=` `.repeat(t);if(t>=I.VALUE_TREE_MAX_DEPTH)return`…`;if(typeof e==`string`)return t===0?e:JSON.stringify(e);if(e===null||typeof e==`number`||typeof e==`boolean`)return String(e);if(Fe(e))return`(无完成值)`;if(typeof e==`object`&&e){if(n.has(e))return`[Circular]`;n.add(e)}if(Array.isArray(e)){let i=e.slice(0,I.VALUE_TREE_MAX_CHILDREN),a=e.length-i.length,o=`[${i.map(e=>JSON.stringify(e)).join(`, `)}]`,s=e.length===0?`[]`:a===0&&i.every(e=>Pe(e))&&o.length<=R?o:`[\n${i.map(e=>z(`${r} ${B(e,t+1,n)}`)).join(`,
16
+ `)}${a>0?`,\n${r} …(余 ${a} 项)`:``}\n${r}]`;return n.delete(e),s}if(typeof e==`object`&&e){let i=Object.entries(e),a=i.slice(0,I.VALUE_TREE_MAX_CHILDREN),o=i.length-a.length,s=`{ ${a.map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)} }`,c=i.length===0?`{}`:o===0&&a.every(([,e])=>Pe(e))&&s.length<=R?s:`{\n${a.map(([e,i])=>z(`${r} ${e}: ${B(i,t+1,n)}`)).join(`,
17
+ `)}${o>0?`,\n${r} …(余 ${o} 项)`:``}\n${r}}`;return n.delete(e),c}return String(e)}function Pe(e){return e===null||[`string`,`number`,`boolean`].includes(typeof e)}function Fe(e){return typeof e==`object`&&!!e&&e.$void===!0}const V=`pi-ptc-output-`;let Ie=!1;function Le(){Ie=!0;let e;try{e=c(O())}catch{return}for(let t of e)if(t.startsWith(V))try{let e=m(O(),t);Date.now()-d(e).mtimeMs>864e5&&u(e,{force:!0})}catch{}}function H(e){let t=e.split(`
20
18
  `),n=Buffer.byteLength(e,`utf8`);if(n<=51200&&t.length<=2e3)return{text:e,truncated:!1};let r=t.slice(-2e3),i=r.join(`
21
19
  `);for(;Buffer.byteLength(i,`utf8`)>51200&&r.length>1;)r=r.slice(Math.max(1,Math.floor(r.length/2))),i=r.join(`
22
- `);let a=Buffer.from(i,`utf8`);a.length>51200&&(i=a.subarray(a.length-51200).toString(`utf8`));let s=p(de(),`${rf}${ne()}.txt`);return o(de(),{recursive:!0}),f(s,e,`utf8`),af||of(),{text:[`…(已截断:省略前 ${t.length-r.length} 行 / ${n-Buffer.byteLength(i,`utf8`)} 字节,全文在 ${s})`,i].join(`
23
- `),truncated:!0,fullOutputPath:s}}function cf(e,t=10){let n=e.filter(e=>!md(e.status)),r=e.filter(e=>md(e.status)).sort((e,t)=>(t.finishedAt??0)-(e.finishedAt??0)).slice(0,t);return[...n,...r]}function lf(e){return e.length>0}function uf(e,t={}){return{id:e.id,status:e.status,...e.label?{label:$d(e.label,120)}:{},...e.finishedAt===void 0?{}:{finishedAt:e.finishedAt},...e.task?{task:$d(e.task,80)}:{},...e.report?.summary?{summary:$d(e.report.summary,100)}:{},...t.archived?{archived:!0}:{},...t.withSession&&e.sessionId?{sessionId:e.sessionId}:{}}}function df(e,t){let n=[],r=2;for(let i of e){if(n.length>=t)break;let e=Buffer.byteLength(JSON.stringify(i),`utf8`)+1;if(r+e>49152)break;n.push(i),r+=e}return n}const ff={ptc_run_code:{name:`ptc_run_code`,description:e=>[`写一段 TypeScript 程序批量调用工具:tools.<name>(args)。支持顶层 await、Promise.all 并行、循环与条件;程序返回值是归约后的结果,中间产物不进上下文。`,e===`codemode_ptc`?`本会话里我从 codemode 脚本可达,模型直走 codemode。`:`什么时候写程序而不是逐个调工具,看系统提示词 <ptc> 节的路由表。程序内可调本会话已启用的同名工具(read / write / edit / grep / find / ls;bash 默认不可用),参数与直接调用该工具完全一致;每次调用返回 Promise,要 await,返回文本结果,失败抛异常。程序内还可调 task_records({ scope: "all" }) 取任务记录(all 含压缩归档)——要挑很多条时在程序里筛完只 return 要的几条。程序内还可调 task_output({ taskId }) 取孩子交回的正文——返回 {text}(孩子的散文,不是原始事件流);text 空时看 status:还在跑就等一会儿再取,别当没产出;收多份正文时读完只 return 汇总。例:const files = await tools.find({ pattern: "*.py" }); for (const f of files) await tools.write({ path: f, content: body });`].join(``)},ptc_workflow:{name:`ptc_workflow`,description:e=>[`结构化的多阶段程序:script 里可用 workflow.log / workflow.phase / workflow.parallel / workflow.pipeline。适合阶段明确的批处理。`,e===`codemode_ptc`?`本会话里我从 codemode 脚本可达。`:`与 ptc_run_code 的取舍看 <ptc> 节的路由表。`].join(``)},pi_task_codemode:{name:`pi_task_codemode`,description:()=>`建一条子代理任务,默认立刻返回 handle(taskId + label);wait:true 时阻塞到终态再返回结果。任务在任务记录里排队,由派发引擎起独立 pi 进程执行;完成后的报告与产出经 ptc_task_output 读取。`},ptc_task_list:{name:`ptc_task_list`,description:()=>`列出在飞的任务与最近完成的任务(默认最近 50 条已完成)。响应给精简条目(id/status/label/finishedAt/任务摘要)与候选总数——总数比返回条数大,说明还有更早的记录没列出来。scope=all 连压缩归档一起列(更全也更慢),status 与 session 可筛。`},ptc_task_output:{name:`ptc_task_output`,description:()=>`按 task_id 读一条任务记录:状态、报告、孩子的正文(text——那是交付物,报告只是摘要)与实测轨迹。正文超长时按截断契约给尾部与全文路径;记录里的 outputPath 指向原始事件流。`},ptc_task_stop:{name:`ptc_task_stop`,description:()=>`按 task_id 叫停任务:排队中的直接抽掉(canceled),在跑的转 stopping。`}},$={task:`孩子要干的活`,agent:`已注册的 agent 名字;省略 = 通用孩子`,agentScope:`agent 定义的查找范围(user / project / both)`,why:`这一刀为什么切出来(调用方自己的话)——它会进孩子的提示词、多花孩子的 token;孩子从 task 里已经能读懂就别传`,model:`覆盖孩子跑的模型`,thinkingLevel:`覆盖孩子的思考档位——孩子的思考 token 是可调的成本项`,wait:`true = 等这个任务完成再返回结果;false = 立刻返回 handle,结果走任务面/通知`,label:`后台任务给人看的标签`,readOnly:`strict = 孩子只有读工具(read/grep/find/ls,搜索开启时含 web_ds_search);lenient = 默认全工具。只需要读的活别给写权限`,timeoutMs:`孩子的运行时长上限(毫秒)——超了按超时收尸;不传 = 不限(与不传时同)`,projectContext:`孩子的项目上下文(AGENTS.md/CLAUDE.md):auto = 照常加载;none = 不加载——注意 none 只关「注入」不关「知识」:文件还在工作目录里,孩子会自己去翻(实测输入只差约 15%,不是省一半);这活不需要项目约定就传 none,要孩子遵守项目规矩就照常传(auto 也可能把项目里的写码规矩套进答案)`},pf=`交付核对(引擎实测)`;function mf(e){let t=e.delivery;if(!t)return``;let n=Object.entries(t.tools),r=n.reduce((e,[,t])=>e+t,0),i=[];if(n.length>0){let e=n.map(([e,t])=>`${e}×${t}`).join(` `),r=t.paths.length>0?`(${t.paths.slice(0,5).join(`、`)}${t.paths.length>5?` 等 ${t.paths.length} 条`:``})`:``;i.push(`工具 ${e}${r}`)}else i.push(`没调用任何工具`);i.push(`报错 ${t.errors}`),i.push(`正文 ${t.textChars} 字`);let a=e.findings??0;return i.push(`报告 ${a} 条(${e.channel??`none`})`),r===0&&a===0&&t.textChars===0?`${pf}:零产出——${i.join(` · `)}。这孩子的结论没有依据:重派它,或明说缺口,别替它补数。`:`${pf}:${i.join(` · `)}`}const hf=[{id:`create-a-task`,name:`派一个子代理`,when:`材料多、主题互不相干、每份都要读一堆材料时派——父一个人扛会算错(实测 92%→100%,n=3);成本 10 倍上下,一件能算完的活别派`,how:{full_ptc:`tools.pi_task_ptc({ task, label? })(程序内)——task 是孩子的唯一规格(写死路径/命令/交付物格式);要报告就点名 child report 的 JSON 块(summary/findings),别自创报告格式`,codemode_ptc:`tools.pi_task_codemode({ task, label? })(脚本内)——task 是孩子的唯一规格(写死路径/命令/交付物格式);要报告就点名 child report 的 JSON 块(summary/findings),别自创报告格式;汇总前核对孩子产出(delivery),零产出就重派别补数`},detail:`docs/routes/create-a-task.md`},{id:`run-one-program`,name:`批量调工具的一段程序`,when:`连续多次工具调用、结果要过滤/归约后再看`,how:{full_ptc:`ptc_run_code({ code, description })`,codemode_ptc:`不适用——写程序是 full_ptc 面的编排能力;本面用 codemode 编排、pi_task_codemode 派任务`},detail:`docs/routes/run-one-program.md`},{id:`run-a-phased-workflow`,name:`分阶段 workflow`,when:`批处理有明确阶段,要阶段性可见进度`,how:{full_ptc:`ptc_workflow({ meta, script, args? })`,codemode_ptc:`不适用——同 run-one-program:workflow 是 full_ptc 的编排能力`},detail:`docs/routes/run-a-phased-workflow.md`},{id:`use-the-built-in-tools`,name:`直接用内置工具`,when:`单次调用就够,或每步都要模型判断(写操作、审批敏感)`,how:{full_ptc:`程序内可调同名工具;逐个直调走 pi 自己的工具`,codemode_ptc:`脚本内 tools.<内置名> 直接调`},detail:`docs/routes/use-the-built-in-tools.md`},{id:`report-what-you-did`,name:`交报告`,when:`子代理收工:结论要有证据、副作用与用量要可核对`,how:{full_ptc:`孩子的契约:最终消息末尾 fenced JSON(summary/findings/files_touched/usage);宿主自动解析`,codemode_ptc:`同左——契约在孩子的追加提示词里,与 surface 无关`},detail:`docs/routes/report-what-you-did.md`},{id:`reach-the-web`,name:`上网查资料`,when:`需要网页搜索、抓页面、页内找内容——判断力在干活的子代理侧`,how:{full_ptc:`派子代理(pi_task_ptc),孩子用 web_ds_search`,codemode_ptc:`同左——搜索只在子代理进程里注册,父会话没有这个工具`},detail:`docs/routes/reach-the-web.md`},{id:`manage-a-task`,name:`管一个任务`,when:`要知道孩子跑得怎样、读它的产出、或叫停它`,how:{full_ptc:`ptc_task_list / ptc_task_output / ptc_task_stop(模型直调)——产出里的 delivery 是引擎实测轨迹`,codemode_ptc:`同左(模型直调;脚本经结构化返回)——产出里的 delivery 是引擎实测轨迹`},detail:`docs/routes/manage-a-task.md`}];function gf(e){if(e.report&&e.reportChannel&&e.reportChannel!==`none`){let t=(e.report.findings??[]).slice(0,5).map(e=>`- ${e.what}${e.evidence?`(证据:${e.evidence})`:``}`).join(`
20
+ `);let a=Buffer.from(i,`utf8`);a.length>51200&&(i=a.subarray(a.length-51200).toString(`utf8`));let s=m(O(),`${V}${v()}.txt`);return o(O(),{recursive:!0}),f(s,e,`utf8`),Ie||Le(),{text:[`…(已截断:省略前 ${t.length-r.length} 行 / ${n-Buffer.byteLength(i,`utf8`)} 字节,全文在 ${s})`,i].join(`
21
+ `),truncated:!0,fullOutputPath:s}}function Re(e,t=10){let n=e.filter(e=>!M(e.status)),r=e.filter(e=>M(e.status)).sort((e,t)=>(t.finishedAt??0)-(e.finishedAt??0)).slice(0,t);return[...n,...r]}function ze(e){return e.length>0}function Be(e,t={}){return{id:e.id,status:e.status,...e.label?{label:z(e.label,120)}:{},...e.finishedAt===void 0?{}:{finishedAt:e.finishedAt},...e.task?{task:z(e.task,80)}:{},...e.report?.summary?{summary:z(e.report.summary,100)}:{},...t.archived?{archived:!0}:{},...t.withSession&&e.sessionId?{sessionId:e.sessionId}:{}}}function Ve(e,t){let n=[],r=2;for(let i of e){if(n.length>=t)break;let e=Buffer.byteLength(JSON.stringify(i),`utf8`)+1;if(r+e>49152)break;n.push(i),r+=e}return n}const U={ptc_run_code:{name:`ptc_run_code`,description:e=>[`写一段 TypeScript 程序批量调用工具:tools.<name>(args)。支持顶层 await、Promise.all 并行、循环与条件;程序返回值是归约后的结果,中间产物不进上下文。`,e===`codemode_ptc`?`本会话里我从 codemode 脚本可达,模型直走 codemode。`:`什么时候写程序而不是逐个调工具,看系统提示词 <ptc> 节的路由表。程序内可调本会话已启用的同名工具(read / write / edit / grep / find / ls;bash 默认不可用),参数与直接调用该工具完全一致;每次调用返回 Promise,要 await,返回文本结果,失败抛异常。程序内还可调 task_records({ scope: "all" }) 取任务记录(all 含压缩归档)——要挑很多条时在程序里筛完只 return 要的几条。程序内还可调 task_output({ taskId }) 取孩子交回的正文——返回 {text}(孩子的散文,不是原始事件流);text 空时看 status:还在跑就等一会儿再取,别当没产出;收多份正文时读完只 return 汇总。例:const files = await tools.find({ pattern: "*.py" }); for (const f of files) await tools.write({ path: f, content: body });`].join(``)},ptc_workflow:{name:`ptc_workflow`,description:e=>[`结构化的多阶段程序:script 里可用 workflow.log / workflow.phase / workflow.parallel / workflow.pipeline。适合阶段明确的批处理。`,e===`codemode_ptc`?`本会话里我从 codemode 脚本可达。`:`与 ptc_run_code 的取舍看 <ptc> 节的路由表。`].join(``)},pi_task_codemode:{name:`pi_task_codemode`,description:()=>`建一条子代理任务,默认立刻返回 handle(taskId + label);wait:true 时阻塞到终态再返回结果。任务在任务记录里排队,由派发引擎起独立 pi 进程执行;完成后的报告与产出经 ptc_task_output 读取。`},ptc_task_list:{name:`ptc_task_list`,description:()=>`列出在飞的任务与最近完成的任务(默认最近 50 条已完成)。响应给精简条目(id/status/label/finishedAt/任务摘要)与候选总数——总数比返回条数大,说明还有更早的记录没列出来。scope=all 连压缩归档一起列(更全也更慢),status 与 session 可筛。`},ptc_task_output:{name:`ptc_task_output`,description:()=>`按 task_id 读一条任务记录:状态、报告、孩子的正文(text——那是交付物,报告只是摘要)与实测轨迹。正文超长时按截断契约给尾部与全文路径;记录里的 outputPath 指向原始事件流。`},ptc_task_stop:{name:`ptc_task_stop`,description:()=>`按 task_id 叫停任务:排队中的直接抽掉(canceled),在跑的转 stopping。`}},W={task:`孩子要干的活`,agent:`已注册的 agent 名字;省略 = 通用孩子`,agentScope:`agent 定义的查找范围(user / project / both)`,why:`这一刀为什么切出来(调用方自己的话)——它会进孩子的提示词、多花孩子的 token;孩子从 task 里已经能读懂就别传`,model:`覆盖孩子跑的模型`,thinkingLevel:`覆盖孩子的思考档位——孩子的思考 token 是可调的成本项`,wait:`true = 等这个任务完成再返回结果;false = 立刻返回 handle,结果走任务面/通知`,label:`后台任务给人看的标签`,readOnly:`strict = 孩子只有读工具(read/grep/find/ls,搜索开启时含 web_ds_search);lenient = 默认全工具。只需要读的活别给写权限`,timeoutMs:`孩子的运行时长上限(毫秒)——超了按超时收尸;不传 = 不限(与不传时同)`,projectContext:`孩子的项目上下文(AGENTS.md/CLAUDE.md):auto = 照常加载;none = 不加载——注意 none 只关「注入」不关「知识」:文件还在工作目录里,孩子会自己去翻(实测输入只差约 15%,不是省一半);这活不需要项目约定就传 none,要孩子遵守项目规矩就照常传(auto 也可能把项目里的写码规矩套进答案)`},He=`交付核对(引擎实测)`;function Ue(e){let t=e.delivery;if(!t)return``;let n=Object.entries(t.tools),r=n.reduce((e,[,t])=>e+t,0),i=[];if(n.length>0){let e=n.map(([e,t])=>`${e}×${t}`).join(` `),r=t.paths.length>0?`(${t.paths.slice(0,5).join(`、`)}${t.paths.length>5?` 等 ${t.paths.length} 条`:``})`:``;i.push(`工具 ${e}${r}`)}else i.push(`没调用任何工具`);i.push(`报错 ${t.errors}`),i.push(`正文 ${t.textChars} 字`);let a=e.findings??0;return i.push(`报告 ${a} 条(${e.channel??`none`})`),r===0&&a===0&&t.textChars===0?`${He}:零产出——${i.join(` · `)}。这孩子的结论没有依据:重派它,或明说缺口,别替它补数。`:`${He}:${i.join(` · `)}`}const We=[{id:`create-a-task`,name:`派一个子代理`,when:`材料多、主题互不相干、每份都要读一堆材料时派——父一个人扛会算错(实测 92%→100%,n=3);成本 10 倍上下,一件能算完的活别派`,how:{full_ptc:`tools.pi_task_ptc({ task, label? })(程序内)——task 是孩子的唯一规格(写死路径/命令/交付物格式);要报告就点名 child report 的 JSON 块(summary/findings),别自创报告格式`,codemode_ptc:`tools.pi_task_codemode({ task, label? })(脚本内)——task 是孩子的唯一规格(写死路径/命令/交付物格式);要报告就点名 child report 的 JSON 块(summary/findings),别自创报告格式;汇总前核对孩子产出(delivery),零产出就重派别补数`},detail:`docs/routes/create-a-task.md`},{id:`run-one-program`,name:`批量调工具的一段程序`,when:`连续多次工具调用、结果要过滤/归约后再看`,how:{full_ptc:`ptc_run_code({ code, description })`,codemode_ptc:`不适用——写程序是 full_ptc 面的编排能力;本面用 codemode 编排、pi_task_codemode 派任务`},detail:`docs/routes/run-one-program.md`},{id:`run-a-phased-workflow`,name:`分阶段 workflow`,when:`批处理有明确阶段,要阶段性可见进度`,how:{full_ptc:`ptc_workflow({ meta, script, args? })`,codemode_ptc:`不适用——同 run-one-program:workflow 是 full_ptc 的编排能力`},detail:`docs/routes/run-a-phased-workflow.md`},{id:`use-the-built-in-tools`,name:`直接用内置工具`,when:`单次调用就够,或每步都要模型判断(写操作、审批敏感)`,how:{full_ptc:`程序内可调同名工具;逐个直调走 pi 自己的工具`,codemode_ptc:`脚本内 tools.<内置名> 直接调`},detail:`docs/routes/use-the-built-in-tools.md`},{id:`report-what-you-did`,name:`交报告`,when:`子代理收工:结论要有证据、副作用与用量要可核对`,how:{full_ptc:`孩子的契约:最终消息末尾 fenced JSON(summary/findings/files_touched/usage);宿主自动解析`,codemode_ptc:`同左——契约在孩子的追加提示词里,与 surface 无关`},detail:`docs/routes/report-what-you-did.md`},{id:`reach-the-web`,name:`上网查资料`,when:`需要网页搜索、抓页面、页内找内容——判断力在干活的子代理侧`,how:{full_ptc:`派子代理(pi_task_ptc),孩子用 web_ds_search`,codemode_ptc:`同左——搜索只在子代理进程里注册,父会话没有这个工具`},detail:`docs/routes/reach-the-web.md`},{id:`manage-a-task`,name:`管一个任务`,when:`要知道孩子跑得怎样、读它的产出、或叫停它`,how:{full_ptc:`ptc_task_list / ptc_task_output / ptc_task_stop(模型直调)——产出里的 delivery 是引擎实测轨迹`,codemode_ptc:`同左(模型直调;脚本经结构化返回)——产出里的 delivery 是引擎实测轨迹`},detail:`docs/routes/manage-a-task.md`}];function Ge(e){if(e.report&&e.reportChannel&&e.reportChannel!==`none`){let t=(e.report.findings??[]).slice(0,5).map(e=>`- ${e.what}${e.evidence?`(证据:${e.evidence})`:``}`).join(`
24
22
  `);return`产出超过截断阈值({bytes} 字节)。先看孩子的报告(归约层):{report}——响应里的 output 是截断后的尾部;报告没收录的完整原文用 read 读记录上的 outputPath。`.replace(`{bytes}`,String(e.bytes)).replace(`{report}`,[`summary: ${e.report.summary}`,t].filter(Boolean).join(`
25
- `))}return`产出超过截断阈值({bytes} 字节),且孩子未交报告(reportChannel=none,散文可信度存疑)。响应里的 output 是截断后的尾部;完整原文用 read 读记录上的 outputPath。`.replace(`{bytes}`,String(e.bytes))}function _f(e){return[`<compacted-tasks>`,`对话刚被压缩——启动这些任务的消息已经不在上下文里了,但任务还在跑或已经跑完。用 ptc_task_list 看全部(scope=all 连压缩归档一起列),用 ptc_task_output 取产出(给的是孩子的正文,不是原始事件流)。`,...e.map(e=>`- ${e.id}${e.label?` (${e.label})`:``}: ${e.status}`),`</compacted-tasks>`].join(`
26
- `)}function vf(e){return[`<bg-task-notifications>`,...e.map(e=>`- task ${e.taskId}${e.label?` (${e.label})`:``}: ${e.status}${e.stopReason?` — ${e.stopReason}`:``}`),`</bg-task-notifications>`].join(`
27
- `)}function yf(e){return Math.ceil(e.length/2)}const bf={full_ptc:`批量调工具默认先写程序(ptc_run_code);单次调用或逐步判断、审批敏感的才直连。派不派子代理自己判断——第一行写了代价。`,codemode_ptc:`编排写 codemode 脚本;批量派活经脚本内的 pi_task_codemode;要查/停任务用任务面三工具。派不派自己判断——路由表第一行写了代价。`};function xf(e,t,n=!0){let r=hf.map(n=>`- ${n.name} — ${n.when}。这面怎么走:${n.how[e]}。细节:${t?n.detail.split(`/`).pop():n.detail}`),i=[`<ptc>`,...n?[bf[e]]:[],...t?[`详情目录:${t}`]:[],`路由表(一条一行,详情按需 read):`,...r,`</ptc>`].join(`
28
- `),a=yf(i);return a>560&&(i+=`\n> WARNING: index over token budget (${a} > 560); move detail into docs/routes/*.md`),i}function Sf(e,t={},n=[]){let r=t.scope===`all`?`all`:`recent`,i=Math.min(Math.max(t.limit??50,1),200),a=(r===`all`?[...e.list(),...n]:e.list()).filter(e=>!(t.status&&e.status!==t.status||t.session&&e.sessionId!==t.session)),o=cf(a,i),s=t.session!==void 0;return{scope:r,total:a.length,tasks:df(o.map(e=>uf(e,{archived:`archived`in e,withSession:s})),i)}}function Cf(e){return lf(e.list())}function wf(e){let t=e.list(),n=t.filter(e=>!md(e.status)),r=t.filter(e=>md(e.status)).sort((e,t)=>(t.finishedAt??0)-(e.finishedAt??0)).slice(0,5);if(n.length!==0||r.length!==0)return _f([...n,...r].map(e=>({id:e.id,status:e.status,label:e.label})))}async function Tf(e,t){let n=t.id,r=await e.outputSize(n);if(r===void 0)return{};let i=await e.readOutputTail(n,51200)??``,a=Bd(i).text;return!a&&r>51200&&(a=Bd(await e.readOutput(n)??``).text),a?{text:sf(a).text}:{output:sf(i).text,guidance:gf({bytes:r,report:t.report,reportChannel:t.reportChannel??`none`})}}function Ef(e){return(t,n,r,i)=>{let a=i.args,o=new fe,s=e===`workflow`?`workflow · ${a.meta?.name??``}`:a.description??`程序`;o.addChild(new pe(n.isPartial?`${s} …`:s));let c=t.details;if(!n.isPartial&&c){let e=[c.status,c.truncated?`已截断`:``,c.fullOutputPath?`全文在 ${c.fullOutputPath}`:``].filter(Boolean).join(` · `);o.addChild(new pe(e))}if(n.expanded&&!n.isPartial)for(let e of t.content){if(e.type!==`text`)continue;let t=e.text.split(`
29
- `),n=t.slice(0,Jd.MAX_LOG_LINES_EXPANDED);for(let e of n)o.addChild(new pe(e));t.length>n.length&&o.addChild(new pe(`…(共 ${t.length} 行,省略 ${t.length-n.length} 行)`))}return o}}const Df=`ptc-tasks`,Of={queued:{glyph:`○`,color:`muted`},running:{glyph:`●`,color:`accent`},stopping:{glyph:`◐`,color:`warning`},succeeded:{glyph:`✓`,color:`success`},failed:{glyph:`✗`,color:`error`},canceled:{glyph:`⊘`,color:`muted`},lost:{glyph:`?`,color:`dim`}},kf=[`queued`,`running`,`stopping`];function Af(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function jf(e,t,n){let r=n?e.filter(e=>e.sessionId===n):e,i=r.filter(e=>kf.includes(e.status));if(i.length===0)return[];let a=e=>r.filter(t=>t.status===e).length,o=[t.fg(`accent`,`Tasks · ${i.length} running · ${a(`succeeded`)} succeeded · ${a(`failed`)} failed`)],s=i.slice(0,6);for(let[e,n]of s.entries()){let r=Of[n.status],a=$d(Zd(n.label||n.task).replace(/\s+/g,` `).trim(),48),c=e===s.length-1&&i.length<=6;o.push(t.fg(`dim`,c?`└─ `:`├─ `)+t.fg(r.color,`${r.glyph} ${a}`)+(n.startedAt?t.fg(`dim`,` · ${Af(n.startedAt)}`):``))}return i.length>6&&o.push(t.fg(`dim`,`└─ …${i.length-6} more`)),o}function Mf(e){let{ui:t,source:n,sessionId:r}=e;if(!t)return{dispose(){}};let i=!1,a=()=>{if(i)return;let e=jf(n.list(),t.theme,r);t.setWidget(Df,e.length>0?e:void 0)};return n.subscribe(a),a(),{dispose(){i=!0,t.setWidget(Df,void 0)}}}const Nf={min:1,max:50};function Pf(e){return e===402?`账号余额不足:充值后再试`:e===408||e===429||e>=500?`临时性失败:稍后重试`:e>=400?`请求不合法:修改请求后再试(原样重试无益)`:e===0?`网络不可达:检查连接后重试`:``}function Ff(e,t){return t?e.split(t).join(`[REDACTED]`):e}async function If(e,t,n){let r;try{r=await fetch(`https://api.deepseek.com/v1/tools${e}`,{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(t),signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,status:0,error:`network: ${e instanceof Error?e.message:String(e)}`}}let i=await r.text();if(!r.ok){let e=Ff(i.slice(0,300),n),t=Pf(r.status);return{ok:!1,status:r.status,error:t?`${e}(${t})`:e}}try{return{ok:!0,value:JSON.parse(i)}}catch{return{ok:!1,status:r.status,error:`bad json: ${Ff(i.slice(0,200),n)}`}}}function Lf(e){let t=e?.results??e?.data??[];return Array.isArray(t)?t.map(e=>{let t=e;return{title:String(t.title??``),url:String(t.url??t.link??``),snippet:t.snippet===void 0?void 0:String(t.snippet),summary:t.summary===void 0?void 0:String(t.summary),rank:typeof t.rank==`number`?t.rank:typeof t.rerank==`number`?t.rerank:void 0,date:t.date===void 0?void 0:String(t.date)}}).filter(e=>e.url.length>0):[]}function Rf(e){return{id:`deepseek`,async search(t,n){let r=await If(`/search`,{query:t,count:n?.count??10},e);return r.ok?{ok:!0,value:Lf(r.value)}:r},async open(t){let n=await If(`/fetch`,{url:t},e);if(!n.ok)return n;let r=n.value;return{ok:!0,value:Ff(String(r.content??r.text??r.markdown??``),e)}}}}function zf(e){let t=0,n=0,r=e<=0;return{tryAcquire(){return r?!0:n+t>=e?!1:(t++,!0)},release(e=!0){r||(t=Math.max(0,t-1),e&&n++)},remaining(){return r?1/0:Math.max(0,e-n-t)}}}function Bf(e,t){try{let n=new URL(e),r=new URL(t);return n.host!==r.host||n.protocol!==r.protocol||n.pathname.replace(/\/$/,``)!==r.pathname.replace(/\/$/,``)?!1:n.search===r.search||n.search===``||r.search===``}catch{return e===t}}function Vf(){let e=[],t=/* @__PURE__ */ new Map,n=0,r=0,i=()=>{for(;r>4e5;){let i=t.keys().next();if(!i.done){let e=t.get(i.value)?.length??0;n-=e,r-=e,t.delete(i.value);continue}let a=e.shift();if(!a)break;r-=a.chars}for(;e.length>5;){let t=e.shift();if(!t)break;r-=t.chars}};return{remember(t,n){e.push({query:t,matches:n,textByUrl:/* @__PURE__ */ new Map,chars:t.length}),i()},storeText(a,o){for(let t=e.length-1;t>=0;t--){let n=e[t],s=n.matches.find(e=>Bf(e.url,a));if(s){n.textByUrl.set(s.url,o),n.chars+=o.length,r+=o.length,i();return}}n-=t.get(a)?.length??0,t.set(a,o),n+=o.length,r+=o.length,i()},lookup(n){for(let t=e.length-1;t>=0;t--)for(let[r,i]of e[t].textByUrl)if(Bf(r,n))return i;for(let[e,r]of[...t].reverse())if(Bf(e,n))return r}}}const Hf=/* @__PURE__ */ new Map;function Uf(e){let t=e;try{t=new URL(e).host}catch{}let n=(Hf.get(t)??Promise.resolve()).then(()=>new Promise(e=>setTimeout(e,50)));return Hf.set(t,n),n}function Wf(e){return[`- ${e.title||`(no title)`}`,` url: ${e.url}`,e.snippet?` snippet: ${e.snippet}`:``,e.date?` date: ${e.date}`:``].filter(Boolean).join(`
30
- `)}function Gf(e,t){let n=[],r=[],i=0;for(let a of e){let e=Wf(a);n.length>0&&i+e.length>t?r.push(a):(n.push(a),i+=e.length+1)}let a=n.map(Wf);return r.length>0&&a.push(`(预算内放不下的 ${r.length} 条按排名整条丢弃:${r.map(e=>e.url).join(`、`)}——要哪个用 open 按 url 抓)`),a.join(`
31
- `)}async function Kf(e,t){let n=t.textBudgetChars??12e3;if(e.kind===`search`){let r=Math.min(Nf.max,Math.max(Nf.min,e.count??10));if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};let i=await t.provider.search(e.query,{count:r});return i.ok?(t.quota.release(i.value.length>0),t.memory.remember(e.query,i.value),i.value.length===0?{ok:!0,text:`「${e.query}」没有命中。`}:{ok:!0,text:Zd(Gf(i.value,n))}):(t.quota.release(!1),{ok:!1,error:`search 失败(HTTP ${i.status}):${i.error}`})}if(e.kind===`open`){let r=t.memory.lookup(e.url);if(r!==void 0)return{ok:!0,text:Zd(`(记忆命中,未发请求)\n${r.slice(0,n)}`)};if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};await Uf(e.url);let i=await t.provider.open(e.url);return i.ok?(t.quota.release(i.value.length>0),t.memory.storeText(e.url,i.value),{ok:!0,text:Zd(i.value.slice(0,n))}):(t.quota.release(!1),{ok:!1,error:`open 失败(HTTP ${i.status}):${i.error}`})}let r;try{r=new RegExp(e.pattern,`i`)}catch{return{ok:!1,error:`非法正则:${e.pattern}`}}let i=await qf(e.url,t);if(!i.ok)return i;let a=i.text.split(`
32
- `).map((e,t)=>({line:e,index:t})).filter(({line:e})=>r.test(e));return{ok:!0,text:Zd(a.length>0?a.slice(0,50).map(({line:e,index:t})=>`${t+1}: ${e}`).join(`
33
- `):`(页内无匹配行)`).slice(0,n)}}async function qf(e,t){let n=t.memory.lookup(e);if(n!==void 0)return{ok:!0,text:n};if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};await Uf(e);let r=await t.provider.open(e);return r.ok?(t.quota.release(r.value.length>0),t.memory.storeText(e,r.value),{ok:!0,text:r.value}):(t.quota.release(!1),{ok:!1,error:`open 失败(HTTP ${r.status}):${r.error}`})}const Jf=j({action:B([I(`search`),I(`open`),I(`find`)]),query:A(z({description:`search:搜索词`})),url:A(z({description:`open/find:目标页面 url`})),pattern:A(z({description:`find:页内行匹配(正则)`})),count:A(Gt({minimum:1,maximum:50,description:`search:条数 1–50,默认 10`}))});function Yf(e){return{name:`web_ds_search`,label:`联网搜索`,description:`联网能力(三动作):search 概览(title/url/snippet)· open 抓整页 · find 页内行匹配。open/find 命中最近记忆则免费。配额按每进程计。`,parameters:Jf,execute:async(t,n)=>{let r=n.action===`search`?{kind:`search`,query:n.query??``,count:n.count}:n.action===`open`?{kind:`open`,url:n.url??``}:{kind:`find`,url:n.url??``,pattern:n.pattern??``};if(r.kind===`search`&&r.query===``)return{content:[{type:`text`,text:`search 动作需要 query`}],details:void 0,isError:!0};if(r.kind!==`search`&&r.url===``)return{content:[{type:`text`,text:`${r.kind} 动作需要 url`}],details:void 0,isError:!0};let i=await Kf(r,e);return{content:[{type:`text`,text:i.ok?i.text:i.error}],details:void 0,isError:!i.ok}}}}const Xf=`pi-ptc-subagents`,Zf=[`Added`,`Changed`,`Fixed`];function Qf(e){if(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e))return;let t=e.split(`.`).map(Number);return(t[0]??0)*0xe8d4a51000+(t[1]??0)*1e6+(t[2]??0)}function $f(e){let t=[];for(let n of e.split(/^## /m).slice(1)){let e=/^\[(\d+\.\d+\.\d+)\]/.exec(n)?.[1];if(!e)continue;let r=[],i=!1,a=[],o=()=>{a.length>0&&r.push(a.join(` `)),a=[]};for(let e of n.split(`
34
- `)){let t=/^###\s+(.+)$/.exec(e);t?(o(),i=Zf.includes(t[1]?.trim()??``)):i&&(e.startsWith(`- `)?(o(),a=[e.slice(2).trim()]):a.length>0&&e.trim().length>0?a.push(e.trim()):o())}o(),t.push({version:e,bullets:r})}return t}function ep(e){let t=/^\*\*(.+?)\*\*/.exec(e);if(t)return fp(dp(t[1]??``).replace(/\.$/,``));let n=/(?<!\d)\.(?=\s)/.exec(e);return fp(dp(n?e.slice(0,n.index+1):e).replace(/\.$/,``))}function tp(e,t,n){let r=Qf(t),i=Qf(n);if(r===void 0||i===void 0)return[];let a=[];for(let t of e){let e=Qf(t.version);if(!(e===void 0||e<=r||e>i))for(let e of t.bullets)a.push(ep(e))}return a}function np(e,t){if(!e.hasUI||typeof e.ui?.notify!=`function`)return;let n=t??ip();if(!n)return;let r=Qf(n.version);if(r===void 0)return;let i=cp(n.statePath),a=Qf(i);if(a===r||a!==void 0&&a>r||!lp(n.statePath,n.version))return;let o=$f(up(n.changelogPath)),s=a===void 0?ap(o,n.version):i;if(s===void 0)return;let c=tp(o,s,n.version);e.ui.notify(op(a===void 0?void 0:i,n.version,c,sp(n.repository)),`info`)}function rp(e=import.meta.url){for(let t of[`..`,`../../..`])try{let n=ue(new URL(`${t}/`,e)).replace(/[\\/]+$/,``),r=JSON.parse(s(p(n,`package.json`),`utf8`));if(r.name!==Xf||!r.version)continue;return{dir:n,version:r.version,repository:typeof r.repository==`string`?r.repository:r.repository?.url}}catch{}}function ip(){let e=rp();if(e)return{version:e.version,repository:e.repository,changelogPath:p(e.dir,`CHANGELOG.md`),statePath:p(i(),Xf,`last-seen-version.json`)}}function ap(e,t){let n=Qf(t);if(n===void 0)return;let r;for(let t of e){let e=Qf(t.version);e===void 0||e>=n||(r===void 0||e>(Qf(r)??0))&&(r=t.version)}return r}function op(e,t,n,r){let i=[`${Xf} ${t}`];if(e!==void 0&&i.push(`Updated from ${e}.`),n.length>0){i.push(``,`What's new:`);for(let e of n.slice(0,5))i.push(`- ${e}`);n.length>5&&i.push(`...and ${n.length-5} more`)}return r&&i.push(``,`Changelog: ${r}`),i.join(`
35
- `)}function sp(e){if(!e)return;let t=e.replace(/^git\+/,``).replace(/\.git$/,``);return t.startsWith(`https://github.com/`)?`${t}/blob/main/CHANGELOG.md`:void 0}function cp(e){try{let t=JSON.parse(s(e,`utf8`));return typeof t.version==`string`?t.version:void 0}catch{return}}function lp(e,t){try{return o(ee(e),{recursive:!0}),f(e,JSON.stringify({version:t})),!0}catch{return!1}}function up(e){try{return s(e,`utf8`)}catch{return``}}function dp(e){return e.replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*/g,``).trim()}function fp(e){if(e.length<=200)return e;let t=e.slice(0,200),n=t.lastIndexOf(` `);return`${t.slice(0,n>0?n:200).trimEnd()}…`}function pp(e){let t;t=e.status===`fulfilled`?(e.logs.length>0?[...e.logs,ef(e.value)]:[ef(e.value)]).join(`
23
+ `))}return`产出超过截断阈值({bytes} 字节),且孩子未交报告(reportChannel=none,散文可信度存疑)。响应里的 output 是截断后的尾部;完整原文用 read 读记录上的 outputPath。`.replace(`{bytes}`,String(e.bytes))}function Ke(e){return[`<compacted-tasks>`,`对话刚被压缩——启动这些任务的消息已经不在上下文里了,但任务还在跑或已经跑完。用 ptc_task_list 看全部(scope=all 连压缩归档一起列),用 ptc_task_output 取产出(给的是孩子的正文,不是原始事件流)。`,...e.map(e=>`- ${e.id}${e.label?` (${e.label})`:``}: ${e.status}`),`</compacted-tasks>`].join(`
24
+ `)}function qe(e){return[`<bg-task-notifications>`,...e.map(e=>`- task ${e.taskId}${e.label?` (${e.label})`:``}: ${e.status}${e.stopReason?` — ${e.stopReason}`:``}`),`</bg-task-notifications>`].join(`
25
+ `)}function Je(e){return Math.ceil(e.length/2)}const Ye={full_ptc:`批量调工具默认先写程序(ptc_run_code);单次调用或逐步判断、审批敏感的才直连。派不派子代理自己判断——第一行写了代价。`,codemode_ptc:`编排写 codemode 脚本;批量派活经脚本内的 pi_task_codemode;要查/停任务用任务面三工具。派不派自己判断——路由表第一行写了代价。`};function Xe(e,t,n=!0){let r=We.map(n=>`- ${n.name} — ${n.when}。这面怎么走:${n.how[e]}。细节:${t?n.detail.split(`/`).pop():n.detail}`),i=[`<ptc>`,...n?[Ye[e]]:[],...t?[`详情目录:${t}`]:[],`路由表(一条一行,详情按需 read):`,...r,`</ptc>`].join(`
26
+ `),a=Je(i);return a>560&&(i+=`\n> WARNING: index over token budget (${a} > 560); move detail into docs/routes/*.md`),i}function Ze(e,t={},n=[]){let r=t.scope===`all`?`all`:`recent`,i=Math.min(Math.max(t.limit??50,1),200),a=(r===`all`?[...e.list(),...n]:e.list()).filter(e=>!(t.status&&e.status!==t.status||t.session&&e.sessionId!==t.session)),o=Re(a,i),s=t.session!==void 0;return{scope:r,total:a.length,tasks:Ve(o.map(e=>Be(e,{archived:`archived`in e,withSession:s})),i)}}function Qe(e){return ze(e.list())}function $e(e){let t=e.list(),n=t.filter(e=>!M(e.status)),r=t.filter(e=>M(e.status)).sort((e,t)=>(t.finishedAt??0)-(e.finishedAt??0)).slice(0,5);if(n.length!==0||r.length!==0)return Ke([...n,...r].map(e=>({id:e.id,status:e.status,label:e.label})))}async function et(e,t){let n=t.id,r=await e.outputSize(n);if(r===void 0)return{};let i=await e.readOutputTail(n,51200)??``,a=F(i).text;return!a&&r>51200&&(a=F(await e.readOutput(n)??``).text),a?{text:H(a).text}:{output:H(i).text,guidance:Ge({bytes:r,report:t.report,reportChannel:t.reportChannel??`none`})}}function tt(e){return(t,n,r,i)=>{let a=i.args,o=new k,s=e===`workflow`?`workflow · ${a.meta?.name??``}`:a.description??`程序`;o.addChild(new A(n.isPartial?`${s} …`:s));let c=t.details;if(!n.isPartial&&c){let e=[c.status,c.truncated?`已截断`:``,c.fullOutputPath?`全文在 ${c.fullOutputPath}`:``].filter(Boolean).join(` · `);o.addChild(new A(e))}if(n.expanded&&!n.isPartial)for(let e of t.content){if(e.type!==`text`)continue;let t=e.text.split(`
27
+ `),n=t.slice(0,I.MAX_LOG_LINES_EXPANDED);for(let e of n)o.addChild(new A(e));t.length>n.length&&o.addChild(new A(`…(共 ${t.length} 行,省略 ${t.length-n.length} 行)`))}return o}}const nt=`ptc-tasks`,rt={queued:{glyph:`○`,color:`muted`},running:{glyph:`●`,color:`accent`},stopping:{glyph:`◐`,color:`warning`},succeeded:{glyph:`✓`,color:`success`},failed:{glyph:`✗`,color:`error`},canceled:{glyph:`⊘`,color:`muted`},lost:{glyph:`?`,color:`dim`}},it=[`queued`,`running`,`stopping`];function at(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function ot(e,t,n){let r=n?e.filter(e=>e.sessionId===n):e,i=r.filter(e=>it.includes(e.status));if(i.length===0)return[];let a=e=>r.filter(t=>t.status===e).length,o=[t.fg(`accent`,`Tasks · ${i.length} running · ${a(`succeeded`)} succeeded · ${a(`failed`)} failed`)],s=i.slice(0,6);for(let[e,n]of s.entries()){let r=rt[n.status],a=z(L(n.label||n.task).replace(/\s+/g,` `).trim(),48),c=e===s.length-1&&i.length<=6;o.push(t.fg(`dim`,c?`└─ `:`├─ `)+t.fg(r.color,`${r.glyph} ${a}`)+(n.startedAt?t.fg(`dim`,` · ${at(n.startedAt)}`):``))}return i.length>6&&o.push(t.fg(`dim`,`└─ …${i.length-6} more`)),o}function st(e){let{ui:t,source:n,sessionId:r}=e;if(!t)return{dispose(){}};let i=!1,a=()=>{if(i)return;let e=ot(n.list(),t.theme,r);t.setWidget(nt,e.length>0?e:void 0)};return n.subscribe(a),a(),{dispose(){i=!0,t.setWidget(nt,void 0)}}}const ct={min:1,max:50};function lt(e){return e===402?`账号余额不足:充值后再试`:e===408||e===429||e>=500?`临时性失败:稍后重试`:e>=400?`请求不合法:修改请求后再试(原样重试无益)`:e===0?`网络不可达:检查连接后重试`:``}function G(e,t){return t?e.split(t).join(`[REDACTED]`):e}async function ut(e,t,n){let r;try{r=await fetch(`https://api.deepseek.com/v1/tools${e}`,{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(t),signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,status:0,error:`network: ${e instanceof Error?e.message:String(e)}`}}let i=await r.text();if(!r.ok){let e=G(i.slice(0,300),n),t=lt(r.status);return{ok:!1,status:r.status,error:t?`${e}(${t})`:e}}try{return{ok:!0,value:JSON.parse(i)}}catch{return{ok:!1,status:r.status,error:`bad json: ${G(i.slice(0,200),n)}`}}}function dt(e){let t=e?.results??e?.data??[];return Array.isArray(t)?t.map(e=>{let t=e;return{title:String(t.title??``),url:String(t.url??t.link??``),snippet:t.snippet===void 0?void 0:String(t.snippet),summary:t.summary===void 0?void 0:String(t.summary),rank:typeof t.rank==`number`?t.rank:typeof t.rerank==`number`?t.rerank:void 0,date:t.date===void 0?void 0:String(t.date)}}).filter(e=>e.url.length>0):[]}function ft(e){return{id:`deepseek`,async search(t,n){let r=await ut(`/search`,{query:t,count:n?.count??10},e);return r.ok?{ok:!0,value:dt(r.value)}:r},async open(t){let n=await ut(`/fetch`,{url:t},e);if(!n.ok)return n;let r=n.value;return{ok:!0,value:G(String(r.content??r.text??r.markdown??``),e)}}}}function pt(e){let t=0,n=0,r=e<=0;return{tryAcquire(){return r?!0:n+t>=e?!1:(t++,!0)},release(e=!0){r||(t=Math.max(0,t-1),e&&n++)},remaining(){return r?1/0:Math.max(0,e-n-t)}}}function K(e,t){try{let n=new URL(e),r=new URL(t);return n.host!==r.host||n.protocol!==r.protocol||n.pathname.replace(/\/$/,``)!==r.pathname.replace(/\/$/,``)?!1:n.search===r.search||n.search===``||r.search===``}catch{return e===t}}function mt(){let e=[],t=/* @__PURE__ */ new Map,n=0,r=0,i=()=>{for(;r>4e5;){let i=t.keys().next();if(!i.done){let e=t.get(i.value)?.length??0;n-=e,r-=e,t.delete(i.value);continue}let a=e.shift();if(!a)break;r-=a.chars}for(;e.length>5;){let t=e.shift();if(!t)break;r-=t.chars}};return{remember(t,n){e.push({query:t,matches:n,textByUrl:/* @__PURE__ */ new Map,chars:t.length}),i()},storeText(a,o){for(let t=e.length-1;t>=0;t--){let n=e[t],s=n.matches.find(e=>K(e.url,a));if(s){n.textByUrl.set(s.url,o),n.chars+=o.length,r+=o.length,i();return}}n-=t.get(a)?.length??0,t.set(a,o),n+=o.length,r+=o.length,i()},lookup(n){for(let t=e.length-1;t>=0;t--)for(let[r,i]of e[t].textByUrl)if(K(r,n))return i;for(let[e,r]of[...t].reverse())if(K(e,n))return r}}}const ht=/* @__PURE__ */ new Map;function gt(e){let t=e;try{t=new URL(e).host}catch{}let n=(ht.get(t)??Promise.resolve()).then(()=>new Promise(e=>setTimeout(e,50)));return ht.set(t,n),n}function _t(e){return[`- ${e.title||`(no title)`}`,` url: ${e.url}`,e.snippet?` snippet: ${e.snippet}`:``,e.date?` date: ${e.date}`:``].filter(Boolean).join(`
28
+ `)}function vt(e,t){let n=[],r=[],i=0;for(let a of e){let e=_t(a);n.length>0&&i+e.length>t?r.push(a):(n.push(a),i+=e.length+1)}let a=n.map(_t);return r.length>0&&a.push(`(预算内放不下的 ${r.length} 条按排名整条丢弃:${r.map(e=>e.url).join(`、`)}——要哪个用 open 按 url 抓)`),a.join(`
29
+ `)}async function yt(e,t){let n=t.textBudgetChars??12e3;if(e.kind===`search`){let r=Math.min(ct.max,Math.max(ct.min,e.count??10));if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};let i=await t.provider.search(e.query,{count:r});return i.ok?(t.quota.release(i.value.length>0),t.memory.remember(e.query,i.value),i.value.length===0?{ok:!0,text:`「${e.query}」没有命中。`}:{ok:!0,text:L(vt(i.value,n))}):(t.quota.release(!1),{ok:!1,error:`search 失败(HTTP ${i.status}):${i.error}`})}if(e.kind===`open`){let r=t.memory.lookup(e.url);if(r!==void 0)return{ok:!0,text:L(`(记忆命中,未发请求)\n${r.slice(0,n)}`)};if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};await gt(e.url);let i=await t.provider.open(e.url);return i.ok?(t.quota.release(i.value.length>0),t.memory.storeText(e.url,i.value),{ok:!0,text:L(i.value.slice(0,n))}):(t.quota.release(!1),{ok:!1,error:`open 失败(HTTP ${i.status}):${i.error}`})}let r;try{r=new RegExp(e.pattern,`i`)}catch{return{ok:!1,error:`非法正则:${e.pattern}`}}let i=await bt(e.url,t);if(!i.ok)return i;let a=i.text.split(`
30
+ `).map((e,t)=>({line:e,index:t})).filter(({line:e})=>r.test(e));return{ok:!0,text:L(a.length>0?a.slice(0,50).map(({line:e,index:t})=>`${t+1}: ${e}`).join(`
31
+ `):`(页内无匹配行)`).slice(0,n)}}async function bt(e,t){let n=t.memory.lookup(e);if(n!==void 0)return{ok:!0,text:n};if(!t.quota.tryAcquire())return{ok:!1,error:`搜索配额已用尽(每会话配额,0 = 不限)`};await gt(e);let r=await t.provider.open(e);return r.ok?(t.quota.release(r.value.length>0),t.memory.storeText(e,r.value),{ok:!0,text:r.value}):(t.quota.release(!1),{ok:!1,error:`open 失败(HTTP ${r.status}):${r.error}`})}const xt=_.Object({action:_.Union([_.Literal(`search`),_.Literal(`open`),_.Literal(`find`)]),query:_.Optional(_.String({description:`search:搜索词`})),url:_.Optional(_.String({description:`open/find:目标页面 url`})),pattern:_.Optional(_.String({description:`find:页内行匹配(正则)`})),count:_.Optional(_.Integer({minimum:1,maximum:50,description:`search:条数 1–50,默认 10`}))});function St(e){return{name:`web_ds_search`,label:`联网搜索`,description:`联网能力(三动作):search 概览(title/url/snippet)· open 抓整页 · find 页内行匹配。open/find 命中最近记忆则免费。配额按每进程计。`,parameters:xt,execute:async(t,n)=>{let r=n.action===`search`?{kind:`search`,query:n.query??``,count:n.count}:n.action===`open`?{kind:`open`,url:n.url??``}:{kind:`find`,url:n.url??``,pattern:n.pattern??``};if(r.kind===`search`&&r.query===``)return{content:[{type:`text`,text:`search 动作需要 query`}],details:void 0,isError:!0};if(r.kind!==`search`&&r.url===``)return{content:[{type:`text`,text:`${r.kind} 动作需要 url`}],details:void 0,isError:!0};let i=await yt(r,e);return{content:[{type:`text`,text:i.ok?i.text:i.error}],details:void 0,isError:!i.ok}}}}const q=`pi-ptc-subagents`,Ct=[`Added`,`Changed`,`Fixed`];function J(e){if(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e))return;let t=e.split(`.`).map(Number);return(t[0]??0)*0xe8d4a51000+(t[1]??0)*1e6+(t[2]??0)}function Y(e){let t=[];for(let n of e.split(/^## /m).slice(1)){let e=/^\[(\d+\.\d+\.\d+)\]/.exec(n)?.[1];if(!e)continue;let r=[],i=!1,a=[],o=()=>{a.length>0&&r.push(a.join(` `)),a=[]};for(let e of n.split(`
32
+ `)){let t=/^###\s+(.+)$/.exec(e);t?(o(),i=Ct.includes(t[1]?.trim()??``)):i&&(e.startsWith(`- `)?(o(),a=[e.slice(2).trim()]):a.length>0&&e.trim().length>0?a.push(e.trim()):o())}o(),t.push({version:e,bullets:r})}return t}function wt(e){let t=/^\*\*(.+?)\*\*/.exec(e);if(t)return It(Ft(t[1]??``).replace(/\.$/,``));let n=/(?<!\d)\.(?=\s)/.exec(e);return It(Ft(n?e.slice(0,n.index+1):e).replace(/\.$/,``))}function Tt(e,t,n){let r=J(t),i=J(n);if(r===void 0||i===void 0)return[];let a=[];for(let t of e){let e=J(t.version);if(!(e===void 0||e<=r||e>i))for(let e of t.bullets)a.push(wt(e))}return a}function Et(e,t){if(!e.hasUI||typeof e.ui?.notify!=`function`)return;let n=t??Ot();if(!n)return;let r=J(n.version);if(r===void 0)return;let i=Mt(n.statePath),a=J(i);if(a===r||a!==void 0&&a>r)return;let o=Y(Pt(n.changelogPath)),s=a===void 0?kt(o,n.version):i;if(s===void 0||!Nt(n.statePath,n.version))return;let c=Tt(o,s,n.version);e.ui.notify(At(a===void 0?void 0:i,n.version,c,jt(n.repository)),`info`)}function Dt(e=import.meta.url){for(let t of[`..`,`../../..`])try{let n=D(new URL(`${t}/`,e)).replace(/[\\/]+$/,``),r=JSON.parse(s(m(n,`package.json`),`utf8`));if(r.name!==q||!r.version)continue;return{dir:n,version:r.version,repository:typeof r.repository==`string`?r.repository:r.repository?.url}}catch{}}function Ot(){let e=Dt();if(e)return{version:e.version,repository:e.repository,changelogPath:m(e.dir,`CHANGELOG.md`),statePath:m(i(),q,`last-seen-version.json`)}}function kt(e,t){let n=J(t);if(n===void 0)return;let r;for(let t of e){let e=J(t.version);e===void 0||e>=n||(r===void 0||e>(J(r)??0))&&(r=t.version)}return r}function At(e,t,n,r){let i=[`${q} ${t}`];if(e!==void 0&&i.push(`Updated from ${e}.`),n.length>0){i.push(``,`What's new:`);for(let e of n.slice(0,5))i.push(`- ${e}`);n.length>5&&i.push(`...and ${n.length-5} more`)}return r&&i.push(``,`Changelog: ${r}`),i.join(`
33
+ `)}function jt(e){if(!e)return;let t=e.replace(/^git\+/,``).replace(/\.git$/,``);return t.startsWith(`https://github.com/`)?`${t}/blob/main/CHANGELOG.md`:void 0}function Mt(e){try{let t=JSON.parse(s(e,`utf8`));return typeof t.version==`string`?t.version:void 0}catch{return}}function Nt(e,t){try{return o(p(e),{recursive:!0}),f(e,JSON.stringify({version:t})),!0}catch{return!1}}function Pt(e){try{return s(e,`utf8`)}catch{return``}}function Ft(e){return e.replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*/g,``).trim()}function It(e){if(e.length<=200)return e;let t=e.slice(0,200),n=t.lastIndexOf(` `);return`${t.slice(0,n>0?n:200).trimEnd()}…`}function Lt(e){let t;t=e.status===`fulfilled`?(e.logs.length>0?[...e.logs,B(e.value)]:[B(e.value)]).join(`
36
34
  `):e.status===`rejected`?[...e.logs,`[rejected] ${e.error}`].join(`
37
35
  `):[...e.logs,`[canceled] ${e.reason}`].join(`
38
- `);let{text:n,truncated:r,fullOutputPath:i}=sf(Zd(t));return{text:n,truncated:r,fullOutputPath:i}}const mp=j({code:z({description:`要执行的 TypeScript 程序体,可用顶层 await 和 return`}),description:z({description:`这段程序要干什么(给人看的一行)`}),timeoutMs:A(R({description:`覆盖默认 2 分钟超时`}))});function hp(e){return{name:`ptc_run_code`,label:`运行程序`,description:ff.ptc_run_code.description(e.surface??`full_ptc`),parameters:mp,renderResult:Ef(`run_code`),execute:async(...t)=>{let r=t[1],i=t.find(e=>typeof e?.executeTool==`function`);e.onToolContext?.(i);let a=await n({code:r.code,surface:`run_code`,cwd:e.cwd,timeoutMs:r.timeoutMs,bindings:e.getBindings(),pool:e.getPool?.()}),{text:o,truncated:s,fullOutputPath:c}=pp(a),l=a.status===`fulfilled`?a.images??[]:[];return{content:[{type:`text`,text:o},...l],details:c?{status:a.status,truncated:s,fullOutputPath:c}:{status:a.status,truncated:s},isError:a.status!==`fulfilled`}}}}const gp=j({meta:j({name:z(),description:z(),phases:A(it(j({name:z()})))}),script:z({description:`workflow 程序体,额外可用 workflow.log/phase/parallel/pipeline`}),args:A(jr(z(),wt())),timeoutMs:A(R())});function _p(e){return{name:`ptc_workflow`,label:`跑 workflow`,description:ff.ptc_workflow.description(e.surface??`full_ptc`),parameters:gp,renderResult:Ef(`workflow`),execute:async(...t)=>{let r=t[1],i=t.find(e=>typeof e?.executeTool==`function`);e.onToolContext?.(i);try{vp(r.args)}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{status:`rejected`},isError:!0}}let a=await n({code:r.script,surface:`workflow`,cwd:e.cwd,timeoutMs:r.timeoutMs,args:r.args??{},bindings:e.getBindings(),pool:e.getPool?.()}),{text:o,truncated:s,fullOutputPath:c}=pp(a),l=a.status===`fulfilled`?a.images??[]:[];return{content:[{type:`text`,text:o},...l],details:{status:a.status,truncated:s,...c?{fullOutputPath:c}:{},meta:r.meta},isError:a.status!==`fulfilled`}}}}function vp(e){if(e!==void 0)try{let t=JSON.stringify(e);if(t===void 0)throw Error(`args 不可序列化`);JSON.parse(t)}catch(e){throw Error(`workflow args 必须是 JSON 值:${e instanceof Error?e.message:String(e)}`)}}const yp=[`read`,`bash`,`grep`,`find`,`ls`,`edit`,`write`],bp=[`bash`],xp=yp.filter(e=>!bp.includes(e));function Sp(e,t=[]){let n=/* @__PURE__ */ new Set([...xp,...t]);return yp.filter(t=>e.includes(t)&&n.has(t))}const Cp=`pi_task_ptc`,wp=j({task:z({minLength:1,description:$.task}),agent:A(z({description:$.agent})),why:A(z({description:$.why})),agentScope:A(B([I(`user`),I(`project`),I(`both`)],{description:$.agentScope})),model:A(z({description:$.model})),thinkingLevel:A(z({description:$.thinkingLevel})),wait:A(Ht({description:$.wait})),label:A(z({description:$.label})),readOnly:A(B([I(`strict`),I(`lenient`)],{description:$.readOnly})),timeoutMs:A(R({description:$.timeoutMs})),projectContext:A(B([I(`auto`),I(`none`)],{description:$.projectContext}))});function Tp(e){return{name:Cp,parameters:wp,execute(t){let n=t??{};return e.createTask(n.task,{label:n.label,wait:n.wait,why:n.why,model:n.model,thinkingLevel:n.thinkingLevel,agent:n.agent,agentScope:n.agentScope,readOnly:n.readOnly,timeoutMs:n.timeoutMs,projectContext:n.projectContext})}}}function Ep(e){return async t=>{let n=t,r=n?.taskId??n?.task_id;if(typeof r!=`string`||r===``)return{error:`taskId 必须是非空字符串`};let i=e.registry.get(r)??await e.readArchivedRecord(r);return i?{...await Tf(e,i),status:i.status}:{error:`unknown task id ${r}`}}}function Dp(e={}){let t=new gd(e.onTransition),n=new qd({registry:t,gates:e.gates,whyEnabled:e.whyEnabled,context:e.context,...e.engine});return{registry:t,engine:n,createTask:(e,t)=>n.dispatch({...t,task:e}),taskListSnapshot:e=>Sf(t,e),stopTask:(e,t)=>n.stop(e,t),faceVisible:()=>Cf(t),shutdown:()=>n.shutdown(),readOutput:e=>n.readOutput(e),outputSize:e=>n.outputSize(e),readOutputTail:(e,t)=>n.readOutputTail(e,t),readArchivedRecord:e=>n.readArchivedRecord(e),readArchivedRecords:()=>n.readArchivedRecords(),get sessionId(){return e.context?.sessionId}}}function Op(e,t){return{depth:0,piVersion:t,get sessionModel(){try{let t=e.model;return t?`${t.provider}/${t.id}`:void 0}catch{return}},get sessionId(){try{return e.sessionManager.getSessionId()}catch{return}}}}const kp=e=>({content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:void 0});function Ap(e){if(!e||typeof e!=`object`)return e;let t=e;if(!(`reportChannel`in t))return e;let n=mf({delivery:t.delivery,findings:Array.isArray(t.report?.findings)?t.report.findings.length:0,channel:t.reportChannel});return n?{...t,deliveryNote:n}:t}const jp=ue(new URL(`..`,import.meta.url)),Mp=p(jp,`docs`,`routes`),Np=a(Mp)?Mp:p(jp,`..`,`routes`,`docs`,`routes`);function Pp(){try{return te(`pi --version`,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||void 0}catch{return}}function Fp(n){n.on(`session_start`,(r,a)=>{if(Number(process.env.PI_PTC_DEPTH??0)>0){Hp(n);return}try{np(a)}catch{}let o=n.getActiveTools().includes(`codemode`)?`codemode_ptc`:`full_ptc`,s=Lp(i()),c=!1,l=()=>{c=o===`full_ptc`&&s};l(),n.on(`before_agent_start`,e=>{l(),ae();let t=e.systemPromptOptions?.sections;t&&(t.ptc=xf(o,Np,c))});let u=new t(e),d=new Vd;n.on(`turn_end`,()=>{for(let e of d.drain())try{let t=vf(e);n.sendMessage({customType:`bg-task-notifications`,content:t,display:!0},{deliverAs:`nextTurn`})}catch{}});let f=!0,ee=!1,te=null,m=Rp(i()),ne=Bp(i()),h={userDir:p(i(),`agents`),projectDir:p(process.cwd(),`.pi`,`agents`)},re=Pp(),g,ie=/* @__PURE__ */ new Set,ae=()=>{let e=n.getActiveTools(),t=g.faceVisible(),r=Ip.filter(t=>e.includes(t));if(t&&r.length===0){n.setActiveTools([...e,...Ip]);for(let e of Ip)ie.add(e)}else if(!t&&r.length>0){let t=r.filter(e=>ie.has(e));if(t.length===0)return;n.setActiveTools(e.filter(e=>!t.includes(e)));for(let e of t)ie.delete(e)}};g=Dp({onTransition:()=>ae(),whyEnabled:()=>te??m,context:Op(a,re),engine:{notifications:d,resolveAgent:(e,t)=>zd(e,h,t),childExtensionPath:ue(import.meta.url),searchEnabled:zp(i()).enabled,storageDir:p(process.cwd(),`.pi`,`ptc-tasks`),output:new Ad(p(process.cwd(),`.pi`,`ptc-tasks`)),terminalRecordKeep:ne.keep,archiveEnabled:ne.archiveEnabled,archiveTtlDays:ne.ttlDays},gates:[bd,Td,xd(()=>f),Sd(()=>ee),Cd(()=>Number(process.env.PI_PTC_DEPTH??0),3),wd,Ed((e,t)=>zd(e,h,t)!==null)]}),n.registerCommand(`ptc`,{description:`/ptc off|on:派发开关 · /ptc why on|off:理由开关 · /ptc mode on|off:PTC 模式(程序优先的引导层)`,handler:async(e,t)=>{let[n,r]=e.trim().split(/\s+/);n===`off`?(f=!1,de(),c&&(s=!1,l())):n===`on`?(f=!0,fe(),s=!0,l()):n===`why`?te=r!==`off`:n===`mode`&&(s=r!==`off`,l()),t.ui.notify(`/ptc:dispatchEnabled=${f},mode=${c?`on(引导层)`:`off`},whyEnabled=${te??m}(在飞任务不受影响)`,`info`)}});let oe=Mf({ui:a.mode===`tui`?a.ui:void 0,source:g.registry,sessionId:g.sessionId});n.on(`session_shutdown`,()=>{ee=!0,oe.dispose(),u.drain(),g.shutdown()}),d.attach(g.registry);let se=/* @__PURE__ */ new Map,ce=[],le=(e=>{se.set(e.name,e),n.registerTool(e)}),de=()=>{for(let[e,t]of se)e.startsWith(`ptc_task_`)||(n.registerTool({...t,exposure:`hidden`}),ce.push(e))},fe=()=>{for(let e of ce.splice(0)){let t=se.get(e);t&&n.registerTool(t)}};Jp(le,g,o),ae();let pe=!1;n.on(`session_compact`,()=>{pe=!0}),n.on(`context`,e=>{if(!pe)return;pe=!1;let t=wf(g.registry);if(t)return{messages:[...e.messages,{role:`user`,content:[{type:`text`,text:t}],timestamp:Date.now()}]}});let me,he=process.cwd();qp(le,{getBindings:()=>Kp(n,g,()=>me,{cwd:he,extCtx:a,piVersion:re}),cwd:he,surface:o,getPool:()=>u,onToolContext:e=>{me=e}},o),o===`codemode_ptc`&&Yp(le,g,o),n.on(`turn_end`,()=>u.drain()),a.ui.notify(`pi-ptc-subagents: surface=${o},任务面 3 工具 + PTC 工具对已注册`,`info`)})}const Ip=[`ptc_task_list`,`ptc_task_output`,`ptc_task_stop`];function Lp(e){try{return JSON.parse(s(p(e,`ptc.json`),`utf8`)).defaultMode!==!1}catch{return!0}}function Rp(e){try{let t=s(p(e,`ptc.json`),`utf8`);return JSON.parse(t).whyEnabled!==!1}catch{return!0}}function zp(e){try{let t=JSON.parse(s(p(e,`ptc.json`),`utf8`)),n=typeof t.searchMaxCalls==`number`?t.searchMaxCalls:30;return{enabled:t.webDsSearch===!0,maxCalls:n}}catch{return{enabled:!1,maxCalls:30}}}function Bp(e){let t={keep:500,archiveEnabled:!0,ttlDays:30};try{let n=JSON.parse(s(p(e,`ptc.json`),`utf8`)),r=(e,t,n,r)=>typeof e==`number`&&Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):r;return{keep:r(n.taskTraceKeep,10,1e4,t.keep),archiveEnabled:typeof n.archiveEnabled==`boolean`?n.archiveEnabled:t.archiveEnabled,ttlDays:r(n.archiveTtlDays,1,365,t.ttlDays)}}catch{return t}}function Vp(e){try{let t=JSON.parse(s(p(e,`auth.json`),`utf8`)),n=t.deepseek?.api_key??t.deepseek?.key;if(n)return n}catch{}try{let t=JSON.parse(s(p(e,`models.json`),`utf8`));if(t.providers?.deepseek?.apiKey)return t.providers.deepseek.apiKey}catch{}return process.env.DEEPSEEK_API_KEY??null}function Hp(e){let t=i(),n=zp(t);if(n.enabled){let r=Vp(t);e.registerTool(Yf({provider:Rf(r??`missing-key`),memory:Vf(),quota:zf(n.maxCalls)}))}e.registerTool({name:`ptc_child_report`,label:`交报告`,description:`Deliver the child report(契约见你的 system prompt)。`,parameters:j({summary:z(),findings:A(it(j({what:z(),evidence:A(z())}))),files_touched:A(it(z())),usage:A(j({input:A(R()),output:A(R()),cost:A(R()),turns:A(R())}))}),execute:async(e,t)=>({content:[{type:`text`,text:`child report received`}],structuredContent:t,details:{report:t}})})}function Up(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>{if(typeof e==`string`)return e;let t=e;return t.type===`image`?`[image]`:t.text??JSON.stringify(e)}).join(`
39
- `);if(e&&typeof e==`object`){let t=e;if(typeof t.content==`string`)return t.content;if(typeof t.text==`string`)return t.text;if(t.type===`image`)return typeof t.note==`string`?t.note:`[image]`}return e}const Wp=Object.fromEntries([`read`,`write`,`edit`,`grep`,`ls`,`find`].map(e=>[e,r[`create${e[0].toUpperCase()}${e.slice(1)}ToolDefinition`]]));function Gp(e){if(!e)return!0;let[t=`0`,n=`0`]=e.trim().replace(/^v/,``).split(`.`),r=Number.parseInt(t,10),i=Number.parseInt(n,10);return Number.isNaN(r)||Number.isNaN(i)?!0:r>0||r===0&&i>=99}function Kp(e,t,n,r){let{cwd:i,extCtx:a,piVersion:o}=r,s=e.getActiveTools(),c=new Set(yp),l=Sp(!n()&&!s.some(e=>c.has(e))?e.getAllTools().map(e=>e.name):s),u,d=e=>{if(!u){u={};for(let[e,t]of Object.entries(Wp))typeof t==`function`&&(u[e]=t(i))}return u[e]},f=Object.fromEntries(l.map(e=>[e,async(t,r)=>{let i=n();if(!i?.executeTool){let n=Gp(o)?void 0:d(e);if(!n)throw Error(`此 pi 版本没有程序内调用工具的通道(需 pi ≥ 0.99,binding: ${e})`);let i=n.prepareArguments?n.prepareArguments(t):t,s=await n.execute(`ptc-${e}`,i,r.signal,void 0,a);for(let e of s.content??[])e.type===`image`&&r.emitImage(e);if(s.isError){let t=(s.content??[]).map(e=>{let t=e;return t.type===`text`?t.text??``:`[${t.type??`block`}]`}).join(`
40
- `);throw Error(t||`工具 ${e} 执行失败`)}return Up(s.structuredContent??s.content)}let s=await i.executeTool(e,t,{signal:r.signal});for(let e of s.result.content)e.type===`image`&&r.emitImage(e);if(s.isError){let t=s.result.content.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(`
41
- `);throw Error(t||`工具 ${e} 执行失败`)}return Up(s.result.structuredContent??s.result.content)}])),ee=Tp(t);return f[Cp]=async e=>Ap(await ee.execute(e)),f.task_records=async e=>{let n=t.registry.list();return e?.scope===`all`?[...n,...await t.readArchivedRecords()]:n},f.task_output=Ep(t),f}function qp(e,t,n){n===`full_ptc`&&(e(hp(t)),e(_p(t)))}function Jp(e,t,n){e({name:`ptc_task_list`,label:`任务列表`,description:ff.ptc_task_list.description(n),parameters:j({scope:A(B([I(`recent`),I(`all`)],{description:`recent = 只热存(默认);all = 含压缩归档(更全但更慢)`})),limit:A(R({description:`取多少条(默认 50,上限 200)`})),status:A(B(pd.map(e=>I(e)),{description:`只看某个状态`})),session:A(z({description:`按会话筛:current = 本会话,或给一个会话 id`}))}),defaultActive:!1,execute:async(e,n)=>{let r={scope:n.scope,limit:n.limit,status:n.status,session:n.session===`current`?t.sessionId:n.session},i=r.scope===`all`?await t.readArchivedRecords():[];return kp(Sf(t.registry,r,i))}}),e({name:`ptc_task_output`,label:`任务产出`,description:ff.ptc_task_output.description(n),parameters:j({task_id:z()}),defaultActive:!1,execute:async(e,n)=>{let r=t.registry.get(n.task_id)??await t.readArchivedRecord(n.task_id);return kp(r?Ap({...r,...await Tf(t,r)}):{error:`unknown task id ${n.task_id}`})}}),e({name:`ptc_task_stop`,label:`停任务`,description:ff.ptc_task_stop.description(n),parameters:j({task_id:z(),reason:A(z())}),defaultActive:!1,execute:async(e,n)=>kp(await t.stopTask(n.task_id,n.reason??`user stop`))})}function Yp(e,t,n){e({name:`pi_task_codemode`,label:`建任务`,description:ff.pi_task_codemode.description(n),parameters:wp,exposure:`codemode`,execute:async(e,n)=>{let r=await t.createTask(n.task,{label:n.label,wait:n.wait,why:n.why,agent:n.agent,agentScope:n.agentScope,model:n.model,thinkingLevel:n.thinkingLevel,readOnly:n.readOnly,timeoutMs:n.timeoutMs,projectContext:n.projectContext}),i=Ap(r);return{...kp(i),structuredContent:i,isError:r.status===`rejected`}}})}export{Dp as assemblePtcSession,Op as buildEngineContext,Ep as createTaskOutputBinding,Fp as default,rp as findInstalledPackage,$f as parseChangelog,tp as pickBullets,np as showUpgradeNotice,ep as summarize,Qf as versionNumber,Ap as withDeliveryNote};
36
+ `);let{text:n,truncated:r,fullOutputPath:i}=H(L(t));return{text:n,truncated:r,fullOutputPath:i}}const Rt=_.Object({code:_.String({description:`要执行的 TypeScript 程序体,可用顶层 await 和 return`}),description:_.String({description:`这段程序要干什么(给人看的一行)`}),timeoutMs:_.Optional(_.Number({description:`覆盖默认 2 分钟超时`}))});function zt(e){return{name:`ptc_run_code`,label:`运行程序`,description:U.ptc_run_code.description(e.surface??`full_ptc`),parameters:Rt,renderResult:tt(`run_code`),execute:async(...t)=>{let r=t[1],i=t.find(e=>typeof e?.executeTool==`function`);e.onToolContext?.(i);let a=await n({code:r.code,surface:`run_code`,cwd:e.cwd,timeoutMs:r.timeoutMs,bindings:e.getBindings(),pool:e.getPool?.()}),{text:o,truncated:s,fullOutputPath:c}=Lt(a),l=a.status===`fulfilled`?a.images??[]:[];return{content:[{type:`text`,text:o},...l],details:c?{status:a.status,truncated:s,fullOutputPath:c}:{status:a.status,truncated:s},isError:a.status!==`fulfilled`}}}}const Bt=_.Object({meta:_.Object({name:_.String(),description:_.String(),phases:_.Optional(_.Array(_.Object({name:_.String()})))}),script:_.String({description:`workflow 程序体,额外可用 workflow.log/phase/parallel/pipeline`}),args:_.Optional(_.Record(_.String(),_.Unknown())),timeoutMs:_.Optional(_.Number())});function Vt(e){return{name:`ptc_workflow`,label:`跑 workflow`,description:U.ptc_workflow.description(e.surface??`full_ptc`),parameters:Bt,renderResult:tt(`workflow`),execute:async(...t)=>{let r=t[1],i=t.find(e=>typeof e?.executeTool==`function`);e.onToolContext?.(i);try{Ht(r.args)}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{status:`rejected`},isError:!0}}let a=await n({code:r.script,surface:`workflow`,cwd:e.cwd,timeoutMs:r.timeoutMs,args:r.args??{},bindings:e.getBindings(),pool:e.getPool?.()}),{text:o,truncated:s,fullOutputPath:c}=Lt(a),l=a.status===`fulfilled`?a.images??[]:[];return{content:[{type:`text`,text:o},...l],details:{status:a.status,truncated:s,...c?{fullOutputPath:c}:{},meta:r.meta},isError:a.status!==`fulfilled`}}}}function Ht(e){if(e!==void 0)try{let t=JSON.stringify(e);if(t===void 0)throw Error(`args 不可序列化`);JSON.parse(t)}catch(e){throw Error(`workflow args 必须是 JSON 值:${e instanceof Error?e.message:String(e)}`)}}const X=[`read`,`bash`,`grep`,`find`,`ls`,`edit`,`write`],Ut=[`bash`],Wt=X.filter(e=>!Ut.includes(e));function Gt(e,t=[]){let n=/* @__PURE__ */ new Set([...Wt,...t]);return X.filter(t=>e.includes(t)&&n.has(t))}const Kt=`pi_task_ptc`,qt=_.Object({task:_.String({minLength:1,description:W.task}),agent:_.Optional(_.String({description:W.agent})),why:_.Optional(_.String({description:W.why})),agentScope:_.Optional(_.Union([_.Literal(`user`),_.Literal(`project`),_.Literal(`both`)],{description:W.agentScope})),model:_.Optional(_.String({description:W.model})),thinkingLevel:_.Optional(_.String({description:W.thinkingLevel})),wait:_.Optional(_.Boolean({description:W.wait})),label:_.Optional(_.String({description:W.label})),readOnly:_.Optional(_.Union([_.Literal(`strict`),_.Literal(`lenient`)],{description:W.readOnly})),timeoutMs:_.Optional(_.Number({description:W.timeoutMs})),projectContext:_.Optional(_.Union([_.Literal(`auto`),_.Literal(`none`)],{description:W.projectContext}))});function Jt(e){return{name:Kt,parameters:qt,execute(t){let n=t??{};return e.createTask(n.task,{label:n.label,wait:n.wait,why:n.why,model:n.model,thinkingLevel:n.thinkingLevel,agent:n.agent,agentScope:n.agentScope,readOnly:n.readOnly,timeoutMs:n.timeoutMs,projectContext:n.projectContext})}}}function Yt(e){return async t=>{let n=t,r=n?.taskId??n?.task_id;if(typeof r!=`string`||r===``)return{error:`taskId 必须是非空字符串`};let i=e.registry.get(r)??await e.readArchivedRecord(r);return i?{...await et(e,i),status:i.status}:{error:`unknown task id ${r}`}}}function Xt(e={}){let t=new re(e.onTransition),n=new je({registry:t,gates:e.gates,whyEnabled:e.whyEnabled,context:e.context,...e.engine});return{registry:t,engine:n,createTask:(e,t)=>n.dispatch({...t,task:e}),taskListSnapshot:e=>Ze(t,e),stopTask:(e,t)=>n.stop(e,t),faceVisible:()=>Qe(t),shutdown:()=>n.shutdown(),readOutput:e=>n.readOutput(e),outputSize:e=>n.outputSize(e),readOutputTail:(e,t)=>n.readOutputTail(e,t),readArchivedRecord:e=>n.readArchivedRecord(e),readArchivedRecords:()=>n.readArchivedRecords(),get sessionId(){return e.context?.sessionId}}}function Zt(e,t){return{depth:0,piVersion:t,get sessionModel(){try{let t=e.model;return t?`${t.provider}/${t.id}`:void 0}catch{return}},get sessionId(){try{return e.sessionManager.getSessionId()}catch{return}}}}const Z=e=>({content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:void 0});function Q(e){if(!e||typeof e!=`object`)return e;let t=e;if(!(`reportChannel`in t))return e;let n=Ue({delivery:t.delivery,findings:Array.isArray(t.report?.findings)?t.report.findings.length:0,channel:t.reportChannel});return n?{...t,deliveryNote:n}:t}const Qt=D(new URL(`..`,import.meta.url)),$t=m(Qt,`docs`,`routes`),en=a($t)?$t:m(Qt,`..`,`routes`,`docs`,`routes`);function tn(){try{return h(`pi --version`,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||void 0}catch{return}}function nn(n){n.on(`session_start`,(r,a)=>{if(Number(process.env.PI_PTC_DEPTH??0)>0){ln(n);return}let o=n.getActiveTools().includes(`codemode`)?`codemode_ptc`:`full_ptc`,s=rn(i()),c=!1,l=()=>{c=o===`full_ptc`&&s};l(),n.on(`before_agent_start`,e=>{l(),S();let t=e.systemPromptOptions?.sections;t&&(t.ptc=Xe(o,en,c))});let u=new t(e),d=new Te;n.on(`turn_end`,()=>{for(let e of d.drain())try{let t=qe(e);n.sendMessage({customType:`bg-task-notifications`,content:t,display:!0},{deliverAs:`nextTurn`})}catch{}});let f=!0,p=!1,h=null,g=an(i()),_=sn(i()),v={userDir:m(i(),`agents`),projectDir:m(process.cwd(),`.pi`,`agents`)},y=tn(),b,x=/* @__PURE__ */ new Set,S=()=>{let e=n.getActiveTools(),t=b.faceVisible(),r=$.filter(t=>e.includes(t));if(t&&r.length===0){n.setActiveTools([...e,...$]);for(let e of $)x.add(e)}else if(!t&&r.length>0){let t=r.filter(e=>x.has(e));if(t.length===0)return;n.setActiveTools(e.filter(e=>!t.includes(e)));for(let e of t)x.delete(e)}};b=Xt({onTransition:()=>S(),whyEnabled:()=>h??g,context:Zt(a,y),engine:{notifications:d,resolveAgent:(e,t)=>we(e,v,t),childExtensionPath:D(import.meta.url),searchEnabled:on(i()).enabled,storageDir:m(process.cwd(),`.pi`,`ptc-tasks`),output:new he(m(process.cwd(),`.pi`,`ptc-tasks`)),terminalRecordKeep:_.keep,archiveEnabled:_.archiveEnabled,archiveTtlDays:_.ttlDays},gates:[oe,de,se(()=>f),ce(()=>p),le(()=>Number(process.env.PI_PTC_DEPTH??0),3),ue,fe((e,t)=>we(e,v,t)!==null)]}),n.registerCommand(`ptc`,{description:`/ptc off|on:派发开关 · /ptc why on|off:理由开关 · /ptc mode on|off:PTC 模式(程序优先的引导层)`,handler:async(e,t)=>{let[n,r]=e.trim().split(/\s+/);n===`off`?(f=!1,ee(),c&&(s=!1,l())):n===`on`?(f=!0,O(),s=!0,l()):n===`why`?h=r!==`off`:n===`mode`&&(s=r!==`off`,l()),t.ui.notify(`/ptc:dispatchEnabled=${f},mode=${c?`on(引导层)`:`off`},whyEnabled=${h??g}(在飞任务不受影响)`,`info`)}});let C=st({ui:a.mode===`tui`?a.ui:void 0,source:b.registry,sessionId:b.sessionId});n.on(`session_shutdown`,()=>{p=!0,C.dispose(),u.drain(),b.shutdown()}),d.attach(b.registry);let w=/* @__PURE__ */ new Map,T=[],E=(e=>{w.set(e.name,e),n.registerTool(e)}),ee=()=>{for(let[e,t]of w)e.startsWith(`ptc_task_`)||(n.registerTool({...t,exposure:`hidden`}),T.push(e))},O=()=>{for(let e of T.splice(0)){let t=w.get(e);t&&n.registerTool(t)}};hn(E,b,o),S();let k=!1;n.on(`session_compact`,()=>{k=!0}),n.on(`context`,e=>{if(!k)return;k=!1;let t=$e(b.registry);if(t)return{messages:[...e.messages,{role:`user`,content:[{type:`text`,text:t}],timestamp:Date.now()}]}});let A,j=process.cwd();mn(E,{getBindings:()=>pn(n,b,()=>A,{cwd:j,extCtx:a,piVersion:y}),cwd:j,surface:o,getPool:()=>u,onToolContext:e=>{A=e}},o),o===`codemode_ptc`&&gn(E,b,o),n.on(`turn_end`,()=>u.drain()),a.ui.notify(`pi-ptc-subagents: surface=${o},任务面 3 工具 + PTC 工具对已注册`,`info`);try{Et(a)}catch{}})}const $=[`ptc_task_list`,`ptc_task_output`,`ptc_task_stop`];function rn(e){try{return JSON.parse(s(m(e,`ptc.json`),`utf8`)).defaultMode!==!1}catch{return!0}}function an(e){try{let t=s(m(e,`ptc.json`),`utf8`);return JSON.parse(t).whyEnabled!==!1}catch{return!0}}function on(e){try{let t=JSON.parse(s(m(e,`ptc.json`),`utf8`)),n=typeof t.searchMaxCalls==`number`?t.searchMaxCalls:30;return{enabled:t.webDsSearch===!0,maxCalls:n}}catch{return{enabled:!1,maxCalls:30}}}function sn(e){let t={keep:500,archiveEnabled:!0,ttlDays:30};try{let n=JSON.parse(s(m(e,`ptc.json`),`utf8`)),r=(e,t,n,r)=>typeof e==`number`&&Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):r;return{keep:r(n.taskTraceKeep,10,1e4,t.keep),archiveEnabled:typeof n.archiveEnabled==`boolean`?n.archiveEnabled:t.archiveEnabled,ttlDays:r(n.archiveTtlDays,1,365,t.ttlDays)}}catch{return t}}function cn(e){try{let t=JSON.parse(s(m(e,`auth.json`),`utf8`)),n=t.deepseek?.api_key??t.deepseek?.key;if(n)return n}catch{}try{let t=JSON.parse(s(m(e,`models.json`),`utf8`));if(t.providers?.deepseek?.apiKey)return t.providers.deepseek.apiKey}catch{}return process.env.DEEPSEEK_API_KEY??null}function ln(e){let t=i(),n=on(t);if(n.enabled){let r=cn(t);e.registerTool(St({provider:ft(r??`missing-key`),memory:mt(),quota:pt(n.maxCalls)}))}e.registerTool({name:`ptc_child_report`,label:`交报告`,description:`Deliver the child report(契约见你的 system prompt)。`,parameters:_.Object({summary:_.String(),findings:_.Optional(_.Array(_.Object({what:_.String(),evidence:_.Optional(_.String())}))),files_touched:_.Optional(_.Array(_.String())),usage:_.Optional(_.Object({input:_.Optional(_.Number()),output:_.Optional(_.Number()),cost:_.Optional(_.Number()),turns:_.Optional(_.Number())}))}),execute:async(e,t)=>({content:[{type:`text`,text:`child report received`}],structuredContent:t,details:{report:t}})})}function un(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>{if(typeof e==`string`)return e;let t=e;return t.type===`image`?`[image]`:t.text??JSON.stringify(e)}).join(`
37
+ `);if(e&&typeof e==`object`){let t=e;if(typeof t.content==`string`)return t.content;if(typeof t.text==`string`)return t.text;if(t.type===`image`)return typeof t.note==`string`?t.note:`[image]`}return e}const dn=Object.fromEntries([`read`,`write`,`edit`,`grep`,`ls`,`find`].map(e=>[e,r[`create${e[0].toUpperCase()}${e.slice(1)}ToolDefinition`]]));function fn(e){if(!e)return!0;let[t=`0`,n=`0`]=e.trim().replace(/^v/,``).split(`.`),r=Number.parseInt(t,10),i=Number.parseInt(n,10);return Number.isNaN(r)||Number.isNaN(i)?!0:r>0||r===0&&i>=99}function pn(e,t,n,r){let{cwd:i,extCtx:a,piVersion:o}=r,s=e.getActiveTools(),c=new Set(X),l=Gt(!n()&&!s.some(e=>c.has(e))?e.getAllTools().map(e=>e.name):s),u,d=e=>{if(!u){u={};for(let[e,t]of Object.entries(dn))typeof t==`function`&&(u[e]=t(i))}return u[e]},f=Object.fromEntries(l.map(e=>[e,async(t,r)=>{let i=n();if(!i?.executeTool){let n=fn(o)?void 0:d(e);if(!n)throw Error(`此 pi 版本没有程序内调用工具的通道(需 pi ≥ 0.99,binding: ${e})`);let i=n.prepareArguments?n.prepareArguments(t):t,s=await n.execute(`ptc-${e}`,i,r.signal,void 0,a);for(let e of s.content??[])e.type===`image`&&r.emitImage(e);if(s.isError){let t=(s.content??[]).map(e=>{let t=e;return t.type===`text`?t.text??``:`[${t.type??`block`}]`}).join(`
38
+ `);throw Error(t||`工具 ${e} 执行失败`)}return un(s.structuredContent??s.content)}let s=await i.executeTool(e,t,{signal:r.signal});for(let e of s.result.content)e.type===`image`&&r.emitImage(e);if(s.isError){let t=s.result.content.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(`
39
+ `);throw Error(t||`工具 ${e} 执行失败`)}return un(s.result.structuredContent??s.result.content)}])),p=Jt(t);return f[Kt]=async e=>Q(await p.execute(e)),f.task_records=async e=>{let n=t.registry.list();return e?.scope===`all`?[...n,...await t.readArchivedRecords()]:n},f.task_output=Yt(t),f}function mn(e,t,n){n===`full_ptc`&&(e(zt(t)),e(Vt(t)))}function hn(e,t,n){e({name:`ptc_task_list`,label:`任务列表`,description:U.ptc_task_list.description(n),parameters:_.Object({scope:_.Optional(_.Union([_.Literal(`recent`),_.Literal(`all`)],{description:`recent = 只热存(默认);all = 含压缩归档(更全但更慢)`})),limit:_.Optional(_.Number({description:`取多少条(默认 50,上限 200)`})),status:_.Optional(_.Union(te.map(e=>_.Literal(e)),{description:`只看某个状态`})),session:_.Optional(_.String({description:`按会话筛:current = 本会话,或给一个会话 id`}))}),defaultActive:!1,execute:async(e,n)=>{let r={scope:n.scope,limit:n.limit,status:n.status,session:n.session===`current`?t.sessionId:n.session},i=r.scope===`all`?await t.readArchivedRecords():[];return Z(Ze(t.registry,r,i))}}),e({name:`ptc_task_output`,label:`任务产出`,description:U.ptc_task_output.description(n),parameters:_.Object({task_id:_.String()}),defaultActive:!1,execute:async(e,n)=>{let r=t.registry.get(n.task_id)??await t.readArchivedRecord(n.task_id);return Z(r?Q({...r,...await et(t,r)}):{error:`unknown task id ${n.task_id}`})}}),e({name:`ptc_task_stop`,label:`停任务`,description:U.ptc_task_stop.description(n),parameters:_.Object({task_id:_.String(),reason:_.Optional(_.String())}),defaultActive:!1,execute:async(e,n)=>Z(await t.stopTask(n.task_id,n.reason??`user stop`))})}function gn(e,t,n){e({name:`pi_task_codemode`,label:`建任务`,description:U.pi_task_codemode.description(n),parameters:qt,exposure:`codemode`,execute:async(e,n)=>{let r=await t.createTask(n.task,{label:n.label,wait:n.wait,why:n.why,agent:n.agent,agentScope:n.agentScope,model:n.model,thinkingLevel:n.thinkingLevel,readOnly:n.readOnly,timeoutMs:n.timeoutMs,projectContext:n.projectContext}),i=Q(r);return{...Z(i),structuredContent:i,isError:r.status===`rejected`}}})}export{Xt as assemblePtcSession,Zt as buildEngineContext,Yt as createTaskOutputBinding,nn as default,Dt as findInstalledPackage,Y as parseChangelog,Tt as pickBullets,Et as showUpgradeNotice,wt as summarize,J as versionNumber,Q as withDeliveryNote};
42
40
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ptc-subagents",
3
- "version": "7.8.0",
3
+ "version": "7.9.1",
4
4
  "description": "Programmable tool calling (PTC) and subagent fan-out for pi",
5
5
  "keywords": [
6
6
  "pi",