@north-light/cli 0.3.453 → 0.3.455

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.
Files changed (54) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/error-codes.d.ts +25 -0
  4. package/dist/api/error-codes.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/guides/apps-on-northlight.md +1 -1
  6. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  7. package/dist/clients/attach/viewer.js +413 -413
  8. package/dist/commands/pkg/browse/catalog.js +1 -1
  9. package/dist/commands/pkg/plugin-manage.js +1 -1
  10. package/dist/core/command-manifests/registry.d.ts +2 -1
  11. package/dist/core/command-plugins/bundle.d.ts +3 -10
  12. package/dist/core/command-plugins/bundle.js +1 -1
  13. package/dist/core/command-plugins/compose.js +1 -1
  14. package/dist/core/command-plugins/discovery.js +1 -1
  15. package/dist/core/command-plugins/endpoint.d.ts +12 -0
  16. package/dist/core/command-plugins/endpoint.js +1 -1
  17. package/dist/core/command.d.ts +13 -0
  18. package/dist/core/command.js +9 -9
  19. package/dist/core/peer/client.d.ts +4 -2
  20. package/dist/core/peer/client.js +1 -1
  21. package/dist/core/peer/directory.d.ts +7 -0
  22. package/dist/core/peer/directory.js +1 -1
  23. package/dist/core/peer/envelope.d.ts +4 -0
  24. package/dist/core/peer/envelope.js +1 -1
  25. package/dist/core/peer/home.js +1 -1
  26. package/dist/core/providers/bundles.d.ts +2 -0
  27. package/dist/core/providers/bundles.js +2 -2
  28. package/dist/core/providers/call.d.ts +2 -0
  29. package/dist/core/providers/call.js +1 -1
  30. package/dist/core/providers/device.d.ts +39 -0
  31. package/dist/core/providers/device.js +1 -0
  32. package/dist/core/providers/errors.js +1 -1
  33. package/dist/core/runtime/output-schema-refs.d.ts +3 -0
  34. package/dist/core/runtime/output-schema-refs.js +1 -0
  35. package/dist/core/runtime/structured-output.d.ts +16 -5
  36. package/dist/core/runtime/structured-output.js +8 -6
  37. package/dist/daemon/api/handlers/messages.js +2 -2
  38. package/dist/daemon/api/handlers/nodes.js +1 -1
  39. package/dist/daemon/api/handlers/objects.js +2 -2
  40. package/dist/daemon/api/handlers/providers.d.ts +2 -0
  41. package/dist/daemon/api/handlers/providers.js +1 -1
  42. package/dist/daemon/api/handlers/runs.js +1 -1
  43. package/dist/daemon/api/handlers/structured-requests.js +1 -1
  44. package/dist/daemon/peer/outbox.js +1 -1
  45. package/dist/daemon/peer/relay-client.js +1 -1
  46. package/dist/daemon/peer/relay-protocol.d.ts +1 -1
  47. package/dist/daemon/peer/relay-protocol.js +1 -1
  48. package/dist/types.d.ts +4 -0
  49. package/docs/ci-runner.md +50 -4
  50. package/docs/sdk/guides/apps-on-northlight.md +1 -1
  51. package/docs/sdk/release-notes.md +6 -0
  52. package/package.json +3 -3
  53. package/packages/crouter-identity/package.json +1 -1
  54. package/runtime.lock.json +12 -12
