@north-light/cli 0.3.712 → 0.3.713
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/input/controller.d.ts +6 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/input/local-files.d.ts +16 -0
- package/dist/clients/attach/input/local-files.js +6 -0
- package/dist/clients/attach/session/editor-frame.d.ts +2 -2
- package/dist/clients/attach/session/editor-frame.js +1 -1
- package/dist/clients/attach/viewer.js +406 -402
- package/dist/commands/node/bash.js +1 -1
- package/dist/core/bash-guard.d.ts +10 -0
- package/dist/core/bash-guard.js +4 -4
- package/dist/core/broker-client/client.d.ts +2 -2
- package/dist/core/conversation-store/row-store.js +1 -1
- package/dist/core/graph/documents.d.ts +5 -5
- package/dist/core/graph/documents.js +9 -9
- package/dist/core/graph/kinds/custom.js +2 -2
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/environment.js +2 -2
- package/dist/core/graph/kinds/job.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +9 -1
- package/dist/core/graph/kinds/live-read.d.ts +4 -2
- package/dist/core/graph/kinds/live-read.js +1 -1
- package/dist/core/graph/kinds/node.js +5 -5
- package/dist/core/graph/kinds/owner.js +2 -2
- package/dist/core/runtime/bearings-render.d.ts +3 -0
- package/dist/core/runtime/bearings-render.js +7 -7
- package/dist/core/runtime/bearings.js +5 -5
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-read.d.ts +5 -1
- package/dist/core/runtime/broker/frame-read.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +37 -2
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/map.d.ts +6 -0
- package/dist/daemon/api/map.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/ci-runner.md +4 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
- package/packages/crouter-api/dist/clients/attach/input/local-files.js +97 -0
- package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
- package/packages/crouter-api/dist/commands/node/bash.js +2 -2
- package/packages/crouter-api/dist/core/bash-guard.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
- package/packages/crouter-api/dist/core/graph/documents.js +12 -24
- package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
- package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
- package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -5
- package/packages/crouter-api/dist/daemon/api/map.js +1 -1
- package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
- /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
- /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}s(N,"escapeAttribute");function
|
|
1
|
+
var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}s(N,"escapeAttribute");function A(){const e=x();return`Host: ${[`${process.platform} ${process.arch}`,C(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function T(e){try{const n=_("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(T,"directoryListingLines");function f(e,t,n,r){const o=k(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(f,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function d(e,t){const n=f(e,"git",t,$());return n.ok?n.stdout:""}s(d,"runGit");function G(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(G,"parseWorktrees");function O(e){const t=f(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
|
|
2
2
|
`).filter(c=>c!=="").length,i=d(e,["worktree","list","--porcelain"]).split(`
|
|
3
|
-
`),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function
|
|
3
|
+
`),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function P(e){const t=T(e),n=O(e);let r=`<project_context>
|
|
4
4
|
|
|
5
5
|
`;return r+=`<environment cwd="${N(e)}">
|
|
6
|
-
`,r+=`${
|
|
6
|
+
`,r+=`${A()}
|
|
7
7
|
`,r+=`Directory:
|
|
8
8
|
${t.map(o=>` ${o}`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
`,r+=`${n.map(o=>`${o}`).join(`
|
|
11
11
|
`)}
|
|
12
12
|
`,r+=`</environment>
|
|
13
|
-
</project_context>`,r}s(
|
|
14
|
-
`)}s(
|
|
15
|
-
`)}s(q,"buildIdentityAssertion");function
|
|
13
|
+
</project_context>`,r}s(P,"buildProjectContextBlock");function W(e,t){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`${m(e,t)}\` (also \`$CRTR_CONTEXT_DIR\`) holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(W,"contextDirNote");function F(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(F,"whereYouRunNote");function X(e,t){if(t==null||t==="")return"";let n;try{n=D(t)}catch{return""}const r=w(n.manifest.projects);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(X,"profileNote");function z(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(z,"orchestratorContextNote");function K(e,t,n){return`Context directory: \`${m(e,t)}\` (\`$CRTR_CONTEXT_DIR\`), for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${n}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(K,"forkContextNote");function y(e){const t=v(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(y,"relativeLabel");const j=5;function U(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${y(c)}`)});const u=r.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const h=o.slice(0,j),l=o.length-h.length;return h.forEach((c,p)=>{const g=p===h.length-1&&l===0;a.push(`${i(u+1)}${g?"\u2514 ":"\u251C "}${y(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
|
|
14
|
+
`)}s(U,"renderGraphMap");function q(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
|
|
15
|
+
`)}s(q,"buildIdentityAssertion");function J(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
|
|
16
16
|
Worktree: \`${e.path}\`
|
|
17
17
|
Base: \`${e.base_ref}\` @ \`${e.base_sha}\`
|
|
18
|
-
Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(
|
|
18
|
+
Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(J,"worktreeNote");export{q as buildIdentityAssertion,P as buildProjectContextBlock,W as contextDirNote,N as escapeAttribute,K as forkContextNote,z as orchestratorContextNote,X as profileNote,y as relativeLabel,U as renderGraphMap,F as whereYouRunNote,J as worktreeNote};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as N,fullName as w,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as f}from"../canvas/node-order.js";import{buildProjectContextBlock as p,contextDirNote as h,orchestratorContextNote as m,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as re}from"../../shared/generated-context.js";async function B(e,r){const n=r!==void 0?r:await s(e);return n===null?"":E(n.cwd,n.profile_id)}i(B,"profileNote");async function T(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const a=await s(o);if(a===null)break;n.unshift(a),o=a.parent??null}return n}i(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>f(r.status)-f(n.status))}i(W,"childNodes");async function D(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await T(e,n),o=await W(e);return O(e,n.kind,n.mode,t,o)}i(D,"buildGraphMap");async function H(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&v(n)?await s(n):null,o=t!==null?`${n} ("${w(t)}")`:n??"";return R(e,r?.kind??"general",r?.mode??"base",n,o)}i(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}i(L,"armerPhrase");async function Q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:w(n)}:{},armedAt:e.created,recur:e.recur}}i(Q,"cronWakeOrigin");function V(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
|
|
2
2
|
${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
|
|
3
|
-
</crtr-wake>`;const t=
|
|
3
|
+
</crtr-wake>`;const t=L(e);return`<crtr-wake>
|
|
4
4
|
${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
|
|
5
|
-
</crtr-wake>`}
|
|
6
|
-
`),r,n,
|
|
7
|
-
`)}
|
|
5
|
+
</crtr-wake>`}i(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}i(M,"managedWorktreeNote");async function P(e,r,n){const t=await s(e),o=await N(e),a=["<crtr-bearings>",await H(e,t)],u=S(o?.runner);u!==""&&a.push("","## Where you run",u);const c=await D(e,t);c!==""&&a.push("","## Your place in the canvas",c),a.push("","## Your documents and context directory",h(e,t?.grantee));const d=await B(e,t);d!==""&&a.push("",d);const l=M(t);l!==""&&a.push("","## Your managed worktree",l),t?.mode==="orchestrator"&&a.push("",m()),a.push("</crtr-bearings>");const y=await C(e)??"",b=t?.cwd!==void 0&&o?.runner==="process"?p(t.cwd):"";return[a.join(`
|
|
6
|
+
`),r,n,y,b].filter(k=>k!=="").join(`
|
|
7
|
+
`)}i(P,"bearingsShell");async function Z(e,r){const n=await Y(r),t=await $(r);return{content:await P(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}i(Z,"buildContextBearings");export{re as CONTEXT_INTRO_CUSTOM_TYPE,Z as buildContextBearings,D as buildGraphMap,p as buildProjectContextBlock,V as buildWakeBearings,h as contextDirNote,Q as cronWakeOrigin,m as orchestratorContextNote,B as profileNote};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as x}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as U,createPromptDispatchTracker as V,createTurnAcceptanceGate as X}from"./turn-ignition.js";import{prependRunDeferredMail as y}from"./run-deferred-mail.js";function ce(n){const{nodeId:e,registry:s,toolGroups:v,projection:k,rebind:l,boundaryReviewId:
|
|
1
|
+
var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as x}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as U,createPromptDispatchTracker as V,createTurnAcceptanceGate as X}from"./turn-ignition.js";import{prependRunDeferredMail as y}from"./run-deferred-mail.js";function ce(n){const{nodeId:e,registry:s,toolGroups:v,projection:k,rebind:l,boundaryReviewId:u,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:M,broadcastModelChanged:F,registryOf:E,formatModelSpec:R,formatExactModelSpec:S,turnAdmission:m,runNode:h,memoryInventory:H,onKickoffAdmitted:P}=n,t=o(()=>l.session(),"currentSession"),T=o(()=>l.services(),"currentServices"),a=j(s),{notWritable:G}=a,c=B(t,e,H),p=V(t),_=X(),f=U({session:t,dispatches:p,turnAdmission:m,prependDeferred:h?r=>y(e,r):void 0,onAdmitted:P}),g=q({nodeId:e,registry:s,replies:a,session:t,dispatches:p,memoryRefs:c,rebind:l,projection:k,toolGroups:v,turnAdmission:m,prependDeferred:h?r=>y(e,r):void 0}),I=o((r,i)=>{G(r,"drive the engine")||((i.type==="prompt"||i.type==="steer"||i.type==="follow_up")&&x(i.text,{type:"human",channel:{type:"viewer"}}),g(r,i))},"handleDriveFrame"),d=z({registry:s,replies:a,session:t,driveEngine:g,turnAcceptance:_,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,disposeAndExit:C}),W=J({registry:s,replies:a,session:t,services:T,registryOf:E,persistModelChoice:M,broadcastModelChanged:o(async(...r)=>{await F(...r),f.drivePending()},"broadcastModelChanged"),formatModelSpec:R}),K=L({nodeId:e,registry:s,replies:a,session:t,boundaryReviewId:u,memoryRefs:c,formatExactModelSpec:S}),N=Q({registry:s,replies:a,rebind:l,session:t,boundaryReviewId:u,memoryRefs:c,reWelcomeAll:A});return{handlers:{hello:d.hello,drive:I,deliver:d.deliver,dialog:d.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{a.ackTo(r,"reload_auth")},"authentication"),bye:d.bye,shutdown:d.shutdown},kickoff:o((r,i)=>f.kickoff(r,i),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:p.pending,resetForSession:o(()=>{},"resetForSession"),refreshMemoryNames:o(r=>r===void 0?c.invalidate():(c.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(ce,"createFrameDispatchContext");function de(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return}}o(de,"handleFrame");export{ce as createFrameDispatchContext,de as handleFrame};
|
|
@@ -8,9 +8,13 @@ import { type BrokerSession } from './read-ops.js';
|
|
|
8
8
|
* `list_sessions` is the exception: it lists conversations beyond this node, so
|
|
9
9
|
* only a controller (one that may message the node) gets it. */
|
|
10
10
|
export type ReadFrame = Extract<ClientToBroker, {
|
|
11
|
-
type: 'get_commands' | 'list_models' | 'list_scoped_models' | 'list_memory_refs' | 'get_tree' | 'get_settings' | 'list_sessions' | 'get_human_fork_coordinates';
|
|
11
|
+
type: 'get_commands' | 'list_models' | 'list_scoped_models' | 'list_memory_refs' | 'get_tree' | 'get_settings' | 'list_sessions' | 'get_human_fork_coordinates' | 'get_git_status' | 'upload_file';
|
|
12
12
|
}>;
|
|
13
|
+
/** Write viewer-sent bytes into the node's attachments folder under a name no
|
|
14
|
+
* earlier file holds (`photo.png`, `photo-2.png`, …); returns the path. */
|
|
15
|
+
export declare function writeViewerUpload(dir: string, name: string, bytes: Buffer): string;
|
|
13
16
|
export declare function createReadHandler(deps: {
|
|
17
|
+
nodeId: string;
|
|
14
18
|
registry: BrokerClientRegistry;
|
|
15
19
|
replies: FrameReplies;
|
|
16
20
|
session: () => BrokerSession;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var g=(n,a)=>k(n,"name",{value:a,configurable:!0});import{mkdirSync as f,writeFileSync as S,openSync as b,closeSync as m,constants as h,readFileSync as E,fstatSync as F}from"node:fs";import{basename as T,extname as L,join as _}from"node:path";import{nodeAgentDir as w}from"../../canvas/paths.js";import{fetchGitInfo as O}from"../../../shared/git-status.js";import{SessionListCache as C}from"../session-list-cache.js";import{sessionListCachePath as D}from"../../canvas/paths.js";import{engineLeadingCommandTokens as I}from"./engine-routing.js";import{buildCommandList as R,buildGetTreeData as M,buildListMemoryRefsData as x,buildListModelsData as N,buildScopedModelsData as v,buildSessionsData as A,buildSettingsData as W}from"./read-ops.js";function $(n,a,o){const t=T(a).replace(/[\u0000-\u001f]/g,"")||"file";f(n,{recursive:!0});const i=L(t),p=i&&i!==t?t.slice(0,-i.length):t;for(let d=1;;d++){const l=_(n,d===1?t:`${p}-${d}${i}`);let c;try{c=b(l,h.O_WRONLY|h.O_CREAT|h.O_EXCL,432)}catch(s){if(s.code==="EEXIST")continue;throw s}try{S(c,o)}finally{m(c)}return l}}g($,"writeViewerUpload");function B(n,a){if(a.length===0)return!1;let o;try{o=b(n,h.O_RDONLY|h.O_NONBLOCK)}catch{return!1}try{const t=F(o);return t.isFile()&&t.size===a.length&&E(o).equals(a)}catch{return!1}finally{m(o)}}g(B,"sameFileAt");function P(n){const{nodeId:a,registry:o,replies:t,session:i,boundaryReviewId:p,memoryRefs:d,formatExactModelSpec:l}=n,c=new C(D());return(s,r)=>{switch(r.type){case"get_commands":{try{t.ackTo(s,"get_commands",!0,JSON.stringify(R(i())))}catch(e){t.engineErrorTo(s)(e)}break}case"list_models":{try{o.sendFrame(s,N(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_scoped_models":{try{o.sendFrame(s,v(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_memory_refs":{try{o.sendFrame(s,x(r.id,d.refs(),I(i())))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_tree":{try{o.sendFrame(s,M(r.id,i(),p))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_settings":{try{o.sendFrame(s,W(r.id,i()))}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"list_sessions":{if(t.notWritable(s,"list sessions",r.id))break;A(r.id,r.scope??"cwd",i(),c).then(e=>o.sendFrame(s,e)).catch(t.engineErrorTo(s,r.id));break}case"get_git_status":{O(i().sessionManager.getCwd(),e=>{o.sendFrame(s,{type:"data",id:r.id,kind:"git_status",...e.branch===void 0?{}:{branch:e.branch},dirty:e.dirty,ahead:e.ahead,behind:e.behind})});break}case"upload_file":{if(t.notWritable(s,"upload a file",r.id))break;try{const e=Buffer.from(r.data,"base64"),u=B(r.source_path,e)?r.source_path:$(_(w(a),"attachments"),r.source_path,e);o.sendFrame(s,{type:"data",id:r.id,kind:"upload_file",path:u})}catch(e){t.engineErrorTo(s,r.id)(e)}break}case"get_human_fork_coordinates":{try{const e=i().sessionManager,u=e.getSessionFile(),y=e.getLeafId();if(u===void 0||u===""||y===null){t.engineErrorTo(s,r.id)(new Error("no persisted source session leaf"));break}o.sendFrame(s,{type:"data",id:r.id,kind:"human_fork_coordinates",sourceFile:u,sourceSessionId:e.getSessionId(),leafId:y,modelSpec:l(i().model,i().thinkingLevel)})}catch(e){t.engineErrorTo(s,r.id)(e)}break}}}}g(P,"createReadHandler");export{P as createReadHandler,$ as writeViewerUpload};
|
|
@@ -385,7 +385,24 @@ export interface GetHumanForkCoordinatesFrame {
|
|
|
385
385
|
type: 'get_human_fork_coordinates';
|
|
386
386
|
id: string;
|
|
387
387
|
}
|
|
388
|
-
|
|
388
|
+
/** Read the git branch and status of the node's own working directory, where the
|
|
389
|
+
* broker runs (a viewer on another machine cannot read it). Observer-safe. */
|
|
390
|
+
export interface GetGitStatusFrame {
|
|
391
|
+
type: 'get_git_status';
|
|
392
|
+
id: string;
|
|
393
|
+
}
|
|
394
|
+
/** Write one file from the viewer's machine into this node's attachments folder,
|
|
395
|
+
* so a path the person typed or pasted can be read by the node. Controller only.
|
|
396
|
+
* `data` is the file's bytes in base64; the reply names the written path. */
|
|
397
|
+
export interface UploadFileFrame {
|
|
398
|
+
type: 'upload_file';
|
|
399
|
+
id: string;
|
|
400
|
+
/** The path on the viewer's machine. When the broker reads the same bytes at
|
|
401
|
+
* this path (viewer and node share a disk) it answers with it and writes nothing. */
|
|
402
|
+
source_path: string;
|
|
403
|
+
data: string;
|
|
404
|
+
}
|
|
405
|
+
export type ClientToBroker = HelloFrame | GetGitStatusFrame | UploadFileFrame | PromptFrame | SteerFrame | FollowUpFrame | AbortFrame | DeliverFrame | BashFrame | ByeFrame | ShutdownFrame | SetModelFrame | DeliverCustomMessageFrame | CycleModelFrame | CycleLadderFrame | CycleThinkingFrame | SetThinkingLevelFrame | DequeueFrame | SetAutoRetryFrame | SetAutoCompactionFrame | CompactFrame | NewSessionFrame | SwitchSessionFrame | ForkFrame | SetSessionNameFrame | GetCommandsFrame | NavigateTreeFrame | ReloadFrame | ExportFrame | ListModelsFrame | ListSessionsFrame | GetTreeFrame | GetSettingsFrame | ListScopedModelsFrame | ListMemoryRefsFrame | ExtensionUIResponseFrame | CloneFrame | ShareFrame | ReloadAuthFrame | GetHumanForkCoordinatesFrame;
|
|
389
406
|
export interface WelcomeFrame {
|
|
390
407
|
type: 'welcome';
|
|
391
408
|
snapshot: BrokerSnapshot;
|
|
@@ -622,8 +639,26 @@ export interface HumanForkCoordinatesData {
|
|
|
622
639
|
leafId: string;
|
|
623
640
|
modelSpec: string | null;
|
|
624
641
|
}
|
|
642
|
+
/** The `get_git_status` result: git context of the node's working directory. */
|
|
643
|
+
export interface GitStatusData {
|
|
644
|
+
type: 'data';
|
|
645
|
+
id: string;
|
|
646
|
+
kind: 'git_status';
|
|
647
|
+
/** Undefined outside a repository. */
|
|
648
|
+
branch?: string;
|
|
649
|
+
dirty: boolean;
|
|
650
|
+
ahead: number;
|
|
651
|
+
behind: number;
|
|
652
|
+
}
|
|
653
|
+
/** The `upload_file` result: where the node can read the file. */
|
|
654
|
+
export interface UploadFileData {
|
|
655
|
+
type: 'data';
|
|
656
|
+
id: string;
|
|
657
|
+
kind: 'upload_file';
|
|
658
|
+
path: string;
|
|
659
|
+
}
|
|
625
660
|
/** All correlated data replies (read-ops + dequeue). Discriminate on `kind`. */
|
|
626
|
-
export type BrokerDataFrame = ListModelsData | ListSessionsData | GetTreeData | GetSettingsData | ListScopedModelsData | ListMemoryRefsData | DequeueData | HumanForkCoordinatesData;
|
|
661
|
+
export type BrokerDataFrame = GitStatusData | UploadFileData | ListModelsData | ListSessionsData | GetTreeData | GetSettingsData | ListScopedModelsData | ListMemoryRefsData | DequeueData | HumanForkCoordinatesData;
|
|
627
662
|
/** An extension UI call routed to viewers — pi's public RPC request type. */
|
|
628
663
|
export type ExtensionUIRequestFrame = RpcExtensionUIRequest;
|
|
629
664
|
/** Broker → client: dismiss a previously-forwarded blocking dialog by request id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var K=Object.defineProperty;var s=(t,e)=>K(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as z,findNodeBySessionFile as Q,getNode as g,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as x,subscriptionsOf as te,updateNode as b,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ie,recordExecutionPid as re}from"../../../core/canvas/executions.js";import{bindSession as oe,readLiveSession as ae,transferSession as se}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ce}from"../../../core/canvas/paths.js";import{isPidAlive as de}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as le}from"../../../core/substrate/subject.js";import{shareCorpusReads as ue}from"../../../core/substrate/delivery/corpus.js";import{openDb as A,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Be}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Ne}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Le,writeNodeTelemetryRecord as De}from"./telemetry-record.js";import{mapAsync as Me}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as $e}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as je,cycleCompatible as Ue}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as We,drainBearings as He}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Je}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ge}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ye}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ke}from"../../../core/runtime/stamp/protocol.js";import{ApiError as ze}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Qe(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Qe,"parseSettleBody");function Xe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw d("brokerVersion must be a non-empty string");return e}s(Xe,"parseCycleBody");function Ze(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ze,"parseParkCompleteBody");function Ie(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");const n=Le(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ie,"parseTelemetryBody");function qe(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(qe,"parseModelCommitBody");async function y(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function k(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(k,"extensionNode");async function V(t,e){const n=await y(t),r=[],i=new Set([t]);let a=n.parent??null;for(;a!==null&&a!==""&&!i.has(a);){i.add(a);const u=await g(a);if(u===null)break;r.unshift(await k(u)),a=u.parent??null}const o=await Me((await X((await te(t)).map(u=>u.node_id))).filter(u=>u.kind!=="human").sort((u,p)=>u.status===p.status?0:u.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw R(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await Z(t),situational_card:await Oe(t),ancestors:r,children:o,fork_source:c===null?null:await k(c),subject:l,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function et(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(et,"parseGeneratedNameBody");function tt(t){const e=m(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw d(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(tt,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:z(e.sessionFile);return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t);if(await re(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await Q(n);if(o!==null&&o.node_id!==t){if(de(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await ae(o.node_id);if(c===null||await se({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await oe(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await _(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function nt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(nt,"handleSessionBound");function it(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw d("bearings must be fresh, inherited or present");return e}s(it,"parseCycleStartBody");async function rt(t,e,n,r,i,a){const o=r.warm_spare||a,c=!o&&i!=="present",l=await O(t,e,{activity:"names"},n),u=c?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{}},n):void 0,p=o?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...u===void 0?{}:{boot:{content:u.content,...u.inherited===!0?{inherited:!0}:{}}},...p===void 0?{}:{system_prompt:p.content}}}s(rt,"startupDelivery");async function j(t,e,n,r=!1){r||await Fe(await A(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Ce(o,t,async(p,v,Y)=>await Te(o,p,v,Y));ue(c);const l=await Be(o,c),u=await V(t,l);return{state:u,delivery:await rt(o,c,l,u,e,n)}});if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,l=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function fn(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(fn,"renderCarriedStart");async function ot(t){const e=t.params.id,n=it(t.body),r=await y(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await $(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:p,sha256:v})=>({path:p,sha256:v})),structured_request:await N(e)}}}s(ot,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function at(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ee(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await _(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(at,"settleBroker");async function st(t){const e=t.params.id,n=Xe(t.body);await f(e,n.expected_execution_id);const r=await y(e);if(r.intent!=="refresh")throw new ze(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Ve(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&Ue(i.launchJson,await $e(e,a,r.cwd))?{status:200,body:await ct(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(st,"handleCycle");async function ct(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await He(e,n),a=await We(e,i);await Je(t),await Ge(t,e,!1),await Ye(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await b(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of je)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ke({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(ct,"startCycleRecord");async function dt(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await ie(n.expected_execution_id),{status:204}}s(dt,"handleIdle");async function lt(t){const e=t.params.id,n=Qe(t.body);await f(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(lt,"handleSettle");async function ut(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const r=await T(e),i=await w(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await F(r))?(await h(e),await _(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ce(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await B(e),{status:200,body:i}}s(ut,"handleParkComplete");async function pt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await w(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(pt,"handleParkActivity");async function ft(t){const e=t.params.id,n=Ie(t.body);return await f(e,n.expected_execution_id),await w(async()=>{await ne(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),De(e,n)}),{status:204}}s(ft,"handleTelemetry");async function mt(t){const e=t.params.id,n=qe(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await w(async()=>await ve(await y(e),n.spec,n.intent,n.userSelected))).model_override}}}s(mt,"handleModelCommit");let J=!0;function mn(t){J=t}s(mn,"setRequestsStartRunObservers");async function wt(t){const e=t.params.id,n=await y(e);return n.run_id&&J&&await Ne(e,n.run_id),{status:200,body:await V(e)}}s(wt,"handleExtensionState");async function yt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),{status:200,body:await w(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await y(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const l=await b(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(l),description:l.description??"",title:l.title??"",icon:l.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await b(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(yt,"handleGeneratedName");async function ht(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(ht,"handlePersonaAck");async function G(t,e,n){return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await b(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const wn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:nt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:ot},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:mt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ht}]);export{wn as brokerOperationRoutes,k as extensionNode,fn as renderCarriedStart,j as renderStartData,mn as setRequestsStartRunObservers};
|
|
1
|
+
var K=Object.defineProperty;var s=(t,e)=>K(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as z,findNodeBySessionFile as Q,getNode as g,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as x,subscriptionsOf as te,updateNode as _,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ie,recordExecutionPid as re}from"../../../core/canvas/executions.js";import{bindSession as oe,readLiveSession as ae,transferSession as se}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ce}from"../../../core/canvas/paths.js";import{isPidAlive as de}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as le}from"../../../core/substrate/subject.js";import{shareCorpusReads as ue}from"../../../core/substrate/delivery/corpus.js";import{openDb as A,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as b}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as _e}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as be,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Be}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Ne}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Le,writeNodeTelemetryRecord as De}from"./telemetry-record.js";import{mapAsync as Me}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as $e}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as je,cycleCompatible as Ue}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as We,drainBearings as He}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Je}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ge}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ye}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ke}from"../../../core/runtime/stamp/protocol.js";import{ApiError as ze}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Qe(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Qe,"parseSettleBody");function Xe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw d("brokerVersion must be a non-empty string");return e}s(Xe,"parseCycleBody");function Ze(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ze,"parseParkCompleteBody");function Ie(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");const n=Le(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ie,"parseTelemetryBody");function qe(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(qe,"parseModelCommitBody");async function y(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function k(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(k,"extensionNode");async function V(t,e){const n=await y(t),r=[],i=new Set([t]);let a=n.parent??null;for(;a!==null&&a!==""&&!i.has(a);){i.add(a);const u=await g(a);if(u===null)break;r.unshift(await k(u)),a=u.parent??null}const o=await Me((await X((await te(t)).map(u=>u.node_id))).filter(u=>u.kind!=="human").sort((u,p)=>u.status===p.status?0:u.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw R(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await Z(t),situational_card:await Oe(t),ancestors:r,children:o,fork_source:c===null?null:await k(c),subject:l,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function et(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(et,"parseGeneratedNameBody");function tt(t){const e=m(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw d(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(tt,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:z(e.sessionFile);return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t);if(await re(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await Q(n);if(o!==null&&o.node_id!==t){if(de(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await ae(o.node_id);if(c===null||await se({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await oe(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await b(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function nt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(nt,"handleSessionBound");function it(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw d("bearings must be fresh, inherited or present");return e}s(it,"parseCycleStartBody");async function rt(t,e,n,r,i,a){const o=r.warm_spare||a,c=!o&&i!=="present",l=await O(t,e,{activity:"names"},n),u=c?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{}},n):void 0,p=o?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...u===void 0?{}:{boot:{content:u.content,...u.inherited===!0?{inherited:!0}:{}}},...p===void 0?{}:{system_prompt:p.content}}}s(rt,"startupDelivery");async function j(t,e,n,r=!1){r||await Fe(await A(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Ce(o,t,async(p,v,Y)=>await Te(o,p,v,Y));ue(c);const l=await Be(o,c),u=await V(t,l);return{state:u,delivery:await rt(o,c,l,u,e,n)}});if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,l=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function fn(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(fn,"renderCarriedStart");async function ot(t){const e=t.params.id,n=it(t.body),r=await y(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await $(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:p,sha256:v})=>({path:p,sha256:v})),structured_request:await N(e)}}}s(ot,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t,e){return t.inPlaceCycle!==!0?{action:"shutdown"}:e.cycle_pending===!0?{action:"stay_dormant"}:{action:"new_cycle"}}s(H,"refreshDirective");async function at(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ee(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await b(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e,r),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await be(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:H(e,r),closePane:!1};const a=await _e(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await b(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(at,"settleBroker");async function st(t){const e=t.params.id,n=Xe(t.body);await f(e,n.expected_execution_id);const r=await y(e);if(r.intent!=="refresh")throw new ze(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Ve(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&Ue(i.launchJson,await $e(e,a,r.cwd))?{status:200,body:await ct(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(st,"handleCycle");async function ct(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await He(e,n),a=await We(e,i);await Je(t),await Ge(t,e,!1),await Ye(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of je)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ke({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(ct,"startCycleRecord");async function dt(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await ie(n.expected_execution_id),{status:204}}s(dt,"handleIdle");async function lt(t){const e=t.params.id,n=Qe(t.body);await f(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(lt,"handleSettle");async function ut(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const r=await T(e),i=await w(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await F(r))?(await h(e),await b(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ce(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await B(e),{status:200,body:i}}s(ut,"handleParkComplete");async function pt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await w(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(pt,"handleParkActivity");async function ft(t){const e=t.params.id,n=Ie(t.body);return await f(e,n.expected_execution_id),await w(async()=>{await ne(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),De(e,n)}),{status:204}}s(ft,"handleTelemetry");async function mt(t){const e=t.params.id,n=qe(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await w(async()=>await ve(await y(e),n.spec,n.intent,n.userSelected))).model_override}}}s(mt,"handleModelCommit");let J=!0;function mn(t){J=t}s(mn,"setRequestsStartRunObservers");async function wt(t){const e=t.params.id,n=await y(e);return n.run_id&&J&&await Ne(e,n.run_id),{status:200,body:await V(e)}}s(wt,"handleExtensionState");async function yt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),{status:200,body:await w(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await y(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const l=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(l),description:l.description??"",title:l.title??"",icon:l.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(yt,"handleGeneratedName");async function ht(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(ht,"handlePersonaAck");async function G(t,e,n){return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const wn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:nt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:ot},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:mt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ht}]);export{wn as brokerOperationRoutes,k as extensionNode,fn as renderCarriedStart,j as renderStartData,mn as setRequestsStartRunObservers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}:void 0,
|
|
3
|
-
`),{status:200}}
|
|
1
|
+
var S=Object.defineProperty;var s=(t,e)=>S(t,"name",{value:e,configurable:!0});import{randomUUID as g}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as k}from"../../../core/llm/body-limits.js";import{llmCallerOf as h,parseLlmRequest as O,runLlm as T}from"../../../core/llm/run.js";import{RunError as u}from"../../../core/runs/operations.js";import{errorCodes as q}from"../../../api/error-codes.js";import{getNode as x}from"../../../core/canvas/canvas.js";import{emitEvent as R}from"../../../core/events/emit.js";import{boundedCause as I}from"../map.js";import{socketPrincipal as l}from"../server.js";import{activeGrant as N,activeGrantForApp as w,grantFor as G,grantsSource as b,payerOfGrant as L}from"../../../core/grants/mirror.js";import{parseUsageMonth as M,usageFor as $}from"../../../core/ledger/index.js";function v(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:a,...n}=t;return n}s(v,"operatorDetails");const j="app:terminal";async function A(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run};if(t?.class==="app"){const a=await b();if(a===null||a==="local")return{grantee:t.app};let n;try{n=await w(t.app)}catch{throw new u(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!n)throw new u(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:n.sub}}return{grantee:j}}s(A,"spendTarget");async function B(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await N(t.grant):await G(t.app,t.sub);if(!e&&await L(t.grant)==="app")throw new u(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return h(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await b();return e===null||e==="local"?void 0:h(await w(t.app))}}s(B,"llmCaller");function E(t){const e=q[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}s(E,"errorType");function C(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const a=t.details?.payment;return a===void 0?{}:{payment:a}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}s(C,"capFields");const W=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:k,handler:s(async({body:t,res:e,req:a,causedBy:n})=>{const f=g();e.setHeader("Request-Id",f);const y=new AbortController,_=s(()=>y.abort(),"abort");e.on("close",_);let p;try{const o=O(t),r=l(a),d=r?.class==="broker"?await x(r.node):null;if(r?.class==="broker"&&!d)throw new u(401,"unauthorized","node not found");const i={...await A(r,d??void 0),request:f},m=await T(o,y.signal,o.stream?c=>{typeof c.served_model=="string"&&(p=c.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(c)}
|
|
2
|
+
`)}:void 0,d?{cwd:d.cwd,profileId:d.profile_id??null}:void 0,i,await B(r),n);return o.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:m.completion}}catch(o){o instanceof u||R({event:"api.request.failed",level:"error",error:o instanceof Error?o:new Error(String(o)),...l(a)?.class==="broker"?{node_id:l(a).node}:{},fields:{method:"POST",path:"/v1/llm"}});const r=o instanceof u?o:new u(503,"upstream_model_unavailable",I(o));if(e.headersSent){const m=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:{},c=v(p!==void 0&&typeof m.served_model!="string"?{...m,served_model:p}:r.details,l(a)?.class);return e.end(`${JSON.stringify({error:{code:r.code,message:r.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:r.retryable,request_id:f}})}
|
|
3
|
+
`),{status:200}}const d=v(r.details,l(a)?.class),i=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return i!==void 0&&e.setHeader("Retry-After",String(i)),{status:r.status,body:{error:{code:r.code,message:r.message,...d===void 0?{}:{details:d},type:E(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:f,...i!==void 0?{retry_after_s:i}:{},...C(r)}}}}finally{e.off("close",_)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:s(async({req:t})=>{const e=g(),a={"Request-Id":e};try{const n=await A(l(t));return{status:200,headers:a,body:await $(n.grantee,M(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(n){if(!(n instanceof u))throw n;return{status:n.status,headers:a,body:{error:{code:n.code,message:n.message,type:E(n),...n.param?{param:n.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{C as capFields,W as llmRoutes,A as spendTarget};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
content unavailable: ${o.unavailable}`,data:{...f,content:"markdown"in o?"live":"unavailable"}}})}u(ct,"read");function te(e,t,n,a){if(e!=null){if(!n.includes(e)){a.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}u(te,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await ze(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await Ve(e)).join(", ")}`,received:t});return}return t}}u(ge,"kindName");function je(e,t,n,a){if(e==null)return a;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),a):i}u(je,"limitOf");function _e(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!q(n)||Object.values(n).some(a=>!q(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}u(_e,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}u(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await N(),t.get("type"),n),i=te(t.get("privacy"),"privacy",Ae,n),r=je(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const s=t.get("deleted");s!==null&&!["0","1","true","false"].includes(s)&&n.push({field:"deleted",problem:"must be true or false",received:s});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const l=_e(t.get("extensions"),n),f=ke(t.get("schema_type"),n);return n.length>0&&U("object list request",n),await R(e.principal),await v(async w=>{const b=await T(w,e),_={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...l?{extensions:l}:{},...f?{schemaType:f}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},g=t.get("owner");if(g!==null){const m=await he(w,b,g);if(m===null)return{items:[],next_cursor:null};_.owner=m}const p=await Je(w,b,_,{limit:r,after_seq:o===null?0:Number(o)}),d=p.at(-1);return{items:await pe(w,p),next_cursor:p.length===r&&d?String(d.seq):null}})}u(ve,"listLocal");const ut={ms:3e4},lt="self",ne=u((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=P.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(at(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:ne(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}u(Oe,"remotePage");async function ft(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([P.current.machines().catch(()=>null),t])}u(ft,"machinesWithin");async function dt(e){const t=e.query.get("machine");if(!we(e.principal)||!P.current.joined()||t===lt)return await ve(Ee(e));const a=P.current.self(),i=t!==null&&F(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,s=setTimeout(()=>o.abort(),ut.ms);s.unref?.();try{const c=await ft(o.signal);if(c===null){if(i)throw new h(503,"runtime_unreachable",`The directory did not answer, so ${F(t)} cannot be listed.`,{machine:F(t)});return r}const l=u(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=l(a),w=c.filter(d=>d.machine_id!==a&&d.kind!=="device"),b=H(e);if(t!==null){if(!i)return{items:ne(r.items,f),next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null}]};const d=F(t);if(!w.some(L=>L.machine_id===d))throw new h(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await Oe(e,l(d),b,o.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:l(d).name,state:m.state,more:m.next!==null}]}}const{cursor:_,...g}=b,p=await Promise.all(w.map(d=>Oe(e,l(d.machine_id),g,o.signal)));return{items:[...ne(r.items,f),...p.flatMap(d=>d.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null},...w.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:p[m].state,more:p[m].next!==null}))]}}finally{clearTimeout(s)}}u(dt,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}u(Ee,"withoutMachine");async function wt(e){const t=[],n=q(e.body)?e.body:{};q(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const a=n.text;(typeof a!="string"||a.trim()==="")&&t.push({field:"text",problem:"is required",received:a});const i=n.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(y){t.push({field:"grep",problem:`is not a valid regular expression: ${y.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await N(),n.type,t);n.kind!==void 0&&typeof n.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:n.kind}),n.owner!==void 0&&typeof n.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:n.owner});const o=je(n.limit,"limit",t,50),s=_e(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&U("object search request",t),await R(e.principal);const l=await v(async y=>{const k=await T(y,e),$e=typeof n.owner=="string"?await he(y,k,n.owner):null;return{reader:k,owner:$e}}),{reader:f,owner:w}=l;if(typeof n.owner=="string"&&w===null)return{items:[]};const b={...s?{extensions:s}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...w?{owner:w}:{}},_=await N(),g=await ue(_,f,{text:a,body:n.body===!0||typeof i=="string",...b}),p=new Set(g.map(y=>y.object.id)),m=(typeof i=="string"?(await ue(_,f,{text:i,grep:!0,...b})).filter(y=>p.has(y.object.id)):g).slice(0,o),L=await pe(_,m.map(y=>y.object));return{items:m.map((y,k)=>({object:L[k],...y.line!==void 0?{matches:[{line:y.line,text:y.text??""}]}:{}}))}}u(wt,"search");const Te=["interrupt","steer","after-turn","next-turn"],mt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function pt(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!mt.test(n)||n.includes(">")&&!n.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}u(pt,"patternsOf");function ht(e,t){if(e===void 0)return;if(!q(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const n=[];for(const[a,i]of Object.entries(e)){const r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Te.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Te.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}u(ht,"configOf");async function Re(e){const t=await x(e);if(t!==null)throw new h(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}u(Re,"refuseStubWatch");async function ae(e,t){const n=await I(e,t)??await(async()=>{const a=await Le(e,await We(e,{class:"person"},async()=>[]),t);return"object"in a?a.object:null})();return n===null||n.deleted_at!==null||!(n.type.includes(".")||n.type==="node")?null:n}u(ae,"findWatcher");const E=u(()=>{throw new h(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new h(400,"invalid_request","invalid watcher_machine");if(await ae(e,t)!==null)return null;const a=P.current;let i;try{i=await a.machines()}catch{throw new h(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=F(n);return(r===a.self()||!i.some(o=>F(o.machine_id)===r))&&E(),r}u(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return E();const i=await T(e,t);if(i.class==="person")return E();let r;try{r=await S(e,i,a)}catch{return E()}const o=r.owner===null?null:await I(e,r.owner);return o===null||!await oe(e,i,o)||!await De(e,i,"link",n)||(await Me(e,n)).id===i.app.id&&!(await D(e,i,n)&&await D(e,await C(e,n),r))?E():(await J(e,t,n),{actor:i.app,object:r})}u(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await T(e,t),i=n.owner===null?null:await I(e,n.owner);return i!==null&&await oe(e,a,i)&&await Ge(e,a,n)}u(Ie,"ownsWatcher");async function yt(e){const t=O(e),n=q(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Re(t),typeof n.watcher!="string"){const i=await ee(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw me(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw z(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Y(i.body,i.machine)}}const a=await qe(await N(),n.watcher,n.watcher_machine);return await bt(e,a)}u(yt,"watch");async function bt(e,t=null){const n=[],a=e.body===void 0?{}:q(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=pt(a.patterns,n),r=ht(a.config,n);return a.filter!==void 0&&!q(a.filter)&&n.push({field:"filter",problem:"must be an object",received:a.filter}),a.watcher!==void 0&&typeof a.watcher!="string"&&n.push({field:"watcher",problem:"must be a custom-object ref",received:a.watcher}),a.watcher_machine!==void 0&&typeof a.watcher_machine!="string"&&n.push({field:"watcher_machine",problem:"must be a machine id",received:a.watcher_machine}),n.length>0&&U("watch request",n),await R(e.principal),await v(async o=>{const s=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new h(404,"not_found","watcher not found");const c=i??[">"],l={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(s){const _=a.watcher,g=t===null?null:await gt(o,e,_,t),p=g??(e.publishToken?await se(o,_):await ae(o,_));if(p===null)return E();if(g===null&&await Ie(o,e,p)){const L=await ce(o,e,p);await J(o,e,p);const y=await C(o,p),k=await S(o,y,O(e));if(!await D(o,y,k))throw new h(404,"not_found","object not found");return await M(o,p,k,"act",l),await G(o,p,k),await B(o,{event:"watched",object:k,actor:L,attrs:{}},await A(o)),{object:await $(o,k,await j(o,k)),patterns:c}}const{actor:d,object:m}=await Ne(o,e,p,O(e));return await M(o,p,m,"act",{...l,linkApp:d}),await G(o,p,m),await B(o,{event:"watched",object:m,actor:d,attrs:{}},await A(o)),{object:await $(o,m,await j(o,m)),patterns:c}}const f=await T(o,e),w=await Q(o,e)??ie(f),b=await S(o,f,O(e));return await M(o,w,b,"ask",l),await G(o,w,b),await B(o,{event:"watched",object:b,actor:w,attrs:{}},await A(o)),{object:await $(o,b,await j(o,b)),patterns:c}})}u(bt,"watchLocal");async function gt(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?E():await tt(e,n,a)}u(gt,"ensureNodeStubFor");async function Se(e,t,n,a){const i=u(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
-
WHERE w.watcher = ? AND w.object = ?`).get(t.id,n.id)).n,"count"),r=await i();await
|
|
1
|
+
var Ae=Object.defineProperty;var s=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{ApiError as j}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Fe}from"../../../api/dto/objects.js";import{openDb as T,withCanvasWrite as v}from"../../../core/canvas/db.js";import{actorOf as ae}from"../../../core/graph/documents.js";import{readerForObject as P,readerFor as We}from"../../../core/graph/reader.js";import{resolveName as Le,stubsNamed as Pe,unwrapRef as ie}from"../../../core/graph/names.js";import{shareReads as Ce}from"../../../core/permissions/evaluator.js";import{canRead as C,holdsObjectsScope as De,spaceOf as Me}from"../../../core/graph/access.js";import{customReachable as Ge,mayActAs as re}from"../../../core/graph/custom.js";import{customObjectRef as oe,authorizeCustom as se,fenceArgv as J}from"./custom-objects.js";import{edgesOf as Ue}from"../../../core/graph/edges.js";import{publish as B}from"../../../core/graph/events.js";import{objectDTO as He}from"../../../core/graph/kinds/dto.js";import{isKind as ze,kindNames as Ve,kindOf as ce}from"../../../core/graph/kinds/registry.js";import{recordRead as Je}from"../../../core/graph/kinds/live-read.js";import{listObjects as Be,searchObjects as ue}from"../../../core/graph/objects.js";import{checkoutsForCwd as Ke}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as D,unwatch as Ze,watchersOf as Qe,watchesOf as Ye}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as M,settleObjectWaitForUnwatch as Xe}from"../../../core/graph/object-waits.js";import{readerFor as q,resolveRef as K,warmReaderRepos as N}from"../reader.js";import{readDelegationFor as le,runReadLeaf as xe}from"../../plugin-objects/read-leaf.js";import{invalidRequest as G,isRecord as I}from"./validate.js";import{callerNode as de,callerStub as Z,forwardNamed as et,forwardVerb as fe,originates as we,queryWithoutMachine as U,relayError as H,remoteStub as tt,unknownError as me,forwarding as L,withMachine as Q}from"../../peer/forward.js";import{getById as S}from"../../../core/graph/objects.js";import{ensureNodeStub as nt,isStub as Y,stubOf as at,withKindDecl as z}from"../../../core/peer/stubs.js";import{isUnreachable as it}from"../../../core/peer/client.js";import{normalizeMachineId as A}from"../../../core/peer/directory.js";import{mapAsync as rt}from"../../../core/async-array.js";const F=s(async e=>async(t,n)=>await Ke(e,t,n),"reposFnFor");async function k(e,t){return{...await He(e,t),...t.type==="document"?{schema_type:t.schema_type??null}:{}}}s(k,"objectDTO");async function ot(e,t){const n=t.filter(r=>r.type==="document").map(r=>r.id),a=new Map;if(n.length===0)return a;const i=await e.prepareUncached(`SELECT object, extensions_json FROM documents WHERE object IN (${n.map(()=>"?").join(", ")})`).all(...n);for(const r of i)r.extensions_json!==null&&a.set(r.object,JSON.parse(r.extensions_json));return a}s(ot,"extensionsOf");async function pe(e,t){const n=await ot(e,t);return await rt(t,async a=>({...await k(e,a),...await(await ce(e,a.type)).listItem?.(e,a),...a.type==="document"?{extensions:n.get(a.id)??{}}:{}}))}s(pe,"listItems");function st(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}s(st,"remoteMessage");async function he(e,t,n){try{return await $(e,t,n)}catch(a){if(a instanceof j&&a.code==="not_found"&&!a.details?.deleted)return null;throw a}}s(he,"ownerFilter");async function $(e,t,n){const a=await K(e,t,n);if("remote"in a)throw new j(404,"not_found",st(a.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in a)throw new j(404,"not_found",`${a.deleted.name} is deleted`,{id:a.deleted.id,deleted:!0});return a}s($,"liveRef");const E=s(e=>decodeURIComponent(e.params.ref),"refParam"),ye=s(e=>{const t=ie(e),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");async function X(e){const t=await S(await T(),ye(e));return t!==null&&await Y(await T(),t)?t.id:null}s(X,"stubIdOf");async function ct(e,t){const n=await X(e);return n!==null?{stub:n,hit:!0}:(await N(t.principal),await v(async a=>{try{const i=await q(a,t),r=s(async()=>{const u=await Pe(a,i,e);if(u.length>1)throw new j(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:u.map(c=>c.id),next:"Read one by its object id."});return{stub:u[0]?.id??null,hit:!1}},"named");let o;try{o=await K(a,i,e)}catch(u){if(u instanceof j&&u.code==="not_found")return await r();throw u}if("remote"in o)return await r();if("deleted"in o){const u=await r();return u.stub===null?{stub:null,hit:!0}:u}return{stub:await Y(a,o)?o.id:null,hit:!0}}catch(i){if(i instanceof j&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}}))}s(ct,"resolvedLocally");async function x(e,t,n){const a=await ct(t,e);if(a.stub!==null)return fe(e,a.stub,n);if(a.hit||!we(e.principal))return{kind:"local"};const i=await fe(e,ye(t),n);return i.kind==="local"&&ie(t).includes("/")?et(e,n,{method:"GET",path:V(t),query:U(e)}):i}s(x,"forwardRef");const V=s(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,n,a,i){const r=t?.object;!r?.id||!r.type||await v(async o=>{const u=await de(o,e);if(u===null)return;const c=await tt(o,r.id,r.type,n,{kind:r.kind??null,name:r.name??r.id,...r.preview===void 0?{}:{preview:r.preview},owner:r.owner??null,...r.kind_decl===void 0?{}:{kind_decl:r.kind_decl},...r.privacy===void 0?{}:{privacy:r.privacy}});await D(o,u,c,a,i===void 0?{}:{patterns:i}),a==="ask"&&await M(o,u,c)})}s(be,"watchRemote");async function ut(e){const t=E(e),n=["1","true"].includes(e.query.get("fields")??""),a=s(async d=>{const m=await Z(d,e);return Ce(m===null?await q(d,e):await P(d,m,await F(d)))},"readerOf"),i=s(async(d,m,f)=>{const l=await S(d,f);if(l===null||l.deleted_at===null&&!await C(d,m,l))throw new j(404,"not_found","object not found");return l.deleted_at===null?l:{state:"deleted",deleted:await k(d,l)}},"stillReadable"),r=s(async(d,m,f)=>await(await ce(d,f.type)).read(d,m,f,{fields:n,reposFn:await F(d)}),"render"),o=s(async(d,m,{data:f,text:l,record:O})=>await v(async p=>{const g=await i(p,d,m);return"state"in g?g:(await Je(p,d,g,O,await F(p)),{state:"object",type:g.type,object:await z(p,g,await k(p,g)),text:l,data:f})}),"recorded"),u=s(async d=>{await N(e.principal);const m=await T(),f=await v(a),l=await K(m,f,t).catch(p=>{if(d||p instanceof j&&p.code==="ambiguous_name")throw p;return null});if(l===null||!d&&!("id"in l))return null;if("remote"in l)return{state:"remote",remote:l.remote};if("deleted"in l)return{state:"deleted",deleted:await k(m,l.deleted)};const O=await le(m,l);return O!==null?{delegate:O,hitId:l.id}:await o(f,l.id,await r(m,f,l))},"local"),c=(await X(t)===null?await u(!1):null)??await x(e,t,{method:"GET",path:V(t),query:U(e)}).then(async d=>{if(d.kind==="local")return await u(!0);if(d.kind==="unknown")return{state:"unknown",ref:t,unreachable:d.unreachable};if(d.status>=400)throw H(d.status,d.body);return await be(e,d.body,d.machine.id,"read").then(()=>Q(d.body,d.machine))});if(!("delegate"in c))return c;const w=await xe(c.delegate,e.principal);await N(e.principal);const h=await T(),y=await v(a),b=await i(h,y,c.hitId);if("state"in b)return b;const _=await o(y,b.id,await r(h,y,b));return _.state!=="object"||await le(h,b)===null?_:{..._,text:"markdown"in w?w.markdown:`${_.text}
|
|
2
|
+
content unavailable: ${w.unavailable}`,data:{..._.data,content:"markdown"in w?"live":"unavailable"}}}s(ut,"read");function ee(e,t,n,a){if(e!=null){if(!n.includes(e)){a.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}s(ee,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await ze(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await Ve(e)).join(", ")}`,received:t});return}return t}}s(ge,"kindName");function _e(e,t,n,a){if(e==null)return a;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),a):i}s(_e,"limitOf");function je(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!I(n)||Object.values(n).some(a=>!I(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}s(je,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}s(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await T(),t.get("type"),n),i=ee(t.get("privacy"),"privacy",Fe,n),r=_e(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const u=t.get("deleted");u!==null&&!["0","1","true","false"].includes(u)&&n.push({field:"deleted",problem:"must be true or false",received:u});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const w=je(t.get("extensions"),n),h=ke(t.get("schema_type"),n);return n.length>0&&G("object list request",n),await N(e.principal),await v(async y=>{const b=await q(y,e),_={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...u==="1"||u==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...w?{extensions:w}:{},...h?{schemaType:h}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},d=t.get("owner");if(d!==null){const l=await he(y,b,d);if(l===null)return{items:[],next_cursor:null};_.owner=l}const m=await Be(y,b,_,{limit:r,after_seq:o===null?0:Number(o)}),f=m.at(-1);return{items:await pe(y,m),next_cursor:m.length===r&&f?String(f.seq):null}})}s(ve,"listLocal");const lt={ms:3e4},dt="self",te=s((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=L.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(it(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:te(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}s(Oe,"remotePage");async function ft(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([L.current.machines().catch(()=>null),t])}s(ft,"machinesWithin");async function wt(e){const t=e.query.get("machine");if(!we(e.principal)||!L.current.joined()||t===dt)return await ve(Ee(e));const a=L.current.self(),i=t!==null&&A(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,u=setTimeout(()=>o.abort(),lt.ms);u.unref?.();try{const c=await ft(o.signal);if(c===null){if(i)throw new j(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return r}const w=s(f=>({id:f,name:c.find(l=>l.machine_id===f)?.name??f}),"labelOf"),h=w(a),y=c.filter(f=>f.machine_id!==a&&f.kind!=="device"),b=U(e);if(t!==null){if(!i)return{items:te(r.items,h),next_cursor:r.next_cursor,machines:[{machine_id:a,name:h.name,state:"ok",more:r.next_cursor!==null}]};const f=A(t);if(!y.some(O=>O.machine_id===f))throw new j(404,"not_found",`no machine ${f} on your account`,{machine:f});const l=await Oe(e,w(f),b,o.signal);return{items:l.items,next_cursor:l.next,machines:[{machine_id:f,name:w(f).name,state:l.state,more:l.next!==null}]}}const{cursor:_,...d}=b,m=await Promise.all(y.map(f=>Oe(e,w(f.machine_id),d,o.signal)));return{items:[...te(r.items,h),...m.flatMap(f=>f.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:h.name,state:"ok",more:r.next_cursor!==null},...y.map((f,l)=>({machine_id:f.machine_id,name:f.name,state:m[l].state,more:m[l].next!==null}))]}}finally{clearTimeout(u)}}s(wt,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}s(Ee,"withoutMachine");async function mt(e){const t=[],n=I(e.body)?e.body:{};I(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const a=n.text;(typeof a!="string"||a.trim()==="")&&t.push({field:"text",problem:"is required",received:a});const i=n.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(p){t.push({field:"grep",problem:`is not a valid regular expression: ${p.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await T(),n.type,t);n.kind!==void 0&&typeof n.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:n.kind}),n.owner!==void 0&&typeof n.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:n.owner});const o=_e(n.limit,"limit",t,50),u=je(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&G("object search request",t),await N(e.principal);const w=await v(async p=>{const g=await q(p,e),$e=typeof n.owner=="string"?await he(p,g,n.owner):null;return{reader:g,owner:$e}}),{reader:h,owner:y}=w;if(typeof n.owner=="string"&&y===null)return{items:[]};const b={...u?{extensions:u}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...y?{owner:y}:{}},_=await T(),d=await ue(_,h,{text:a,body:n.body===!0||typeof i=="string",...b}),m=new Set(d.map(p=>p.object.id)),l=(typeof i=="string"?(await ue(_,h,{text:i,grep:!0,...b})).filter(p=>m.has(p.object.id)):d).slice(0,o),O=await pe(_,l.map(p=>p.object));return{items:l.map((p,g)=>({object:O[g],...p.line!==void 0?{matches:[{line:p.line,text:p.text??""}]}:{}}))}}s(mt,"search");const Re=["interrupt","steer","after-turn","next-turn"],pt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function ht(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!pt.test(n)||n.includes(">")&&!n.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}s(ht,"patternsOf");function yt(e,t){if(e===void 0)return;if(!I(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const n=[];for(const[a,i]of Object.entries(e)){const r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Re.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Re.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}s(yt,"configOf");async function Te(e){const t=await X(e);if(t!==null)throw new j(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}s(Te,"refuseStubWatch");async function ne(e,t){const n=await S(e,t)??await(async()=>{const a=await Le(e,await We(e,{class:"person"},async()=>[]),t);return"object"in a?a.object:null})();return n===null||n.deleted_at!==null||!(n.type.includes(".")||n.type==="node")?null:n}s(ne,"findWatcher");const R=s(()=>{throw new j(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new j(400,"invalid_request","invalid watcher_machine");if(await ne(e,t)!==null)return null;const a=L.current;let i;try{i=await a.machines()}catch{throw new j(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=A(n);return(r===a.self()||!i.some(o=>A(o.machine_id)===r))&&R(),r}s(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return R();const i=await q(e,t);if(i.class==="person")return R();let r;try{r=await $(e,i,a)}catch{return R()}const o=r.owner===null?null:await S(e,r.owner);return o===null||!await re(e,i,o)||!await De(e,i,"link",n)||(await Me(e,n)).id===i.app.id&&!(await C(e,i,n)&&await C(e,await P(e,n),r))?R():(await J(e,t,n),{actor:i.app,object:r})}s(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await q(e,t),i=n.owner===null?null:await S(e,n.owner);return i!==null&&await re(e,a,i)&&await Ge(e,a,n)}s(Ie,"ownsWatcher");async function bt(e){const t=E(e),n=I(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Te(t),typeof n.watcher!="string"){const i=await x(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw me(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw H(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Q(i.body,i.machine)}}const a=await qe(await T(),n.watcher,n.watcher_machine);return await gt(e,a)}s(bt,"watch");async function gt(e,t=null){const n=[],a=e.body===void 0?{}:I(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=ht(a.patterns,n),r=yt(a.config,n);return a.filter!==void 0&&!I(a.filter)&&n.push({field:"filter",problem:"must be an object",received:a.filter}),a.watcher!==void 0&&typeof a.watcher!="string"&&n.push({field:"watcher",problem:"must be a custom-object ref",received:a.watcher}),a.watcher_machine!==void 0&&typeof a.watcher_machine!="string"&&n.push({field:"watcher_machine",problem:"must be a machine id",received:a.watcher_machine}),n.length>0&&G("watch request",n),await N(e.principal),await v(async o=>{const u=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!u)throw new j(404,"not_found","watcher not found");const c=i??[">"],w={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(u){const _=a.watcher,d=t===null?null:await _t(o,e,_,t),m=d??(e.publishToken?await oe(o,_):await ne(o,_));if(m===null)return R();if(d===null&&await Ie(o,e,m)){const O=await se(o,e,m);await J(o,e,m);const p=await P(o,m),g=await $(o,p,E(e));if(!await C(o,p,g))throw new j(404,"not_found","object not found");return await D(o,m,g,"act",w),await M(o,m,g),await B(o,{event:"watched",object:g,actor:O,attrs:{}},await F(o)),{object:await z(o,g,await k(o,g)),patterns:c}}const{actor:f,object:l}=await Ne(o,e,m,E(e));return await D(o,m,l,"act",{...w,linkApp:f}),await M(o,m,l),await B(o,{event:"watched",object:l,actor:f,attrs:{}},await F(o)),{object:await z(o,l,await k(o,l)),patterns:c}}const h=await q(o,e),y=await Z(o,e)??ae(h),b=await $(o,h,E(e));return await D(o,y,b,"ask",w),await M(o,y,b),await B(o,{event:"watched",object:b,actor:y,attrs:{}},await F(o)),{object:await z(o,b,await k(o,b)),patterns:c}})}s(gt,"watchLocal");async function _t(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?R():await nt(e,n,a)}s(_t,"ensureNodeStubFor");async function Se(e,t,n,a){const i=s(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
+
WHERE w.watcher = ? AND w.object = ?`).get(t.id,n.id)).n,"count"),r=await i();await Ze(e,t,n,a??void 0);const o=await i();return o===0&&await Xe(e,t,n),{object:await k(e,n),removed:r-o}}s(Se,"dropWatch");async function jt(e){const t=E(e);if(e.query.get("watcher")&&await Te(t),!e.query.get("watcher")){const a=await x(e,t,{method:"DELETE",path:`${V(t)}/watch`,query:U(e)});if(a.kind==="unknown")throw me(t,a.unreachable);if(a.kind==="remote"){const i=a.status===404?a.body.error?.details:void 0,r=i?.deleted===!0?i.id:void 0;if(a.status>=400&&r===void 0)throw H(a.status,a.body);const o=r??a.body.object?.id,u=await v(async c=>{const w=await de(c,e),h=o===void 0?null:await S(c,o);return w===null||h===null||!await Y(c,h)?null:await Se(c,w,h,e.query.get("pattern"))});if(r!==void 0){if(u===null)throw H(a.status,a.body);return{...u,machine:a.machine}}return Q(a.body,a.machine)}}const n=await qe(await T(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await kt(e,n)}s(jt,"unwatchRoute");async function kt(e,t=null){const n=e.query.get("pattern"),a=e.query.get("watcher");return await N(e.principal),await v(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!a)throw new j(404,"not_found","watcher not found");const r=s(async(c,w)=>await Se(i,c,w,n),"drop");if(a){const c=t===null?null:await(async()=>{const h=await S(i,a);return h!==null&&await at(i,h)!==null?h:null})();if(t!==null&&c===null)return R();const w=c??(e.publishToken?await oe(i,a):await ne(i,a));return w===null?R():c===null&&await Ie(i,e,w)?(await se(i,e,w),await J(i,e,w),await r(w,await $(i,await P(i,w),E(e)))):await r(w,(await Ne(i,e,w,E(e))).object)}const o=await q(i,e),u=await Z(i,e)??ae(o);return await r(u,await $(i,o,E(e)))})}s(kt,"unwatchLocal");async function vt(e){const t=[],n=ee(e.query.get("type"),"type",["acted-on","links-to","watches"],t),a=ee(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&G("edges request",t),await N(e.principal),await v(async i=>{const r=await q(i,e),o=await $(i,r,E(e)),u=[];if(n!=="watches")for(const c of await Ue(i,r,o,{...n?{type:n}:{},direction:a??"both"}))u.push({type:c.type,src:await k(i,c.src),dst:await k(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...a!=="in"?await Ye(i,r,o):[],...a!=="out"?await Qe(i,r,o):[]];for(const w of c)u.push({type:"watches",src:await k(i,w.watcher),dst:await k(i,w.object)})}return{items:u}})}s(vt,"edges");const W=s(e=>async t=>({status:200,body:await e(t)}),"ok"),xt=[{method:"POST",pattern:"/v1/objects/search",handler:W(mt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:W(vt)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:W(bt)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:W(jt)},{method:"GET",pattern:"/v1/objects/:ref",handler:W(ut)},{method:"GET",pattern:"/v1/objects",handler:W(wt)}];export{lt as listBudget,xt as objectRoutes,ct as resolvedLocally};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var s=(n,e)=>g(n,"name",{value:e,configurable:!0});import{ApiError as p}from"../../../api/index.js";import{isCloudRole as R}from"../../../core/canvas/person.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{readDocument as q}from"../../../core/graph/documents.js";import{
|
|
1
|
+
var g=Object.defineProperty;var s=(n,e)=>g(n,"name",{value:e,configurable:!0});import{ApiError as p}from"../../../api/index.js";import{isCloudRole as R}from"../../../core/canvas/person.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{readDocument as q}from"../../../core/graph/documents.js";import{recordRead as S}from"../../../core/graph/kinds/live-read.js";import{getById as E}from"../../../core/graph/objects.js";import{checkoutsForCwd as T}from"../../../core/graph/repo-sync/repos.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{assertScope as C}from"../../../core/scopes.js";import{createReview as A}from"../../../core/review/birth.js";import{readAnchorBase as $,listReviews as I,requireVisibleReview as b}from"../../../core/review/store.js";import{canvasOrigin as D}from"../canvas-host.js";import{cancelReview as O,submitReviewApproval as L}from"../../review/finish.js";import{toFeedbackResultDTO as F,toReviewDTO as N}from"../map.js";import{readerFor as P,resolveRef as j,warmReaderRepos as B}from"../reader.js";import{actsAsPerson as G,canReadNode as V}from"../router.js";import{invalidRequest as K,objectBody as v,optionalString as c,requireParam as W,requiredString as y}from"./validate.js";import{filterAsync as M}from"../../../core/async-array.js";const U=new Set(["open","approved","canceled"]),z=["origin_kind","origin_node_id","document","idempotency_key","subtitle","output_path"],H=["reason","actor","disposition"];function l(n){K("review request",n)}s(l,"invalidRequest");function w(n,e){return W(n,"review_id","must be a safe review id",h,e)}s(w,"requireReviewId");function m(n){return{...N(n,n.state==="approved"?{result_path:`${n.review_dir}/result.json`}:{}),review_dir:n.review_dir}}s(m,"toReviewResponseDTO");function J(n){const e=[],i=v(n.body,z,e),o=i.origin_kind,t=o==="ticket"||o==="inline"?o:void 0;t===void 0&&e.push({field:"origin_kind",problem:"must be ticket or inline",...o===void 0?{}:{received:o}});const r=y(i,"origin_node_id",e);r!==void 0&&!h(r)&&e.push({field:"origin_node_id",problem:"must be a safe node id",received:r});const d=c(i,"document",e);d===void 0&&e.push({field:"document",problem:"is required"});const a=y(i,"idempotency_key",e);a!==void 0&&a.length>128&&e.push({field:"idempotency_key",problem:"must be at most 128 characters",received:a});const f=c(i,"subtitle",e),u=c(i,"output_path",e);return t==="ticket"&&f===void 0&&i.subtitle===void 0&&e.push({field:"subtitle",problem:"is required for ticket reviews"}),t==="inline"&&i.subtitle!==void 0&&e.push({field:"subtitle",problem:"is only allowed for ticket reviews",received:i.subtitle}),t==="inline"&&i.output_path!==void 0&&e.push({field:"output_path",problem:"is only allowed for ticket reviews",received:i.output_path}),u!==void 0&&R()&&e.push({field:"output_path",problem:"is not supported on the cloud: a review result is projected only to its own request files",received:u}),(e.length>0||t===void 0||r===void 0||d===void 0||!h(r)||a===void 0||a.length>128)&&l(e),{origin_kind:t,origin_node_id:r,document:d,idempotency_key:a,...f===void 0?{}:{subtitle:f},...u===void 0?{}:{output_path:u}}}s(J,"parseCreate");function Q(n){const e=[],i={},o=new Set(["state","origin_node_id","file"]);for(const[t,r]of n.query.entries())o.has(t)||e.push({field:t,problem:"is not allowed",received:r});for(const t of o){const r=n.query.getAll(t);if(r.length>1){e.push({field:t,problem:"must appear at most once",received:r});continue}const d=r[0];d!==void 0&&(t==="state"?U.has(d)?i.state=d:e.push({field:t,problem:"must be open, approved, or canceled",received:d}):t==="origin_node_id"?h(d)?i.origin_node_id=d:e.push({field:t,problem:"must be a safe node id",received:d}):d===""?e.push({field:t,problem:"must be a non-empty string",received:d}):i.file=d)}return e.length>0&&l(e),i}s(Q,"parseList");function X(n,e){const i=n.body===void 0?{}:v(n.body,H,e),o=c(i,"reason",e),t=c(i,"actor",e),r=c(i,"disposition",e);return r!==void 0&&r!=="canceled"&&r!=="dismissed"&&e.push({field:"disposition",problem:'must be "canceled" or "dismissed"',received:r}),{...o===void 0?{}:{reason:o},...t===void 0?{}:{actor:t},...r==="canceled"||r==="dismissed"?{disposition:r}:{}}}s(X,"parseCancel");function Y(n,e){v(n.body,[],e)}s(Y,"requireEmptyBody");async function Z(n){const e=J(n);if(D()===void 0)throw new p(409,"no_canvas_host","this runtime has no canvas host to serve the review page",{next:"Reviews open in the browser at the canvas host (`CRTR_CANVAS_URL`); file this review from a cloud runtime."});const i=await _(e.origin_node_id);i!==null&&C(i,"crtr:act");const{document:o,...t}=e,r=await A({...t,document:await x(n,o)});return{status:200,body:m(r)}}s(Z,"handleCreate");async function x(n,e){return await B(n.principal),await k(async i=>{const o=await P(i,n),t=await j(i,o,e);if("remote"in t)throw new p(404,"not_found",`no document named ${t.remote} on this runtime`,{next:"Check the name with `crtr canvas search`."});if("deleted"in t)throw new p(404,"not_found",`${t.deleted.name} is deleted`,{id:t.deleted.id,deleted:!0});if(t.type!=="document")throw new p(400,"invalid_request",`${e} is a ${t.type}, not a document`);const r=await q(i,o,t);if(await S(i,o,t,{headsKey:r.record.heads_key,delivered:[]},async(f,u)=>await T(i,f,u)),r.needsMerge)throw new p(409,"needs_merge",`${t.name} has ${r.heads.length} heads; merge them before a review`,{id:t.id,next:`Read it with \`crtr canvas read ${t.id}\` and write the merged body with \`crtr doc edit\`.`});const d=t.owner===null?null:await E(i,t.owner),a=d===null?"":d.type==="node"?d.id:d.name;return{id:t.id,name:a===""?t.name:`${a}/${t.name}`,base:r.record.heads_key,body:r.heads[0].body}})}s(x,"reviewedDocument");async function ee(n){const e=Q(n);return{status:200,body:{reviews:(await M(await I(e),async o=>{if(G(n.principal))return!0;const t=await _(o.origin_node_id);return t!==null&&await V(n.principal,t.grantee??"app:terminal",t.node_id)})).map(m)}}}s(ee,"handleList");async function te(n){const e=[],i=w(n,e);return(e.length>0||i===void 0)&&l(e),{status:200,body:m(await b(i))}}s(te,"handleRead");async function ie(n){const e=[],i=w(n,e);Y(n,e),(e.length>0||i===void 0)&&l(e);const o=await L(i);return{status:200,body:o.outcome==="awaiting_companion"?{review:m(o.record),outcome:o.outcome}:{review:m(o.record),result:F(o.result),outcome:o.outcome}}}s(ie,"handleSubmit");async function ne(n){const e=[],i=w(n,e),o=X(n,e);(e.length>0||i===void 0)&&l(e);const t=await O(i,o);return{status:200,body:{review:m(t.record),outcome:t.outcome}}}s(ne,"handleCancel");async function oe(n){const e=[],i=w(n,e);(e.length>0||i===void 0)&&l(e);const o=await b(i),t=await $(o.review_id);if(t===null)throw new Error(`review anchor base is missing: ${o.review_id}`);return{status:200,body:{review_id:o.review_id,anchor_base_sha256:t.sha256,anchor_base_text:new TextDecoder("utf-8",{fatal:!0}).decode(t.bytes),file:o.file}}}s(oe,"handleDocument");const Se=[{method:"POST",pattern:"/v1/human/reviews",scope:"crtr:act",handler:Z},{method:"GET",pattern:"/v1/human/reviews",handler:ee},{method:"GET",pattern:"/v1/human/reviews/:review_id",handler:te},{method:"POST",pattern:"/v1/human/reviews/:review_id/submit",handler:ie},{method:"POST",pattern:"/v1/human/reviews/:review_id/cancel",handler:ne},{method:"GET",pattern:"/v1/human/reviews/:review_id/document",handler:oe}];export{J as parseCreate,Se as reviewRoutes};
|
package/dist/daemon/api/map.d.ts
CHANGED
|
@@ -155,6 +155,12 @@ export declare function errorToStatus(thrown: unknown): {
|
|
|
155
155
|
status: number;
|
|
156
156
|
code: string;
|
|
157
157
|
};
|
|
158
|
+
/** The single-line, length-bounded cause a 500 body may safely carry. A curated
|
|
159
|
+
* `Error.message` is a diagnostic, not a raw stack trace: surfacing its first
|
|
160
|
+
* line (capped) turns an opaque `internal error` into an actionable one while
|
|
161
|
+
* still refusing to leak multi-line traces. The router logs the FULL error
|
|
162
|
+
* (with stack) server-side alongside this. */
|
|
163
|
+
export declare function boundedCause(err: unknown): string;
|
|
158
164
|
/** Build the uniform JSON error body (spec §8) for a thrown value, using
|
|
159
165
|
* `errorToStatus` for the status/code. Structured `details` are surfaced for a
|
|
160
166
|
* CrtrError or ApiError (they let the client reconstruct the error verbatim). A 500 still
|