@north-light/crouter 0.3.321 → 0.3.323
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/bin/progress-painter.mjs +89 -0
- package/bin/runtime-selector.mjs +123 -4
- package/dist/api/client.d.ts +35 -18
- package/dist/api/client.js +2 -2
- package/dist/api/dto/broker-ops.d.ts +9 -0
- package/dist/api/dto/canvas.d.ts +23 -1
- package/dist/api/dto/modelauth.d.ts +15 -0
- package/dist/api/dto/nodes.d.ts +8 -0
- package/dist/api/errors.d.ts +6 -3
- package/dist/api/errors.js +1 -1
- package/dist/api/index.d.ts +2 -2
- package/dist/api/index.js +1 -1
- package/dist/api/node-transport.d.ts +18 -0
- package/dist/api/node-transport.js +1 -0
- package/dist/api/routes.d.ts +3 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-sdk.md +86 -0
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.js +1 -1
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.ts +1 -1
- package/dist/cli.js +8 -2
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/overlays/graph.d.ts +6 -5
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +5 -1
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/session/frames.d.ts +1 -0
- package/dist/clients/attach/session/frames.js +1 -1
- package/dist/clients/attach/viewer.js +576 -576
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/memory/read.js +2 -2
- package/dist/commands/node/create.js +3 -3
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/connect.d.ts +1 -0
- package/dist/commands/sys/connect.js +3 -0
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys/panels/plugins-panel.js +1 -1
- package/dist/commands/sys/panels/provider-panel.d.ts +4 -0
- package/dist/commands/sys/panels/provider-panel.js +1 -1
- package/dist/commands/sys/provider-login.d.ts +8 -0
- package/dist/commands/sys/provider-login.js +9 -0
- package/dist/commands/sys/setup-core.d.ts +4 -0
- package/dist/commands/sys/setup-core.js +7 -4
- package/dist/commands/sys/setup-wizard.d.ts +1 -1
- package/dist/commands/sys/setup-wizard.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/canvas.d.ts +24 -0
- package/dist/core/canvas/canvas.js +29 -15
- package/dist/core/canvas/migrations.js +35 -32
- package/dist/core/canvas/nav-model.d.ts +1 -1
- package/dist/core/canvas/nav-model.js +1 -1
- package/dist/core/canvas/nav-render.d.ts +31 -25
- package/dist/core/canvas/nav-render.js +1 -1
- package/dist/core/canvas/paths.d.ts +4 -4
- package/dist/core/canvas/render-source.d.ts +6 -16
- package/dist/core/canvas/render-source.js +9 -9
- package/dist/core/canvas/types.d.ts +16 -0
- package/dist/core/config.js +1 -1
- package/dist/core/provider-credential.d.ts +6 -0
- package/dist/core/provider-credential.js +1 -0
- package/dist/core/runtime/boot-root.d.ts +2 -0
- package/dist/core/runtime/boot-root.js +1 -1
- package/dist/core/runtime/broker/daemon-ops.d.ts +2 -1
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/front-door-login.d.ts +2 -0
- package/dist/core/runtime/front-door-login.js +1 -0
- package/dist/core/runtime/front-door.js +7 -5
- package/dist/core/runtime/nerd-font.d.ts +19 -1
- package/dist/core/runtime/nerd-font.js +2 -2
- package/dist/core/runtime/progress-bar.d.ts +13 -0
- package/dist/core/runtime/progress-bar.js +2 -0
- package/dist/core/runtime/provider-credential-gate.d.ts +4 -0
- package/dist/core/runtime/provider-credential-gate.js +2 -0
- package/dist/core/runtime/spawn-env.d.ts +7 -0
- package/dist/core/runtime/spawn-env.js +1 -1
- package/dist/core/secrets.d.ts +3 -0
- package/dist/core/secrets.js +2 -2
- package/dist/core/subscription-state.d.ts +1 -1
- package/dist/core/subscription-state.js +3 -3
- package/dist/core/termrender/termrender.d.ts +3 -1
- package/dist/core/termrender/termrender.js +13 -13
- package/dist/core/user-settings.d.ts +4 -0
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +4 -4
- package/dist/daemon/api/handlers/health.d.ts +1 -1
- package/dist/daemon/api/handlers/health.js +3 -3
- package/dist/daemon/api/handlers/modelauth.js +1 -1
- package/dist/daemon/api/map.d.ts +15 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/server.d.ts +5 -1
- package/dist/daemon/api/server.js +4 -4
- package/dist/daemon/crtrd-cli.js +1 -1
- package/dist/daemon/fleet.js +1 -1
- package/dist/daemon/manage.d.ts +1 -0
- package/dist/daemon/manage.js +2 -2
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/types.d.ts +7 -0
- package/dist/types.js +1 -1
- package/docs/sdk/README.md +54 -0
- package/docs/sdk/client.md +92 -0
- package/docs/sdk/docker.md +63 -0
- package/docs/sdk/errors.md +85 -0
- package/docs/sdk/getting-started.md +160 -0
- package/docs/sdk/memory.md +107 -0
- package/docs/sdk/migration.md +108 -0
- package/docs/sdk/nodes.md +193 -0
- package/docs/sdk/resources.md +71 -0
- package/docs/sdk/streaming.md +124 -0
- package/package.json +1 -1
- package/runtime.lock.json +6 -6
- package/scripts/install-runtime.mjs +7 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);if(e.length>0){const i=s.findIndex(d=>{const o=d.toLowerCase();return e.some(c=>o.includes(c))});if(i!==-1)return s.slice(i,i+n).map(d=>d.trim()).filter(d=>d!=="").join(" \u23CE ")}const a=s.map(i=>i.trim()).filter(i=>i!=="").slice(0,n).join(" \u23CE ");return a!==""?a:t.title}u(
|
|
3
|
-
`).forEach((y,
|
|
1
|
+
var P=Object.defineProperty;var u=(t,e)=>P(t,"name",{value:e,configurable:!0});import{graphNodes as I,pruneNodes as K,pruneToLimit as A,rosterEdges as C,rosterNodes as D}from"../../../core/canvas/canvas.js";import{activeBackgroundBashJobs as q}from"../../../core/bash-jobs.js";import{contextDir as H}from"../../../core/canvas/paths.js";import{nowIso as k}from"../../../core/fs-utils.js";import{isPidPresent as J}from"../../../core/canvas/pid.js";import{dashboardRowsAllFromSource as z,enrichRowsFromSource as Q}from"../../../core/canvas/render-source.js";import{localCanvasSource as M}from"../../../core/canvas/source.js";import{ticketCountsForNodes as j,ticketsAcrossCanvas as U}from"../../../core/canvas/attention.js";import{buildCorpus as Y,groupCorpus as V,resolveRef as W}from"../../../core/canvas/history.js";import{listFocuses as R,reapEmptyNodes as X}from"../../../core/runtime/placement.js";import{notFound as Z,usage as p}from"../../../core/errors.js";import{toGraphNodeDTO as ee}from"../map.js";function te(){return{status:200,body:{items:U().map(e=>({node_id:e.node_id,name:e.name,cwd:e.cwd,count:e.count,subjects:e.subjects}))}}}u(te,"handleAttention");function ne(t){const e=t.body;if(e===null||typeof e!="object"||!Array.isArray(e.node_ids))throw p("attention count request requires node_ids: string[]");const n=e.node_ids;if(!n.every(s=>typeof s=="string"))throw p("attention count request node_ids must contain only strings");return{status:200,body:{counts:j(n)}}}u(ne,"handleAttentionCounts");function B(t){return Buffer.from(String(t),"utf8").toString("base64")}u(B,"encodeCursor");function x(t){const e=Number(Buffer.from(t,"base64").toString("utf8"));if(!Number.isInteger(e)||e<0)throw p(`invalid cursor: ${t}`);return e}u(x,"decodeCursor");function oe(t,e,n){const s=t.loadBody().split(`
|
|
2
|
+
`);if(e.length>0){const i=s.findIndex(d=>{const o=d.toLowerCase();return e.some(c=>o.includes(c))});if(i!==-1)return s.slice(i,i+n).map(d=>d.trim()).filter(d=>d!=="").join(" \u23CE ")}const a=s.map(i=>i.trim()).filter(i=>i!=="").slice(0,n).join(" \u23CE ");return a!==""?a:t.title}u(oe,"snippet");function re(t,e,n){const r=[...t];return e==="relevance"&&n!==void 0?r.sort((s,a)=>(n.get(a.ref)??0)-(n.get(s.ref)??0)||a.tsMs-s.tsMs||s.ref.localeCompare(a.ref)):e==="oldest"?r.sort((s,a)=>s.tsMs-a.tsMs||s.ref.localeCompare(a.ref)):r.sort((s,a)=>a.tsMs-s.tsMs||s.ref.localeCompare(a.ref)),r}u(re,"sortArtifacts");function se(t){if(t==null)return{};if(typeof t!="object")throw p("history search body must be a JSON object");return t}u(se,"parseSearchBody");function ie(t){if(t===null||typeof t!="object")throw p("history grep body must be a JSON object");const e=t;if(typeof e.pattern!="string"||e.pattern==="")throw p("history grep body requires a non-empty pattern");return e}u(ie,"parseGrepBody");function $(t){const e={cwd:t.cwd,allCwds:t.all_cwds===!0,under:t.under,nodes:t.nodes},n={types:t.types,reportKind:t.report_kind,kinds:t.kinds,statuses:t.statuses,sinceMs:t.since_ms,untilMs:t.until_ms,origins:t.origins,roles:t.roles,from:t.from};return Y(e,n)}u($,"buildCorpusFromQuery");function de(t){if(t==null)return{};if(typeof t!="object")throw p("history stats body must be a JSON object");return t}u(de,"parseStatsBody");const L=["origin","node","kind","day","type","role"];function ae(t){const e=de(t.body),n=e.group_by??"type";if(!L.includes(n))throw p(`--group-by must be one of: ${L.join(", ")}; received: ${String(e.group_by)}`);const r=$(e),s=V(r,n);return{status:200,body:{group_by:n,groups:s,total:s.reduce((i,d)=>i+d.count,0),scanned:r.length}}}u(ae,"handleHistoryStats");function ce(t){const e=ie(t.body),n=Math.min(100,Math.max(1,e.limit??20)),r=$(e),s=e.cursor!==void 0?x(e.cursor):0;let a;try{a=new RegExp(e.pattern,"i")}catch{throw p(`invalid regex pattern: ${e.pattern}`)}const i=[];for(const f of r)f.loadBody().split(`
|
|
3
|
+
`).forEach((y,b)=>{a.test(y)&&i.push({ref:f.ref,node:`${f.nodeName} (${f.nodeId})`,ts:f.ts,line:b+1,text:y.trim()})});i.sort((f,m)=>f.ref.localeCompare(m.ref)||f.line-m.line);const d=i.slice(s,s+n),o=s+n<i.length?B(s+n):null;return{status:200,body:{hits:d,next_cursor:o,total:i.length}}}u(ce,"handleHistoryGrep");function ue(t){const e=se(t.body),n=(e.query??"").trim(),r=e.weigh_body===!0,s=e.full===!0,a=Math.max(1,e.snippet_lines??1),i=Math.min(100,Math.max(1,e.limit??20)),d=$(e),o=e.cursor!==void 0?x(e.cursor):0,c=n.toLowerCase().split(/\s+/).filter(l=>l.length>0);let f=d,m;const y=e.sort??(c.length>0?"relevance":"recency");if(c.length>0&&y==="relevance"){m=new Map;const l=[];for(const h of d){const S=h.title.toLowerCase(),F=h.nodeName.toLowerCase(),G=h.nodeDesc.toLowerCase(),N=r?h.loadBody().toLowerCase():null;let _=0;for(const v of c)S.includes(v)&&(_+=10),F.includes(v)&&(_+=5),G.includes(v)&&(_+=3),N!==null&&N.includes(v)&&(_+=1);_>0&&(m.set(h.ref,_),l.push(h))}f=l}else c.length>0&&(f=d.filter(l=>{const h=`${l.title}
|
|
4
4
|
${l.nodeName}
|
|
5
5
|
${l.nodeDesc}${r?`
|
|
6
|
-
`+l.loadBody():""}`.toLowerCase();return c.some(S=>h.includes(S))}));const
|
|
6
|
+
`+l.loadBody():""}`.toLowerCase();return c.some(S=>h.includes(S))}));const b=re(f,y,m),T=b.slice(o,o+i),E=o+i<b.length?B(o+i):null;return{status:200,body:{hits:T.map(l=>{const h={ref:l.ref,node:`${l.nodeName} (${l.nodeId})`,kind:l.nodeKind,source:l.source==="report"&&l.reportKind?`report:${l.reportKind}`:l.source,ts:l.ts};return y==="relevance"&&m!==void 0&&(h.score=m.get(l.ref)??0),s?h.body=l.loadBody():h.snippet=oe(l,c,a),h}),next_cursor:E,total:b.length}}}u(ue,"handleHistorySearch");function le(t){const e=(t.query.get("ref")??"").trim(),n=t.query.get("frontmatter")==="true";if(!e.includes(":"))throw p(`ref must be <node-id>:<relpath>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search` or `crtr node inspect artifacts <node-id>`."});let r;try{r=W(e)}catch(o){throw p(`ref rejected: ${o.message}`,{received:e,next:"Refs come verbatim from `crtr canvas history search`; do not hand-construct relpaths."})}if(r===null)throw Z(`no artifact for ref: ${e}`,{ref:e,next:"The node or file may not exist. Re-run `crtr canvas history search` for a current ref, or `crtr node inspect artifacts <node-id>` to list a node's artifacts."});const s=r.source==="report"&&r.reportKind?`report:${r.reportKind}`:r.source,i=(t.query.get("format")==="raw"||n)&&r.raw!==null?r.raw:r.body;return{status:200,body:{ref:e,node:`${r.nodeName} (${r.nodeId})`,source:s,ts:r.ts,content:i}}}u(le,"handleHistoryRead");function fe(t){for(const[r]of t.query)if(r!=="live")throw p(`unknown snapshot query parameter: ${r}`);const e=t.query.getAll("live");if(e.length>1)throw p("live must appear at most once");const n=e[0];if(n===void 0||n==="false"||n==="0")return!1;if(n==="true"||n==="1")return!0;throw p("live must be true or false")}u(fe,"snapshotLiveOnly");async function me(t){const e=new Set(R().map(o=>o.node_id)),n=await z(M,e,fe(t)),r=j(n.map(o=>o.node_id));await Q(M,n,r);const s=n.map(o=>{const c=o.srcRow,f=c?.host_kind??"tmux";return{node_id:o.node_id,name:o.name,title:o.handle??o.name,description:o.description??null,kind:o.kind,mode:o.mode,lifecycle:o.lifecycle??c?.lifecycle,status:o.status,cwd:o.cwd,profile_id:o.profile_id??null,parent:c?.parent??null,created:o.created,host_kind:f,enterable:f==="broker",attention_count:o.asks,...c?.cycles!=null?{cycles:c.cycles}:{},...o.mtimeMs!==void 0?{last_activity:new Date(o.mtimeMs).toISOString()}:{},ctx_tokens:o.ctx_tokens,streaming:o.streaming??!1,jobs_active:c!==void 0&&J(c.pi_pid)?q(H(o.node_id)).length:0,waiting_for:c?.waiting_for??null,hanging:o.hanging??null,viewed:o.viewed??!1,final_report:c?.final_report??null,finalized_at:c?.finalized_at??null}}),a=new Map;for(const o of C()){const c=a.get(o.from_id);c===void 0?a.set(o.from_id,[o.to_id]):c.push(o.to_id)}const i=Object.fromEntries(n.map(o=>[o.node_id,a.get(o.node_id)??[]]));return{status:200,body:{generated_at:k(),nodes:s,subscriptions:i}}}u(me,"handleSnapshot");function O(){const t=D().map(n=>{const r=n.host_kind??"tmux";return{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:r,enterable:r==="broker",parent:n.parent,created:n.created}}),e=C().map(n=>({from_id:n.from_id,to_id:n.to_id,active:n.active,created:n.created}));return{generated_at:k(),nodes:t,edges:e}}u(O,"buildRoster");let g=null,w=null;function pe(){return g===null?(g=Promise.resolve().then(()=>O()).finally(()=>{g=null}),g):(w===null&&(w=g.then(()=>O()).finally(()=>{w=null})),w)}u(pe,"rosterCoalesced");async function he(){return{status:200,body:await pe()}}u(he,"handleRoster");function ye(){return{status:200,body:{generated_at:k(),nodes:I().map(ee),edges:C().map(e=>({from_id:e.from_id,to_id:e.to_id,active:e.active,created:e.created})),focused_node_ids:R().map(e=>e.node_id)}}}u(ye,"handleGraph");function _e(t){if(t==null)return{};if(typeof t!="object")throw p("prune body must be a JSON object");const e=t,n=u(f=>{const m=e[f];if(m!==void 0){if(typeof m!="number"||!Number.isFinite(m))throw p(`${f} must be a number`);return m}},"num"),r=u(f=>{const m=e[f];if(m!==void 0){if(typeof m!="boolean")throw p(`${f} must be a boolean`);return m}},"bool"),s={},a=n("limit");a!==void 0&&(s.limit=a);const i=n("ttl_days");i!==void 0&&(s.ttl_days=i);const d=r("include_stale");d!==void 0&&(s.include_stale=d);const o=r("empty");o!==void 0&&(s.empty=o);const c=r("dry_run");return c!==void 0&&(s.dry_run=c),s}u(_e,"parsePruneBody");function be(t){const e=_e(t.body),n=e.ttl_days??14,r=e.dry_run??!1;let s;return e.limit!==void 0?s=A({maxNodes:e.limit,dryRun:r}).pruned.map(d=>({node_id:d.node_id,status:d.status,created:d.created})):e.empty===!0?s=X({dryRun:r}).map(d=>({node_id:d,status:"empty",created:""})):s=K({ttlDays:n,dryRun:r,includeStale:e.include_stale??!1}).pruned.map(d=>({node_id:d.node_id,status:d.status,created:d.created})),{status:200,body:{pruned:s,dry_run:r,ttl_days:n}}}u(be,"handlePrune");const Te=[{method:"GET",pattern:"/v1/canvas/attention",handler:te},{method:"POST",pattern:"/v1/canvas/attention/counts",handler:ne},{method:"POST",pattern:"/v1/canvas/history/search",handler:ue},{method:"POST",pattern:"/v1/canvas/history/grep",handler:ce},{method:"GET",pattern:"/v1/canvas/history/read",handler:le},{method:"POST",pattern:"/v1/canvas/history/stats",handler:ae},{method:"GET",pattern:"/v1/canvas/snapshot",handler:me},{method:"GET",pattern:"/v1/canvas/roster",handler:he},{method:"GET",pattern:"/v1/canvas/graph",handler:ye},{method:"POST",pattern:"/v1/canvas/prune",handler:be}];export{Te as canvasRoutes};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { RouteTable } from '../router.js';
|
|
2
|
-
export declare
|
|
2
|
+
export declare function healthRoutes(tcpAddress: () => string | null): RouteTable;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var u=Object.defineProperty;var e=(t
|
|
1
|
+
var u=Object.defineProperty;var e=(o,t)=>u(o,"name",{value:t,configurable:!0});import{openDb as n}from"../../../core/canvas/db.js";import{apiSocketPath as i}from"../../../core/canvas/paths.js";import{currentVersion as c}from"../../../core/self-update.js";import{API_VERSION as p}from"../../../api/index.js";import{DEFAULT_INTERVAL_MS as d}from"../../supervise-cadence.js";import{isPidAlive as l}from"../../../core/canvas/pid.js";import{boundDaemonControl as s}from"../../control.js";const _=d;function a(){try{return n().prepare("SELECT 1 FROM nodes LIMIT 1").get(),!0}catch{return!1}}e(a,"canvasAccessible");function m(){const o={},t=n().prepare(`
|
|
2
2
|
SELECT status, COUNT(*) AS count
|
|
3
3
|
FROM node_rows
|
|
4
4
|
WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
5
5
|
GROUP BY status
|
|
6
|
-
`).all();for(const
|
|
6
|
+
`).all();for(const r of t)o[r.status]=r.count;return o}e(m,"nodeCounts");function h(){return n().prepare(`
|
|
7
7
|
SELECT pi_pid
|
|
8
8
|
FROM node_rows
|
|
9
9
|
WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
@@ -11,4 +11,4 @@ var u=Object.defineProperty;var e=(t,o)=>u(t,"name",{value:o,configurable:!0});i
|
|
|
11
11
|
AND pi_pid IS NOT NULL
|
|
12
12
|
AND turn_open_at IS NOT NULL
|
|
13
13
|
AND turn_closed_at IS NULL
|
|
14
|
-
`).all().filter(
|
|
14
|
+
`).all().filter(t=>l(t.pi_pid)).length}e(h,"busyNodeCount");function E(){const o=a(),t=s()?.startupBlock()??null,r={ok:o&&t===null,daemon_up:!0,store_accessible:o,brokers_reconciled:t===null,startup_phase:t?.phase??"ready",...t===null?{}:{startup_blocked:t.message}};return{status:r.ok?200:503,body:r}}e(E,"handleHealthz");function f(o){if(!a())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:{daemon_pid:process.pid,tick_interval_ms:_,node_counts:m(),busy_node_count:h(),listeners:{socket_path:i(),tcp:o()},runtime_version:c(),api_version:p,startup_phase:s()?.startupBlock()?.phase??"ready"}}}e(f,"handleStatus");function R(o){return[{method:"GET",pattern:"/healthz",handler:e(t=>E(),"handler")},{method:"GET",pattern:"/v1/status",handler:e(t=>f(o),"handler")}]}e(R,"healthRoutes");export{R as healthRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var o=(n,t)=>L(n,"name",{value:t,configurable:!0});import{homedir as P}from"node:os";import{join as k}from"node:path";import{deleteAuthCredential as A,readAuthCredentials as I,setAuthCredential as q}from"../../../core/auth-file.js";import{ApiError as u}from"../../../api/index.js";import{usage as y}from"../../../core/errors.js";import{resolveLaunchTarget as R}from"../../../core/runtime/launch-target.js";import{ANTHROPIC_PROVIDER_ID as D,OPENAI_CODEX_PROVIDER_ID as O,commitManagedLogin as $,readSubscriptionPool as w,removeAllManagedAccounts as M}from"../../../core/subscription-state.js";function l(){const n=process.env.PI_CODING_AGENT_DIR,t=n!==void 0&&n!==""?n:k(P(),".pi","agent");return k(t,"auth.json")}o(l,"authPath");function f(n){return n===D||n===O}o(f,"isManagedProvider");function E(n,t){if(typeof t!="string"||t==="")throw new u(400,"invalid_request",`oauth credential requires \`${n}\``);const e=Date.parse(t);if(Number.isNaN(e))throw new u(400,"invalid_request",`\`${n}\` is not a valid ISO timestamp`);return e}o(E,"parseExpiry");function h(n,t,e){if(typeof e!="string"||e==="")throw new u(400,"invalid_request",`${n} credential requires \`${t}\``);return e}o(h,"requireField");function N(n){return{label:n.label,expires_at:new Date(n.expires).toISOString(),rate_limited_until:new Date(n.rateLimitedUntil).toISOString(),...n.authFailure?{auth_failure:n.authFailure}:{},...n.accountId?{account_id:n.accountId}:{}}}o(N,"toManagedAccountStatus");function S(n){const t=w(n).map(N);return{provider:n,managed:!0,configured:t.length>0,accounts:t}}o(S,"managedStatus");function g(n,t){const e=n.query.getAll(t);if(e.length>1)throw y(`${t} must appear at most once`);return e[0]}o(g,"singleQueryValue");function T(n){const t=n.indexOf("/"),e=t>0?n.slice(0,t):"";if(e==="")throw new u(422,"unresolved_model","the selected launch has no concrete model provider");return e}o(T,"providerFromModel");async function C(){const n=await I(l()),t=[S(D),S(O)];for(const[e,a]of Object.entries(n))f(e)||a.type!=="api_key"&&a.type!=="oauth"||t.push({provider:e,managed:!1,configured:!0,kind:a.type});return{status:200,body:{providers:t}}}o(C,"handleList");async function F(n){for(const[s]of n.query)if(s!=="profile"&&s!=="cwd"&&s!=="kind"&&s!=="model")throw y(`unknown model-auth readiness query parameter: ${s}`);const t=g(n,"profile"),e=g(n,"cwd"),a=g(n,"kind"),r=g(n,"model");if(a!==void 0&&a.trim()==="")throw y("kind must be a non-empty string when provided");if(r!==void 0&&r.trim()==="")throw y("model must be a non-empty string when provided");const d=await R({root:!0,...t!==void 0?{profile:t}:{},...e!==void 0?{cwd:e}:{},...a!==void 0?{kind:a}:{},...r!==void 0?{model:r}:{}},{readOnlyProfileSelection:!0});if(d.launch.model===void 0)throw new u(422,"unresolved_model","the selected launch has no concrete model");const i=T(d.launch.model),c=await I(l());if(f(i)){const s=w(i),m=s.filter(p=>p.authFailure===void 0);if(m.length===0)return{status:200,body:s.length===0?{provider:i,model:d.launch.model,credential:"missing"}:{provider:i,model:d.launch.model,credential:"unusable",reason:"invalid_grant"}};const v=Date.now(),x=m.some(p=>p.rateLimitedUntil<=v),b=Math.min(...m.map(p=>p.rateLimitedUntil));return{status:200,body:{provider:i,model:d.launch.model,credential:"ready",...!x&&b>v?{rate_limited_until:new Date(b).toISOString()}:{}}}}const _=c[i];return{status:200,body:{provider:i,model:d.launch.model,credential:_?.type==="api_key"||_?.type==="oauth"?"ready":"missing"}}}o(F,"handleReadiness");async function j(n){const t=n.params.provider,e=n.body;if(e===void 0||typeof e!="object"||typeof e.kind!="string")throw new u(400,"invalid_request","a credential `kind` is required");switch(e.kind){case"api_key":{const a=h("api_key","api_key",e.api_key);return await q(t,{type:"api_key",key:a},l()),{status:200,body:{provider:t,installed:!0,managed:!1}}}case"oauth":{if(f(t))throw new u(422,"unprocessable",`provider ${t} stores oauth credentials as managed accounts \u2014 use kind \`managed_account\``);const a=h("oauth","access_token",e.access_token),r=h("oauth","refresh_token",e.refresh_token),d=E("expires_at",e.expires_at),i=e.extra??{};await q(t,{type:"oauth",...i,access:a,refresh:r,expires:d},l());const c={provider:t,installed:!0,managed:!1};return typeof e.account_id=="string"&&e.account_id!==""&&(c.account_id=e.account_id),{status:200,body:c}}case"managed_account":{if(!f(t))throw new u(422,"unprocessable",`provider ${t} does not support managed accounts`);const a=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0;if(!a&&e.auto_label!==!0)throw new u(400,"invalid_request","managed_account credential requires `label` or `auto_label`");const r=typeof e.account_id=="string"&&e.account_id!==""?e.account_id:void 0,d=h("managed_account","access_token",e.access_token),i=h("managed_account","refresh_token",e.refresh_token),c=E("expires_at",e.expires_at),_=typeof e.last_rate_limited_at=="number"?e.last_rate_limited_at:Math.max(0,...w(t).map(m=>m.lastRateLimitedAt));await $(t,a,{refresh:i,access:d,expires:c,...r?{accountId:r}:{},lastRateLimitedAt:_,autoLabel:e.auto_label===!0});const s={provider:t,installed:!0,managed:!0};return r&&(s.account_id=r),{status:200,body:s}}default:throw new u(400,"invalid_request",`unknown credential kind: ${String(e.kind)}`)}}o(j,"handleInstall");async function G(n){const t=n.params.provider;if(f(t)){const a=await M(t),r=await A(t,l());return{status:200,body:{provider:t,removed_accounts:a+(r?1:0)}}}const e=await A(t,l())?1:0;return{status:200,body:{provider:t,removed_accounts:e}}}o(G,"handleDelete");const J=[{method:"GET",pattern:"/v1/model-auth",handler:C},{method:"GET",pattern:"/v1/model-auth/readiness",handler:F},{method:"PUT",pattern:"/v1/model-auth/:provider",handler:j},{method:"DELETE",pattern:"/v1/model-auth/:provider",handler:G}];export{J as modelAuthRoutes};
|
package/dist/daemon/api/map.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { CloseNodeResult } from '../../core/runtime/close.js';
|
|
|
7
7
|
import { type PushResult } from '../../core/feed/feed.js';
|
|
8
8
|
import type { PageFeedback, PageFeedbackComment } from '../../core/human/feedback.js';
|
|
9
9
|
import type { OnDiskMigrationRunResult } from '../../migrations/runner.js';
|
|
10
|
-
import type { CloseResultDTO, CronDTO, CronRunDTO, ErrorBody, NodeEdgesDTO, NodeOutcomeDTO, NodeOutcomeSummaryDTO, NodePathsDTO, NodeStatusDTO, OutcomeDeliveryDTO, NodeSummaryDTO, NodeDetailDTO, NodeWorktreeDTO, ProfileDTO, ReviewCommentDTO, ReviewCommentEventDTO, ReviewDTO, FeedbackResultDTO, PageFeedbackCommentDTO, PageFeedbackDTO, PushReportResultDTO, ReviveResultDTO, MigrateStateDTO, SubscriptionDTO } from '../../api/index.js';
|
|
10
|
+
import type { CloseResultDTO, CronDTO, CronRunDTO, ErrorBody, NodeEdgesDTO, NodeOutcomeDTO, NodeOutcomeSummaryDTO, NodePathsDTO, NodeStatusDTO, OutcomeDeliveryDTO, NodeSummaryDTO, NodeDetailDTO, NodeWorktreeDTO, ProfileDTO, ReviewCommentDTO, ReviewCommentEventDTO, ReviewDTO, FeedbackResultDTO, GraphNodeDTO, PageFeedbackCommentDTO, PageFeedbackDTO, PushReportResultDTO, ReviveResultDTO, MigrateStateDTO, SubscriptionDTO } from '../../api/index.js';
|
|
11
11
|
export declare function toMigrateStateDTO(result: OnDiskMigrationRunResult, options: {
|
|
12
12
|
resumed: boolean;
|
|
13
13
|
resumeError?: string;
|
|
@@ -37,6 +37,20 @@ export interface OutcomeDeliveryDTOInput {
|
|
|
37
37
|
/** Project a durable delivery row without exposing its execution coordinates or stderr tail. */
|
|
38
38
|
export declare function toOutcomeDeliveryDTO(row: OutcomeDeliveryDTOInput): OutcomeDeliveryDTO;
|
|
39
39
|
/** Project the queryable row (what `listNodes` yields) into a summary DTO. */
|
|
40
|
+
export declare function toGraphNodeDTO(row: {
|
|
41
|
+
node_id: string;
|
|
42
|
+
name: string;
|
|
43
|
+
description: string | null;
|
|
44
|
+
cycles: number | null;
|
|
45
|
+
kind: string;
|
|
46
|
+
status: NodeStatusDTO;
|
|
47
|
+
frozen_at: string | null;
|
|
48
|
+
pi_pid: number | null;
|
|
49
|
+
telemetry_context_tokens: number | null;
|
|
50
|
+
telemetry_last_activity: string | null;
|
|
51
|
+
fault: NodeRow['fault'];
|
|
52
|
+
streaming: boolean;
|
|
53
|
+
}): GraphNodeDTO;
|
|
40
54
|
export declare function toNodeSummaryDTO(row: NodeRow): NodeSummaryDTO;
|
|
41
55
|
/** The subscription/child edges a detail projection needs. The handler gathers
|
|
42
56
|
* these from `subscriptionsOf`/`subscribersOf` + a children query and passes
|
package/dist/daemon/api/map.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{existsSync as h,readFileSync as v}from"node:fs";import{join as g}from"node:path";import{outputResultPath as b}from"../../core/runtime/structured-output.js";import{ReviewOperationError as u}from"../../core/review/types.js";import{cronSinkDisplay as k}from"../../core/canvas/crons.js";import{isProfilePaused as l,sanitizeProfileMetadata as x}from"../../core/profiles/manifest.js";import{contextDir as y,nodeDir as O,nodeMetaPath as D,reportsDir as c,transcriptPath as T,viewSocketPath as S}from"../../core/canvas/paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as A}from"../../core/runtime/nodes.js";import{readContextTokens as E}from"../../core/canvas/telemetry.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as N}from"../../core/worktree.js";import{ApiError as z}from"../../api/errors.js";import{ExitCode as d}from"../../types.js";function se(e,t){const{discovery:i,snapshots:r}=e;return{profiles:e.profiles,stores:i.stores.length,changed:e.changed,applied:e.applied,skipped:e.skipped,blockers:e.blockers.map(n=>({kind:n.kind,message:n.message,...n.storeRoot===void 0?{}:{store:n.storeRoot},...n.targetId===void 0?{}:{target:n.targetId},...n.path===void 0?{}:{path:n.path},...n.name===void 0?{}:{name:n.name},...n.paths===void 0?{}:{paths:n.paths}})),discovery_roots:i.roots.map(n=>({reason:n.reason,root:n.root,boundary:n.boundary,...n.detail===void 0?{}:{detail:n.detail}})),discovered_stores:i.stores.map(n=>({store:n.key,scope:n.descriptor.scope,namespace:n.descriptor.namespace,mount_status:n.descriptor.mountStatus,writable:n.writable,reasons:[...new Set(n.discovery.map(a=>a.reason))],targets:n.targets,docs:r.get(n.key)?.docs.length??0})),discovered_targets:i.targets.map(n=>({id:n.id,kind:n.kind,origin:n.origin,cwd:n.target.cwd,profile_id:n.target.profileId,node_id:n.target.nodeId,stores:n.storeKeys})),repository_namespaces:e.repositories.map(n=>({repository_root:n.repositoryRoot,repository_key:n.repositoryKey,declaration_path:n.declarationPath,namespace:n.namespace,source:n.source,action:n.action})),store_prefixes:e.storePrefixes.map(n=>({store_root:n.storeRoot,owner_dir:n.ownerDir,repository_root:n.repositoryRoot,owner_relative_path:n.ownerRelativePath,old_prefix:n.oldPrefix,old_rule:n.oldRule,effective_prefix:n.effectivePrefix,nested_declaration_action:n.nestedDeclarationAction,front_door_action:n.frontDoorAction})),renames:e.renames.map(n=>({store_root:n.storeRoot,path:n.path,from:n.from,to:n.to})),references:e.references.map(n=>({store_root:n.storeRoot,path:n.path,kind:n.kind,from:n.from,to:n.to})),dryRun:e.dryRun,blocked:e.blocked,corpus_phase:e.corpusPhase,wrote:{profile_manifests:e.wrote.profileManifests,documents:e.wrote.documents,corpus_consumers:e.wrote.corpusConsumers,corpus_identities:e.wrote.corpusIdentities},resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}o(se,"toMigrateStateDTO");function C(e){const t=b(e);try{return h(t)?JSON.parse(v(t,"utf8")):null}catch{return null}}o(C,"readStructuredResult");function P(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}o(P,"toNodeOutcomeSummaryDTO");function j(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const i=e.final_report??null,r={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:i,final_report_path:i===null?null:`${c(e.node_id)}/${i}`,structured_result:e.outcome_kind==="result"?C(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...r,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...r,kind:"failure",reason:"declined",declined:t?.declined??null}:{...r,kind:"failure",reason:e.outcome_reason,declined:null}}o(j,"toNodeOutcomeDTO");function _e(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}o(_e,"toOutcomeDeliveryDTO");function ue(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,profile_paused:l(e.profile_id),parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,outcome:P(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}o(ue,"toNodeSummaryDTO");function I(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(i=>i.node_id),subscribers:t.subscribers.map(i=>i.node_id),children:[...t.children]}}o(I,"toNodeEdgesDTO");function q(e){return{node_dir:O(e),context_dir:y(e),reports_dir:c(e),meta_path:D(e),transcript_path:T(e),view_socket:S(e)}}o(q,"toNodePathsDTO");function F(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}o(F,"toNodeWorktreeDTO");function le(e,t){const i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,profile_paused:l(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,outcome:j(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:I(e,t),paths:q(e.node_id)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=E(e.node_id),e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=F(e.managed_worktree)),i}o(le,"toNodeDetailDTO");function ce(e,t,i){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:i,outcome:t.outcome}}o(ce,"toReviveResultDTO");function pe(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}o(pe,"toCloseResultDTO");function fe(e,t,i){const r={report_path:e.reportPath,notified:[...e.deliveredTo]};return t!==void 0&&(r.transitioned=t),i!==void 0&&(r.worktree_auto_dropped=!0,r.worktree_auto_dropped_path=i),r}o(fe,"toReportResultDTO");function me(e){return{node_id:e.node_id,active:e.active,created:e.created}}o(me,"toSubscriptionDTO");function M(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}o(M,"envKeys");function he(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:M(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:k(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}o(he,"toCronDTO");function ve(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}o(ve,"toCronRunDTO");function ge(e){return{id:e.profileId,name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),home:e.manifest.home,paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:x(e.manifest.metadata),default_dir:null}}o(ge,"toProfileDTO");function p(e,t={}){const i={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.opened_at!==null&&(i.opened_at=e.opened_at),e.submit_requested_at!==null&&(i.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(i.approved_at=e.approved_at),e.changed!==null&&(i.changed=e.changed),e.comments_total!==null&&(i.comments_total=e.comments_total),e.comments_unresolved!==null&&(i.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(i.canceled_at=e.canceled_at),e.cancel_reason!==null&&(i.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(i.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(i.result_path=t.result_path),e.delivery_error!==null&&(i.delivery_error=e.delivery_error),e.projection_error!==null&&(i.projection_error=e.projection_error),i}o(p,"toReviewDTO");function be(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}o(be,"toReviewCommentDTO");function U(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}o(U,"toPageFeedbackCommentDTO");function ke(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(U)}}o(ke,"toPageFeedbackDTO");function xe(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}o(xe,"toReviewCommentEventDTO");function ye(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(i=>({...i})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}o(ye,"toFeedbackResultDTO");const G=!0,K=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_origin_unstable:{status:409,code:"review_origin_unstable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function w(e){const t=f(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof A)return{status:409,code:"node_id_exists"};if(t instanceof u)return K[t.code];if(t instanceof s)return{status:$(t.exitCode),code:t.code};if(t instanceof Error){const i=t.message;if(/unknown node/i.test(i))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(i))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(i))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}o(w,"errorToStatus");function f(e){if(!(e instanceof N))return e;const t=e.code==="unknown_node"?d.NOT_FOUND:d.GENERAL,i={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(i.received=e.detail),new s(e.code,e.message,t,i)}o(f,"normalizeThrow");function L(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...i}=e.detail;return{...i,review:W(t)}}o(L,"reviewErrorDetails");function W(e){return e.state!=="approved"?p(e):p(e,{result_path:g(e.review_dir,"result.json")})}o(W,"terminalConflictReviewDTO");function $(e){switch(e){case d.NOT_FOUND:return 404;case d.USAGE:return 400;case d.AMBIGUOUS:return 400;case d.NETWORK:return 503;case d.GENERAL:return 400;default:return 500}}o($,"statusForExitCode");function B(e){const i=(e instanceof Error?e.message:String(e)).split(`
|
|
2
|
-
`,1)[0].trim();return i===""?"internal error":i.length>500?`${i.slice(0,497)}\u2026`:i}o(B,"boundedCause");function
|
|
1
|
+
var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{existsSync as h,readFileSync as v}from"node:fs";import{join as g}from"node:path";import{outputResultPath as y}from"../../core/runtime/structured-output.js";import{ReviewOperationError as l}from"../../core/review/types.js";import{cronSinkDisplay as k}from"../../core/canvas/crons.js";import{isProfilePaused as u,sanitizeProfileMetadata as b}from"../../core/profiles/manifest.js";import{contextDir as x,nodeDir as O,nodeMetaPath as D,reportsDir as c,transcriptPath as T,viewSocketPath as S}from"../../core/canvas/paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as A}from"../../core/runtime/nodes.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as E}from"../../core/worktree.js";import{ApiError as N}from"../../api/errors.js";import{ExitCode as d}from"../../types.js";function de(e,t){const{discovery:i,snapshots:r}=e;return{profiles:e.profiles,stores:i.stores.length,changed:e.changed,applied:e.applied,skipped:e.skipped,blockers:e.blockers.map(n=>({kind:n.kind,message:n.message,...n.storeRoot===void 0?{}:{store:n.storeRoot},...n.targetId===void 0?{}:{target:n.targetId},...n.path===void 0?{}:{path:n.path},...n.name===void 0?{}:{name:n.name},...n.paths===void 0?{}:{paths:n.paths}})),discovery_roots:i.roots.map(n=>({reason:n.reason,root:n.root,boundary:n.boundary,...n.detail===void 0?{}:{detail:n.detail}})),discovered_stores:i.stores.map(n=>({store:n.key,scope:n.descriptor.scope,namespace:n.descriptor.namespace,mount_status:n.descriptor.mountStatus,writable:n.writable,reasons:[...new Set(n.discovery.map(a=>a.reason))],targets:n.targets,docs:r.get(n.key)?.docs.length??0})),discovered_targets:i.targets.map(n=>({id:n.id,kind:n.kind,origin:n.origin,cwd:n.target.cwd,profile_id:n.target.profileId,node_id:n.target.nodeId,stores:n.storeKeys})),repository_namespaces:e.repositories.map(n=>({repository_root:n.repositoryRoot,repository_key:n.repositoryKey,declaration_path:n.declarationPath,namespace:n.namespace,source:n.source,action:n.action})),store_prefixes:e.storePrefixes.map(n=>({store_root:n.storeRoot,owner_dir:n.ownerDir,repository_root:n.repositoryRoot,owner_relative_path:n.ownerRelativePath,old_prefix:n.oldPrefix,old_rule:n.oldRule,effective_prefix:n.effectivePrefix,nested_declaration_action:n.nestedDeclarationAction,front_door_action:n.frontDoorAction})),renames:e.renames.map(n=>({store_root:n.storeRoot,path:n.path,from:n.from,to:n.to})),references:e.references.map(n=>({store_root:n.storeRoot,path:n.path,kind:n.kind,from:n.from,to:n.to})),dryRun:e.dryRun,blocked:e.blocked,corpus_phase:e.corpusPhase,wrote:{profile_manifests:e.wrote.profileManifests,documents:e.wrote.documents,corpus_consumers:e.wrote.corpusConsumers,corpus_identities:e.wrote.corpusIdentities},resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}o(de,"toMigrateStateDTO");function z(e){const t=y(e);try{return h(t)?JSON.parse(v(t,"utf8")):null}catch{return null}}o(z,"readStructuredResult");function P(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}o(P,"toNodeOutcomeSummaryDTO");function C(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const i=e.final_report??null,r={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:i,final_report_path:i===null?null:`${c(e.node_id)}/${i}`,structured_result:e.outcome_kind==="result"?z(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...r,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...r,kind:"failure",reason:"declined",declined:t?.declined??null}:{...r,kind:"failure",reason:e.outcome_reason,declined:null}}o(C,"toNodeOutcomeDTO");function ae(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}o(ae,"toOutcomeDeliveryDTO");function se(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}o(se,"toGraphNodeDTO");function _e(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,profile_paused:u(e.profile_id),parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:P(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}o(_e,"toNodeSummaryDTO");function j(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(i=>i.node_id),subscribers:t.subscribers.map(i=>i.node_id),children:[...t.children]}}o(j,"toNodeEdgesDTO");function I(e){return{node_dir:O(e),context_dir:x(e),reports_dir:c(e),meta_path:D(e),transcript_path:T(e),view_socket:S(e)}}o(I,"toNodePathsDTO");function q(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}o(q,"toNodeWorktreeDTO");function le(e,t){const i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,profile_paused:u(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:C(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:j(e,t),paths:I(e.node_id)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=q(e.managed_worktree)),i}o(le,"toNodeDetailDTO");function ue(e,t,i){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:i,outcome:t.outcome}}o(ue,"toReviveResultDTO");function ce(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}o(ce,"toCloseResultDTO");function pe(e,t,i){const r={report_path:e.reportPath,notified:[...e.deliveredTo]};return t!==void 0&&(r.transitioned=t),i!==void 0&&(r.worktree_auto_dropped=!0,r.worktree_auto_dropped_path=i),r}o(pe,"toReportResultDTO");function fe(e){return{node_id:e.node_id,active:e.active,created:e.created}}o(fe,"toSubscriptionDTO");function F(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}o(F,"envKeys");function me(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:F(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:k(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}o(me,"toCronDTO");function he(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}o(he,"toCronRunDTO");function ve(e){return{id:e.profileId,name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),home:e.manifest.home,paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:b(e.manifest.metadata),default_dir:null}}o(ve,"toProfileDTO");function p(e,t={}){const i={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.opened_at!==null&&(i.opened_at=e.opened_at),e.submit_requested_at!==null&&(i.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(i.approved_at=e.approved_at),e.changed!==null&&(i.changed=e.changed),e.comments_total!==null&&(i.comments_total=e.comments_total),e.comments_unresolved!==null&&(i.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(i.canceled_at=e.canceled_at),e.cancel_reason!==null&&(i.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(i.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(i.result_path=t.result_path),e.delivery_error!==null&&(i.delivery_error=e.delivery_error),e.projection_error!==null&&(i.projection_error=e.projection_error),i}o(p,"toReviewDTO");function ge(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}o(ge,"toReviewCommentDTO");function M(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}o(M,"toPageFeedbackCommentDTO");function ye(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(M)}}o(ye,"toPageFeedbackDTO");function ke(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}o(ke,"toReviewCommentEventDTO");function be(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(i=>({...i})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}o(be,"toFeedbackResultDTO");const U=!0,G=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_origin_unstable:{status:409,code:"review_origin_unstable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function K(e){const t=f(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof A)return{status:409,code:"node_id_exists"};if(t instanceof l)return G[t.code];if(t instanceof s)return{status:$(t.exitCode),code:t.code};if(t instanceof Error){const i=t.message;if(/unknown node/i.test(i))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(i))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(i))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}o(K,"errorToStatus");function f(e){if(!(e instanceof E))return e;const t=e.code==="unknown_node"?d.NOT_FOUND:d.GENERAL,i={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(i.received=e.detail),new s(e.code,e.message,t,i)}o(f,"normalizeThrow");function L(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...i}=e.detail;return{...i,review:W(t)}}o(L,"reviewErrorDetails");function W(e){return e.state!=="approved"?p(e):p(e,{result_path:g(e.review_dir,"result.json")})}o(W,"terminalConflictReviewDTO");function $(e){switch(e){case d.NOT_FOUND:return 404;case d.USAGE:return 400;case d.AMBIGUOUS:return 400;case d.NETWORK:return 503;case d.GENERAL:return 400;default:return 500}}o($,"statusForExitCode");function B(e){const i=(e instanceof Error?e.message:String(e)).split(`
|
|
2
|
+
`,1)[0].trim();return i===""?"internal error":i.length>500?`${i.slice(0,497)}\u2026`:i}o(B,"boundedCause");function xe(e){const t=f(e),{status:i,code:r}=K(t);if(i>=500)return{status:i,body:{error:{code:r,message:B(t)}}};const n=t instanceof Error?t.message:String(t),a=t instanceof l?L(t):(t instanceof s||t instanceof N)&&t.details!==void 0?t.details:void 0,_={error:{code:r,message:n}};return a!==void 0&&(_.error.details=a),{status:i,body:_}}o(xe,"toErrorBody");export{G as REVIEW_ERROR_MAP,K as errorToStatus,ce as toCloseResultDTO,me as toCronDTO,he as toCronRunDTO,xe as toErrorBody,be as toFeedbackResultDTO,se as toGraphNodeDTO,de as toMigrateStateDTO,le as toNodeDetailDTO,j as toNodeEdgesDTO,C as toNodeOutcomeDTO,P as toNodeOutcomeSummaryDTO,I as toNodePathsDTO,_e as toNodeSummaryDTO,q as toNodeWorktreeDTO,ae as toOutcomeDeliveryDTO,M as toPageFeedbackCommentDTO,ye as toPageFeedbackDTO,ve as toProfileDTO,pe as toReportResultDTO,ge as toReviewCommentDTO,ke as toReviewCommentEventDTO,p as toReviewDTO,ue as toReviveResultDTO,fe as toSubscriptionDTO};
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
export interface CreateApiServerOptions {
|
|
2
2
|
/** Opt-in TCP listener as `host:port` (or `:port` for all interfaces).
|
|
3
|
-
* Falls back to `CRTRD_TCP
|
|
3
|
+
* Falls back to `CRTRD_TCP`, then the user setting. Absent → unix socket only. */
|
|
4
4
|
tcp?: string;
|
|
5
|
+
/** Bearer token for the TCP listener. Falls back to `CRTRD_TOKEN`, then the 0600 user secrets store. */
|
|
6
|
+
token?: string;
|
|
5
7
|
}
|
|
6
8
|
export interface ApiServer {
|
|
7
9
|
/** Settles only after the mandatory Unix socket binds; rejects on its bind failure. */
|
|
8
10
|
ready: Promise<void>;
|
|
11
|
+
/** The actual bound TCP address, including a kernel-selected port; null when TCP is off or not yet bound. */
|
|
12
|
+
tcpAddress(): string | null;
|
|
9
13
|
/** Tear down both listeners and unlink the socket file. Double-close safe. */
|
|
10
14
|
close(): Promise<void>;
|
|
11
15
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var j=Object.defineProperty;var i=(t
|
|
1
|
+
var j=Object.defineProperty;var i=(e,t)=>j(e,"name",{value:t,configurable:!0});import{createServer as w}from"node:http";import{chmodSync as z,existsSync as C,unlinkSync as O}from"node:fs";import{apiSocketPath as x}from"../../core/canvas/paths.js";import{readConfig as G}from"../../core/config.js";import{getApiToken as J}from"../../core/secrets.js";import{emitEvent as g}from"../../core/events/emit.js";import{envCrtrdTcp as L,envCrtrdToken as _}from"../../shared/env.js";import{Router as U}from"./router.js";import{handleAttachUpgrade as D}from"./bridge.js";import{boundDaemonControl as F}from"../control.js";import{attachRoutes as M}from"./handlers/attach.js";import{bashJobRoutes as Y}from"./handlers/bash-jobs.js";import{brokerOperationRoutes as k}from"./handlers/broker-ops.js";import{brokerRecoveryRoutes as E,nodeFaultRoutes as Z}from"./handlers/broker-recovery.js";import{canvasRoutes as K}from"./handlers/canvas.js";import{chatInventoryRoutes as Q}from"./handlers/chat-inventory.js";import{daemonRoutes as V}from"./handlers/daemon.js";import{fileRoutes as W}from"./handlers/files.js";import{focusRoutes as X}from"./handlers/focus.js";import{healthRoutes as q}from"./handlers/health.js";import{humanRequestRoutes as ee}from"./handlers/human-requests.js";import{inboxRoutes as re}from"./handlers/inbox.js";import{feedbackCommentRoutes as te}from"./handlers/feedback-comments.js";import{memoryRoutes as oe}from"./handlers/memory.js";import{brokerMailRoutes as P,messageRoutes as ne}from"./handlers/messages.js";import{modelAuthRoutes as ie}from"./handlers/modelauth.js";import{modelConfigRoutes as se}from"./handlers/model-config.js";import{nodeRoutes as le}from"./handlers/nodes.js";import{nodeOutcomeRoutes as ce}from"./handlers/node-outcomes.js";import{profileRoutes as ae}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as ue}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as de}from"./handlers/reports.js";import{reviewCommentRoutes as pe}from"./handlers/review-comments.js";import{reviewRoutes as me}from"./handlers/reviews.js";import{subscriptionRoutes as fe}from"./handlers/subscriptions.js";import{cronRoutes as ge}from"./handlers/crons.js";import{worktreeRoutes as he}from"./handlers/worktree.js";function Ae(e){return new U().registerAll(q(e)).registerAll(V).registerAll(le).registerAll(ce).registerAll(Y).registerAll(k).registerAll(E).registerAll(Z).registerAll(he).registerAll(P).registerAll(ne).registerAll(de).registerAll(M).registerAll(K).registerAll(W).registerAll(oe).registerAll(X).registerAll(fe).registerAll(ge).registerAll(ae).registerAll(ie).registerAll(se).registerAll(me).registerAll(pe).registerAll(re).registerAll(ee).registerAll(Q).registerAll(ue).registerAll(te)}i(Ae,"buildRouter");function ye(e,t){if(e.toUpperCase()!=="GET")return null;const s=t.split("/").filter(m=>m.length>0);if(s.length!==4||s[0]!=="v1"||s[1]!=="nodes"||s[3]!=="attach")return null;const a=s[2];return a===void 0||a===""?null:decodeURIComponent(a)}i(ye,"attachNodeId");function Re(e){const t=e.trim();if(t==="")return null;const s=t.lastIndexOf(":");if(s<0)return null;const a=t.slice(0,s),m=t.slice(s+1),c=Number(m);return!Number.isInteger(c)||c<0||c>65535?null:{host:a===""?"0.0.0.0":a,port:c}}i(Re,"parseTcp");function ve(e,t){return`${e.includes(":")?`[${e}]`:e}:${t}`}i(ve,"formatTcpAddress");const H={error:{code:"unauthorized",message:"missing or invalid bearer token"}};function N(e,t){return e.headers.authorization===`Bearer ${t}`}i(N,"isAuthorized");function Te(e){const t=JSON.stringify(H);e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(t)}i(Te,"writeUnauthorized");function Se(e,t){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:t}}))}i(Se,"writeStartupBlocked");function be(e,t){const s=JSON.stringify({error:{code:"startup_blocked",message:t}}),a=`HTTP/1.1 503 Service Unavailable\r
|
|
2
2
|
content-type: application/json; charset=utf-8\r
|
|
3
3
|
content-length: ${Buffer.byteLength(s)}\r
|
|
4
4
|
connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
${s}`;try{
|
|
6
|
+
${s}`;try{e.end(a)}catch{e.destroy()}}i(be,"destroyUpgradeStartupBlocked");function we(e){const t=JSON.stringify(H),s=`HTTP/1.1 401 Unauthorized\r
|
|
7
7
|
content-type: application/json; charset=utf-8\r
|
|
8
|
-
content-length: ${Buffer.byteLength(
|
|
8
|
+
content-length: ${Buffer.byteLength(t)}\r
|
|
9
9
|
connection: close\r
|
|
10
10
|
\r
|
|
11
|
-
${
|
|
11
|
+
${t}`;try{e.end(s)}catch{try{e.destroy()}catch{}}}i(we,"destroyUpgradeUnauthorized");function I(e){return new Promise(t=>{try{e.closeAllConnections()}catch{}e.close(()=>t())})}i(I,"closeServer");function ur(e={}){let t=null;const s=Ae(()=>t),a=new U().registerAll(k).registerAll(E).registerAll(P),m=i((o,r)=>{const u=F()?.startupBlock()??null;return u===null||o==="GET"&&(r==="/healthz"||r==="/v1/status")||o==="POST"&&(r==="/v1/daemon/migrate"||r==="/v1/daemon/admit")||u.phase==="recovering"&&a.match(o,r)!==null?null:u},"startupBlockFor"),c=x(),A=i((o,r)=>{const u=i(n=>{g({event:"api.request.failed",level:"error",error:n instanceof Error?n:new Error(String(n))});try{r.headersSent||r.writeHead(500,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify({error:{code:"internal",message:"internal error"}}))}catch{}},"internalFailure");let p;try{p=new URL(o.url??"/","http://127.0.0.1")}catch{try{r.writeHead(400,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid"}}))}catch{}return}try{const n=m((o.method??"GET").toUpperCase(),p.pathname);if(n!==null){Se(r,n.message);return}s.handle(o,r).catch(u)}catch(n){u(n)}},"onRequest"),y=i((o,r,u)=>{r.on("error",()=>{});try{const p=new URL(o.url??"/","http://127.0.0.1"),n=m((o.method??"GET").toUpperCase(),p.pathname);if(n!==null){be(r,n.message);return}const l=ye(o.method??"GET",p.pathname);if(l===null){r.destroy();return}D(o,r,u,l).catch(()=>{try{r.destroy()}catch{}})}catch{try{r.destroy()}catch{}}},"onUpgrade"),B=i(o=>{o.on("error",r=>{g({event:"api.server.failed",level:"error",error:r})})},"bindErrorHandler"),f=w(A);f.on("upgrade",y);let v=!1,T,S;const $=new Promise((o,r)=>{T=o,S=r});f.once("listening",()=>{v=!0,T()}),f.on("error",o=>{g({event:"api.server.failed",level:"error",error:o}),v||S(o)});try{C(c)&&O(c)}catch{}f.listen(c,()=>{try{z(c,384)}catch(o){g({event:"api.socket.chmod_failed",level:"error",error:o instanceof Error?o:new Error(String(o))})}});let d;const h=e.tcp??L()??G("user").api.tcp;if(h!==void 0&&h!==""){const o=Re(h);if(o===null)g({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${h}`)});else{const r=e.token??_()??J("user"),u=r===void 0?A:(n,l)=>{if((n.method??"GET").toUpperCase()==="OPTIONS"){l.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"authorization, content-type","Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),l.end();return}if(!N(n,r)){Te(l);return}l.setHeader("Access-Control-Allow-Origin","*"),A(n,l)},p=r===void 0?y:(n,l,R)=>{if(!N(n,r)){we(l);return}y(n,l,R)};d=w(u),d.on("upgrade",p),B(d),d.once("listening",()=>{const n=d?.address();if(n!==null&&typeof n=="object"){const{address:l,port:R}=n;t=ve(l,R)}}),d.listen(o.port,o.host)}}let b=!1;return{ready:$,tcpAddress:i(()=>t,"tcpAddress"),close:i(async()=>{if(!b){b=!0,await Promise.all([I(f),d!==void 0?I(d):Promise.resolve()]);try{C(c)&&O(c)}catch{}}},"close")}}i(ur,"createApiServer");export{ur as createApiServer};
|
package/dist/daemon/crtrd-cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var i=Object.defineProperty;var n=(r,e)=>i(r,"name",{value:e,configurable:!0});import"../suppress-experimental-warnings.js";import{runDaemon as c}from"./crtrd.js";function s(r){for(let e=0;e<r.length;e++){const t=r[e];if(t==="--tcp")return r[e+1];if(t!==void 0&&t.startsWith("--tcp="))return t.slice(6)}}n(s,"parseTcpArg");function a(r){return r.includes("--prepare")}n(a,"parsePrepareArg");const p=process.argv.slice(2);await c({tcp:s(p),prepare:a(p)});
|
package/dist/daemon/fleet.js
CHANGED
|
@@ -14,4 +14,4 @@ Fix the crash cause, then revive the node if the work still needs doing.`;await
|
|
|
14
14
|
|
|
15
15
|
The daemon refused this recovery before starting a broker: ${r}
|
|
16
16
|
|
|
17
|
-
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await v(s.node_id,t,{from:s.node_id})}l(D,"surfaceRecoveryFailure");function B(s){return s?.cycle_pending!==!0}l(B,"retryResumeMode");function L(s,e,r=!0){return s===null||s.status==="done"||s.status==="canceled"||s.status==="dead"?"forget":s.intent==="refresh"?"respawn-fresh":s.intent==="idle-release"?"dormant":s.lifecycle==="resident"&&!e&&!r&&s.pi_session_id!=null?"release-idle":s.pi_session_id!=null?B(s)?"respawn-resume":"respawn-cycle":e||s.fork_from!=null?"respawn-fresh":"boot-failure"}l(L,"classifyDeadNode");const W=3e4;class te{static{l(this,"DaemonFleet")}#n;#o;#s;#l;#e=new Map;#r=new Set;#i=new Set;#t=new Map;#c=Number.NEGATIVE_INFINITY;constructor(e){this.#n=e.epoch,this.#o=e.enqueue,this.#s=e.now??Date.now,this.#l=e.probeOnline??(()=>M())}epoch(){return this.#n}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#r.delete(e),this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}has(e){return this.#e.has(e)}isClaimed(e){return this.#e.has(e)||this.#r.has(e)}get(e){return this.#e.get(e)}size(){return this.#e.size}occupancy(){return this.#e.size+this.#r.size}reserveSlot(e){if(this.#r.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=A();if(this.occupancy()<r)return this.#r.add(e),!0;const t=this.#s();return t-this.#c>=W&&(this.#c=t,c({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:this.occupancy(),hard_cap:r}})),!1}releaseReservation(e){this.#r.delete(e)}entries(){return this.#e.entries()}interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r!==void 0){this.#i.add(e);try{process.kill(r,"SIGTERM")}catch{}}}hasProfilePauseInterruption(e){return this.#i.has(e)}forget(e){this.#e.delete(e),this.#r.delete(e),this.#t.delete(e)}onChildExit(e,r){const t=d(e),n=t?.launched_at==null?Number.NaN:Date.parse(t.launched_at),o=Number.isFinite(n)?Math.max(0,this.#s()-n):null,i=t?.respawn_failures??0;
|
|
17
|
+
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await v(s.node_id,t,{from:s.node_id})}l(D,"surfaceRecoveryFailure");function B(s){return s?.cycle_pending!==!0}l(B,"retryResumeMode");function L(s,e,r=!0){return s===null||s.status==="done"||s.status==="canceled"||s.status==="dead"?"forget":s.intent==="refresh"?"respawn-fresh":s.intent==="idle-release"?"dormant":s.lifecycle==="resident"&&!e&&!r&&s.pi_session_id!=null?"release-idle":s.pi_session_id!=null?B(s)?"respawn-resume":"respawn-cycle":e||s.fork_from!=null?"respawn-fresh":"boot-failure"}l(L,"classifyDeadNode");const W=3e4;class te{static{l(this,"DaemonFleet")}#n;#o;#s;#l;#e=new Map;#r=new Set;#i=new Set;#t=new Map;#c=Number.NEGATIVE_INFINITY;constructor(e){this.#n=e.epoch,this.#o=e.enqueue,this.#s=e.now??Date.now,this.#l=e.probeOnline??(()=>M())}epoch(){return this.#n}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#r.delete(e),this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}has(e){return this.#e.has(e)}isClaimed(e){return this.#e.has(e)||this.#r.has(e)}get(e){return this.#e.get(e)}size(){return this.#e.size}occupancy(){return this.#e.size+this.#r.size}reserveSlot(e){if(this.#r.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=A();if(this.occupancy()<r)return this.#r.add(e),!0;const t=this.#s();return t-this.#c>=W&&(this.#c=t,c({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:this.occupancy(),hard_cap:r}})),!1}releaseReservation(e){this.#r.delete(e)}entries(){return this.#e.entries()}interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r!==void 0){this.#i.add(e);try{process.kill(r,"SIGTERM")}catch{}}}hasProfilePauseInterruption(e){return this.#i.has(e)}forget(e){this.#e.delete(e),this.#r.delete(e),this.#t.delete(e)}onChildExit(e,r){this.#e.delete(e),this.#o(()=>{const t=d(e),n=t?.launched_at==null?Number.NaN:Date.parse(t.launched_at),o=Number.isFinite(n)?Math.max(0,this.#s()-n):null,i=t?.respawn_failures??0;t?.status==="done"||t?.status==="canceled"||t?.status==="dead"?this.#t.delete(e):this.#t.set(e,r),this.#u(e,r,o,i)})}deliverExit(e,r){this.onChildExit(e,r)}async applyDeadRowPolicy(e){const r=this.#t.get(e);try{await this.#f(e,r)}finally{this.#t.get(e)===r&&this.#t.delete(e)}}async terminalizeIfStillNonTerminal(e,r,t,n,o){const i=d(e);return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?!1:(await this.#a(e,i,{event:r,reason:n,detail:o,wake:`Child crashed \u2014 ${p(i)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>D(i,t),"surface")}),!0)}dispose(){}#u(e,r,t,n){c({level:"info",event:"broker.exit.observed",...a(e)?{node_id:e}:{},fields:{...a(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:n}})}async#f(e,r){return this.#h(e,r)}async#h(e,r){const t=d(e);if(t!==null&&$(t.profile_id))return h(e),"forget";if(this.#i.delete(e))return h(e),"forget";const n=P(e)?.interrupted===!0,o=L(t,n,E(e));switch(o){case"forget":h(e);break;case"dormant":h(e);break;case"release-idle":h(e),m(e,"release"),c({level:"info",event:"broker.recovery.released",...a(e)?{node_id:e}:{},fields:{...a(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#a(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:w(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>y(t,r),"surface")});break;case"respawn-fresh":case"respawn-cycle":case"respawn-resume":await this.#d(e,t,o,n);break}return o}async#d(e,r,t,n){const o=g(e);if(o===null)return;const i=o.respawn_failures??0;if(!await this.#l()){N(e,i,this.#s()),c({level:"info",event:"broker.respawn.offline_deferred",...a(e)?{node_id:e}:{},fields:{...a(e)?{}:{affected_node_id:e},action:t,retry_in_ms:C,consecutive_failures:i}});return}const _=o.respawn_not_before==null,f=_?F(o,this.#s()):{failures:i,notBefore:o.respawn_not_before,exhausted:i>=R};if(f.exhausted){const u=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${f.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#a(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:u,respawn_failures:f.failures},wake:u,...r.pi_session_id!=null?{surface:l(()=>z(r),"surface")}:{}});return}if(_&&f.notBefore!==null){c({level:"info",event:"broker.respawn.deferred",...a(e)?{node_id:e}:{},fields:{...a(e)?{}:{affected_node_id:e},action:t,backoff_ms:S(f.failures),consecutive_failures:f.failures}});return}c({level:"info",event:"broker.respawn.started",...a(e)?{node_id:e}:{},fields:{...a(e)?{}:{affected_node_id:e},action:t,consecutive_failures:f.failures}});try{await O(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&n?"runtime-restart-abort":void 0,recovery:!0})}catch(u){c({level:"error",event:"broker.respawn.failed",...a(e)?{node_id:e}:{},error:u,fields:{...a(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",u,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:u instanceof Error?u.message:String(u)})}}async#a(e,r,t){c({level:"error",event:t.event,...a(e)?{node_id:e}:{fields:{affected_node_id:e}}}),m(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>y(r)))()}catch(n){c({level:"error",event:"broker.boot_failure_surface.failed",...a(e)?{node_id:e}:{fields:{affected_node_id:e}},error:n})}T(e,k(e),t.wake,{reason:"child-crashed",child:e})}}export{te as DaemonFleet,L as classifyDeadNode,B as retryResumeMode,y as surfaceBootFailure};
|
package/dist/daemon/manage.d.ts
CHANGED
|
@@ -62,6 +62,7 @@ export interface SpawnDaemonResult {
|
|
|
62
62
|
}
|
|
63
63
|
/** Make one `/healthz` observation without client-side recovery. The caller owns the availability window, so this probe cannot extend it. */
|
|
64
64
|
export declare function probeDaemonHealth(timeoutMs?: number): Promise<HealthDTO>;
|
|
65
|
+
export declare function probeErrorMessage(error: unknown): string;
|
|
65
66
|
/** True only when one mandatory Unix API socket probe answers the existing ready health contract. */
|
|
66
67
|
export declare function probeDaemonServing(timeoutMs?: number): Promise<void>;
|
|
67
68
|
/** True only when one mandatory Unix API socket probe answers `/healthz`.
|
package/dist/daemon/manage.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var H=Object.defineProperty;var o=(e,t)=>H(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as k}from"node:child_process";import{createRequire as K}from"node:module";import{dirname as T,join as h}from"node:path";import{fileURLToPath as G,pathToFileURL as b}from"node:url";import{existsSync as j,lstatSync as Y,mkdirSync as X,openSync as z,closeSync as V}from"node:fs";import{crtrHome as x}from"../core/canvas/paths.js";import{bindDaemonEventSource as q,eventSource as J}from"../core/events/source.js";import{hostExecPath as L}from"../core/runtime/branded-host.js";import{isDaemonRunning as Q,readPidfile as
|
|
2
|
-
`)){if(!n.includes("daemon/crtrd")||!ie(n,t))continue;const
|
|
1
|
+
var H=Object.defineProperty;var o=(e,t)=>H(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as k}from"node:child_process";import{createRequire as K}from"node:module";import{dirname as T,join as h}from"node:path";import{fileURLToPath as G,pathToFileURL as b}from"node:url";import{existsSync as j,lstatSync as Y,mkdirSync as X,openSync as z,closeSync as V}from"node:fs";import{crtrHome as x}from"../core/canvas/paths.js";import{bindDaemonEventSource as q,eventSource as J}from"../core/events/source.js";import{hostExecPath as L}from"../core/runtime/branded-host.js";import{isDaemonRunning as Q,readPidfile as g,isPidAlive as w}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as C}from"./startup-policy.js";import{exclusiveLockOwnerPid as Z}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ee}from"../core/canvas/paths.js";import{envNoDaemonAutostart as te}from"../shared/env.js";import{waitForDaemonAvailability as re}from"../api/index.js";import{localClient as ne}from"../api/node-transport.js";const oe=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function $(){const e={...process.env};for(const t of oe)delete e[t];return e}o($,"sanitizedDaemonEnv");function ae(){for(let e=T(G(import.meta.url));;e=T(e)){if(j(h(e,"bin","runtime-generation-manifest.mjs")))return e;if(T(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(ae,"generationRoot");async function F(){const e=ae(),t=b(h(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{Y(h(r(),"selected"))}catch(c){if(c.code!=="ENOENT")throw c;return["--conditions","crtr-src","--import",b(K(import.meta.url).resolve("tsx/esm")).href,h(e,"src","daemon","crtrd-cli.ts")]}const n=b(h(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:i}=await import(n),s=i("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(F,"resolveDaemonLaunch");function ie(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(ie,"daemonCommandDeclaresCanvasHome");function se(){let e;try{e=k("ps",["-ax","-o","pid=,command="],{encoding:"utf8",timeout:2e3})}catch{return[]}const t=x(),r=[];for(const n of e.split(`
|
|
2
|
+
`)){if(!n.includes("daemon/crtrd")||!ie(n,t))continue;const i=n.trim(),s=i.indexOf(" ");if(s<0)continue;const c=Number.parseInt(i.slice(0,s),10);Number.isInteger(c)&&c!==process.pid&&r.push(c)}return r}o(se,"findDaemonPids");function Ce(e){const t=se().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>w(n));)k("sleep",["0.1"]);for(const n of t)if(w(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(Ce,"sweepStrayDaemons");async function $e(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=L(),r=await F();return e(t,[t,...r,"--canvas-home",x()],$())}o($e,"execDaemon");const U=2e4,O=10,M=1e3;async function N(e=M){const t=Math.min(e,M);return ne({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(N,"probeDaemonHealth");function ce(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,i=typeof r=="string"?r:n?.code;return typeof i=="string"&&!t.includes(i)?`${t}: ${i}`:t}o(ce,"probeErrorMessage");async function W(e=M){const t=await N(e);if(t.startup_blocked!==void 0){const r=g()??process.pid;throw new R(r,t.startup_blocked)}if(!t.ok)throw new Error("crtrd health check reported not ready")}o(W,"probeDaemonServing");async function Fe(){try{return await W(),!0}catch{return!1}}o(Fe,"isDaemonServing");function I(e){return new Promise(t=>{setTimeout(t,e)})}o(I,"sleepMs");class R extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class A extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function ue(e,t=C,r={},n="ready"){const i=r.readPidfile??g,s=r.isPidAlive??w,c=r.childExited,u=r.isDaemonServing,_=r.probeDaemonServing??(async f=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await W(f)}),E=r.probeDaemonHealth??N,a=r.sleepMs??I,D=r.now??Date.now;let y=null,l=null;return await re({windowMs:t,pollIntervalMs:O,now:D,sleep:a,retry:o(f=>f!==l,"retry"),probe:o(async f=>{const d=i();if(d===null||!s(d)){const p=c?.();throw p!=null&&(p.signal!==null?l=new Error(`daemon ${e} exited before becoming ready (by ${p.signal})`):p.code!==0&&(l=new Error(`daemon ${e} exited before becoming ready (with exit code ${p.code??"?"})`)),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await _(f)}catch(p){throw p instanceof R&&(l=p),p}y=d;return}const m=await E(f);if(m.startup_phase==="prepared"){y=d;return}throw m.startup_phase==="blocked"?(l=new R(d,m.startup_blocked??"on-disk migration is blocked"),l):m.startup_phase==="ready"?(l=new A(d,m.startup_phase),l):new Error(`daemon ${d} is ${m.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),y===e?null:y}o(ue,"verifyDaemonStartup");async function le(e,t=U,r={}){const n=r.readPidfile??g,i=r.isPidAlive??w,s=r.sleepMs??I,c=r.now??Date.now,u=c()+t;for(;c()<=u;){if(!i(e)&&n()!==e)return;await s(O)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(le,"waitForDaemonExit");const pe=2e3,de=5e3;async function fe(e,t=U,r={}){const n=r.isPidAlive??w,i=r.sleepMs??I,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await le(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const c=s()+pe;for(;s()<=c;){if(!n(e))return"killed";await i(O)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(fe,"stopDaemonProcess");async function me(e={}){const t=e.targetPhase??"ready",r=g();if(r!==null&&w(r))try{const a=await N();if(t==="prepared"){if(a.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:a.startup_phase};throw new A(r,a.startup_phase)}return a.ok?{started:!1,existing_pid:r,...a.startup_phase===void 0?{}:{startup_phase:a.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:a.startup_blocked??"crtrd health check reported not ready",...a.startup_phase===void 0?{}:{startup_phase:a.startup_phase}}}catch(a){if(a instanceof A)throw a;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:ce(a)}}X(x(),{recursive:!0});const n=await F(),i=h(x(),"crtrd.err"),s=z(i,"a");J()===void 0&&q();const c=B(L(),[...n,"--canvas-home",x(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:$()});V(s);const u=c.pid;if(u===void 0)throw new Error("daemon spawn did not return a pid");let _=null;c.once("exit",(a,D)=>{_={code:a,signal:D}}),c.unref();let E;try{E=await ue(u,C,{childExited:o(()=>_,"childExited")},t)}catch(a){const D=Z(ee())===u;if(_===null&&!D&&!(a instanceof R))try{await fe(u,de)}catch{}throw a}return E!==null?{started:!1,existing_pid:E,startup_phase:t}:{started:!0,pid:u,startup_phase:t}}o(me,"spawnDaemon");function he(){return te()||process.argv.includes("--no-autostart")}o(he,"autostartDisabled");const we=5e3,_e=6e4;let P=!1,v=0,S=0;function Ee(e){return Math.min(we*2**(e-1),_e)}o(Ee,"autostartBackoffMs");function De(){v=0,S=0}o(De,"resetDaemonAutostart");function Ue(e={}){const t=e.isDaemonRunning??Q,r=e.spawnDaemon??me,n=e.now??Date.now;if(!he()&&!P&&!(n()<S)){if(t()){De();return}P=!0,r().then(()=>{v=0,S=0},i=>{v+=1,S=n()+Ee(v)}).finally(()=>{P=!1})}}o(Ue,"ensureDaemon");export{oe as DAEMON_ENV_STRIP_KEYS,A as DaemonNotPreparedError,R as DaemonStartupBlockedError,he as autostartDisabled,ie as daemonCommandDeclaresCanvasHome,Ue as ensureDaemon,$e as execDaemon,se as findDaemonPids,Fe as isDaemonServing,N as probeDaemonHealth,W as probeDaemonServing,ce as probeErrorMessage,De as resetDaemonAutostart,$ as sanitizedDaemonEnv,me as spawnDaemon,fe as stopDaemonProcess,Ce as sweepStrayDaemons,ue as verifyDaemonStartup,le as waitForDaemonExit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var J=Object.defineProperty;var
|
|
1
|
+
var J=Object.defineProperty;var c=(t,e)=>J(t,"name",{value:e,configurable:!0});import{envNodeId as j}from"../shared/env.js";import{writeFileSync as q,mkdirSync as H,existsSync as M,readFileSync as W}from"node:fs";import{join as Y}from"node:path";import{contextDir as z,jobDir as G}from"../core/canvas/paths.js";import{mutateBrokerFault as T,recordBrokerTelemetry as L,recordBrokerTurn as v}from"../core/runtime/broker/daemon-ops.js";import{clearStopSignals as V,consumeStopSignals as X}from"../core/runtime/stop-signals.js";import{bindBrokerSession as K,brokerExtensionState as F,relaunchBrokerRoot as Q,settleBroker as O}from"../core/runtime/broker/daemon-ops.js";import{emitEvent as C}from"../core/events/emit.js";import{activeBackgroundBashJobs as Z}from"../core/bash-jobs.js";import{CONTEXT_NUDGE_CUSTOM_TYPE as ee,formatCard as te}from"../shared/generated-context.js";import{isReviewBoundary as ne}from"../core/runtime/session-visibility.js";import{clearRefusedTurn as oe,isRuntimeTeardownInProgress as re,refuseTurn as se,runRefreshAbort as ae}from"../core/runtime/broker/extension-abort.js";import{announceMessageOrigin as N}from"../core/runtime/stamp/channel.js";const P=80;function ie(t,e){const a=e??{},o=c(p=>typeof p=="string"?p:"","pick"),i=o(a.command)||o(a.path)||o(a.file_path)||o(a.pattern)||o(a.description)||o(a.prompt),u=(i!==""?`${t}: ${i}`:t).replace(/\s+/g," ").trim();return u.length>P?u.slice(0,P):u}c(ie,"summarizeActivity");function ce(t,e,a,o,i,u,p){try{M(t)||H(t,{recursive:!0});const m=Y(t,"telemetry.json");let g={};if(M(m))try{g=JSON.parse(W(m,"utf8"))}catch{}const b={tokens_in:e,tokens_out:a,context_tokens:i??g.context_tokens,last_activity:u??g.last_activity,model:o!==""?o:g.model??"",updated_at:p};q(m,JSON.stringify(b,null,2),"utf8")}catch{}}c(ce,"flushTelemetry");function le(t){for(let e=t.length-1;e>=0;e--)if(t[e]?.role==="assistant")return t[e]}c(le,"lastAssistantMessage");function de(t){try{const e=t?.sessionManager?.getBranch();if(!Array.isArray(e))return[];const a=new Set;for(const o of e){if(!ne(o))continue;const i=o.details?.reviewId;typeof i=="string"&&a.add(i)}return[...a]}catch{return[]}}c(de,"currentReviewBoundaryIds");const D=1e4,S=[13e4,15e4,17e4,185e3,2e5];function ue(t){const e=S[0],a=S[S.length-1];if(t<e)return null;if(t>=a)return a+Math.floor((t-a)/D)*D;let o=e;for(const i of S)t>=i&&(o=i);return o}c(ue,"steerBand");function fe(t,e,a){const o=Math.round(t/1e3),i=t>=185e3;if(a==="orchestrator")return t<15e4?`Context ~${o}k and growing. When you reach a good stopping point, consider updating context/roadmap.md and running \`crtr node yield\` to refresh against it \u2014 no rush yet.`:i?`Context ~${o}k \u2014 this is getting long. Stop taking on new work now: checkpoint context/roadmap.md, hand off anything outstanding, and \`crtr node yield\` immediately to refresh before this context overflows.`:`Context ~${o}k. Update context/roadmap.md so a fresh revive can continue, delegate any outstanding work, then \`crtr node yield\` to refresh.`;if(e==="resident"){const u="If substantial work remains, `crtr node yield` to continue fresh against your goal and your note. Add --promote only when worthwhile independent work can run in parallel and coordinating it should become your primary job; `crtr node yield -h` has the boundary.";return t<15e4?`Context ~${o}k and growing. ${u} Otherwise no rush \u2014 wrap up when you reach a good stopping point.`:i?`Context ~${o}k \u2014 this is getting long. Wrap up now before this context overflows: finish what's in hand, or \`crtr node yield\` immediately to continue fresh against your goal and your note if substantial work remains.`:`Context ~${o}k. ${u} If you're near done, just finish here; if there's more open-ended work, \`crtr node yield\` rather than letting this context grow.`}return t<15e4?`Context ~${o}k and growing. If you're near done, finish with \`crtr push final\`. If real work remains, \`crtr node yield\` to continue in a fresh window against your goal and your note \u2014 no rush yet.`:i?`Context ~${o}k \u2014 this is getting long. Wrap up now before this context overflows: \`crtr push final\` if you're close, otherwise \`crtr node yield\` immediately to continue in a fresh window against your goal and your note.`:`Context ~${o}k. If you're close, finish with \`crtr push final\`; otherwise \`crtr node yield\` now to refresh into a clean window and keep going against your goal and your note.`}c(fe,"steerNote");function he(t){const e=j();if(e===void 0||e.trim()==="")return;const a=G(e);let o=0,i=0,u="",p=null,m=null;const g=new Set,b=c(()=>Z(z(e)).length>0,"backgroundJobsRunning"),f=c((n,s)=>{C({event:"broker.daemon.operation.failed",level:"error",node_id:e,error:s,fields:{operation:n}})},"emitDaemonOperationFailure"),I=c((n,s)=>{if(n.action==="reprompt"){N(n.prompt,{type:"runtime",kind:"stop-guard"}),t.sendUserMessage(n.prompt,{deliverAs:"followUp"});return}if(n.action==="shutdown")try{s?.shutdown?.()}catch{}},"enactSettleDirective"),U=3e3;let R=0,B=Promise.resolve();const E=c((n,s)=>{const r=new Date().toISOString();ce(a,o,i,u,n,s,r);const h={tokens_in:o,context_tokens:n,last_activity:s,updated_at:r};B=B.then(()=>L(e,h)).catch(y=>f("telemetry",y))},"publishTelemetry"),k=c(()=>{const n=Date.now();n-R<U||(R=n,Promise.all([v(e,{event:"progress"}),T(e,{op:"clear",link:"daemon\u2192node"})]).catch(s=>f("turn_progress",s)))},"heartbeat");t.on("session_start",async(n,s)=>{try{const r=s?.sessionManager?.getSessionId?.();if(typeof r!="string"||r==="")return;const h=s?.sessionManager?.getSessionFile?.(),y=typeof h=="string"&&h!==""?h:null,w=typeof n?.reason=="string"?n.reason:null;w==="new"&&(o=0,i=0,g.clear());const l=await K(e,{piSessionId:r,sessionFile:y,pid:process.pid,reason:w,reviewBoundaryIds:de(s)});if(l.action==="shutdown"){try{s?.shutdown?.()}catch{}return}if(l.action==="relaunch_root"){Q(e).catch(d=>{const _=d instanceof Error?d.message:String(d);s?.ui?.notify?.(`/new refused: ${_}`,"error"),C({event:"broker.daemon.operation.failed",level:"error",node_id:e,error:d,fields:{operation:"relaunch_root"}})});return}}catch(r){C({event:"broker.daemon.operation.failed",level:"error",node_id:e,error:r,fields:{operation:"session_bound"}})}}),t.on("agent_start",async(n,s)=>{try{if(!(await v(e,{event:"started"})).applied)throw new Error("daemon refused turn open")}catch(r){f("turn_open",r),s?.ui?.notify?.("Turn refused: the broker no longer owns this node.","error"),se(()=>s?.abort?.())}}),t.on("input",()=>{oe();try{V(e)}catch{}}),t.on("tool_execution_start",n=>{try{m=ie(String(n?.toolName??""),n?.args),E(p,m),k()}catch{}}),t.on("tool_execution_update",()=>{try{k()}catch{}}),t.on("message_update",()=>{try{k()}catch{}}),t.on("tool_execution_end",async(n,s)=>{try{if(k(),(await F(e)).node.intent==="refresh")try{ae(()=>s?.abort?.())}catch{}}catch{}}),t.on("session_shutdown",async(n,s)=>{try{await v(e,{event:"closed",end_reason:"teardown-aborted"})}catch(r){f("turn_close_teardown",r)}if(n?.reason==="quit")try{const r=await O(e,{stopReason:"quit",backgroundJobsRunning:b(),pushedFinal:!1});I(r,s)}catch(r){f("settle_quit",r)}});const $=c(n=>{n?.role!=="assistant"||n.usage==null||(o+=Number(n.usage.input??0)||0,i+=Number(n.usage.output??0)||0,typeof n.model=="string"&&n.model!==""&&(u=n.model))},"accumulate");t.on("turn_end",async(n,s)=>{$(n?.message);let r=null;try{const l=s.getContextUsage()?.tokens;typeof l=="number"&&(r=l)}catch{}r!==null&&(p=r),E(r,m),k();try{await Promise.all([T(e,{op:"clear",link:"daemon\u2192node"}),T(e,{op:"clear",link:"pi\u2192provider"})])}catch(l){f("turn_end_fault_clear",l)}const h=Array.isArray(n?.message?.content)?n.message.content:[],y=n?.message?.stopReason??"",w=y!=="error"&&y!=="aborted"&&h.some(l=>l?.type==="toolCall");try{const d=(await F(e)).node,_=r!==null?ue(r):null;if(_!==null&&!g.has(_)){g.add(_);const A=te("context-nudge",{},fe(_,d.lifecycle,d.mode));w?(N(A,{type:"runtime",kind:"context-nudge"}),t.sendUserMessage(A,{deliverAs:"steer"})):t.sendMessage({customType:ee,content:A,display:!0},{deliverAs:"nextTurn"})}}catch(l){f("turn_boundary",l)}});let x=null;t.on("agent_end",n=>{x=n;try{const s=Array.isArray(n?.messages)?n.messages:[];for(const r of s)$(r)}catch{}}),t.on("agent_settled",async(n,s)=>{const r=x;if(x=null,re())return;try{await v(e,{event:"closed",end_reason:"settled"})}catch(d){f("turn_close",d);return}const h=Array.isArray(r?.messages)?r.messages:[],y=le(h),w=typeof y?.stopReason=="string"?y.stopReason:"",l=r===null?{pushedFinal:!1}:X(e);try{const d=await O(e,{stopReason:w,backgroundJobsRunning:b(),pushedFinal:l.pushedFinal});I(d,s)}catch(d){f("settle",d)}})}c(he,"registerCanvasStophook");var Ie=he;export{Ie as default,he as registerCanvasStophook,fe as steerNote};
|
package/dist/types.d.ts
CHANGED
|
@@ -354,6 +354,8 @@ export interface ScopeConfig {
|
|
|
354
354
|
* via `crtr canvas use`. Unset
|
|
355
355
|
* via `sys config set` — not in `TOP_LEVEL_KEYS`. */
|
|
356
356
|
remoteCanvas: RemoteCanvasConfig;
|
|
357
|
+
/** The user-owned TCP listener address. Empty leaves the TCP listener off. */
|
|
358
|
+
api: ApiConfig;
|
|
357
359
|
/** Extra env-var names/globs a scope explicitly admits across the broker
|
|
358
360
|
* spawn-env boundary (`buildBrokerEnv`, `core/runtime/spawn-env.ts`) — the
|
|
359
361
|
* "I accept this crosses as a shell-visible credential" escape hatch for a
|
|
@@ -394,6 +396,11 @@ export interface RemoteCanvasTarget {
|
|
|
394
396
|
export interface RemoteCanvasConfig {
|
|
395
397
|
targets: Record<string, RemoteCanvasTarget>;
|
|
396
398
|
}
|
|
399
|
+
/** User-owned daemon TCP listener settings. The bearer token lives separately
|
|
400
|
+
* in the 0600 secrets store. */
|
|
401
|
+
export interface ApiConfig {
|
|
402
|
+
tcp: string;
|
|
403
|
+
}
|
|
397
404
|
export interface ScopeState {
|
|
398
405
|
marketplaces: Record<string, {
|
|
399
406
|
last_updated?: string;
|
package/dist/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,f=".crouter-plugin",E="plugin.json",v=".crouter-marketplace",w="marketplace.json",k=".crouter",x="config.json",b="state.json",S="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],T=["random","go-faster"],c="random",l=2,I=["tmux","on","off"],A=["none","user","agent","both"],h="none";function D(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:h,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,keybindings:{},tmux_passthrough:[],modelLadders:u(),providerOptions:{},kinds:
|
|
1
|
+
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,f=".crouter-plugin",E="plugin.json",v=".crouter-marketplace",w="marketplace.json",k=".crouter",x="config.json",b="state.json",S="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],T=["random","go-faster"],c="random",l=2,I=["tmux","on","off"],A=["none","user","agent","both"],h="none";function D(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:h,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,keybindings:{},tmux_passthrough:[],modelLadders:u(),providerOptions:{},kinds:d(),remoteCanvas:p(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}e(D,"defaultScopeConfig");function p(){return{targets:{}}}e(p,"defaultRemoteCanvasConfig");function d(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}e(d,"defaultKindsConfig");function u(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5:medium",medium:"anthropic/claude-sonnet-5:xhigh",light:"anthropic/claude-haiku-4-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-5.6-sol:high",medium:"openai-codex/gpt-5.6-terra:medium",light:"openai-codex/gpt-5.6-luna:low"}}}e(u,"defaultModelLaddersConfig");function M(){return{marketplaces:{},plugins:{}}}e(M,"defaultScopeState");export{S as AGENTS_DIR,A as CONDENSED_HISTORY_MODES,x as CONFIG_FILE,k as CRTR_DIR_NAME,h as DEFAULT_CONDENSED_HISTORY,l as DEFAULT_LIVE_CYCLES,i as DEFAULT_MAX_PANES_PER_WINDOW,s as DEFAULT_WHIP_MESSAGES,c as DEFAULT_WHIP_MESSAGE_MODE,_ as ExitCode,v as MARKETPLACE_MANIFEST_DIR,w as MARKETPLACE_MANIFEST_FILE,I as MOUSE_MODE_DEFAULTS,f as PLUGIN_MANIFEST_DIR,E as PLUGIN_MANIFEST_FILE,y as PROFILE_DIR,r as SCHEMA_VERSION,b as STATE_FILE,T as WHIP_MESSAGE_MODES,d as defaultKindsConfig,u as defaultModelLaddersConfig,p as defaultRemoteCanvasConfig,D as defaultScopeConfig,M as defaultScopeState};
|