@@ -1,6 +1,8 @@
1
- var P=Object.defineProperty;var s=(t,e)=>P(t,"name",{value:e,configurable:!0});import{existsSync as l,mkdirSync as d,readFileSync as a,unlinkSync as f,writeFileSync as h,renameSync as S}from"node:fs";import{dirname as g,resolve as j}from"node:path";import{randomUUID as b}from"node:crypto";import{nodeDir as R,nodeRunDir as O,contextDir as x,nodeAgentDir as y}from"../canvas/paths.js";import{readTextBeneathIfExists as T,unlinkBeneath as E,writeFileBeneath as q}from"../spaces/open-beneath.js";import{InputError as N}from"../io.js";import{isRecord as c}from"../../shared/predicates.js";import{setModeBeneath as A}from"../spaces/open-beneath.js";import{LAUNCHER_SOCKET as M}from"../../launcher/spec.js";const Y="submit_result",Z="A .json file path, or inline JSON beginning with `{`.",tt='The full schema (including enum, pattern, and numeric bounds) is enforced when the target submits its result (its `submit_result` tool, or `crtr push result`); a mismatch rejects with the field errors and records nothing, so an over-constrained schema costs the target retries. A target that cannot honestly satisfy the schema declines (`submit_result` with `decline`, or `crtr push result --decline "<reason>" --code <token> [--retryable]`), which records a failure outcome with reason `declined` carrying the reason, code, and retryable flag instead of a value.';function m(t){return`${R(t)}/output-schema.json`}s(m,"outputSchemaPath");function _(t){return`${O(t)}/output-schema.json`}s(_,"brokerOutputSchemaPath");function U(){const t=a("/etc/group","utf8").split(`
2
- `).find(r=>r.startsWith("crtr-data:")),e=Number(t?.split(":")[2]);if(!Number.isInteger(e))throw new Error("crtr-data group is required on sandboxed Linux");return e}s(U,"dataGroupId");function k(t,e){process.platform!=="linux"||!l(M)||A(O(t),e,432,{uid:process.getuid(),gid:U()})}s(k,"shareRunFileWithBroker");function B(t){const e=m(t),r=_(t);l(e)&&(q(O(t),r,a(e),{atomic:!0}),k(t,r))}s(B,"projectOutputSchema");function $(t,e){return`${x(t,e)}/result.json`}s($,"outputResultPath");function et(t,e){const r=T(y(t,e),$(t,e));return r===null?void 0:JSON.parse(r)}s(et,"readOutputResult");function D(t,e,r,n){return r==="terminal"?$(t,n):`${x(t,n)}/structured-requests/${e}/result.json`}s(D,"structuredRequestResultPath");function w(t,e){return`${x(t,e)}/declined.json`}s(w,"outputDeclinedPath");function rt(t){const e=t?.trim();if(e===void 0||e==="")return null;let r,n;if(e.startsWith("{"))r=e,n="inline JSON";else{const o=j(e);n=o;try{r=a(o,"utf8")}catch(i){throw new N({error:"bad_output_schema",message:`could not read output schema from ${o}: ${i.message}`,field:"output-schema",next:"Pass a readable JSON Schema file path, or inline JSON beginning with `{`."})}}let u;try{u=JSON.parse(r)}catch(o){throw new N({error:"bad_output_schema",message:`output schema from ${n} is not valid JSON: ${o.message}`,field:"output-schema",next:"Pass valid JSON whose top-level value is an object."})}if(!c(u))throw new N({error:"bad_output_schema",message:`output schema from ${n} must be a JSON object`,field:"output-schema",next:"Pass a JSON Schema object, not an array, string, number, boolean, or null."});return u}s(rt,"parseOutputSchemaValue");function nt(t){if(t.node_id===null)throw new Error(`cannot publish structured request ${t.request_id} before node binding`);const e=t.node_id,r=m(e);d(g(r),{recursive:!0});const n={request_id:t.request_id,mode:t.submission,schema:t.schema,...t.request_message_id==null?{}:{requestMessageId:t.request_message_id}},u=`${r}.${b()}.tmp`;return h(u,`${JSON.stringify(n,null,2)}
3
- `,"utf8"),S(u,r),B(e),r}s(nt,"writeStructuredRequestSidecar");function C(t){return J(m(t))}s(C,"readOutputRequest");function st(t){return J(_(t))}s(st,"readBrokerOutputRequest");function J(t){if(!l(t))return{state:"absent"};let e;try{e=a(t,"utf8")}catch(p){return{state:"invalid",error:`could not read request file: ${p.message}`}}let r;try{r=JSON.parse(e)}catch(p){return{state:"invalid",error:`request file is not valid JSON: ${p.message}`}}if(!c(r))return{state:"invalid",error:"request file top-level value must be an object"};const n=r.request_id,u=r.mode,o=r.schema;if(typeof n!="string"||n==="")return{state:"invalid",error:"request_id must be a non-empty string"};if(u!=="terminal"&&u!=="oneoff")return{state:"invalid",error:`mode must be 'terminal' or 'oneoff', got ${JSON.stringify(u)}`};if(!c(o))return{state:"invalid",error:`schema must be an object, got ${typeof o}`};const i=r.requestMessageId;return i!==void 0&&typeof i!="string"?{state:"invalid",error:`requestMessageId must be a string, got ${typeof i}`}:{state:"valid",request:{request_id:n,mode:u,schema:o,...i===void 0?{}:{requestMessageId:i}}}}s(J,"readOutputRequestAt");function ut(t){try{const e=JSON.parse(a(m(t),"utf8"));if(!c(e)||Object.hasOwn(e,"request_id"))return null;const r=e.mode,n=e.schema,u=e.requestMessageId;return r!=="terminal"&&r!=="oneoff"||!c(n)?null:{mode:r,schema:n,...typeof u=="string"?{requestMessageId:u}:{}}}catch{return null}}s(ut,"readLegacyOutputRequest");async function ot(t,e){const{validateToolArguments:r}=await import("@earendil-works/pi-ai");return r({name:"submit",description:"",parameters:t},{type:"toolCall",id:"structured-output",name:"submit",arguments:e})}s(ot,"validateStructuredResult");function it(t,e,r){const n=y(t,r),u=$(t,r);q(n,u,`${JSON.stringify(e,null,2)}
4
- `,{atomic:!0});try{E(n,w(t,r))}catch(o){if(o.code!=="ENOENT")throw o}return u}s(it,"writeOutputResult");function at(t,e,r){const n=w(t,r);return q(y(t,r),n,`${JSON.stringify(e,null,2)}
5
- `,{atomic:!0}),n}s(at,"writeOutputDeclined");function v(t){return`${R(t)}/output-schema-reprompts.json`}s(v,"schemaRepromptsPath");function ct(t){try{const e=JSON.parse(a(v(t),"utf8"));if(c(e)&&Number.isSafeInteger(e.count)&&Number.isFinite(e.at))return{count:e.count,at:e.at}}catch{}return{count:0,at:0}}s(ct,"readSchemaReprompts");function mt(t,e){const r=v(t);d(g(r),{recursive:!0});const n=`${r}.${b()}.tmp`;h(n,JSON.stringify(e),"utf8"),S(n,r)}s(mt,"writeSchemaReprompts");function F(t){try{f(v(t))}catch{}}s(F,"clearSchemaReprompts");function pt(t,e){const r=m(t);if(e!==void 0){const u=C(t);if(u.state!=="valid"||u.request.request_id!==e)return}try{f(r)}catch{}F(t);const n=_(t);try{f(n)}catch{}}s(pt,"removeOutputSchema");function lt(t,e,r,n,u){const o=D(t,e,r,u);d(g(o),{recursive:!0});const i=`${o}.${b()}.tmp`;return h(i,`${JSON.stringify(n,null,2)}
6
- `,"utf8"),{path:o,tmpPath:i}}s(lt,"stageStructuredResult");function dt(t){return S(t.tmpPath,t.path),t.path}s(dt,"installStagedStructuredProjection");export{tt as OUTPUT_SCHEMA_CONSTRAINTS,Z as OUTPUT_SCHEMA_TRANSPORT,Y as SUBMIT_RESULT_TOOL,_ as brokerOutputSchemaPath,F as clearSchemaReprompts,dt as installStagedStructuredProjection,w as outputDeclinedPath,$ as outputResultPath,m as outputSchemaPath,rt as parseOutputSchemaValue,B as projectOutputSchema,st as readBrokerOutputRequest,ut as readLegacyOutputRequest,C as readOutputRequest,et as readOutputResult,ct as readSchemaReprompts,pt as removeOutputSchema,v as schemaRepromptsPath,k as shareRunFileWithBroker,lt as stageStructuredResult,D as structuredRequestResultPath,ot as validateStructuredResult,at as writeOutputDeclined,it as writeOutputResult,mt as writeSchemaReprompts,nt as writeStructuredRequestSidecar};
1
+ var j=Object.defineProperty;var o=(t,e)=>j(t,"name",{value:e,configurable:!0});import{existsSync as d,mkdirSync as f,readFileSync as a,unlinkSync as h,writeFileSync as S,renameSync as g}from"node:fs";import{dirname as b,resolve as T}from"node:path";import{randomUUID as x}from"node:crypto";import{nodeDir as R,nodeRunDir as O,contextDir as y,nodeAgentDir as $}from"../canvas/paths.js";import{readTextBeneathIfExists as E,unlinkBeneath as k,writeFileBeneath as q}from"../spaces/open-beneath.js";import{outputSchemaRefProblem as v}from"./output-schema-refs.js";import{InputError as l}from"../io.js";import{isRecord as c}from"../../shared/predicates.js";import{setModeBeneath as A}from"../spaces/open-beneath.js";import{LAUNCHER_SOCKET as B}from"../../launcher/spec.js";const et="submit_result",rt="A .json file path, or inline JSON beginning with `{`.",nt='The full schema (including enum, pattern, and numeric bounds) is enforced when the target submits its result (its `submit_result` tool, or `crtr push result`); a mismatch rejects with the field errors and records nothing, so an over-constrained schema costs the target retries. A target that cannot honestly satisfy the schema declines (`submit_result` with `decline`, or `crtr push result --decline "<reason>" --code <token> [--retryable]`), which records a failure outcome with reason `declined` carrying the reason, code, and retryable flag instead of a value.';function p(t){return`${R(t)}/output-schema.json`}o(p,"outputSchemaPath");function _(t){return`${O(t)}/output-schema.json`}o(_,"brokerOutputSchemaPath");function M(){const t=a("/etc/group","utf8").split(`
2
+ `).find(r=>r.startsWith("crtr-data:")),e=Number(t?.split(":")[2]);if(!Number.isInteger(e))throw new Error("crtr-data group is required on sandboxed Linux");return e}o(M,"dataGroupId");function U(t,e){process.platform!=="linux"||!d(B)||A(O(t),e,432,{uid:process.getuid(),gid:M()})}o(U,"shareRunFileWithBroker");function C(t){const e=p(t),r=_(t);d(e)&&(q(O(t),r,a(e),{atomic:!0}),U(t,r))}o(C,"projectOutputSchema");function w(t,e){return`${y(t,e)}/result.json`}o(w,"outputResultPath");function ot(t,e){const r=E($(t,e),w(t,e));return r===null?void 0:JSON.parse(r)}o(ot,"readOutputResult");function D(t,e,r,n){return r==="terminal"?w(t,n):`${y(t,n)}/structured-requests/${e}/result.json`}o(D,"structuredRequestResultPath");function P(t,e){return`${y(t,e)}/declined.json`}o(P,"outputDeclinedPath");function st(t){const e=t?.trim();if(e===void 0||e==="")return null;let r,n;if(e.startsWith("{"))r=e,n="inline JSON";else{const u=T(e);n=u;try{r=a(u,"utf8")}catch(i){throw new l({error:"bad_output_schema",message:`could not read output schema from ${u}: ${i.message}`,field:"output-schema",next:"Pass a readable JSON Schema file path, or inline JSON beginning with `{`."})}}let s;try{s=JSON.parse(r)}catch(u){throw new l({error:"bad_output_schema",message:`output schema from ${n} is not valid JSON: ${u.message}`,field:"output-schema",next:"Pass valid JSON whose top-level value is an object."})}if(!c(s))throw new l({error:"bad_output_schema",message:`output schema from ${n} must be a JSON object`,field:"output-schema",next:"Pass a JSON Schema object, not an array, string, number, boolean, or null."});return s}o(st,"parseOutputSchemaValue");function ut(t){if(t.node_id===null)throw new Error(`cannot publish structured request ${t.request_id} before node binding`);const e=t.node_id,r=p(e);f(b(r),{recursive:!0});const n={request_id:t.request_id,mode:t.submission,schema:t.schema,...t.request_message_id==null?{}:{requestMessageId:t.request_message_id}},s=`${r}.${x()}.tmp`;return S(s,`${JSON.stringify(n,null,2)}
3
+ `,"utf8"),g(s,r),C(e),r}o(ut,"writeStructuredRequestSidecar");function F(t){return J(p(t))}o(F,"readOutputRequest");function it(t){return J(_(t))}o(it,"readBrokerOutputRequest");function J(t){if(!d(t))return{state:"absent"};let e;try{e=a(t,"utf8")}catch(m){return{state:"invalid",error:`could not read request file: ${m.message}`}}let r;try{r=JSON.parse(e)}catch(m){return{state:"invalid",error:`request file is not valid JSON: ${m.message}`}}if(!c(r))return{state:"invalid",error:"request file top-level value must be an object"};const n=r.request_id,s=r.mode,u=r.schema;if(typeof n!="string"||n==="")return{state:"invalid",error:"request_id must be a non-empty string"};if(s!=="terminal"&&s!=="oneoff")return{state:"invalid",error:`mode must be 'terminal' or 'oneoff', got ${JSON.stringify(s)}`};if(!c(u))return{state:"invalid",error:`schema must be an object, got ${typeof u}`};const i=r.requestMessageId;return i!==void 0&&typeof i!="string"?{state:"invalid",error:`requestMessageId must be a string, got ${typeof i}`}:{state:"valid",request:{request_id:n,mode:s,schema:u,...i===void 0?{}:{requestMessageId:i}}}}o(J,"readOutputRequestAt");function at(t){try{const e=JSON.parse(a(p(t),"utf8"));if(!c(e)||Object.hasOwn(e,"request_id"))return null;const r=e.mode,n=e.schema,s=e.requestMessageId;return r!=="terminal"&&r!=="oneoff"||!c(n)?null:{mode:r,schema:n,...typeof s=="string"?{requestMessageId:s}:{}}}catch{return null}}o(at,"readLegacyOutputRequest");async function ct(t,e){const{Compile:r}=await import("typebox/compile"),n=r(t);if(n.Check(e))return e;const s=n.Errors(e).map(u=>` - ${(u.keyword==="required"?[...u.instancePath.split("/").filter(Boolean),String(u.params.requiredProperties?.[0]??"")].filter(Boolean).join("."):u.instancePath.split("/").filter(Boolean).join("."))||"root"}: ${u.message}`);throw new Error(`Validation failed:
4
+ ${s.join(`
5
+ `)||" - Unknown validation error"}`)}o(ct,"validateStructuredResult");async function L(t){const e=v(t);if(e!==null)return e;try{const{Compile:r}=await import("typebox/compile");r(t)}catch(r){return`the schema cannot be compiled: ${r.message}`}return null}o(L,"outputSchemaProblem");async function pt(t){const e=await L(t);if(e!==null)throw new l({error:"bad_output_schema",message:`output_schema is not usable: ${e}`,field:"output-schema",next:"Fix the schema (bundle referenced documents under $defs with their own $id) and send it again."})}o(pt,"assertOutputSchemaAccepted");function lt(t,e,r){const n=$(t,r),s=w(t,r);q(n,s,`${JSON.stringify(e,null,2)}
6
+ `,{atomic:!0});try{k(n,P(t,r))}catch(u){if(u.code!=="ENOENT")throw u}return s}o(lt,"writeOutputResult");function mt(t,e,r){const n=P(t,r);return q($(t,r),n,`${JSON.stringify(e,null,2)}
7
+ `,{atomic:!0}),n}o(mt,"writeOutputDeclined");function N(t){return`${R(t)}/output-schema-reprompts.json`}o(N,"schemaRepromptsPath");function dt(t){try{const e=JSON.parse(a(N(t),"utf8"));if(c(e)&&Number.isSafeInteger(e.count)&&Number.isFinite(e.at))return{count:e.count,at:e.at}}catch{}return{count:0,at:0}}o(dt,"readSchemaReprompts");function ft(t,e){const r=N(t);f(b(r),{recursive:!0});const n=`${r}.${x()}.tmp`;S(n,JSON.stringify(e),"utf8"),g(n,r)}o(ft,"writeSchemaReprompts");function I(t){try{h(N(t))}catch{}}o(I,"clearSchemaReprompts");function ht(t,e){const r=p(t);if(e!==void 0){const s=F(t);if(s.state!=="valid"||s.request.request_id!==e)return}try{h(r)}catch{}I(t);const n=_(t);try{h(n)}catch{}}o(ht,"removeOutputSchema");function St(t,e,r,n,s){const u=D(t,e,r,s);f(b(u),{recursive:!0});const i=`${u}.${x()}.tmp`;return S(i,`${JSON.stringify(n,null,2)}
8
+ `,"utf8"),{path:u,tmpPath:i}}o(St,"stageStructuredResult");function gt(t){return g(t.tmpPath,t.path),t.path}o(gt,"installStagedStructuredProjection");export{nt as OUTPUT_SCHEMA_CONSTRAINTS,rt as OUTPUT_SCHEMA_TRANSPORT,et as SUBMIT_RESULT_TOOL,pt as assertOutputSchemaAccepted,_ as brokerOutputSchemaPath,I as clearSchemaReprompts,gt as installStagedStructuredProjection,P as outputDeclinedPath,w as outputResultPath,p as outputSchemaPath,L as outputSchemaProblem,v as outputSchemaRefProblem,st as parseOutputSchemaValue,C as projectOutputSchema,it as readBrokerOutputRequest,at as readLegacyOutputRequest,F as readOutputRequest,ot as readOutputResult,dt as readSchemaReprompts,ht as removeOutputSchema,N as schemaRepromptsPath,U as shareRunFileWithBroker,St as stageStructuredResult,D as structuredRequestResultPath,ct as validateStructuredResult,mt as writeOutputDeclined,lt as writeOutputResult,ft as writeSchemaReprompts,ut as writeStructuredRequestSidecar};
@@ -1,2 +1,2 @@
1
- var de=Object.defineProperty;var u=(t,e)=>de(t,"name",{value:e,configurable:!0});import{randomBytes as ce}from"node:crypto";import{claimNodeMail as ue,acknowledgeNodeMail as le}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as fe}from"../../../core/feed/inbox.js";import{enqueueNodeMail as J,cancelPendingNodeMail as me}from"../../../core/feed/messages.js";import{reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as R}from"../../../core/runtime/model-swap.js";import{deliverLive as pe,interruptLive as ye}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as he}from"../../../core/profiles/manifest.js";import{getNode as A,withFreshTerminalGuard as be}from"../../../core/canvas/canvas.js";import{getById as D,nodeObject as F,ownerForGrantee as we}from"../../../core/graph/objects.js";import{recordActedOn as ge}from"../../../core/graph/edges.js";import{recordWatch as G}from"../../../core/graph/watches.js";import{publish as H}from"../../../core/graph/events.js";import{readerFor as V}from"../reader.js";import{canRead as ve}from"../../../core/graph/access.js";import{withCanvasWrite as _}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as K}from"../../../core/canvas/structured-requests.js";import{cancelCronsOnWake as Q}from"../../../core/canvas/crons.js";import{assertNotFinalized as M,assertFinalizedForReopen as _e,commitReopenResident as P}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as ke}from"../../structured-requests/sidecar.js";import{appendSituationalContext as E,formatSituationalProse as Se}from"../../../core/runtime/situational-context.js";import{formatDataCard as X}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as $e}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as Ne}from"../../park-pending.js";import{wantsExecution as je}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as qe}from"../../../core/runtime/revive.js";import{CrtrError as xe,notFound as C,usage as c}from"../../../core/errors.js";import{emitEvent as Ae}from"../../../core/events/emit.js";import{assertScope as Ce}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Oe}from"../../../api/index.js";import{describeObject as Re,stubOf as Fe}from"../../../core/peer/stubs.js";import{machineNameOf as Y}from"../../../core/peer/names.js";import{callerNode as Me,callerStub as Pe,forwardVerb as Z,relayError as ee,remoteStub as Ee,unknownError as te,withMachine as re}from"../../peer/forward.js";import{ownerOnly as Ie}from"../router.js";const Te=["critical","urgent","normal","deferred"];function ne(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`${e} must be an object { kind, facts?, body? }`);const i=t,n=i.kind;if(typeof n!="string"||n.trim()==="")throw c(`${e}.kind is required`);if(!n.includes(":"))throw c(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=i.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw c(`${e}.facts must be an object of string or number values`);const d={};for(const[f,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw c(`${e}.facts.${f} must be a string or number`);d[f]=m}r.facts=d}const s=i.body;if(s!==void 0){if(typeof s!="string")throw c(`${e}.body must be a string`);r.body=s}return r}u(ne,"parseCardRequest");function oe(t,e){try{return X(t.kind,t.facts??{},t.body??"")}catch(i){throw c(`${e}: ${i instanceof Error?i.message:String(i)}`)}}u(oe,"renderCard");function Be(t){if(typeof t!="object"||t===null)throw c("a message requires a JSON body { body, tier?, fresh? }");const e=t,i=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,s=e.output_schema,d=typeof i=="string"&&i.trim()!=="",f=typeof o=="string"&&o.trim()!=="",m=typeof s=="string"&&s.trim()!=="",S=e.situational_card,g=e.context_cards,h=S===void 0?void 0:ne(S,"situational_card");if(g!==void 0&&!Array.isArray(g))throw c("context_cards must be an array of { kind, facts?, body? }");const p=g?.map((k,N)=>ne(k,`context_cards[${N}]`));if(h!==void 0&&typeof o=="string"&&o!=="")throw c("situational_card and situational_context are mutually exclusive");const $=h!==void 0||p!==void 0&&p.length>0;if(!n&&!d&&!f&&!m&&!$)throw c("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw c("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Te.includes(r))throw c(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const l={body:typeof i=="string"?i:""};r!==void 0&&(l.tier=r),n&&(l.fresh=!0),e.reopen===!0&&(l.reopen=!0),typeof o=="string"&&(l.situational_context=o),h!==void 0&&(l.situational_card=h),p!==void 0&&(l.context_cards=p),typeof s=="string"&&(l.output_schema=s),typeof e.from=="string"&&(l.from=e.from);const b=e.delivery;if(b!==void 0&&b!=="interactive")throw c(`invalid delivery: ${String(b)} (expected interactive)`);if(b==="interactive"){if(n||l.situational_context!==void 0||l.output_schema!==void 0)throw c("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!d)throw c("interactive delivery requires a non-empty body");if(l.tier==="deferred")throw c("interactive delivery cannot be deferred");l.delivery="interactive"}return l}u(Be,"parseSendBody");function ze(t){try{return JSON.parse(t)}catch{throw c("output_schema must be a JSON schema string")}}u(ze,"parseSchema");function We(t){return t.split(`
2
- `)[0].slice(0,120)}u(We,"label");function ie(t,e){return e===null?"":X("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");function Je(t,e,i){if(i!==null&&i!=="human"&&D(t,i)?.type==="node"){const o=F(t,i);return{actor:o,senderNode:o}}if(i==="human")return{actor:we(t,"user:local"),senderNode:null};const n=V(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Je,"messageActor");function ae(t,e,i,n,r,o){const s=F(t,i),{actor:d,senderNode:f}=Je(t,e,n),m=r===null?{}:{pointer:r};ge(t,d,s),f!==null&&f.rowid!==s.rowid&&G(t,f,s,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),H(t,{event:"messaged",object:s,actor:d,attrs:{},...m}),f!==null&&H(t,{event:"sent",object:f,actor:f,attrs:{to:s.id},...m})}u(ae,"recordMessage");function Le(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Le,"deferredNoNaturalCycle");function Ue(t){if(!qe(t))throw new Oe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Ue,"assertRecoverableForFresh");function De(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof xe?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(De,"wakeFailure");async function Ge(t,e){const i=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof i=="object"&&i!==null&&delete i.from;const n=await Z(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:i});if(n.kind==="local")return null;if(n.kind==="unknown")throw te(e,n.unreachable);if(n.status>=400)throw ee(n.status,n.body);return _(r=>{const o=Me(r,t);if(o===null)return;const s=n.body?.object,d=Ee(r,e,"node",n.machine.id,s);G(r,o,d,"message",{endsOn:"final"})}),{status:n.status,body:re(n.body,n.machine)}}u(Ge,"forwardMessage");async function He(t){const e=await Ve(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const i=_(n=>{const r=F(n,t.params.id);return ve(n,V(n,t),r)?Re(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:i}}}u(He,"handleMessage");async function Ve(t){const e=t.params.id,i=await Ge(t,e);if(i!==null)return i;const n=A(e);if(n===null)throw C(`unknown node: ${e}`,{received:e});const r=Be(t.body),o=r.tier??"normal",s=he(n.profile_id),d=t.principal.class==="forwarded"?_(a=>Pe(a,t)?.id??null):r.from??null;if(d!==null){const a=A(d);a!==null&&Ce(a,"crtr:act")}const f=d===null?null:_(a=>{const y=D(a,d);return y===null?null:Fe(a,y)?.home_machine??null}),m=f===null?void 0:`${d} on ${Y(f)}`,S=f===null?{}:{from_machine:Y(f)},g=r.body.trim()!=="",h=r.situational_card!==void 0?oe(r.situational_card,"situational_card"):r.situational_context!==void 0?Se(r.situational_context.trim()):"",p=h!=="",$=(r.context_cards??[]).map((a,y)=>oe(a,`context_cards[${y}]`)),l=r.output_schema!==void 0&&r.output_schema.trim()!==""?ze(r.output_schema):null;let b=!1;const k=u(a=>{if(!(l===null||b)){if(K(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});ke(e,"oneoff",l,a),b=!0}},"ensureSchema");if(r.fresh){const a=r.reopen?_e(e):null;r.reopen||M(e),Ue(e),k(),p&&E(e,h),r.reopen&&P(e,a);const y=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:y.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&M(e);let N=!1,v="";if(r.delivery==="interactive"&&r.reopen&&(v=ie(e,P(e)),N=!0),r.delivery==="interactive"&&k(),r.delivery==="interactive"&&!s&&!n.run_id&&R(n))try{return p&&E(e,h),await pe(e,r.body,{cards:[...v===""?[]:[v],...p?[h]:[],...$],origin:d==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...d===null?{}:{from:d},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),_(y=>ae(y,t,e,d,null,!1)),Q(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(a){if(!(a instanceof U))throw a}const T=u(()=>{r.reopen||M(e);const a=ce(16).toString("hex"),y=u(x=>ae(x,t,e,d,a,l!==null),"withinEnqueue");k(a),p&&E(e,h),r.reopen&&!N&&(v=ie(e,P(e)));const O=[...v===""?[]:[v],...$],W=O.length>0?{cards:O}:{};if(g||l!==null){const x=g?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${K(e)?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return J(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:a,withinEnqueue:y,label:We(x),bodyJson:{body:x,...S,...p?{situational:!0}:{},...W}})}return J(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:a,withinEnqueue:y,label:p?"(ambient context updated)":"(context delivered)",bodyJson:{...p?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),w=u(()=>{if(o==="deferred"){const a=be(e,$e,T);if(a.kind==="missing")throw C(`unknown node: ${e}`,{received:e});if(a.kind==="terminal")throw Le(e,a.status);return a.result}return T()},"deliver")();w.urgency!=="deferred"&&_(()=>Ne(e));const j=A(e);if(j===null)throw C(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&Q(e);let B=!1,z=!1,q;if((r.reopen||j.lifecycle==="terminal"||!je(j))&&w.urgency!=="deferred"&&!s&&!R(j))try{const a=await L(e,{resume:!0,capacity:"freeze"});B=a.launch!==void 0,z=a.outcome==="frozen"}catch(a){q=De(a,w.messageId),Ae({level:"error",event:"message.wake_failed",node_id:e,error:a,fields:{message_id:w.messageId,error_code:q.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:B,...z?{not_revived_reason:"capacity_frozen"}:{},...q===void 0?{}:{wake_failed:q},delivered_at:w.createdAt,...w.urgency===o?{}:{delivered_tier:w.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(Ve,"handleMessageHere");async function Ke(t){const e=t.params.id,i=await Z(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(i.kind==="unknown")throw te(e,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw ee(i.status,i.body);return{status:i.status,body:re(i.body,i.machine)}}const n=A(e);if(n===null)throw C(`unknown node: ${e}`,{received:e});const r=me(e,{senderNodeId:"human",kind:"message"});let o=!1;if(R(n))try{o=await ye(e)!=="idle"}catch(d){if(!(d instanceof U))throw d}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(Ke,"handleInterrupt");function se(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw c("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw c("execution_id is required");return e}u(se,"mailBody");function Qe(t){const e=se(t),i=e.channel;if(i!=="wake"&&i!=="passive"&&i!=="deferred_run")throw c("channel must be wake, passive, or deferred_run");const n=ue(t.params.id,e.execution_id,i);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...fe(o),seq:o.message.seq}}))}}}u(Qe,"handleMailClaim");function Xe(t){const e=se(t);if(!Array.isArray(e.deliveries))throw c("deliveries must be an array");const i=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw c("each delivery must be an object");const s=o;if(typeof s.delivery_id!="string"||s.delivery_id==="")throw c("delivery_id is required");if(!Number.isSafeInteger(s.attempts)||s.attempts<1)throw c("attempts must be a positive integer");if(s.disposition!=="acknowledged"&&s.disposition!=="released")throw c("disposition must be acknowledged or released");return{delivery_id:s.delivery_id,attempts:s.attempts,disposition:s.disposition}}),n=le(t.params.id,e.execution_id,i.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(Xe,"handleMailAcknowledge");const Tt=Ie([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:Qe},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:Xe}]),Bt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:He},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:Ke}];export{Tt as brokerMailRoutes,He as handleMessage,Bt as messageRoutes};
1
+ var de=Object.defineProperty;var u=(t,e)=>de(t,"name",{value:e,configurable:!0});import{randomBytes as ce}from"node:crypto";import{claimNodeMail as ue,acknowledgeNodeMail as le}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as fe}from"../../../core/feed/inbox.js";import{enqueueNodeMail as J,cancelPendingNodeMail as me}from"../../../core/feed/messages.js";import{reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as R}from"../../../core/runtime/model-swap.js";import{deliverLive as pe,interruptLive as ye}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as he}from"../../../core/profiles/manifest.js";import{getNode as O,withFreshTerminalGuard as be}from"../../../core/canvas/canvas.js";import{getById as D,nodeObject as F,ownerForGrantee as we}from"../../../core/graph/objects.js";import{recordActedOn as ge}from"../../../core/graph/edges.js";import{recordWatch as G}from"../../../core/graph/watches.js";import{publish as H}from"../../../core/graph/events.js";import{readerFor as V}from"../reader.js";import{canRead as ve}from"../../../core/graph/access.js";import{withCanvasWrite as _}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as K}from"../../../core/canvas/structured-requests.js";import{cancelCronsOnWake as Q}from"../../../core/canvas/crons.js";import{assertNotFinalized as M,assertFinalizedForReopen as _e,commitReopenResident as P}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as ke}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Se}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as E,formatSituationalProse as $e}from"../../../core/runtime/situational-context.js";import{formatDataCard as X}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Ne}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as je}from"../../park-pending.js";import{wantsExecution as Ae}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as qe}from"../../../core/runtime/revive.js";import{CrtrError as Oe,notFound as x,usage as c}from"../../../core/errors.js";import{emitEvent as xe}from"../../../core/events/emit.js";import{assertScope as Ce}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Re}from"../../../api/index.js";import{describeObject as Fe,stubOf as Me}from"../../../core/peer/stubs.js";import{machineNameOf as Y}from"../../../core/peer/names.js";import{callerNode as Pe,callerStub as Ee,forwardVerb as Z,relayError as ee,remoteStub as Ie,unknownError as te,withMachine as re}from"../../peer/forward.js";import{ownerOnly as Te}from"../router.js";const Be=["critical","urgent","normal","deferred"];function ne(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`${e} must be an object { kind, facts?, body? }`);const i=t,n=i.kind;if(typeof n!="string"||n.trim()==="")throw c(`${e}.kind is required`);if(!n.includes(":"))throw c(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=i.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw c(`${e}.facts must be an object of string or number values`);const d={};for(const[f,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw c(`${e}.facts.${f} must be a string or number`);d[f]=m}r.facts=d}const s=i.body;if(s!==void 0){if(typeof s!="string")throw c(`${e}.body must be a string`);r.body=s}return r}u(ne,"parseCardRequest");function oe(t,e){try{return X(t.kind,t.facts??{},t.body??"")}catch(i){throw c(`${e}: ${i instanceof Error?i.message:String(i)}`)}}u(oe,"renderCard");function ze(t){if(typeof t!="object"||t===null)throw c("a message requires a JSON body { body, tier?, fresh? }");const e=t,i=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,s=e.output_schema,d=typeof i=="string"&&i.trim()!=="",f=typeof o=="string"&&o.trim()!=="",m=typeof s=="string"&&s.trim()!=="",S=e.situational_card,g=e.context_cards,h=S===void 0?void 0:ne(S,"situational_card");if(g!==void 0&&!Array.isArray(g))throw c("context_cards must be an array of { kind, facts?, body? }");const p=g?.map((k,N)=>ne(k,`context_cards[${N}]`));if(h!==void 0&&typeof o=="string"&&o!=="")throw c("situational_card and situational_context are mutually exclusive");const $=h!==void 0||p!==void 0&&p.length>0;if(!n&&!d&&!f&&!m&&!$)throw c("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw c("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Be.includes(r))throw c(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const l={body:typeof i=="string"?i:""};r!==void 0&&(l.tier=r),n&&(l.fresh=!0),e.reopen===!0&&(l.reopen=!0),typeof o=="string"&&(l.situational_context=o),h!==void 0&&(l.situational_card=h),p!==void 0&&(l.context_cards=p),typeof s=="string"&&(l.output_schema=s),typeof e.from=="string"&&(l.from=e.from);const b=e.delivery;if(b!==void 0&&b!=="interactive")throw c(`invalid delivery: ${String(b)} (expected interactive)`);if(b==="interactive"){if(n||l.situational_context!==void 0||l.output_schema!==void 0)throw c("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!d)throw c("interactive delivery requires a non-empty body");if(l.tier==="deferred")throw c("interactive delivery cannot be deferred");l.delivery="interactive"}return l}u(ze,"parseSendBody");function We(t){let e;try{e=JSON.parse(t)}catch{throw c("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw c("output_schema must be a JSON schema object");return e}u(We,"parseSchema");function Je(t){return t.split(`
2
+ `)[0].slice(0,120)}u(Je,"label");function ie(t,e){return e===null?"":X("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");function Le(t,e,i){if(i!==null&&i!=="human"&&D(t,i)?.type==="node"){const o=F(t,i);return{actor:o,senderNode:o}}if(i==="human")return{actor:we(t,"user:local"),senderNode:null};const n=V(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Le,"messageActor");function ae(t,e,i,n,r,o){const s=F(t,i),{actor:d,senderNode:f}=Le(t,e,n),m=r===null?{}:{pointer:r};ge(t,d,s),f!==null&&f.rowid!==s.rowid&&G(t,f,s,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),H(t,{event:"messaged",object:s,actor:d,attrs:{},...m}),f!==null&&H(t,{event:"sent",object:f,actor:f,attrs:{to:s.id},...m})}u(ae,"recordMessage");function Ue(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ue,"deferredNoNaturalCycle");function De(t){if(!qe(t))throw new Re(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(De,"assertRecoverableForFresh");function Ge(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Oe?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Ge,"wakeFailure");async function He(t,e){const i=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof i=="object"&&i!==null&&delete i.from;const n=await Z(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:i});if(n.kind==="local")return null;if(n.kind==="unknown")throw te(e,n.unreachable);if(n.status>=400)throw ee(n.status,n.body);return _(r=>{const o=Pe(r,t);if(o===null)return;const s=n.body?.object,d=Ie(r,e,"node",n.machine.id,s);G(r,o,d,"message",{endsOn:"final"})}),{status:n.status,body:re(n.body,n.machine)}}u(He,"forwardMessage");async function Ve(t){const e=await Ke(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const i=_(n=>{const r=F(n,t.params.id);return ve(n,V(n,t),r)?Fe(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:i}}}u(Ve,"handleMessage");async function Ke(t){const e=t.params.id,i=await He(t,e);if(i!==null)return i;const n=O(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=ze(t.body),o=r.tier??"normal",s=he(n.profile_id),d=t.principal.class==="forwarded"?_(a=>Ee(a,t)?.id??null):r.from??null;if(d!==null){const a=O(d);a!==null&&Ce(a,"crtr:act")}const f=d===null?null:_(a=>{const y=D(a,d);return y===null?null:Me(a,y)?.home_machine??null}),m=f===null?void 0:`${d} on ${Y(f)}`,S=f===null?{}:{from_machine:Y(f)},g=r.body.trim()!=="",h=r.situational_card!==void 0?oe(r.situational_card,"situational_card"):r.situational_context!==void 0?$e(r.situational_context.trim()):"",p=h!=="",$=(r.context_cards??[]).map((a,y)=>oe(a,`context_cards[${y}]`)),l=r.output_schema!==void 0&&r.output_schema.trim()!==""?We(r.output_schema):null;l!==null&&await Se(l);let b=!1;const k=u(a=>{if(!(l===null||b)){if(K(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});ke(e,"oneoff",l,a),b=!0}},"ensureSchema");if(r.fresh){const a=r.reopen?_e(e):null;r.reopen||M(e),De(e),k(),p&&E(e,h),r.reopen&&P(e,a);const y=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:y.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&M(e);let N=!1,v="";if(r.delivery==="interactive"&&r.reopen&&(v=ie(e,P(e)),N=!0),r.delivery==="interactive"&&k(),r.delivery==="interactive"&&!s&&!n.run_id&&R(n))try{return p&&E(e,h),await pe(e,r.body,{cards:[...v===""?[]:[v],...p?[h]:[],...$],origin:d==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...d===null?{}:{from:d},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),_(y=>ae(y,t,e,d,null,!1)),Q(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(a){if(!(a instanceof U))throw a}const T=u(()=>{r.reopen||M(e);const a=ce(16).toString("hex"),y=u(q=>ae(q,t,e,d,a,l!==null),"withinEnqueue");k(a),p&&E(e,h),r.reopen&&!N&&(v=ie(e,P(e)));const C=[...v===""?[]:[v],...$],W=C.length>0?{cards:C}:{};if(g||l!==null){const q=g?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${K(e)?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return J(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:a,withinEnqueue:y,label:Je(q),bodyJson:{body:q,...S,...p?{situational:!0}:{},...W}})}return J(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:a,withinEnqueue:y,label:p?"(ambient context updated)":"(context delivered)",bodyJson:{...p?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),w=u(()=>{if(o==="deferred"){const a=be(e,Ne,T);if(a.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(a.kind==="terminal")throw Ue(e,a.status);return a.result}return T()},"deliver")();w.urgency!=="deferred"&&_(()=>je(e));const j=O(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&Q(e);let B=!1,z=!1,A;if((r.reopen||j.lifecycle==="terminal"||!Ae(j))&&w.urgency!=="deferred"&&!s&&!R(j))try{const a=await L(e,{resume:!0,capacity:"freeze"});B=a.launch!==void 0,z=a.outcome==="frozen"}catch(a){A=Ge(a,w.messageId),xe({level:"error",event:"message.wake_failed",node_id:e,error:a,fields:{message_id:w.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:B,...z?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:w.createdAt,...w.urgency===o?{}:{delivered_tier:w.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(Ke,"handleMessageHere");async function Qe(t){const e=t.params.id,i=await Z(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(i.kind==="unknown")throw te(e,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw ee(i.status,i.body);return{status:i.status,body:re(i.body,i.machine)}}const n=O(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=me(e,{senderNodeId:"human",kind:"message"});let o=!1;if(R(n))try{o=await ye(e)!=="idle"}catch(d){if(!(d instanceof U))throw d}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(Qe,"handleInterrupt");function se(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw c("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw c("execution_id is required");return e}u(se,"mailBody");function Xe(t){const e=se(t),i=e.channel;if(i!=="wake"&&i!=="passive"&&i!=="deferred_run")throw c("channel must be wake, passive, or deferred_run");const n=ue(t.params.id,e.execution_id,i);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...fe(o),seq:o.message.seq}}))}}}u(Xe,"handleMailClaim");function Ye(t){const e=se(t);if(!Array.isArray(e.deliveries))throw c("deliveries must be an array");const i=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw c("each delivery must be an object");const s=o;if(typeof s.delivery_id!="string"||s.delivery_id==="")throw c("delivery_id is required");if(!Number.isSafeInteger(s.attempts)||s.attempts<1)throw c("attempts must be a positive integer");if(s.disposition!=="acknowledged"&&s.disposition!=="released")throw c("disposition must be acknowledged or released");return{delivery_id:s.delivery_id,attempts:s.attempts,disposition:s.disposition}}),n=le(t.params.id,e.execution_id,i.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(Ye,"handleMailAcknowledge");const zt=Te([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:Xe},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:Ye}]),Wt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ve},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:Qe}];export{zt as brokerMailRoutes,Ve as handleMessage,Wt as messageRoutes};
@@ -1 +1 @@
1
- var Se=Object.defineProperty;var a=(e,t)=>Se(e,"name",{value:t,configurable:!0});import{prepared as X}from"../../../core/sqlite-statements.js";import{envProfileId as Re}from"../../../shared/env.js";import{pausedCanvasProfiles as Oe}from"../../../core/profiles/manifest.js";import{existsSync as A,realpathSync as Z,statSync as q}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as Ie,formatSituationalProse as $e}from"../../../core/runtime/situational-context.js";import{closeNode as Ce}from"../../../core/runtime/close.js";import{reviveNode as Ne}from"../../../core/runtime/revive.js";import{nowIso as G}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as B,forkNode as Ae,resolveForkSource as Te,spawnChildPrepared as Ee}from"../../../core/runtime/spawn.js";import{forkSourceNode as Pe,newNodeId as ee}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ne,childrenOf as De,completeCreateRequest as te,findCreateRequest as Le,getNode as k,recordCreateRequestNode as Me,reserveCreateRequest as oe,reserveCreateRequestNode as je,listNodes as re,recordRespawnAttempt as Fe,subscribersOf as Ge,subscriptionsOf as ie,setMessageWait as Be,updateNode as N}from"../../../core/canvas/canvas.js";import{subtreeIds as Ke}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{nodeObject as xe}from"../../../core/graph/objects.js";import{recordActedOn as We}from"../../../core/graph/edges.js";import{publish as Ve}from"../../../core/graph/events.js";import{readerFor as ze}from"../reader.js";import{relocateSessionCwd as Je,unbindSession as Ue}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as He}from"../../../core/canvas/attention.js";import{isSafeNodeId as Ye}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as Qe}from"../../cron/authority.js";import{cronBirthPlacement as Xe}from"../../cron/armed-context.js";import{existsBeneath as Ze,isAbsentOrRefused as qe,isBeneathRefusal as en,readdirBeneath as nn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as tn,readNodeSession as on,readNodeSnapshot as rn,transcriptMarkdown as dn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as sn}from"../../../core/substrate/subject.js";import{reviveAll as an}from"../../../core/runtime/revive-all.js";import{promoteAsync as ln,requestYieldAsync as cn,reshapeNodeAsync as W}from"../../../core/runtime/promote.js";import{recycleNode as fn}from"../../../core/runtime/recycle.js";import{relaunchRoot as un}from"../../../core/runtime/reset.js";import{assertReopenGate as pn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as mn,readGoal as hn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as wn,hasRoadmap as yn}from"../../../core/runtime/roadmap.js";import{renameWindow as _n}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as gn,explicitModelIntent as bn,normalizeModel as vn,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as kn}from"../../../core/model-routes.js";import{persistDormantModel as Sn,setModelLive as Rn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as On}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as In}from"../../../core/runtime/broker-request.js";import{boundFleet as V}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as $n}from"../../structured-requests/sidecar.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ae}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Cn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Nn}from"../../../core/human-actions.js";import{parseDurationMs as An}from"../../../core/wake.js";import{claimWarmNode as Tn,refillWarmPool as le,resumeWarmClaim as En,warmPoolEnabled as Pn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Dn,resolveLaunchTarget as Ln}from"../../../core/runtime/launch-target.js";import{fullName as Mn}from"../../../core/canvas/labels.js";import{reportsForNode as ce}from"./reports.js";import{requireUsableProfile as jn}from"./profiles.js";import{assertProfileActive as Fn,loadExactProfileManifest as Gn}from"../../../core/profiles/manifest.js";import{getCron as fe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Bn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Kn}from"../../control.js";import{notFound as E,usage as h}from"../../../core/errors.js";import{assertScope as xn,validateScopes as ue}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Wn,toNodeDetailDTO as J,toNodeSummaryDTO as Vn,toReviveResultDTO as zn}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{brokerMayReach as U,canReadNode as pe,resolvedScopes as Jn}from"../router.js";import{forwardVerb as Un,queryWithoutMachine as Hn,relayError as Yn,unknownError as Qn,withMachine as Xn}from"../../peer/forward.js";import{fileRoot as Zn}from"../../../core/spaces/file-root.js";import{activeGrant as qn,terminalGrant as et}from"../../../core/grants/mirror.js";import{readConfig as nt}from"../../../core/config.js";import{hasConfiguredProviderCredential as tt,NO_PROVIDER_CREDENTIAL_MESSAGE as me}from"../../../core/runtime/provider-credential-gate.js";function y(e){const t=k(e);if(t===null)throw E(`unknown node: ${e}`,{received:e});return t}a(y,"requireMeta");function H(e){return{subscribesTo:ie(e),subscribers:Ge(e),children:De(e)}}a(H,"edgesFor");function g(e){const t=y(e);return J(t,H(e))}a(g,"detailOf");function ot(e){let t=ce(e).length;try{t+=nn(x(e),de(e)).length}catch(n){if(!qe(n))throw n}return t}a(ot,"countFiles");function rt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&ue(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new m(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(rt,"parseCreateBody");function it(e){if(e===void 0)return;const t=An(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(it,"parseDeadline");function dt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Cn.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ae)throw new m(413,"payload_too_large",`serialized payload exceeds ${ae} bytes`)}return e}}a(dt,"parseOutcomeDelivery");function st(e,t){const n=Nn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new m(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(st,"resolveOutcomeDelivery");function at(e,t,n){const r={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),t!==void 0&&(r.parent=t),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=T(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}a(at,"buildRecipe");function lt(e,t,n){return!Pn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(lt,"warmRequestFor");import{resolveCreateKind as tr}from"../../../core/runtime/launch-target.js";function he(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return kn(e.model,t,e.modelExact===!0)}a(he,"requestFromLaunch");function ct(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!O(t,r));if(n.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(ct,"withinCeiling");async function we(e,t,n){const r=(await gn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await B(he(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(we,"assertNodeModelChangeRegistered");function ye(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=Zn({app:n.app,resolved:Jn(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new m(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ye,"assertCallerReaches");const Y=new Map;async function ft(e,t={},n={}){const r=ct(rt(e.body),e.ceiling);if(e.principal.class==="broker"){const l=e.principal;if(r.prefer_warm===!0&&l.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=y(r.parent);if(i.grantee!==l.app)throw new m(403,"other_app_run","cannot create a child under another app's node");if(!U(l,r.parent,i.grantee??"app:terminal"))throw E(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==l.node)throw new m(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Pe(Te(r.fork_from))}catch{}if(i?.grantee!==l.app||!U(l,i.node_id,i.grantee))throw new m(403,"other_app_run","cannot fork another app's conversation")}r.creator=l.node}if(e.principal.class==="cron"){const l=e.principal;for(const c of["parent","creator","fork_from","node_id"])if(r[c]!=null)throw new m(403,"permission_error",`a cron cannot set ${c} on a node it starts`);r.prefer_warm=!1;const i=Qe({grantee:l.app,sub:l.sub,grant_id:l.grant,scopes:l.scopes});if(!i.allowed)throw new m(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const c=r.scopes.find(p=>!O(i.effectiveScopes,p)||!O(l.scopes,p));if(c!==void 0)throw new m(403,"scope_missing",`scope ${c} is not held by this cron`,void 0,void 0,{scope:c})}else l.scopes!==null&&(r.scopes=[...l.scopes]);r.node_id=ee(),l.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,l.app))}r.creator!==void 0&&xn(y(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&Ye(r.node_id)&&k(r.node_id)!==null&&Le(o)?.nodeId!==r.node_id)return P(e,r,t,n);const d=Y.get(o);if(d!==void 0)return d;const s=ut(e,r,o,t,n);Y.set(o,s);try{return await s}finally{Y.delete(o)}}a(ft,"handleCreate");async function ut(e,t,n,r,o){const d=oe(n);if(d.nodeId!==null&&k(d.nodeId)!==null){if(d.state!=="warm_claimed"){const s=k(d.nodeId);if(e.principal.class!=="person"&&!pe(e.principal,s.grantee??"app:terminal",d.nodeId))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(d.nodeId)}}return P(e,t,r,o,d)}try{return await P(e,t,r,o,d)}catch(s){const l=oe(n);throw(l.nodeId===null||k(l.nodeId)===null)&&ne(n,l.nodeId),s}}a(ut,"handleKeyedCreateRequest");async function P(e,t,n,r,o=void 0){const d=r.deadlineAt??it(t.deadline),s=dt(t.outcome_delivery),l=e.principal.class==="cron"?Xe({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:fe(e.principal.cron)?.created_by??null},t.node_id):null;l!==null&&(t.root=l.root===!0);const i=l?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let c=null;if(t.output_schema!==void 0)try{c=JSON.parse(t.output_schema)}catch{throw h("output_schema must be a JSON schema string")}const{profileId:p,kind:u,cwd:f,launch:_}=await Ln(t,{validateKind:ke});ye(e,f),t.worktree!==void 0&&ye(e,T(t.pin_cwd??t.cwd??f));const S={...t,kind:u},I=s===void 0?void 0:st(s,f);if(await B(he(_),{cwd:f,profileId:p},n.modelRegistry),!await tt(p))throw new m(412,"no_provider_credential",me,{error:"no_provider_credential",message:me,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let L=null;{const $=o===void 0||o.nodeId===null||o.state==="warm_claimed"?lt(S,f,p):null,M=c===null&&r.beforeBrokerLaunch===void 0?void 0:v=>{c!==null&&$n(v,"terminal",c),r.beforeBrokerLaunch?.(v)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const v=$===null?null:await En($,o.nodeId,M);if(v===null)throw ne(o.requestKey,o.nodeId),new m(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return te(o.requestKey,v),{status:201,body:g(v)}}if($!==null){const v=await Tn($,{...d===void 0?{}:{deadlineAt:d},...I===void 0?{}:{outcomeDelivery:I},...o===void 0?{}:{requestKey:o.requestKey}},M);if(v!==null)return o!==void 0&&te(o.requestKey,v),le($),{status:201,body:g(v)};L=$}const j=o?.nodeId??t.node_id??(o===void 0?void 0:ee());o!==void 0&&o.nodeId===null&&je(o.requestKey,j);const R=at(j===void 0?S:{...S,node_id:j},i,f);l!==null&&(l.rootLifecycle!==void 0&&(R.rootLifecycle=l.rootLifecycle),l.scopes!==void 0&&S.scopes===void 0&&(R.scopes=l.scopes),l.run!==void 0&&(R.run=l.run),l.withinCreate!==void 0&&(R.withinCreate=l.withinCreate)),d!==void 0&&(R.deadlineAt=d),I!==void 0&&(R.outcomeDelivery=I),R.readiness=t.root===!0?"await":"launch";const Q=await Ee(R,M,()=>{L!==null&&le(L)});return o!==void 0&&Me(o.requestKey,Q.node.node_id),{status:201,body:g(Q.node.node_id)}}}a(P,"handleCreateRequest");function b(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(b,"singleQueryValue");function _e(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(_e,"optionalBoolean");function D(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(D,"oneOf");function pt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[_]of e.query)if(!t.has(_))throw h(`unknown nodes query parameter: ${_}`);const n=D(b(e,"status"),"status",["active","idle","done","dead","canceled"]),r=D(b(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=b(e,"kind"),d=D(b(e,"mode"),"mode",["base","orchestrator"]),s=b(e,"profile_id"),l=b(e,"profile_prefix"),i=b(e,"parent"),c=_e(b(e,"top_level"),"top_level"),p=b(e,"under"),u=_e(b(e,"hanging"),"hanging"),f=D(b(e,"include"),"include",["activity"]);if(i!==void 0&&c===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...d!==void 0?{mode:d}:{},...s!==void 0?{profile_id:s}:{},...l!==void 0?{profile_prefix:l}:{},...i!==void 0?{parent:i}:{},...c!==void 0?{top_level:c}:{},...p!==void 0?{under:p}:{},...u!==void 0?{hanging:u}:{},...f!==void 0?{include:f}:{}}}a(pt,"parseListQuery");function mt(e){const t=pt(e);let n=t.status!==void 0?re({status:t.status}):re();if(e.principal.class!=="person"&&(n=n.filter(s=>pe(e.principal,s.grantee??"app:terminal",s.node_id))),t.lifecycle!==void 0&&(n=n.filter(s=>s.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(s=>s.kind===t.kind)),t.mode!==void 0&&(n=n.filter(s=>s.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(s=>s.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(s=>s.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(s=>s.parent===t.parent)),t.top_level===!0&&(n=n.filter(s=>s.parent===null)),t.under!==void 0){const s=new Set(Ke(t.under));n=n.filter(l=>s.has(l.node_id))}t.hanging===!0&&(n=n.filter(s=>s.parent!==null&&k(s.parent)===null));const r=t.include==="activity"?He(n.map(s=>s.node_id)):null,o=n.length>0?Oe():new Set;return{status:200,body:n.map(s=>{const l=Vn(s,s.profile_id!==null&&o.has(s.profile_id));if(r!==null){const i=ce(s.node_id);l.activity={latest_report:i[0]??null,final_report:s.final_report===null?null:i.find(c=>c.name===s.final_report)??null,pending_human_count:r[s.node_id]??0}}return l})}}a(mt,"handleList");async function ht(e){const t=e.params.id,n=await Un(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:Hn(e)});if(n.kind==="unknown")throw Qn(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw Yn(n.status,n.body);return{status:n.status,body:Xn(n.body,n.machine)}}return y(t),{status:200,body:g(t)}}a(ht,"handleDetail");async function wt(e){const t=e.params.id;y(t);const n=await rn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:G()}}}a(wt,"handleSnapshot");async function yt(e){const t=e.params.id,n=sn(t);if(n===null)throw E(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(yt,"handleSubject");function _t(e){for(const[d]of e.query)if(d!=="cursor"&&d!=="limit")throw h(`unknown messages query parameter: ${d}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(_t,"parseMessagesQuery");async function gt(e){const t=e.params.id,n=await tn(t,_t(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:G()}}}a(gt,"handleMessages");function bt(e){const t=e.params.id;y(t);const n=on(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:G()}}}a(bt,"handleSession");async function vt(e){const t=e.params.id;return y(t),{status:200,body:{node_id:t,markdown:await dn(t)}}}a(vt,"handleTranscript");function kt(e){const t=e.params.id;y(t);const n=a((o,d)=>({node_id:o,label:k(o)?.name??o,dir:de(o),self:d,files:ot(o)}),"root"),r=[n(t,!0),...ie(t).map(o=>n(o.node_id,!1))].filter(o=>St(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(kt,"handleContext");function St(e,t){try{return Ze(x(e),t)}catch(n){if(en(n))return!1;throw n}}a(St,"hasDir");async function Rt(e){const t=y(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(d=>O(n,d)),...n.filter(d=>O(t.scopes,d))])],o=await Ae(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Rt,"handleFork");async function Ot(e){const t=e.params.id;y(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;pn(t,o);const d=!r&&n?.cron_id!==void 0?fe(n.cron_id):null,s=await Ne(t,{resume:r,capacity:"refuse",...d!==null?{wakeReason:Bn(d,"schedule_revive")}:{}});s.outcome!=="already-live"&&Fe(t,{failures:0,notBefore:null});const l=k(t)?.status??"active";return{status:200,body:zn(t,s,l)}}a(Ot,"handleRevive");async function It(e){const t=e.params.id;return{status:200,body:{newNodeId:(await un(t))?.newNodeId??null}}}a(It,"handleRelaunchRoot");function $t(e){const t=e.params.id;y(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Kn(),o=Ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Wn(o)}}a($t,"handleClose");async function Ct(e){const t=e.params.id;y(t);const n=await fn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Ct,"handleRecycle");async function Nt(e){const t=e.params.id;return y(t),await W(t,{lifecycle:"terminal"}),C(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Nt,"handleDemote");async function At(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const d=await ln(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});C(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const s=J(d.meta,H(n));return s.roadmap_written=d.roadmapWritten,s.roadmap_ref=d.roadmapRef,s.goal_path=d.goalPath,{status:200,body:s}}a(At,"handlePromote");async function Tt(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const d=o.note??"Refresh: continue against your roadmap or goal.";mn(n,d);const s=await cn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(s.meta,H(n))}}a(Tt,"handleYield");function Et(e){const t=e.params.id;y(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=k(n.controller);if(r===null)throw E(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new m(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return Be(t,n.controller),{status:200,body:g(t)}}a(Et,"handleWait");async function Pt(e){const t=e.principal,n=await an(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(Pt,"handleReviveAll");const Dt=new Set(["interrupt","steer","after-turn","next-turn"]);function Lt(e){if(e===null)return null;const t=a(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!Dt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(Lt,"listenJson");function C(e,t,n,r){n.length===0&&r===void 0||K(o=>{if(r?.(o),n.length===0)return;const d=xe(o,t),s=ze(o,e),l=s.class==="person"?s.person:s.class==="app"?s.app:s.node;We(o,l,d),Ve(o,{event:"configured",object:d,actor:l,attrs:{changed:n.join(",")}})})}a(C,"recordConfigured");function ge(e){const t=V().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ge,"restartLiveBroker");function be(e,t){try{return Z(e)===Z(t)}catch{return!1}}a(be,"sameDirectory");async function Mt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(u=>u!=="profile"&&u!=="restart"&&o[u]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const i=y(n),c=jn(e,o.profile);Fn(c.profileId);const p=Gn(c.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${c.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==c.profileId&&(Dn(i.kind)?(await z(i.kind,i.cwd,c.profileId),await W(n,{profileId:c.profileId})):N(n,{profile_id:c.profileId}),C(e,n,["profile"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const c=y(n),p=A(c.cwd);if(o.keep_session===!0||p&&F(i)&&A(i)&&be(c.cwd,i)){if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let _=!1;try{_=q(f).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!be(c.cwd,f))throw new w({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${c.cwd}; --keep-session only relocates an alias`,received:i,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(c.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const S=c.cwd;return S!==f&&(K(I=>{N(n,{cwd:f}),X(I,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,S),Je(n,S,f)}),C(e,n,["cwd"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(V().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(c.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${n} is a fork and cannot repair its cwd; recorded cwd: ${c.cwd}`,received:i,field:"cwd",next:`Restore ${c.cwd}, then revive the fork normally.`});if(c.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(A(c.cwd))throw new w({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${c.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const u=T(i);if(!A(u))throw new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!q(u).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${u}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof w?f:new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return K(()=>{N(n,{cwd:u}),Ue(n)}),C(e,n,["cwd"]),{status:200,body:g(n)}}let d=y(n);const s=o.listen===void 0?void 0:Lt(o.listen);if(o.scopes!==void 0){const i=ue(o.scopes),c=d.grantee==="app:terminal"?et():d.grant_id?qn(d.grant_id):null,p=d.grantee==="app:terminal"&&!nt("user").runtime?.issuer;if(!i.every(u=>O(d.scopes,u)&&(c?O(c.resolved,u):p)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!O(i,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");d=N(n,{scopes:i})}if(o.situational_context!==void 0&&Ie(n,$e(o.situational_context)),o.model!==void 0){const i=(await se(d.cwd,d.profile_id??null)).modelLadders,c=bn(o.model,i),p=vn(o.model,i);await B({kind:"concrete",spec:p},{cwd:d.cwd,profileId:d.profile_id??null},t.modelRegistry);const u=V();let f=!1;if(u.isClaimed(n)&&await On(n,u.get(n)?.handle.exited)&&(f=await Rn(n,p,c).then(()=>!0,_=>{if(_ instanceof In)return!1;throw _})),!f){if(u.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!p.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);Sn(n,p,c)}d=y(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await ke(o.kind);const i=o.kind??d.kind,c=o.mode??d.mode,p=o.lifecycle??d.lifecycle;let u;c==="orchestrator"&&!yn(n)&&(u=a(()=>{const f=hn(n);wn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),d=await W(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:c}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},u)}o.name!==void 0&&(d=N(n,{name:o.name}),d.window&&_n(d.window,Mn(d)));const l=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return C(e,n,l,s===void 0?void 0:i=>{X(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(s,n)}),{status:200,body:g(n)}}a(Mt,"handleConfig");async function ve(){return(await se(process.cwd(),Re()||null)).kinds}a(ve,"daemonKinds");async function ke(e){const t=Object.keys(await ve());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(ke,"assertKindServer");async function jt(){const e=await ve();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(jt,"handleListKinds");const qo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ft},{method:"GET",pattern:"/v1/nodes",handler:mt},{method:"GET",pattern:"/v1/kinds",handler:a(()=>jt(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Pt},{method:"GET",pattern:"/v1/nodes/:id",handler:ht},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:wt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:gt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:bt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:vt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:kt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Rt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Ot},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:It},{method:"POST",pattern:"/v1/nodes/:id/close",handler:$t},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ct},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:At},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Et},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mt}];export{Mt as handleConfig,ft as handleCreate,Rt as handleFork,mt as handleList,At as handlePromote,Tt as handleYield,qo as nodeRoutes,tr as resolveCreateKind};
1
+ var Se=Object.defineProperty;var a=(e,t)=>Se(e,"name",{value:t,configurable:!0});import{prepared as X}from"../../../core/sqlite-statements.js";import{envProfileId as Re}from"../../../shared/env.js";import{pausedCanvasProfiles as Oe}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as Z,statSync as q}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as Ie,formatSituationalProse as $e}from"../../../core/runtime/situational-context.js";import{closeNode as Ce}from"../../../core/runtime/close.js";import{reviveNode as Ae}from"../../../core/runtime/revive.js";import{nowIso as G}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as B,forkNode as Ne,resolveForkSource as Te,spawnChildPrepared as Ee}from"../../../core/runtime/spawn.js";import{forkSourceNode as Pe,newNodeId as ee}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ne,childrenOf as De,completeCreateRequest as te,findCreateRequest as je,getNode as k,recordCreateRequestNode as Le,reserveCreateRequest as oe,reserveCreateRequestNode as Me,listNodes as re,recordRespawnAttempt as Fe,subscribersOf as Ge,subscriptionsOf as ie,setMessageWait as Be,updateNode as A}from"../../../core/canvas/canvas.js";import{subtreeIds as Ke}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{nodeObject as xe}from"../../../core/graph/objects.js";import{recordActedOn as We}from"../../../core/graph/edges.js";import{publish as Ve}from"../../../core/graph/events.js";import{readerFor as Je}from"../reader.js";import{relocateSessionCwd as ze,unbindSession as Ue}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as He}from"../../../core/canvas/attention.js";import{isSafeNodeId as Ye}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as Qe}from"../../cron/authority.js";import{cronBirthPlacement as Xe}from"../../cron/armed-context.js";import{existsBeneath as Ze,isAbsentOrRefused as qe,isBeneathRefusal as en,readdirBeneath as nn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as tn,readNodeSession as on,readNodeSnapshot as rn,transcriptMarkdown as dn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as sn}from"../../../core/substrate/subject.js";import{reviveAll as an}from"../../../core/runtime/revive-all.js";import{promoteAsync as ln,requestYieldAsync as cn,reshapeNodeAsync as W}from"../../../core/runtime/promote.js";import{recycleNode as fn}from"../../../core/runtime/recycle.js";import{relaunchRoot as un}from"../../../core/runtime/reset.js";import{assertReopenGate as pn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as mn,readGoal as hn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as wn,hasRoadmap as yn}from"../../../core/runtime/roadmap.js";import{renameWindow as _n}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as gn,explicitModelIntent as bn,normalizeModel as vn,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as kn}from"../../../core/model-routes.js";import{persistDormantModel as Sn,setModelLive as Rn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as On}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as In}from"../../../core/runtime/broker-request.js";import{boundFleet as V}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as $n}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Cn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ae}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as An}from"../../../core/human/action-binding.js";import{resolveHumanAction as Nn}from"../../../core/human-actions.js";import{parseDurationMs as Tn}from"../../../core/wake.js";import{claimWarmNode as En,refillWarmPool as le,resumeWarmClaim as Pn,warmPoolEnabled as Dn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as J,isLaunchKind as jn,resolveLaunchTarget as Ln}from"../../../core/runtime/launch-target.js";import{fullName as Mn}from"../../../core/canvas/labels.js";import{reportsForNode as ce}from"./reports.js";import{requireUsableProfile as Fn}from"./profiles.js";import{assertProfileActive as Gn,loadExactProfileManifest as Bn}from"../../../core/profiles/manifest.js";import{getCron as fe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Kn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as xn}from"../../control.js";import{notFound as E,usage as h}from"../../../core/errors.js";import{assertScope as Wn,validateScopes as ue}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Vn,toNodeDetailDTO as z,toNodeSummaryDTO as Jn,toReviveResultDTO as zn}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{brokerMayReach as U,canReadNode as pe,resolvedScopes as Un}from"../router.js";import{forwardVerb as Hn,queryWithoutMachine as Yn,relayError as Qn,unknownError as Xn,withMachine as Zn}from"../../peer/forward.js";import{fileRoot as qn}from"../../../core/spaces/file-root.js";import{activeGrant as et,terminalGrant as nt}from"../../../core/grants/mirror.js";import{readConfig as tt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ot,NO_PROVIDER_CREDENTIAL_MESSAGE as me}from"../../../core/runtime/provider-credential-gate.js";function y(e){const t=k(e);if(t===null)throw E(`unknown node: ${e}`,{received:e});return t}a(y,"requireMeta");function H(e){return{subscribesTo:ie(e),subscribers:Ge(e),children:De(e)}}a(H,"edgesFor");function g(e){const t=y(e);return z(t,H(e))}a(g,"detailOf");function rt(e){let t=ce(e).length;try{t+=nn(x(e),de(e)).length}catch(n){if(!qe(n))throw n}return t}a(rt,"countFiles");function it(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&ue(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new m(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(it,"parseCreateBody");function dt(e){if(e===void 0)return;const t=Tn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(dt,"parseDeadline");function st(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!An.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ae)throw new m(413,"payload_too_large",`serialized payload exceeds ${ae} bytes`)}return e}}a(st,"parseOutcomeDelivery");function at(e,t){const n=Nn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new m(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(at,"resolveOutcomeDelivery");function lt(e,t,n){const r={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),t!==void 0&&(r.parent=t),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=T(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}a(lt,"buildRecipe");function ct(e,t,n){return!Dn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(ct,"warmRequestFor");import{resolveCreateKind as rr}from"../../../core/runtime/launch-target.js";function he(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return kn(e.model,t,e.modelExact===!0)}a(he,"requestFromLaunch");function ft(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!O(t,r));if(n.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(ft,"withinCeiling");async function we(e,t,n){const r=(await gn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await B(he(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(we,"assertNodeModelChangeRegistered");function ye(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=qn({app:n.app,resolved:Un(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new m(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ye,"assertCallerReaches");const Y=new Map;async function ut(e,t={},n={}){const r=ft(it(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=y(r.parent);if(i.grantee!==c.app)throw new m(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw E(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new m(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Pe(Te(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new m(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new m(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=Qe({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new m(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(i.effectiveScopes,p)||!O(c.scopes,p));if(l!==void 0)throw new m(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ee(),c.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,c.app))}r.creator!==void 0&&Wn(y(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&Ye(r.node_id)&&k(r.node_id)!==null&&je(o)?.nodeId!==r.node_id)return P(e,r,t,n);const d=Y.get(o);if(d!==void 0)return d;const s=pt(e,r,o,t,n);Y.set(o,s);try{return await s}finally{Y.delete(o)}}a(ut,"handleCreate");async function pt(e,t,n,r,o){const d=oe(n);if(d.nodeId!==null&&k(d.nodeId)!==null){if(d.state!=="warm_claimed"){const s=k(d.nodeId);if(e.principal.class!=="person"&&!pe(e.principal,s.grantee??"app:terminal",d.nodeId))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(d.nodeId)}}return P(e,t,r,o,d)}try{return await P(e,t,r,o,d)}catch(s){const c=oe(n);throw(c.nodeId===null||k(c.nodeId)===null)&&ne(n,c.nodeId),s}}a(pt,"handleKeyedCreateRequest");async function P(e,t,n,r,o=void 0){const d=r.deadlineAt??dt(t.deadline),s=st(t.outcome_delivery),c=e.principal.class==="cron"?Xe({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:fe(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await Cn(l)}const{profileId:p,kind:u,cwd:f,launch:_}=await Ln(t,{validateKind:ke});ye(e,f),t.worktree!==void 0&&ye(e,T(t.pin_cwd??t.cwd??f));const S={...t,kind:u},I=s===void 0?void 0:at(s,f);if(await B(he(_),{cwd:f,profileId:p},n.modelRegistry),!await ot(p))throw new m(412,"no_provider_credential",me,{error:"no_provider_credential",message:me,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let j=null;{const $=o===void 0||o.nodeId===null||o.state==="warm_claimed"?ct(S,f,p):null,L=l===null&&r.beforeBrokerLaunch===void 0?void 0:v=>{l!==null&&$n(v,"terminal",l),r.beforeBrokerLaunch?.(v)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const v=$===null?null:await Pn($,o.nodeId,L);if(v===null)throw ne(o.requestKey,o.nodeId),new m(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return te(o.requestKey,v),{status:201,body:g(v)}}if($!==null){const v=await En($,{...d===void 0?{}:{deadlineAt:d},...I===void 0?{}:{outcomeDelivery:I},...o===void 0?{}:{requestKey:o.requestKey}},L);if(v!==null)return o!==void 0&&te(o.requestKey,v),le($),{status:201,body:g(v)};j=$}const M=o?.nodeId??t.node_id??(o===void 0?void 0:ee());o!==void 0&&o.nodeId===null&&Me(o.requestKey,M);const R=lt(M===void 0?S:{...S,node_id:M},i,f);c!==null&&(c.rootLifecycle!==void 0&&(R.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&S.scopes===void 0&&(R.scopes=c.scopes),c.run!==void 0&&(R.run=c.run),c.withinCreate!==void 0&&(R.withinCreate=c.withinCreate)),d!==void 0&&(R.deadlineAt=d),I!==void 0&&(R.outcomeDelivery=I),R.readiness=t.root===!0?"await":"launch";const Q=await Ee(R,L,()=>{j!==null&&le(j)});return o!==void 0&&Le(o.requestKey,Q.node.node_id),{status:201,body:g(Q.node.node_id)}}}a(P,"handleCreateRequest");function b(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(b,"singleQueryValue");function _e(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(_e,"optionalBoolean");function D(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(D,"oneOf");function mt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[_]of e.query)if(!t.has(_))throw h(`unknown nodes query parameter: ${_}`);const n=D(b(e,"status"),"status",["active","idle","done","dead","canceled"]),r=D(b(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=b(e,"kind"),d=D(b(e,"mode"),"mode",["base","orchestrator"]),s=b(e,"profile_id"),c=b(e,"profile_prefix"),i=b(e,"parent"),l=_e(b(e,"top_level"),"top_level"),p=b(e,"under"),u=_e(b(e,"hanging"),"hanging"),f=D(b(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...d!==void 0?{mode:d}:{},...s!==void 0?{profile_id:s}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...u!==void 0?{hanging:u}:{},...f!==void 0?{include:f}:{}}}a(mt,"parseListQuery");function ht(e){const t=mt(e);let n=t.status!==void 0?re({status:t.status}):re();if(e.principal.class!=="person"&&(n=n.filter(s=>pe(e.principal,s.grantee??"app:terminal",s.node_id))),t.lifecycle!==void 0&&(n=n.filter(s=>s.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(s=>s.kind===t.kind)),t.mode!==void 0&&(n=n.filter(s=>s.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(s=>s.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(s=>s.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(s=>s.parent===t.parent)),t.top_level===!0&&(n=n.filter(s=>s.parent===null)),t.under!==void 0){const s=new Set(Ke(t.under));n=n.filter(c=>s.has(c.node_id))}t.hanging===!0&&(n=n.filter(s=>s.parent!==null&&k(s.parent)===null));const r=t.include==="activity"?He(n.map(s=>s.node_id)):null,o=n.length>0?Oe():new Set;return{status:200,body:n.map(s=>{const c=Jn(s,s.profile_id!==null&&o.has(s.profile_id));if(r!==null){const i=ce(s.node_id);c.activity={latest_report:i[0]??null,final_report:s.final_report===null?null:i.find(l=>l.name===s.final_report)??null,pending_human_count:r[s.node_id]??0}}return c})}}a(ht,"handleList");async function wt(e){const t=e.params.id,n=await Hn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:Yn(e)});if(n.kind==="unknown")throw Xn(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw Qn(n.status,n.body);return{status:n.status,body:Zn(n.body,n.machine)}}return y(t),{status:200,body:g(t)}}a(wt,"handleDetail");async function yt(e){const t=e.params.id;y(t);const n=await rn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:G()}}}a(yt,"handleSnapshot");async function _t(e){const t=e.params.id,n=sn(t);if(n===null)throw E(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(_t,"handleSubject");function gt(e){for(const[d]of e.query)if(d!=="cursor"&&d!=="limit")throw h(`unknown messages query parameter: ${d}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(gt,"parseMessagesQuery");async function bt(e){const t=e.params.id,n=await tn(t,gt(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:G()}}}a(bt,"handleMessages");function vt(e){const t=e.params.id;y(t);const n=on(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:G()}}}a(vt,"handleSession");async function kt(e){const t=e.params.id;return y(t),{status:200,body:{node_id:t,markdown:await dn(t)}}}a(kt,"handleTranscript");function St(e){const t=e.params.id;y(t);const n=a((o,d)=>({node_id:o,label:k(o)?.name??o,dir:de(o),self:d,files:rt(o)}),"root"),r=[n(t,!0),...ie(t).map(o=>n(o.node_id,!1))].filter(o=>Rt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(St,"handleContext");function Rt(e,t){try{return Ze(x(e),t)}catch(n){if(en(n))return!1;throw n}}a(Rt,"hasDir");async function Ot(e){const t=y(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(d=>O(n,d)),...n.filter(d=>O(t.scopes,d))])],o=await Ne(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Ot,"handleFork");async function It(e){const t=e.params.id;y(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;pn(t,o);const d=!r&&n?.cron_id!==void 0?fe(n.cron_id):null,s=await Ae(t,{resume:r,capacity:"refuse",...d!==null?{wakeReason:Kn(d,"schedule_revive")}:{}});s.outcome!=="already-live"&&Fe(t,{failures:0,notBefore:null});const c=k(t)?.status??"active";return{status:200,body:zn(t,s,c)}}a(It,"handleRevive");async function $t(e){const t=e.params.id;return{status:200,body:{newNodeId:(await un(t))?.newNodeId??null}}}a($t,"handleRelaunchRoot");function Ct(e){const t=e.params.id;y(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=xn(),o=Ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Vn(o)}}a(Ct,"handleClose");async function At(e){const t=e.params.id;y(t);const n=await fn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(At,"handleRecycle");async function Nt(e){const t=e.params.id;return y(t),await W(t,{lifecycle:"terminal"}),C(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Nt,"handleDemote");async function Tt(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const d=await ln(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});C(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const s=z(d.meta,H(n));return s.roadmap_written=d.roadmapWritten,s.roadmap_ref=d.roadmapRef,s.goal_path=d.goalPath,{status:200,body:s}}a(Tt,"handlePromote");async function Et(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const d=o.note??"Refresh: continue against your roadmap or goal.";mn(n,d);const s=await cn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:z(s.meta,H(n))}}a(Et,"handleYield");function Pt(e){const t=e.params.id;y(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=k(n.controller);if(r===null)throw E(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new m(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return Be(t,n.controller),{status:200,body:g(t)}}a(Pt,"handleWait");async function Dt(e){const t=e.principal,n=await an(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(Dt,"handleReviveAll");const jt=new Set(["interrupt","steer","after-turn","next-turn"]);function Lt(e){if(e===null)return null;const t=a(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!jt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(Lt,"listenJson");function C(e,t,n,r){n.length===0&&r===void 0||K(o=>{if(r?.(o),n.length===0)return;const d=xe(o,t),s=Je(o,e),c=s.class==="person"?s.person:s.class==="app"?s.app:s.node;We(o,c,d),Ve(o,{event:"configured",object:d,actor:c,attrs:{changed:n.join(",")}})})}a(C,"recordConfigured");function ge(e){const t=V().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ge,"restartLiveBroker");function be(e,t){try{return Z(e)===Z(t)}catch{return!1}}a(be,"sameDirectory");async function Mt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(u=>u!=="profile"&&u!=="restart"&&o[u]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const i=y(n),l=Fn(e,o.profile);Gn(l.profileId);const p=Bn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(jn(i.kind)?(await J(i.kind,i.cwd,l.profileId),await W(n,{profileId:l.profileId})):A(n,{profile_id:l.profileId}),C(e,n,["profile"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=y(n),p=N(l.cwd);if(o.keep_session===!0||p&&F(i)&&N(i)&&be(l.cwd,i)){if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let _=!1;try{_=q(f).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!be(l.cwd,f))throw new w({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const S=l.cwd;return S!==f&&(K(I=>{A(n,{cwd:f}),X(I,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,S),ze(n,S,f)}),C(e,n,["cwd"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(V().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new w({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const u=T(i);if(!N(u))throw new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!q(u).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${u}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof w?f:new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return K(()=>{A(n,{cwd:u}),Ue(n)}),C(e,n,["cwd"]),{status:200,body:g(n)}}let d=y(n);const s=o.listen===void 0?void 0:Lt(o.listen);if(o.scopes!==void 0){const i=ue(o.scopes),l=d.grantee==="app:terminal"?nt():d.grant_id?et(d.grant_id):null,p=d.grantee==="app:terminal"&&!tt("user").runtime?.issuer;if(!i.every(u=>O(d.scopes,u)&&(l?O(l.resolved,u):p)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!O(i,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");d=A(n,{scopes:i})}if(o.situational_context!==void 0&&Ie(n,$e(o.situational_context)),o.model!==void 0){const i=(await se(d.cwd,d.profile_id??null)).modelLadders,l=bn(o.model,i),p=vn(o.model,i);await B({kind:"concrete",spec:p},{cwd:d.cwd,profileId:d.profile_id??null},t.modelRegistry);const u=V();let f=!1;if(u.isClaimed(n)&&await On(n,u.get(n)?.handle.exited)&&(f=await Rn(n,p,l).then(()=>!0,_=>{if(_ instanceof In)return!1;throw _})),!f){if(u.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!p.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);Sn(n,p,l)}d=y(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await ke(o.kind);const i=o.kind??d.kind,l=o.mode??d.mode,p=o.lifecycle??d.lifecycle;let u;l==="orchestrator"&&!yn(n)&&(u=a(()=>{const f=hn(n);wn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),d=await W(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},u)}o.name!==void 0&&(d=A(n,{name:o.name}),d.window&&_n(d.window,Mn(d)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return C(e,n,c,s===void 0?void 0:i=>{X(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(s,n)}),{status:200,body:g(n)}}a(Mt,"handleConfig");async function ve(){return(await se(process.cwd(),Re()||null)).kinds}a(ve,"daemonKinds");async function ke(e){const t=Object.keys(await ve());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(ke,"assertKindServer");async function Ft(){const e=await ve();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Ft,"handleListKinds");const nr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ut},{method:"GET",pattern:"/v1/nodes",handler:ht},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Ft(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Dt},{method:"GET",pattern:"/v1/nodes/:id",handler:wt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:_t},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:bt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:vt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:kt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:St},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Ot},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:It},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:$t},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ct},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:At},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Pt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mt}];export{Mt as handleConfig,ut as handleCreate,Ot as handleFork,ht as handleList,Tt as handlePromote,Et as handleYield,nr as nodeRoutes,rr as resolveCreateKind};
@@ -1,2 +1,2 @@
1
- var we=Object.defineProperty;var u=(e,t)=>we(e,"name",{value:t,configurable:!0});import{prepared as ye}from"../../../core/sqlite-statements.js";import{ApiError as w}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as be}from"../../../api/dto/objects.js";import{openDb as T,withCanvasWrite as y}from"../../../core/canvas/db.js";import{actorOf as V}from"../../../core/graph/documents.js";import{readerForObject as A}from"../../../core/graph/reader.js";import{canRead as ge}from"../../../core/graph/access.js";import{customObjectRef as H,authorizeCustom as B,fenceArgv as Z}from"./custom-objects.js";import{edgesOf as je}from"../../../core/graph/edges.js";import{publish as ke}from"../../../core/graph/events.js";import{objectDTO as b}from"../../../core/graph/kinds/dto.js";import{isKind as _e,kindNames as ve,kindOf as J}from"../../../core/graph/kinds/registry.js";import{listObjects as Ee,searchObjects as K}from"../../../core/graph/objects.js";import{checkoutsForCwd as Oe}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as Q,unwatch as Y,watchersOf as qe,watchesOf as Re}from"../../../core/graph/watches.js";import{readerFor as g,resolveRef as L}from"../reader.js";import{invalidRequest as $,isRecord as k}from"./validate.js";import{callerNode as X,callerStub as N,forwardVerb as x,originates as ee,queryWithoutMachine as P,relayError as C,remoteStub as Te,unknownError as te,forwarding as S,withMachine as F}from"../../peer/forward.js";import{getById as ne}from"../../../core/graph/objects.js";import{isStub as re}from"../../../core/peer/stubs.js";import{isUnreachable as $e}from"../../../core/peer/client.js";import{normalizeMachineId as I}from"../../../core/peer/directory.js";const M=u(e=>t=>Oe(e,t),"reposFnFor");function oe(e,t){return{...b(e,t),...J(e,t.type).listItem?.(e,t)}}u(oe,"listItem");function Se(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}u(Se,"remoteMessage");function ie(e,t,n){try{return R(e,t,n)}catch(r){if(r instanceof w&&r.code==="not_found"&&!r.details?.deleted)return null;throw r}}u(ie,"ownerFilter");function R(e,t,n){const r=L(e,t,n);if("remote"in r)throw new w(404,"not_found",Se(r.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in r)throw new w(404,"not_found",`${r.deleted.name} is deleted`,{id:r.deleted.id,deleted:!0});return r}u(R,"liveRef");const _=u(e=>decodeURIComponent(e.params.ref),"refParam"),se=u(e=>{const t=e.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");function ae(e){const t=ne(T(),se(e));return t!==null&&re(T(),t)?t.id:null}u(ae,"stubIdOf");async function W(e,t,n,r){const o=ae(t);return o!==null?x(e,o,n):r()?{kind:"local"}:ee(e.principal)?x(e,se(t),n):{kind:"local"}}u(W,"forwardRef");function D(e,t){return y(n=>{try{return!("remote"in L(n,g(n,t),e))}catch{return!1}})}u(D,"resolvesLocally");const G=u(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");function ue(e,t,n,r,o){const i=t?.object;!i?.id||!i.type||y(s=>{const a=X(s,e);if(a===null)return;const c=Te(s,i.id,i.type,n,{kind:i.kind??null,name:i.name??i.id,...i.preview===void 0?{}:{preview:i.preview},owner:i.owner??null});Q(s,a,c,r,o===void 0?{}:{patterns:o})})}u(ue,"watchRemote");async function Ie(e){const t=_(e),n=["1","true"].includes(e.query.get("fields")??""),r=await W(e,t,{method:"GET",path:G(t),query:P(e)},()=>D(t,e));if(r.kind==="unknown")return{state:"unknown",ref:t,unreachable:r.unreachable};if(r.kind==="remote"){if(r.status>=400)throw C(r.status,r.body);return ue(e,r.body,r.machine.id,"read"),F(r.body,r.machine)}return y(o=>{const i=N(o,e),s=i===null?g(o,e):A(o,i,M(o)),a=L(o,s,t);if("remote"in a)return{state:"remote",remote:a.remote};if("deleted"in a)return{state:"deleted",deleted:b(o,a.deleted)};const{data:c,text:l}=J(o,a.type).read(o,s,a,{fields:n,reposFn:M(o)});return{state:"object",type:a.type,object:b(o,a),text:l,data:c}})}u(Ie,"read");function z(e,t,n,r){if(e!=null){if(!n.includes(e)){r.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}u(z,"oneOf");function ce(e,t,n){if(t!=null){if(typeof t!="string"||!_e(e,t)){n.push({field:"type",problem:`must be a kind: one of ${ve(e).join(", ")}`,received:t});return}return t}}u(ce,"kindName");function le(e,t,n,r){if(e==null)return r;const o=Number(e);return!Number.isInteger(o)||o<1||o>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),r):o}u(le,"limitOf");function fe(e){const t=e.query,n=[],r=ce(T(),t.get("type"),n),o=z(t.get("privacy"),"privacy",be,n),i=le(t.get("limit"),"limit",n,50),s=t.get("cursor");s!==null&&!/^\d+$/.test(s)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:s});const a=t.get("deleted");return a!==null&&!["0","1","true","false"].includes(a)&&n.push({field:"deleted",problem:"must be true or false",received:a}),n.length>0&&$("object list request",n),y(c=>{const l=g(c,e),h={...r?{type:r}:{},...o?{privacy:o}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...a==="1"||a==="true"?{deleted:!0}:{}},p=t.get("owner");if(p!==null){const m=ie(c,l,p);if(m===null)return{items:[],next_cursor:null};h.owner=m}const v=t.get("name"),j=[];let d=s===null?0:Number(s),E=!0;for(;j.length<i&&E;){const m=Ee(c,l,h,{limit:100,after_rowid:d});E=m.length===100;for(const q of m)if(d=q.rowid,(v===null||q.name.startsWith(v))&&j.push(q),j.length===i)break}const f=j.at(-1);return{items:j.map(m=>oe(c,m)),next_cursor:j.length===i&&f?String(f.rowid):null}})}u(fe,"listLocal");const Ae={ms:3e4},Le="self",U=u((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function de(e,t,n,r){const o=S.current;try{const i=await o.call(t.id,{method:"GET",path:"/v1/objects",query:n},o.envelope(e.principal),r);if($e(i))return{state:"unreachable",items:[],next:null};if(i.status===426)return{state:"too_old",items:[],next:null};const s=i.body;return i.status!==200||!Array.isArray(s?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:U(s.items,t),next:s.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}u(de,"remotePage");async function Ne(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([S.current.machines().catch(()=>null),t])}u(Ne,"machinesWithin");async function Pe(e){const t=e.query.get("machine");if(!ee(e.principal)||!S.current.joined()||t===Le)return fe(me(e));const r=S.current.self(),o=t!==null&&I(t)!==r,i=o?null:fe(me(e)),s=new AbortController,a=setTimeout(()=>s.abort(),Ae.ms);a.unref?.();try{const c=await Ne(s.signal);if(c===null){if(o)throw new w(503,"runtime_unreachable",`The directory did not answer, so ${I(t)} cannot be listed.`,{machine:I(t)});return i}const l=u(f=>({id:f,name:c.find(m=>m.machine_id===f)?.name??f}),"labelOf"),h=l(r),p=c.filter(f=>f.machine_id!==r),v=P(e);if(t!==null){if(!o)return{items:U(i.items,h),next_cursor:i.next_cursor,machines:[{machine_id:r,name:h.name,state:"ok",more:i.next_cursor!==null}]};const f=I(t);if(!p.some(q=>q.machine_id===f))throw new w(404,"not_found",`no machine ${f} on your account`,{machine:f});const m=await de(e,l(f),v,s.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:f,name:l(f).name,state:m.state,more:m.next!==null}]}}const{cursor:j,...d}=v,E=await Promise.all(p.map(f=>de(e,l(f.machine_id),d,s.signal)));return{items:[...U(i.items,h),...E.flatMap(f=>f.items)],next_cursor:i.next_cursor,machines:[{machine_id:r,name:h.name,state:"ok",more:i.next_cursor!==null},...p.map((f,m)=>({machine_id:f.machine_id,name:f.name,state:E[m].state,more:E[m].next!==null}))]}}finally{clearTimeout(a)}}u(Pe,"list");function me(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}u(me,"withoutMachine");function Ce(e){const t=[],n=k(e.body)?e.body:{};k(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const r=n.text;(typeof r!="string"||r.trim()==="")&&t.push({field:"text",problem:"is required",received:r});const o=n.grep;if(o!==void 0)if(typeof o!="string")t.push({field:"grep",problem:"must be a regular expression string",received:o});else try{new RegExp(o)}catch(a){t.push({field:"grep",problem:`is not a valid regular expression: ${a.message}`,received:o})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const i=ce(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 s=le(n.limit,"limit",t,50);return t.length>0&&$("object search request",t),y(a=>{const c=g(a,e),l=typeof n.owner=="string"?ie(a,c,n.owner):null;if(typeof n.owner=="string"&&l===null)return{items:[]};const h=K(a,c,{text:r,body:n.body===!0||typeof o=="string"}),p=new Set(h.map(d=>d.object.rowid));return{items:(typeof o=="string"?K(a,c,{text:o,grep:!0}).filter(d=>p.has(d.object.rowid)):h).filter(d=>(!i||d.object.type===i)&&(n.kind===void 0||d.object.kind===n.kind)&&(!l||d.object.owner===l.rowid)).slice(0,s).map(d=>({object:oe(a,d.object),...d.line!==void 0?{matches:[{line:d.line,text:d.text??""}]}:{}}))}})}u(Ce,"search");const he=["interrupt","steer","after-turn","next-turn"],Fe=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function Me(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!Fe.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(Me,"patternsOf");function We(e,t){if(e===void 0)return;if(!k(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[r,o]of Object.entries(e)){const i=Number(r);!Number.isInteger(i)||i<1||i>10?t.push({field:`config.${r}`,problem:"level must be an integer from 1 to 10"}):he.includes(o)?n.push({threshold:i,delivery:o}):t.push({field:`config.${r}`,problem:`delivery must be one of ${he.join(", ")}`,received:o})}return n.sort((r,o)=>o.threshold-r.threshold)}u(We,"configOf");function pe(e){const t=ae(e);if(t!==null)throw new w(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}u(pe,"refuseStubWatch");async function De(e){const t=_(e);if(typeof(k(e.body)?e.body:{}).watcher=="string"&&pe(t),typeof(k(e.body)?e.body:{}).watcher!="string"){const n=await W(e,t,{method:"POST",path:`${G(t)}/watch`,body:e.body},()=>D(t,e));if(n.kind==="unknown")throw te(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);const r=n.body.patterns;return ue(e,n.body,n.machine.id,"ask",r),F(n.body,n.machine)}}return Ge(e)}u(De,"watch");function Ge(e){const t=[],n=e.body===void 0?{}:k(e.body)?e.body:(t.push({field:"body",problem:"must be an object"}),{}),r=Me(n.patterns,t),o=We(n.config,t);return n.filter!==void 0&&!k(n.filter)&&t.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&t.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),t.length>0&&$("watch request",t),y(i=>{const s=typeof n.watcher=="string"?H(i,n.watcher):null;if(e.publishToken&&!s)throw new w(404,"not_found","watcher not found");if(e.principal.class==="anonymous"&&!s)throw new w(404,"not_found","watcher not found");const a=s?B(i,e,s):N(i,e)??V(g(i,e));s&&Z(i,e,s);const c=s?A(i,s):g(i,e),l=s?(()=>{const p=R(i,c,_(e));if(!ge(i,c,p))throw new w(404,"not_found","object not found");return p})():R(i,c,_(e)),h=r??[">"];return Q(i,s??a,l,s?"act":"ask",{patterns:h,...o?{config:o}:{},...n.filter!==void 0?{filter:n.filter}:{}}),ke(i,{event:"watched",object:l,actor:a,attrs:{}},M(i)),{object:b(i,l),patterns:h}})}u(Ge,"watchLocal");async function ze(e){const t=_(e);if(e.query.get("watcher")&&pe(t),!e.query.get("watcher")){const n=await W(e,t,{method:"DELETE",path:`${G(t)}/watch`,query:P(e)},()=>D(t,e));if(n.kind==="unknown")throw te(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);const r=n.body.object?.id;return y(o=>{const i=X(o,e),s=r===void 0?null:ne(o,r);i!==null&&s!==null&&re(o,s)&&Y(o,i,s,e.query.get("pattern")??void 0)}),F(n.body,n.machine)}}return Ue(e)}u(ze,"unwatchRoute");function Ue(e){const t=e.query.get("pattern"),n=e.query.get("watcher");return y(r=>{const o=n?H(r,n):null;if((e.publishToken||e.principal.class==="anonymous")&&!o)throw new w(404,"not_found","watcher not found");const i=o?B(r,e,o):N(r,e)??V(g(r,e));o&&Z(r,e,o);const s=o?A(r,o):g(r,e),a=R(r,s,_(e)),c=u(()=>ye(r,`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.rowid = s.watch
2
- WHERE w.watcher = ? AND w.object = ?`).get((o??i).rowid,a.rowid).n,"count"),l=c();return Y(r,o??i,a,t??void 0),{object:b(r,a),removed:l-c()}})}u(Ue,"unwatchLocal");function Ve(e){const t=[],n=z(e.query.get("type"),"type",["acted-on","links-to","watches"],t),r=z(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&$("edges request",t),y(o=>{const i=g(o,e),s=R(o,i,_(e)),a=[];if(n!=="watches")for(const c of je(o,i,s,{...n?{type:n}:{},direction:r??"both"}))a.push({type:c.type,src:b(o,c.src),dst:b(o,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...r!=="in"?Re(o,i,s):[],...r!=="out"?qe(o,i,s):[]];for(const l of c)a.push({type:"watches",src:b(o,l.watcher),dst:b(o,l.object)})}return{items:a}})}u(Ve,"edges");const O=u(e=>async t=>({status:200,body:await e(t)}),"ok"),ht=[{method:"POST",pattern:"/v1/objects/search",handler:O(Ce)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:O(Ve)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:O(De)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:O(ze)},{method:"GET",pattern:"/v1/objects/:ref",handler:O(Ie)},{method:"GET",pattern:"/v1/objects",handler:O(Pe)}];export{Ae as listBudget,ht as objectRoutes};
1
+ var we=Object.defineProperty;var u=(e,t)=>we(e,"name",{value:t,configurable:!0});import{prepared as ye}from"../../../core/sqlite-statements.js";import{ApiError as w}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as be}from"../../../api/dto/objects.js";import{openDb as T,withCanvasWrite as y}from"../../../core/canvas/db.js";import{actorOf as V}from"../../../core/graph/documents.js";import{readerForObject as A}from"../../../core/graph/reader.js";import{canRead as ge}from"../../../core/graph/access.js";import{customObjectRef as H,authorizeCustom as B,fenceArgv as Z}from"./custom-objects.js";import{edgesOf as je}from"../../../core/graph/edges.js";import{publish as ke}from"../../../core/graph/events.js";import{objectDTO as b}from"../../../core/graph/kinds/dto.js";import{isKind as _e,kindNames as ve,kindOf as J}from"../../../core/graph/kinds/registry.js";import{listObjects as Ee,searchObjects as K}from"../../../core/graph/objects.js";import{checkoutsForCwd as Oe}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as Q,unwatch as Y,watchersOf as qe,watchesOf as Re}from"../../../core/graph/watches.js";import{readerFor as g,resolveRef as L}from"../reader.js";import{invalidRequest as $,isRecord as k}from"./validate.js";import{callerNode as X,callerStub as N,forwardVerb as x,originates as ee,queryWithoutMachine as P,relayError as C,remoteStub as Te,unknownError as te,forwarding as S,withMachine as F}from"../../peer/forward.js";import{getById as ne}from"../../../core/graph/objects.js";import{isStub as re}from"../../../core/peer/stubs.js";import{isUnreachable as $e}from"../../../core/peer/client.js";import{normalizeMachineId as I}from"../../../core/peer/directory.js";const M=u(e=>t=>Oe(e,t),"reposFnFor");function oe(e,t){return{...b(e,t),...J(e,t.type).listItem?.(e,t)}}u(oe,"listItem");function Se(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}u(Se,"remoteMessage");function ie(e,t,n){try{return R(e,t,n)}catch(r){if(r instanceof w&&r.code==="not_found"&&!r.details?.deleted)return null;throw r}}u(ie,"ownerFilter");function R(e,t,n){const r=L(e,t,n);if("remote"in r)throw new w(404,"not_found",Se(r.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in r)throw new w(404,"not_found",`${r.deleted.name} is deleted`,{id:r.deleted.id,deleted:!0});return r}u(R,"liveRef");const _=u(e=>decodeURIComponent(e.params.ref),"refParam"),se=u(e=>{const t=e.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");function ae(e){const t=ne(T(),se(e));return t!==null&&re(T(),t)?t.id:null}u(ae,"stubIdOf");async function W(e,t,n,r){const o=ae(t);return o!==null?x(e,o,n):r()?{kind:"local"}:ee(e.principal)?x(e,se(t),n):{kind:"local"}}u(W,"forwardRef");function D(e,t){return y(n=>{try{return!("remote"in L(n,g(n,t),e))}catch{return!1}})}u(D,"resolvesLocally");const G=u(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");function ue(e,t,n,r,o){const i=t?.object;!i?.id||!i.type||y(s=>{const a=X(s,e);if(a===null)return;const c=Te(s,i.id,i.type,n,{kind:i.kind??null,name:i.name??i.id,...i.preview===void 0?{}:{preview:i.preview},owner:i.owner??null});Q(s,a,c,r,o===void 0?{}:{patterns:o})})}u(ue,"watchRemote");async function Ie(e){const t=_(e),n=["1","true"].includes(e.query.get("fields")??""),r=await W(e,t,{method:"GET",path:G(t),query:P(e)},()=>D(t,e));if(r.kind==="unknown")return{state:"unknown",ref:t,unreachable:r.unreachable};if(r.kind==="remote"){if(r.status>=400)throw C(r.status,r.body);return ue(e,r.body,r.machine.id,"read"),F(r.body,r.machine)}return y(o=>{const i=N(o,e),s=i===null?g(o,e):A(o,i,M(o)),a=L(o,s,t);if("remote"in a)return{state:"remote",remote:a.remote};if("deleted"in a)return{state:"deleted",deleted:b(o,a.deleted)};const{data:c,text:f}=J(o,a.type).read(o,s,a,{fields:n,reposFn:M(o)});return{state:"object",type:a.type,object:b(o,a),text:f,data:c}})}u(Ie,"read");function z(e,t,n,r){if(e!=null){if(!n.includes(e)){r.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}u(z,"oneOf");function ce(e,t,n){if(t!=null){if(typeof t!="string"||!_e(e,t)){n.push({field:"type",problem:`must be a kind: one of ${ve(e).join(", ")}`,received:t});return}return t}}u(ce,"kindName");function le(e,t,n,r){if(e==null)return r;const o=Number(e);return!Number.isInteger(o)||o<1||o>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),r):o}u(le,"limitOf");function fe(e){const t=e.query,n=[],r=ce(T(),t.get("type"),n),o=z(t.get("privacy"),"privacy",be,n),i=le(t.get("limit"),"limit",n,50),s=t.get("cursor");s!==null&&!/^\d+$/.test(s)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:s});const a=t.get("deleted");return a!==null&&!["0","1","true","false"].includes(a)&&n.push({field:"deleted",problem:"must be true or false",received:a}),n.length>0&&$("object list request",n),y(c=>{const f=g(c,e),h={...r?{type:r}:{},...o?{privacy:o}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...a==="1"||a==="true"?{deleted:!0}:{}},p=t.get("owner");if(p!==null){const m=ie(c,f,p);if(m===null)return{items:[],next_cursor:null};h.owner=m}const v=t.get("name"),j=[];let d=s===null?0:Number(s),E=!0;for(;j.length<i&&E;){const m=Ee(c,f,h,{limit:100,after_rowid:d});E=m.length===100;for(const q of m)if(d=q.rowid,(v===null||q.name.startsWith(v))&&j.push(q),j.length===i)break}const l=j.at(-1);return{items:j.map(m=>oe(c,m)),next_cursor:j.length===i&&l?String(l.rowid):null}})}u(fe,"listLocal");const Ae={ms:3e4},Le="self",U=u((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function de(e,t,n,r){const o=S.current;try{const i=await o.call(t.id,{method:"GET",path:"/v1/objects",query:n},o.envelope(e.principal),r);if($e(i))return{state:"unreachable",items:[],next:null};if(i.status===426)return{state:"too_old",items:[],next:null};const s=i.body;return i.status!==200||!Array.isArray(s?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:U(s.items,t),next:s.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}u(de,"remotePage");async function Ne(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([S.current.machines().catch(()=>null),t])}u(Ne,"machinesWithin");async function Pe(e){const t=e.query.get("machine");if(!ee(e.principal)||!S.current.joined()||t===Le)return fe(me(e));const r=S.current.self(),o=t!==null&&I(t)!==r,i=o?null:fe(me(e)),s=new AbortController,a=setTimeout(()=>s.abort(),Ae.ms);a.unref?.();try{const c=await Ne(s.signal);if(c===null){if(o)throw new w(503,"runtime_unreachable",`The directory did not answer, so ${I(t)} cannot be listed.`,{machine:I(t)});return i}const f=u(l=>({id:l,name:c.find(m=>m.machine_id===l)?.name??l}),"labelOf"),h=f(r),p=c.filter(l=>l.machine_id!==r&&l.kind!=="device"),v=P(e);if(t!==null){if(!o)return{items:U(i.items,h),next_cursor:i.next_cursor,machines:[{machine_id:r,name:h.name,state:"ok",more:i.next_cursor!==null}]};const l=I(t);if(!p.some(q=>q.machine_id===l))throw new w(404,"not_found",`no machine ${l} on your account`,{machine:l});const m=await de(e,f(l),v,s.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:l,name:f(l).name,state:m.state,more:m.next!==null}]}}const{cursor:j,...d}=v,E=await Promise.all(p.map(l=>de(e,f(l.machine_id),d,s.signal)));return{items:[...U(i.items,h),...E.flatMap(l=>l.items)],next_cursor:i.next_cursor,machines:[{machine_id:r,name:h.name,state:"ok",more:i.next_cursor!==null},...p.map((l,m)=>({machine_id:l.machine_id,name:l.name,state:E[m].state,more:E[m].next!==null}))]}}finally{clearTimeout(a)}}u(Pe,"list");function me(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}u(me,"withoutMachine");function Ce(e){const t=[],n=k(e.body)?e.body:{};k(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const r=n.text;(typeof r!="string"||r.trim()==="")&&t.push({field:"text",problem:"is required",received:r});const o=n.grep;if(o!==void 0)if(typeof o!="string")t.push({field:"grep",problem:"must be a regular expression string",received:o});else try{new RegExp(o)}catch(a){t.push({field:"grep",problem:`is not a valid regular expression: ${a.message}`,received:o})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const i=ce(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 s=le(n.limit,"limit",t,50);return t.length>0&&$("object search request",t),y(a=>{const c=g(a,e),f=typeof n.owner=="string"?ie(a,c,n.owner):null;if(typeof n.owner=="string"&&f===null)return{items:[]};const h=K(a,c,{text:r,body:n.body===!0||typeof o=="string"}),p=new Set(h.map(d=>d.object.rowid));return{items:(typeof o=="string"?K(a,c,{text:o,grep:!0}).filter(d=>p.has(d.object.rowid)):h).filter(d=>(!i||d.object.type===i)&&(n.kind===void 0||d.object.kind===n.kind)&&(!f||d.object.owner===f.rowid)).slice(0,s).map(d=>({object:oe(a,d.object),...d.line!==void 0?{matches:[{line:d.line,text:d.text??""}]}:{}}))}})}u(Ce,"search");const he=["interrupt","steer","after-turn","next-turn"],Fe=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function Me(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!Fe.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(Me,"patternsOf");function We(e,t){if(e===void 0)return;if(!k(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[r,o]of Object.entries(e)){const i=Number(r);!Number.isInteger(i)||i<1||i>10?t.push({field:`config.${r}`,problem:"level must be an integer from 1 to 10"}):he.includes(o)?n.push({threshold:i,delivery:o}):t.push({field:`config.${r}`,problem:`delivery must be one of ${he.join(", ")}`,received:o})}return n.sort((r,o)=>o.threshold-r.threshold)}u(We,"configOf");function pe(e){const t=ae(e);if(t!==null)throw new w(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}u(pe,"refuseStubWatch");async function De(e){const t=_(e);if(typeof(k(e.body)?e.body:{}).watcher=="string"&&pe(t),typeof(k(e.body)?e.body:{}).watcher!="string"){const n=await W(e,t,{method:"POST",path:`${G(t)}/watch`,body:e.body},()=>D(t,e));if(n.kind==="unknown")throw te(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);const r=n.body.patterns;return ue(e,n.body,n.machine.id,"ask",r),F(n.body,n.machine)}}return Ge(e)}u(De,"watch");function Ge(e){const t=[],n=e.body===void 0?{}:k(e.body)?e.body:(t.push({field:"body",problem:"must be an object"}),{}),r=Me(n.patterns,t),o=We(n.config,t);return n.filter!==void 0&&!k(n.filter)&&t.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&t.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),t.length>0&&$("watch request",t),y(i=>{const s=typeof n.watcher=="string"?H(i,n.watcher):null;if(e.publishToken&&!s)throw new w(404,"not_found","watcher not found");if(e.principal.class==="anonymous"&&!s)throw new w(404,"not_found","watcher not found");const a=s?B(i,e,s):N(i,e)??V(g(i,e));s&&Z(i,e,s);const c=s?A(i,s):g(i,e),f=s?(()=>{const p=R(i,c,_(e));if(!ge(i,c,p))throw new w(404,"not_found","object not found");return p})():R(i,c,_(e)),h=r??[">"];return Q(i,s??a,f,s?"act":"ask",{patterns:h,...o?{config:o}:{},...n.filter!==void 0?{filter:n.filter}:{}}),ke(i,{event:"watched",object:f,actor:a,attrs:{}},M(i)),{object:b(i,f),patterns:h}})}u(Ge,"watchLocal");async function ze(e){const t=_(e);if(e.query.get("watcher")&&pe(t),!e.query.get("watcher")){const n=await W(e,t,{method:"DELETE",path:`${G(t)}/watch`,query:P(e)},()=>D(t,e));if(n.kind==="unknown")throw te(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);const r=n.body.object?.id;return y(o=>{const i=X(o,e),s=r===void 0?null:ne(o,r);i!==null&&s!==null&&re(o,s)&&Y(o,i,s,e.query.get("pattern")??void 0)}),F(n.body,n.machine)}}return Ue(e)}u(ze,"unwatchRoute");function Ue(e){const t=e.query.get("pattern"),n=e.query.get("watcher");return y(r=>{const o=n?H(r,n):null;if((e.publishToken||e.principal.class==="anonymous")&&!o)throw new w(404,"not_found","watcher not found");const i=o?B(r,e,o):N(r,e)??V(g(r,e));o&&Z(r,e,o);const s=o?A(r,o):g(r,e),a=R(r,s,_(e)),c=u(()=>ye(r,`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.rowid = s.watch
2
+ WHERE w.watcher = ? AND w.object = ?`).get((o??i).rowid,a.rowid).n,"count"),f=c();return Y(r,o??i,a,t??void 0),{object:b(r,a),removed:f-c()}})}u(Ue,"unwatchLocal");function Ve(e){const t=[],n=z(e.query.get("type"),"type",["acted-on","links-to","watches"],t),r=z(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&$("edges request",t),y(o=>{const i=g(o,e),s=R(o,i,_(e)),a=[];if(n!=="watches")for(const c of je(o,i,s,{...n?{type:n}:{},direction:r??"both"}))a.push({type:c.type,src:b(o,c.src),dst:b(o,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...r!=="in"?Re(o,i,s):[],...r!=="out"?qe(o,i,s):[]];for(const f of c)a.push({type:"watches",src:b(o,f.watcher),dst:b(o,f.object)})}return{items:a}})}u(Ve,"edges");const O=u(e=>async t=>({status:200,body:await e(t)}),"ok"),ht=[{method:"POST",pattern:"/v1/objects/search",handler:O(Ce)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:O(Ve)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:O(De)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:O(ze)},{method:"GET",pattern:"/v1/objects/:ref",handler:O(Ie)},{method:"GET",pattern:"/v1/objects",handler:O(Pe)}];export{Ae as listBudget,ht as objectRoutes};
@@ -34,6 +34,8 @@ export interface ProviderCallInput {
34
34
  version?: number;
35
35
  /** Outside a run, the answered approval question the repeat names (R5). */
36
36
  approval?: string;
37
+ /** Which device machine takes the call (a `machine_id`, `runtime:` prefix optional); only a provider served by a machine accepts it. */
38
+ machine?: string;
37
39
  }
38
40
  export declare function parseProvider(value: unknown): string;
39
41
  export declare function parseCallInput(body: unknown): ProviderCallInput;
@@ -1 +1 @@
1
- var E=Object.defineProperty;var s=(e,r)=>E(e,"name",{value:r,configurable:!0});import{randomUUID as P}from"node:crypto";import{readConfig as I}from"../../../core/config.js";import{activeGrantForApp as R,localGrants as h}from"../../../core/grants/mirror.js";import{getNode as O}from"../../../core/canvas/canvas.js";import{scopeAllowed as $}from"../../../core/scopes.js";import{ProviderError as u,providerErrorBody as q,scopeMissing as x}from"../../../core/providers/errors.js";import{callProvider as G,providerTools as N}from"../../../core/providers/call.js";import{providerIdsFromGrants as T,providerInstallState as F}from"../../../core/providers/bundles.js";import{listInstalledPlugins as j}from"../../../core/resolver.js";import{listAudit as C,writeProviderAudit as D}from"../../../core/providers/audit.js";import{emitEvent as _}from"../../../core/events/emit.js";import{resolvedScopes as w}from"../router.js";const fe=new Set(["provider.tools","provider.call","audit.list"]);function M(e){if(e.class==="forwarded"||e.class==="machine")throw new u("permission_error","this operation is not available to the caller");if(e.class==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null};if(e.class==="app"){const r=R(e.app);if(!r)throw new u("grant_revoked",`app ${e.app} has no active grant`);return{class:"app",sub:r.sub,grantee:e.app,client_id:null,resolved:r.resolved,nodeScopes:e.scopes,run_id:null,node_id:null}}return e.class==="cron"?{class:"app",sub:e.sub,grantee:e.app,client_id:null,resolved:w(e),nodeScopes:e.scopes,run_id:e.origin_run,node_id:null}:{class:"broker",sub:e.sub,grantee:e.app,client_id:e.client_id,resolved:w(e),nodeScopes:e.scopes,run_id:e.run??O(e.node)?.run_id??null,node_id:e.node}}s(M,"callerFromRequest");function ce(e){return{class:"app",sub:e.sub,grantee:e.grantee,client_id:e.client_id,resolved:e.resolved,nodeScopes:null,run_id:null,node_id:null}}s(ce,"callerFromApp");const U=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function k(e){const r=U.exec(e);return r!==null&&r[1]!=="crtr"}s(k,"isProviderScope");const g=new WeakMap;function z(e){let r=g.get(e);return r===void 0&&(r=new Set(e),g.set(e,r)),r}s(z,"heldSet");function y(e,r){return e===null?!0:k(r)?z(e).has(r):$(e,r)}s(y,"holds");function S(e,r){return e.class==="person"?!0:y(e.resolved??[],r)&&y(e.nodeScopes,r)}s(S,"callerAllows");function pe(e,r,t){const n=`${r}:${t}`;if(!S(e,n))throw x(n)}s(pe,"requireGroup");function L(){return!!I("user").runtime?.issuer}s(L,"providerOperationsEnabled");const V=/^[A-Za-z0-9_-]{1,64}$/;function p(e,r){return new u("invalid_request",e,{param:r})}s(p,"invalid");function A(e){if(typeof e!="string"||!V.test(e)||e==="crtr")throw p("provider must be a provider id","provider");return e}s(A,"parseProvider");function Z(e){if(!e||typeof e!="object"||Array.isArray(e))throw new u("invalid_request","a JSON object is required");const r=e,t=A(r.provider),n=r.tool;if(typeof n!="string"||!n.trim())throw p("tool must be a non-empty string","tool");const i=r.arguments??{};if(!i||typeof i!="object"||Array.isArray(i))throw p("arguments must be an object","arguments");const a=r.version;if(a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw p("version must be an integer >= 1","version");const o=r.approval;if(o!==void 0&&(typeof o!="string"||!o))throw p("approval must be a question id","approval");return{provider:t,tool:n.trim(),arguments:i,...a===void 0?{}:{version:a},...o===void 0?{}:{approval:o}}}s(Z,"parseCallInput");function B(e,r=new URLSearchParams){const t=s((o,f,c)=>{const l=r.get(o);if(l===null)return f;if(!/^\d+$/.test(l)||Number(l)>c||Number(l)<1)throw p(`invalid ${o}`,o);return Number(l)},"numeric"),n=r.has("after")?t("after",0,Number.MAX_SAFE_INTEGER):void 0,i=t("limit",100,1e3),a=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(o=>r.has(o)).map(o=>[o,r.get(o)]));return{status:200,body:C(e.class==="person"?null:e.grantee,{after:n,limit:i,...a})}}s(B,"auditList");async function H(e,r,t){const n=performance.now(),i=new Set(j("user").filter(d=>d.enabled&&d.manifest.provider?.id===d.name).map(d=>d.name)),a=T(h()),o=[...new Set([...i,...a])].sort();if(r!==void 0&&!o.includes(r))throw new u("not_found",`provider "${r}" is not available`);const f=r===void 0?o:[r],c=e.class==="person"?h().flatMap(d=>d.status==="active"?d.resolved_scopes.map(({scope:v})=>v):[]):e.resolved??[],l=await Promise.all(f.map(async d=>{if(!c.some(m=>m.startsWith(`${d}:`)&&S(e,m)))return null;if(i.has(d)){const m=await N(e,d);return m.groups.length>0?m:null}const b=F(d);return{provider:d,display_name:d,status:b.status,...b.error?{error:b.error}:{},groups:[],commands:[]}})).then(d=>d.filter(v=>v!==null));if(_({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-n,fields:{caller:e.class,provider:r??null,providers:l.length}}),r!==void 0){if(l.length===0)throw new u("not_found",`provider "${r}" is not available`);return{status:200,body:l[0]}}return{status:200,body:{providers:l}}}s(H,"providerTools");async function W(e,r,t){return G(e,r,t)}s(W,"providerCall");async function J(e,r,t,n){if(!L())throw new u("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return B(r,t.query);if(e==="provider.tools")return H(r,t.params.provider===void 0?void 0:A(t.params.provider),n);if(e==="provider.call"){let i;try{i=Z(t.body)}catch(a){const o=t.body&&typeof t.body=="object"&&!Array.isArray(t.body)?t.body:{};throw D({request_id:n.requestId,caller:r,provider:typeof o.provider=="string"?o.provider:"",tool:typeof o.tool=="string"?o.tool:"",outcome:`refused:${a instanceof u?a.code:"invalid_request"}`}),a}return W(r,i,n)}throw new u("not_found","unknown operation")}s(J,"handleProviderOperation");function X(e){const r=new AbortController,t=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",t),{signal:r.signal,release:s(()=>e.off("close",t),"release")}}s(X,"abortOnClose");function K(e,r,t,n){const i=q(e,r,t,n??void 0);return i.status>=500&&!(e instanceof u)&&_({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),i}s(K,"providerFailure");const me=[{method:"GET",pattern:"/v1/audit",name:"audit.list"},{method:"GET",pattern:"/v1/providers/tools",name:"provider.tools"},{method:"GET",pattern:"/v1/providers/:provider/tools",name:"provider.tools"},{method:"POST",pattern:"/v1/provider/call",name:"provider.call"}].map(({method:e,pattern:r,name:t})=>({method:e,pattern:r,handler:s(async n=>{const i=P(),{signal:a,release:o}=X(n.res);let f=null;try{return f=M(n.principal),{...await J(t,f,{params:n.params,body:n.body,query:new URL(n.req.url??"/","http://runtime.local").searchParams},{requestId:i,signal:a}),headers:{"Request-Id":i}}}catch(c){return K(c,i,!1,f?.run_id)}finally{o()}},"handler")}));export{fe as PROVIDER_OPERATIONS,X as abortOnClose,S as callerAllows,ce as callerFromApp,M as callerFromRequest,J as handleProviderOperation,Z as parseCallInput,A as parseProvider,K as providerFailure,L as providerOperationsEnabled,me as providerRoutes,pe as requireGroup};
1
+ var E=Object.defineProperty;var s=(e,r)=>E(e,"name",{value:r,configurable:!0});import{randomUUID as P}from"node:crypto";import{readConfig as I}from"../../../core/config.js";import{activeGrantForApp as R,localGrants as b}from"../../../core/grants/mirror.js";import{getNode as O}from"../../../core/canvas/canvas.js";import{scopeAllowed as $}from"../../../core/scopes.js";import{ProviderError as f,providerErrorBody as q,scopeMissing as x}from"../../../core/providers/errors.js";import{callProvider as G,providerTools as N}from"../../../core/providers/call.js";import{providerIdsFromGrants as T,providerInstallState as F}from"../../../core/providers/bundles.js";import{listInstalledPlugins as j}from"../../../core/resolver.js";import{listAudit as C,writeProviderAudit as D}from"../../../core/providers/audit.js";import{emitEvent as w}from"../../../core/events/emit.js";import{resolvedScopes as _}from"../router.js";const fe=new Set(["provider.tools","provider.call","audit.list"]);function M(e){if(e.class==="forwarded"||e.class==="machine")throw new f("permission_error","this operation is not available to the caller");if(e.class==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null};if(e.class==="app"){const r=R(e.app);if(!r)throw new f("grant_revoked",`app ${e.app} has no active grant`);return{class:"app",sub:r.sub,grantee:e.app,client_id:null,resolved:r.resolved,nodeScopes:e.scopes,run_id:null,node_id:null}}return e.class==="cron"?{class:"app",sub:e.sub,grantee:e.app,client_id:null,resolved:_(e),nodeScopes:e.scopes,run_id:e.origin_run,node_id:null}:{class:"broker",sub:e.sub,grantee:e.app,client_id:e.client_id,resolved:_(e),nodeScopes:e.scopes,run_id:e.run??O(e.node)?.run_id??null,node_id:e.node}}s(M,"callerFromRequest");function ce(e){return{class:"app",sub:e.sub,grantee:e.grantee,client_id:e.client_id,resolved:e.resolved,nodeScopes:null,run_id:null,node_id:null}}s(ce,"callerFromApp");const U=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function k(e){const r=U.exec(e);return r!==null&&r[1]!=="crtr"}s(k,"isProviderScope");const g=new WeakMap;function z(e){let r=g.get(e);return r===void 0&&(r=new Set(e),g.set(e,r)),r}s(z,"heldSet");function y(e,r){return e===null?!0:k(r)?z(e).has(r):$(e,r)}s(y,"holds");function S(e,r){return e.class==="person"?!0:y(e.resolved??[],r)&&y(e.nodeScopes,r)}s(S,"callerAllows");function me(e,r,t){const n=`${r}:${t}`;if(!S(e,n))throw x(n)}s(me,"requireGroup");function L(){return!!I("user").runtime?.issuer}s(L,"providerOperationsEnabled");const V=/^[A-Za-z0-9_-]{1,64}$/;function c(e,r){return new f("invalid_request",e,{param:r})}s(c,"invalid");function A(e){if(typeof e!="string"||!V.test(e)||e==="crtr")throw c("provider must be a provider id","provider");return e}s(A,"parseProvider");function Z(e){if(!e||typeof e!="object"||Array.isArray(e))throw new f("invalid_request","a JSON object is required");const r=e,t=A(r.provider),n=r.tool;if(typeof n!="string"||!n.trim())throw c("tool must be a non-empty string","tool");const i=r.arguments??{};if(!i||typeof i!="object"||Array.isArray(i))throw c("arguments must be an object","arguments");const d=r.version;if(d!==void 0&&(typeof d!="number"||!Number.isInteger(d)||d<1))throw c("version must be an integer >= 1","version");const o=r.approval;if(o!==void 0&&(typeof o!="string"||!o))throw c("approval must be a question id","approval");const l=r.machine;if(l!==void 0&&(typeof l!="string"||!l.trim()))throw c("machine must be a machine id","machine");return{provider:t,tool:n.trim(),arguments:i,...d===void 0?{}:{version:d},...o===void 0?{}:{approval:o},...l===void 0?{}:{machine:l.trim()}}}s(Z,"parseCallInput");function B(e,r=new URLSearchParams){const t=s((o,l,m)=>{const u=r.get(o);if(u===null)return l;if(!/^\d+$/.test(u)||Number(u)>m||Number(u)<1)throw c(`invalid ${o}`,o);return Number(u)},"numeric"),n=r.has("after")?t("after",0,Number.MAX_SAFE_INTEGER):void 0,i=t("limit",100,1e3),d=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(o=>r.has(o)).map(o=>[o,r.get(o)]));return{status:200,body:C(e.class==="person"?null:e.grantee,{after:n,limit:i,...d})}}s(B,"auditList");async function H(e,r,t){const n=performance.now(),i=new Set(j("user").filter(a=>a.enabled&&a.manifest.provider?.id===a.name).map(a=>a.name)),d=T(b()),o=[...new Set([...i,...d])].sort();if(r!==void 0&&!o.includes(r))throw new f("not_found",`provider "${r}" is not available`);const l=r===void 0?o:[r],m=e.class==="person"?b().flatMap(a=>a.status==="active"?a.resolved_scopes.map(({scope:v})=>v):[]):e.resolved??[],u=await Promise.all(l.map(async a=>{if(!m.some(p=>p.startsWith(`${a}:`)&&S(e,p)))return null;if(i.has(a)){const p=await N(e,a);return p.groups.length>0?p:null}const h=F(a);return{provider:a,display_name:a,status:h.status,...h.error?{error:h.error}:{},groups:[],commands:[]}})).then(a=>a.filter(v=>v!==null));if(w({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-n,fields:{caller:e.class,provider:r??null,providers:u.length}}),r!==void 0){if(u.length===0)throw new f("not_found",`provider "${r}" is not available`);return{status:200,body:u[0]}}return{status:200,body:{providers:u}}}s(H,"providerTools");async function W(e,r,t){return G(e,r,t)}s(W,"providerCall");async function J(e,r,t,n){if(!L())throw new f("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return B(r,t.query);if(e==="provider.tools")return H(r,t.params.provider===void 0?void 0:A(t.params.provider),n);if(e==="provider.call"){let i;try{i=Z(t.body)}catch(d){const o=t.body&&typeof t.body=="object"&&!Array.isArray(t.body)?t.body:{};throw D({request_id:n.requestId,caller:r,provider:typeof o.provider=="string"?o.provider:"",tool:typeof o.tool=="string"?o.tool:"",outcome:`refused:${d instanceof f?d.code:"invalid_request"}`}),d}return W(r,i,n)}throw new f("not_found","unknown operation")}s(J,"handleProviderOperation");function X(e){const r=new AbortController,t=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",t),{signal:r.signal,release:s(()=>e.off("close",t),"release")}}s(X,"abortOnClose");function K(e,r,t,n){const i=q(e,r,t,n??void 0);return i.status>=500&&!(e instanceof f)&&w({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),i}s(K,"providerFailure");const pe=[{method:"GET",pattern:"/v1/audit",name:"audit.list"},{method:"GET",pattern:"/v1/providers/tools",name:"provider.tools"},{method:"GET",pattern:"/v1/providers/:provider/tools",name:"provider.tools"},{method:"POST",pattern:"/v1/provider/call",name:"provider.call"}].map(({method:e,pattern:r,name:t})=>({method:e,pattern:r,handler:s(async n=>{const i=P(),{signal:d,release:o}=X(n.res);let l=null;try{return l=M(n.principal),{...await J(t,l,{params:n.params,body:n.body,query:new URL(n.req.url??"/","http://runtime.local").searchParams},{requestId:i,signal:d}),headers:{"Request-Id":i}}}catch(m){return K(m,i,!1,l?.run_id)}finally{o()}},"handler")}));export{fe as PROVIDER_OPERATIONS,X as abortOnClose,S as callerAllows,ce as callerFromApp,M as callerFromRequest,J as handleProviderOperation,Z as parseCallInput,A as parseProvider,K as providerFailure,L as providerOperationsEnabled,pe as providerRoutes,me as requireGroup};
@@ -1 +1 @@
1
- var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{callerGrant as p}from"../principal.js";import{grantVersion as g}from"../../../core/grants/mirror.js";import{waitGrantChange as R}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as h,cancelRun as S,deleteRun as N,interruptRun as O,listRuns as $,messageRun as A,renameRun as j,requestedScopes as x,startRun as B,traceRun as J,waitRun as z}from"../../../core/runs/operations.js";import{canReadRun as b,requireRun as f,runCallerApp as C}from"../router.js";import{waitSeconds as v}from"../long-poll-wait.js";function l(a){if(!a||typeof a!="object"||Array.isArray(a))throw new n(400,"invalid_request","a JSON object is required");return a}c(l,"object");function y(a,t,i,u,d){if(a===null)return d;if(!/^(0|[1-9]\d*)$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<i||Number(a)>u)throw new n(400,"invalid_request",`invalid ${t}`,t);return Number(a)}c(y,"integer");const E=256*1024;async function I(a,t,i,u,d,_){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=v("grant.get",u),s=u.get("since");if(s!==null&&!/^[A-Za-z0-9_-]{1,64}$/.test(s))throw new n(400,"invalid_request","invalid since","since");let r=p(t);return e&&s!==null&&g(r)===s&&(await R(t.grant,e),r=p(t)),{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:t.grant,rev:r.rev,resolved_scopes:r.resolved_scopes,spend_cap:r.spend_cap,exp:t.exp,payer:"user",dependencies:r.dependencies??{},version:g(r)}}}case"run.start":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=l(d),s=["mode","parent","fork_from","node_id","env","tools","system_prompt"];for(const o of s)if(e[o]!==void 0)throw new n(403,"owner_only",`${o} is owner-only`,o);const r=["payer","model","model_policy","deadline","kind"];for(const o of r)if(e[o]!==void 0)throw new n(400,"invalid_request",`${o} is not available`,o);for(const o of Object.keys(e))if(!["prompt","scopes","metadata","profile","isolated","cwd","worktree","output_schema","message"].includes(o))throw new n(400,"invalid_request",`unknown field ${o}`,o);if(e.profile!==void 0&&(typeof e.profile!="string"||!e.profile))throw new n(400,"invalid_request","profile must be a profile id","profile");if(e.isolated!==void 0&&typeof e.isolated!="boolean")throw new n(400,"invalid_request","isolated must be a boolean","isolated");if(e.cwd!==void 0&&(e.isolated!==!0||typeof e.cwd!="string"||!e.cwd))throw new n(400,"invalid_request","cwd is available only for an isolated run and must be an absolute path inside its root folder","cwd");if(e.worktree!==void 0&&e.isolated!==!0)throw new n(400,"invalid_request","worktree is not available","worktree");if(e.isolated===!0&&e.worktree!==void 0)throw new n(400,"invalid_request","worktree is unavailable for an isolated run","worktree");if(typeof e.prompt!="string"||!e.prompt.trim())throw new n(400,"invalid_request","prompt is required","prompt");if(e.message!==void 0&&(typeof e.message!="string"||!e.message.trim()))throw new n(400,"invalid_request","message must be a non-empty string","message");const w=e.metadata===void 0?{}:l(e.metadata);if(Buffer.byteLength(JSON.stringify(w))>4096)throw new n(400,"invalid_request","metadata exceeds 4 KB","metadata");let m;if(e.output_schema!==void 0){const o=e.output_schema;if(!o||typeof o!="object"||Array.isArray(o))throw new n(400,"invalid_request","output_schema must be a JSON Schema object","output_schema");if(Buffer.byteLength(JSON.stringify(o))>E)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");m=o}const k=x(t.resolved,e.scopes,t.grantee);return{status:201,body:await B(t,{prompt:e.prompt,scopes:k,metadata:w,profile:e.profile,isolated:e.isolated,cwd:e.cwd,...m===void 0?{}:{output_schema:m},...e.message===void 0?{}:{message:e.message}},h(_))}}case"run.list":{const e=u.get("status")??void 0;if(e&&!["running","waiting_on_user","idle","settled"].includes(e))throw new n(400,"invalid_request","invalid status","status");const s=u.get("app");if(s!==null&&!/^(?:app:)?[a-z0-9][a-z0-9-]*$/.test(s))throw new n(400,"invalid_request","invalid app","app");const r=s===null?C(t):s.startsWith("app:")?s:`app:${s}`;if(r!==null&&!b(t,r))throw new n(404,"not_found","run not found");return{status:200,body:$(r,{status:e,after:u.get("after")??void 0,limit:y(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&r!==null?{visible:c(w=>b(t,r,w),"visible")}:{}})}}case"run.get":{const e=v("run.get",u),s=f(t,i),r=await z(i,s.grantee,e);return f(t,i),{status:200,body:r}}case"run.message":{const e=l(d);if(typeof e.message!="string"||!e.message.trim())throw new n(400,"invalid_request","message is required","message");if(e.start_turn!==void 0&&typeof e.start_turn!="boolean")throw new n(400,"invalid_request","start_turn must be a boolean","start_turn");return{status:202,body:await A(f(t,i,!0),e.message,void 0,e.start_turn,h(_))}}case"run.interrupt":{const e=l(d===void 0?{}:d);if(e.children!==void 0&&e.children!=="stop"&&e.children!=="continue")throw new n(400,"invalid_request","invalid children","children");return{status:200,body:await O(f(t,i,!0),e.children)}}case"run.cancel":{const e=l(d===void 0?{}:d);if(e.keep_schedules!==void 0&&typeof e.keep_schedules!="boolean")throw new n(400,"invalid_request","invalid keep_schedules","keep_schedules");return{status:200,body:await S(f(t,i,!0),{keepSchedules:e.keep_schedules})}}case"run.rename":{const e=l(d);for(const s of Object.keys(e))if(s!=="name")throw new n(400,"invalid_request",`unknown field ${s}`,s);return{status:200,body:j(f(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await N(f(t,i,!0,!0));return{status:200,body:{run_id:i,uploads_pending:e}}}case"trace.get":{const e=u.get("format")??void 0;if(e&&e!=="entries")throw new n(400,"invalid_request","unknown trace format","format");const s=f(t,i);return{status:200,body:J(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}c(I,"handleRunOperation");export{I as handleRunOperation,y as integer};
1
+ var R=Object.defineProperty;var m=(a,t)=>R(a,"name",{value:t,configurable:!0});import{callerGrant as h}from"../principal.js";import{grantVersion as g}from"../../../core/grants/mirror.js";import{waitGrantChange as S}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as b,cancelRun as $,deleteRun as N,interruptRun as O,listRuns as A,messageRun as j,renameRun as x,requestedScopes as B,startRun as J,traceRun as z,waitRun as C}from"../../../core/runs/operations.js";import{canReadRun as v,requireRun as f,runCallerApp as E}from"../router.js";import{waitSeconds as y}from"../long-poll-wait.js";import{outputSchemaProblem as K}from"../../../core/runtime/structured-output.js";function l(a){if(!a||typeof a!="object"||Array.isArray(a))throw new n(400,"invalid_request","a JSON object is required");return a}m(l,"object");function q(a,t,i,u,d){if(a===null)return d;if(!/^(0|[1-9]\d*)$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<i||Number(a)>u)throw new n(400,"invalid_request",`invalid ${t}`,t);return Number(a)}m(q,"integer");const T=256*1024;async function W(a,t,i,u,d,_){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=y("grant.get",u),s=u.get("since");if(s!==null&&!/^[A-Za-z0-9_-]{1,64}$/.test(s))throw new n(400,"invalid_request","invalid since","since");let o=h(t);return e&&s!==null&&g(o)===s&&(await S(t.grant,e),o=h(t)),{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:t.grant,rev:o.rev,resolved_scopes:o.resolved_scopes,spend_cap:o.spend_cap,exp:t.exp,payer:"user",dependencies:o.dependencies??{},version:g(o)}}}case"run.start":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=l(d),s=["mode","parent","fork_from","node_id","env","tools","system_prompt"];for(const r of s)if(e[r]!==void 0)throw new n(403,"owner_only",`${r} is owner-only`,r);const o=["payer","model","model_policy","deadline","kind"];for(const r of o)if(e[r]!==void 0)throw new n(400,"invalid_request",`${r} is not available`,r);for(const r of Object.keys(e))if(!["prompt","scopes","metadata","profile","isolated","cwd","worktree","output_schema","message"].includes(r))throw new n(400,"invalid_request",`unknown field ${r}`,r);if(e.profile!==void 0&&(typeof e.profile!="string"||!e.profile))throw new n(400,"invalid_request","profile must be a profile id","profile");if(e.isolated!==void 0&&typeof e.isolated!="boolean")throw new n(400,"invalid_request","isolated must be a boolean","isolated");if(e.cwd!==void 0&&(e.isolated!==!0||typeof e.cwd!="string"||!e.cwd))throw new n(400,"invalid_request","cwd is available only for an isolated run and must be an absolute path inside its root folder","cwd");if(e.worktree!==void 0&&e.isolated!==!0)throw new n(400,"invalid_request","worktree is not available","worktree");if(e.isolated===!0&&e.worktree!==void 0)throw new n(400,"invalid_request","worktree is unavailable for an isolated run","worktree");if(typeof e.prompt!="string"||!e.prompt.trim())throw new n(400,"invalid_request","prompt is required","prompt");if(e.message!==void 0&&(typeof e.message!="string"||!e.message.trim()))throw new n(400,"invalid_request","message must be a non-empty string","message");const c=e.metadata===void 0?{}:l(e.metadata);if(Buffer.byteLength(JSON.stringify(c))>4096)throw new n(400,"invalid_request","metadata exceeds 4 KB","metadata");let w;if(e.output_schema!==void 0){const r=e.output_schema;if(!r||typeof r!="object"||Array.isArray(r))throw new n(400,"invalid_request","output_schema must be a JSON Schema object","output_schema");if(Buffer.byteLength(JSON.stringify(r))>T)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");const p=await K(r);if(p!==null)throw new n(400,"invalid_request",`output_schema is not usable: ${p}`,"output_schema");w=r}const k=B(t.resolved,e.scopes,t.grantee);return{status:201,body:await J(t,{prompt:e.prompt,scopes:k,metadata:c,profile:e.profile,isolated:e.isolated,cwd:e.cwd,...w===void 0?{}:{output_schema:w},...e.message===void 0?{}:{message:e.message}},b(_))}}case"run.list":{const e=u.get("status")??void 0;if(e&&!["running","waiting_on_user","idle","settled"].includes(e))throw new n(400,"invalid_request","invalid status","status");const s=u.get("app");if(s!==null&&!/^(?:app:)?[a-z0-9][a-z0-9-]*$/.test(s))throw new n(400,"invalid_request","invalid app","app");const o=s===null?E(t):s.startsWith("app:")?s:`app:${s}`;if(o!==null&&!v(t,o))throw new n(404,"not_found","run not found");return{status:200,body:A(o,{status:e,after:u.get("after")??void 0,limit:q(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&o!==null?{visible:m(c=>v(t,o,c),"visible")}:{}})}}case"run.get":{const e=y("run.get",u),s=f(t,i),o=await C(i,s.grantee,e);return f(t,i),{status:200,body:o}}case"run.message":{const e=l(d);if(typeof e.message!="string"||!e.message.trim())throw new n(400,"invalid_request","message is required","message");if(e.start_turn!==void 0&&typeof e.start_turn!="boolean")throw new n(400,"invalid_request","start_turn must be a boolean","start_turn");return{status:202,body:await j(f(t,i,!0),e.message,void 0,e.start_turn,b(_))}}case"run.interrupt":{const e=l(d===void 0?{}:d);if(e.children!==void 0&&e.children!=="stop"&&e.children!=="continue")throw new n(400,"invalid_request","invalid children","children");return{status:200,body:await O(f(t,i,!0),e.children)}}case"run.cancel":{const e=l(d===void 0?{}:d);if(e.keep_schedules!==void 0&&typeof e.keep_schedules!="boolean")throw new n(400,"invalid_request","invalid keep_schedules","keep_schedules");return{status:200,body:await $(f(t,i,!0),{keepSchedules:e.keep_schedules})}}case"run.rename":{const e=l(d);for(const s of Object.keys(e))if(s!=="name")throw new n(400,"invalid_request",`unknown field ${s}`,s);return{status:200,body:x(f(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await N(f(t,i,!0,!0));return{status:200,body:{run_id:i,uploads_pending:e}}}case"trace.get":{const e=u.get("format")??void 0;if(e&&e!=="entries")throw new n(400,"invalid_request","unknown trace format","format");const s=f(t,i);return{status:200,body:z(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}m(W,"handleRunOperation");export{W as handleRunOperation,q as integer};