@north-light/cli 0.3.747 → 0.3.749
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/objects.d.ts +6 -1
- package/dist/api/dto/plugins.d.ts +2 -0
- package/dist/clients/attach/chrome/canvas-panels.d.ts +2 -0
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.d.ts +2 -0
- package/dist/clients/attach/chrome/roster.js +5 -5
- package/dist/clients/attach/chrome/run-facts.d.ts +12 -0
- package/dist/clients/attach/chrome/run-facts.js +1 -0
- package/dist/clients/attach/chrome/widgets.d.ts +3 -1
- package/dist/clients/attach/chrome/widgets.js +1 -1
- package/dist/clients/attach/viewer.js +487 -487
- package/dist/commands/canvas/list.js +2 -2
- package/dist/commands/canvas/read.js +4 -4
- package/dist/commands/canvas/search.js +1 -1
- package/dist/core/canvas/canvas.js +16 -16
- package/dist/core/canvas/schema-pg/035-environment-payer.sql +2 -0
- package/dist/core/canvas/schema-pg/036-ledger-holder-app-path.sql +13 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command-manifests/registry.d.ts +2 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.d.ts +11 -0
- package/dist/core/command.js +9 -9
- package/dist/core/environments.d.ts +2 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/grants/mirror.d.ts +4 -0
- package/dist/core/grants/mirror.js +8 -6
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/reader.js +1 -1
- package/dist/core/ledger/environment-payer.d.ts +2 -0
- package/dist/core/ledger/environment-payer.js +1 -0
- package/dist/core/ledger/index.d.ts +1 -0
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/payer.d.ts +4 -1
- package/dist/core/ledger/payer.js +1 -1
- package/dist/core/llm/run.d.ts +1 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/peer/envelope.js +1 -1
- package/dist/core/peer/stubs.js +1 -1
- package/dist/core/permissions/ceiling.js +10 -10
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runs/node-sub.d.ts +2 -0
- package/dist/core/runs/node-sub.js +1 -0
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/recap.js +6 -6
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/start-check.d.ts +1 -0
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/spaces/process.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/api/handlers/hook-exec.js +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/providers.d.ts +2 -0
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/peer/authority.d.ts +1 -1
- package/dist/daemon/peer/authority.js +1 -1
- package/package.json +4 -4
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +19 -1
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +1 -0
- package/packages/crouter-api/dist/clients/attach/chrome/run-facts.js +76 -0
- package/packages/crouter-api/dist/clients/attach/chrome/widgets.js +14 -5
- package/packages/crouter-api/dist/clients/attach/viewer.js +7 -1
- package/packages/crouter-api/dist/commands/canvas/list.js +3 -1
- package/packages/crouter-api/dist/commands/canvas/read.js +4 -2
- package/packages/crouter-api/dist/commands/canvas/search.js +3 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +2 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -3
- package/packages/crouter-api/dist/core/command.js +34 -1
- package/packages/crouter-api/dist/core/environments.js +2 -2
- package/packages/crouter-api/dist/core/grants/mirror.js +16 -1
- package/packages/crouter-api/dist/core/grants/on-sync.js +2 -2
- package/packages/crouter-api/dist/core/graph/reader.js +1 -1
- package/packages/crouter-api/dist/core/ledger/environment-payer.js +15 -0
- package/packages/crouter-api/dist/core/ledger/index.js +1 -0
- package/packages/crouter-api/dist/core/ledger/payer.js +4 -0
- package/packages/crouter-api/dist/core/llm/run.js +2 -1
- package/packages/crouter-api/dist/core/peer/envelope.js +2 -1
- package/packages/crouter-api/dist/core/peer/stubs.js +5 -1
- package/packages/crouter-api/dist/core/permissions/ceiling.js +4 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +16 -5
- package/packages/crouter-api/dist/core/providers/call.js +2 -2
- package/packages/crouter-api/dist/core/runs/node-sub.js +10 -0
- package/packages/crouter-api/dist/core/runtime/host.js +2 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
- package/packages/crouter-api/dist/core/runtime/warm-pool.js +1 -1
- package/packages/crouter-api/dist/core/spaces/process.js +5 -4
- package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +1 -1
- package/packages/crouter-api/dist/daemon/api/handlers/providers.js +5 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/dist/index.d.ts +8 -0
- package/packages/crouter-identity/dist/index.js +18 -0
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/lib/install-source.mjs +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var u=(e,r)=>$(e,"name",{value:r,configurable:!0});import{existsSync as
|
|
1
|
+
var $=Object.defineProperty;var u=(e,r)=>$(e,"name",{value:r,configurable:!0});import{existsSync as _}from"node:fs";import{assertGranteeRunsHere as N}from"../runtime/unsandboxed.js";import{randomUUID as O}from"node:crypto";import{join as h}from"node:path";import{getNode as R}from"../canvas/canvas.js";import{nodeAgentDir as k,nodeHome as H,nodeRunDir as K}from"../canvas/paths.js";import{appSpace as B}from"../layout.js";import{activeGrant as g,activeGrantForApp as S,grantFor as I,grantsGeneration as y}from"../grants/mirror.js";import{emitEvent as G}from"../events/emit.js";import{ensureAppSpace as F}from"./space.js";import{compileLaunch as A,launchStillGranted as M}from"./mounts.js";import{pinSandboxRuntimeHome as j}from"./runtime-home.js";import{sandboxCacheEnv as q}from"./cache-env.js";import{launcherRequest as b}from"../../launcher/client.js";import{LAUNCHER_SOCKET as D}from"../../launcher/spec.js";import{isCloudRole as U}from"../canvas/person.js";import{launchSub as E}from"../runs/node-sub.js";function W(e){return`cron-${e}`}u(W,"cronLaunchId");function le(){if(process.platform!=="linux")return!1;if(_(D))return!0;throw new Error("root launcher socket is unavailable; refusing an unsandboxed app process")}u(le,"appProcessSandboxed");function me(){return L??(process.platform==="linux"&&_(D))}u(me,"appProcessesSandboxed");let L;function pe(e){L=e}u(pe,"__setAppProcessesSandboxedForTest");async function we(e,r,n,a=!1,o,d){const t=n===void 0?null:await R(n),s=d!==void 0?d.grantId?await g(d.grantId):await I(e,d.sub):t?null:await S(e);if((d!==void 0||!t)&&!s)throw new Error(`no active grant for ${e}`);return(await A({nodeId:n??"proc-cwd-check",app:e,...d!==void 0?{sub:d.sub,grantId:s?.id??null,scopes:d.scopes}:{sub:t?E(t.sub,t.node_id):s.sub,grantId:t?t.grant_id??null:s.id,scopes:t?.scopes??null},command:["true"],env:{},...n===void 0?{withoutNode:!0}:{},...o===void 0?{}:{folder:o},isolated:t?.isolated===!0||a,auditMissing:u(()=>{},"auditMissing")})).mounts.some(({source:c})=>r===c||r.startsWith(c==="/"?"/":`${c}/`))}u(we,"cwdIsMounted");async function P(e,r="SIGKILL",n){if(!("ok"in await b({operation:"stop",pid:e,signal:r,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}u(P,"stopAppProcess");function z(e,r,n,a,o){return a?o??k(e,r):n}u(z,"appProcessCwd");async function he(e){if(U())throw new Error("a cloud role launches no app process; the node runs in its sandbox");if(e.cron!==void 0&&(e.nodeId!==void 0||e.principal===void 0))throw new Error("a cron launch has a stored principal and no node");const r=e.nodeId===void 0?null:await R(e.nodeId);if(e.nodeId!==void 0&&!r)throw new Error(`missing node ${e.nodeId}`);const n=r?.grantee??e.app??"app:terminal";if(N(n),e.app!==void 0&&e.app!==n)throw new Error("app does not match node");const a=e.principal;let o=null;if(a!==void 0){if(o=a.grantId?await g(a.grantId):await I(n,a.sub),!o||o.grantee!==n||o.sub!==a.sub)throw new Error(`no active grant for ${n}`)}else if(r){if(n!=="app:terminal"&&!(r.grant_id?await g(r.grant_id):await I(n,E(r.sub,r.node_id))))throw new Error(`no active grant for ${n}`)}else if(o=await S(n),!o)throw new Error(`no active grant for ${n}`);await F(n);const d=e.cron===void 0?e.nodeId??`proc-${O()}`:W(e.cron.executionId),t=r?.isolated===!0||e.isolated===!0;if(t&&!r&&e.folder===void 0)throw new Error("isolated process requires a live node");const s=B(n),m=z(d,n,e.cwd,t,e.folder),c=r?H(d,n,t):t&&e.folder!==void 0?h(e.folder,"home"):s.home,C=j(Object.fromEntries(Object.entries({...e.env,...process.platform==="linux"?q(n):{},HOME:c,PI_CODING_AGENT_DIR:h(c,".pi","agent"),PWD:m,...e.nodeId===void 0&&e.cron===void 0?{}:{CRTR_API_SOCKET:h(K(d),"cli.sock")}}).filter(i=>i[1]!==void 0))),x=a!==void 0?{nodeId:d,app:n,sub:a.sub,grantId:o?.id??null,scopes:a.scopes}:{nodeId:d,app:n,sub:r?E(r.sub,r.node_id):o.sub,grantId:r?r.grant_id??null:o.id,scopes:r?.scopes??null},T=u(async()=>{const i=await A({...x,command:e.command,env:C,...e.nodeId===void 0?{withoutNode:!0}:{},isolated:t,cwd:m,...e.folder===void 0?{}:{folder:e.folder},...e.cron===void 0?{}:{cron:e.cron.anchorDir===void 0?{}:{anchorDir:e.cron.anchorDir}},...e.pluginRoot===void 0?{}:{pluginRoot:e.pluginRoot},auditMissing:u(w=>G({level:"warn",event:"process.mount.missing",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{source:w}}),"auditMissing")});if(e.pluginRoot!==void 0&&(i.pluginRoot=e.pluginRoot),e.capture===!1){if(e.nodeId===void 0||e.stdin!==void 0)throw new Error("uncaptured process requires a node and no stdin")}else i.capture={stdoutBytes:e.stdoutBytes??256*1024,stderrBytes:e.stderrBytes??256*1024,...e.stderrTail?{stderrTail:!0}:{},...e.stdin===void 0?{}:{stdin:e.stdin}};return i},"compile");let f;for(let i=0;i<2&&f===void 0;i++){const w=await y(),v=await T(),l=await b({operation:"launch",spec:v});if(!("pid"in l))throw new Error("launcher did not return a process id");if(await y()===w||await M(x,v)){f=l.pid;break}G({level:"info",event:"process.launch.regranted",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{pid:l.pid}}),await P(l.pid,"SIGKILL").catch(()=>{})}if(f===void 0)throw new Error("grant changed during every launch attempt");const p=f;return{pid:p,get completion(){return b({operation:"wait",pid:p}).then(i=>{if(!("result"in i))throw new Error("launcher did not return process completion");return i.result})},stop:u((i="SIGKILL")=>P(p,i,e.cron===void 0?e.nodeId:d),"stop")}}u(he,"launchAppProcess");export{pe as __setAppProcessesSandboxedForTest,z as appProcessCwd,le as appProcessSandboxed,me as appProcessesSandboxed,W as cronLaunchId,we as cwdIsMounted,he as launchAppProcess,P as stopAppProcess};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var M=Object.defineProperty;var
|
|
1
|
+
var M=Object.defineProperty;var m=(e,t)=>M(e,"name",{value:t,configurable:!0});import{queueJobStop as C}from"../../cron/machine-fire.js";import{killBashJobObject as D,recordBashJobObject as L}from"../../../core/spaces/stop.js";import{readerFor as x}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as z,appProcessSandboxed as G}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as Q}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as E}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as J}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as W}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as Y}from"../../../core/runtime/reopen.js";import{reviveNode as Z}from"../../../core/runtime/revive.js";import{checkStart as V}from"../../../core/runtime/start-check.js";import{bashJobPaths as N,isBashJobProcessGroupAlive as tt,isSafeBashJobId as O,readBashNiceness as et,signalBashJob as ot,stopBackgroundBashJob as nt}from"../../../core/bash-jobs.js";import{applyJobReport as rt,jobRow as it,ownerRunsRemotely as A,runningJobs as q,setJobDeadline as T,markJobQuietOk as at}from"../../../core/graph/jobs.js";import{withCanvasWrite as B,openDb as h}from"../../../core/canvas/db.js";import{getById as I}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as st,BASH_JOB_OUTPUT_MAX_BYTES as dt}from"../../../api/index.js";import{notFound as ut}from"../../../core/errors.js";import{freshChildNodeExecPath as pt}from"../../../core/runtime/branded-host.js";async function y(e){const t=e.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw ut(`unknown node: ${t}`,{received:t});const r=e.params.jobId;if(r!==void 0){if(!O(r))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(r)}`);return{nodeId:t,jobId:r,dir:await J(t)}}return{nodeId:t,dir:await J(t)}}m(y,"requireTarget");async function lt(e){const{nodeId:t,dir:o}=await y(e);if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const r=e.body;if(!r||typeof r!="object"||Array.isArray(r))throw new a(400,"invalid_request","job.start requires a JSON body");const i=r;await E(t,i.expected_execution_id);const n=i.job_id,s=i.cwd,u=i.env;if(typeof n!="string"||!O(n)||typeof s!="string"||!u||typeof u!="object"||Array.isArray(u)||Object.entries(u).some(([c,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const f=await S(t);if(await V({grantee:f.grantee??"app:terminal",sub:f.sub,grant_id:f.grant_id,profile_id:f.profile_id}),!G())throw new a(400,"invalid_request","job.start is only used with the root launcher");const d=N(o,n);if(!(k(d.root,d.jobRun)||k(d.root,d.jobBg))||![d.cmdSh,d.jobLog].every(c=>k(d.root,c)))throw new a(404,"job_not_found","job was not prepared by this node");const l=H(d.dir,"job.starting");try{$(d.root,l,"")}catch(c){throw c.code==="EEXIST"?new a(409,"job_already_started","job was already started"):c}let b;try{const c=u,p=X("bash",c,s),g=await S(t),j=await pt();return b=await z({nodeId:t,app:g.grantee??"app:terminal",isolated:g.isolated,cwd:s,env:c,capture:!1,command:[p,"-c",Q,"--",d.cmdSh,d.jobLog,d.jobExit,d.jobRun,d.jobDone,p,String(et(o)),j,d.jobActivity]}),$(d.root,d.jobPgid,String(b.pid),384),$(d.root,d.jobPgidIdentity,`launcher:${b.pid}`,384),{status:201,body:{pid:b.pid}}}catch(c){if(b!==void 0)try{await b.stop()}catch(p){throw new AggregateError([c,p],`job ${n} launched but could not be recorded or stopped`)}try{U(d.root,l)}catch(p){if(p.code!=="ENOENT")throw p}throw c}}m(lt,"handleStart");async function ct(e){const{nodeId:t}=await y(e),o=Date.now(),r=await A(await h(),t);return{status:200,body:(await q(await h(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,o-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!r&&n.pgid!==null&&n.pgidIdentity!==null&&tt(n.pgid,n.pgidIdentity)}))}}m(ct,"handleList");function R(e,t,o){const r=e.query.get(t);if(r===null)return;const i=Number(r);if(!/^[0-9]+$/.test(r)||!Number.isSafeInteger(i)||i<1||i>o)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${o}`);return i}m(R,"boundedQueryInt");async function bt(e){const{nodeId:t,jobId:o}=await y(e),r=R(e,"tail_lines",Number.MAX_SAFE_INTEGER),i=R(e,"max_bytes",dt)??st,n=await h(),s=await I(n,o??"");if(s===null||s.type!=="job"||s.owner!==t||s.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(o)} for ${t}`);const u=await it(n,s);if(u===null)throw new Error(`job object ${s.id} has no jobs row`);const f=await P(),d=await f.list(`${u.output_key}/`),v=[];let l=0,b=0,c=d.length;for(;c>0&&l<=i&&(r===void 0||b<=r+1);){const w=d[--c],_=await f.get(w);if(_===null)throw new Error(`job ${s.id} output chunk ${w} is listed but cannot be read`);v.unshift(_),l+=_.length;for(const F of _)F===10&&b++}let p=Buffer.concat(v),g=c>0;if(p.length>i){p=p.subarray(p.length-i);let w=0;for(;w<p.length&&(p[w]&192)===128;)w++;p=p.subarray(w),g=!0}let j=p.toString("utf8");if(r!==void 0){const w=j.split(`
|
|
2
2
|
`),_=w[w.length-1]===""?r+1:r;w.length>_&&(j=w.slice(w.length-_).join(`
|
|
3
|
-
`),g=!0)}return{status:200,body:{job_id:s.id,output:j,truncated:g}}}
|
|
3
|
+
`),g=!0)}return{status:200,body:{job_id:s.id,output:j,truncated:g}}}m(bt,"handleOutput");async function wt(e){const{nodeId:t,jobId:o,dir:r}=await y(e);if(o===void 0)throw new a(400,"invalid_request","a job id is required");if(e.query.get("foreground")==="1"){if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await E(t,e.body?.expected_execution_id);const l=await nt(r,o,!0,t);if(l.kind==="missing")throw new a(404,"job_not_found",`no job ${o} for ${t}`);if(l.kind==="retired")throw new a(404,"job_not_found",`job ${o} for ${t} is no longer running`);if(l.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${o} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:o,signaled:l.signaled}}}const n=(await q(await h(),t)).find(l=>l.jobId===o);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${o} for ${t}`);const s=await A(await h(),t);if(!s&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${o} reported no trusted process identity`);await Y(t);const u=s?!0:await ot(n.pgid,n.pgidIdentity,t);await D(o,async l=>{const b=await x(l,e);return b.class==="person"?b.person:b.class==="app"?b.app:b.node});let f;if(s)try{await C(t,o)}catch(l){f=l instanceof Error?l.message:String(l)}const d=await S(t);if(d!==null&&!W(d))try{await Z(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:o,signaled:u,...s?{stop_pending_on_machine:!0}:{},...f===void 0?{}:{stop_queue_error:f}}}}m(wt,"handleStop");async function ft(e){const{nodeId:t,jobId:o,dir:r}=await y(e);if(o===void 0)throw new a(400,"invalid_request","a job id is required");if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const i=e.body,n=N(r,o),s=i?.purpose,u=i?.deadline_at_ms;if(typeof i?.command!="string"||s!=null&&typeof s!="string"||u!=null&&!Number.isFinite(u))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!await A(await h(),t)&&!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${o} of ${t} is not backgrounded`);return{status:201,body:{id:(await L(t,o,{command:i.command,purpose:s??null,deadlineAtMs:u??null})).id}}}m(ft,"handleBackground");async function mt(e,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const o=await I(await h(),t);if(o===null||o.type!=="job"||o.owner!==e)throw new a(404,"job_not_found",`no job ${t} for ${e}`);if(!(await q(await h(),e)).some(r=>r.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${e} is no longer running`);return t}m(mt,"requireRunningJob");async function ht(e,t,o){const r=await I(await h(),t);if(r===null||r.type!=="job"||r.owner!==e)throw new a(404,"job_not_found",`no job ${String(t)} for ${e}`);if(!(await q(await h(),e)).some(s=>s.jobId===t))throw new a(409,"job_not_running",`job ${String(t)} for ${e} is no longer running`);const i=o.output;if(i!==void 0){if(!Number.isSafeInteger(i.seq)||i.seq<0||typeof i.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const s=await B(async u=>await u.prepare("SELECT output_key FROM jobs WHERE object = ?").get(t));await(await P()).put(`${s.output_key}/${String(i.seq).padStart(8,"0")}`,Buffer.from(i.data_base64,"base64"))}const n=o.activity;if(n!==void 0&&(!Number.isFinite(n.last_ms)||!Number.isFinite(n.sampled_ms)||!Array.isArray(n.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");await B(async s=>rt(s,t,{...typeof o.pgid=="number"?{pgid:o.pgid}:{},...typeof o.pgid_identity=="string"?{pgidIdentity:o.pgid_identity}:{},...typeof o.exit_code=="number"?{exitCode:o.exit_code}:{},...o.vanished===!0?{vanished:!0}:{},...n===void 0?{}:{activity:{lastActivityMs:n.last_ms,sampledAtMs:n.sampled_ms,files:n.files}}}))}m(ht,"storeJobReport");async function _t(e){const{nodeId:t,jobId:o}=await y(e);if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const r=e.body;if(!r||typeof r!="object"||Array.isArray(r))throw new a(400,"invalid_request","job.report requires a JSON body");return await E(t,r.expected_execution_id),await ht(t,o??"",r),{status:204}}m(_t,"handleReport");async function yt(e){const{nodeId:t,jobId:o}=await y(e),r=await mt(t,o),i=e.body,n=i?.deadline_at_ms,s=i?.keep===!0;if(i?.quiet_ok!==!0&&!s&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(s&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await B(async u=>{i?.quiet_ok===!0&&await at(u,r),s?await T(u,r,null):Number.isFinite(n)&&await T(u,r,n)}),{status:204}}m(yt,"handlePatch");const Qt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:_t},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:ct},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:bt},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:wt}];export{Qt as bashJobRoutes,ht as storeJobReport};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var
|
|
1
|
+
var x=Object.defineProperty;var p=(o,n)=>x(o,"name",{value:n,configurable:!0});import{realpathSync as E}from"node:fs";import{isAbsolute as y,relative as _,sep as h}from"node:path";import{ApiError as r}from"../../../api/index.js";import{coreHookCatalog as P}from"../../../build-root.js";import{getNode as T}from"../../../core/canvas/canvas.js";import{isSafeNodeId as A,nodeAgentDir as O}from"../../../core/canvas/paths.js";import{discoverHookRegistry as S}from"../../../core/command-hooks/discovery.js";import{EXEC_HOOK_TIMEOUT_MS as I}from"../../../core/command-hooks/transport/exec-invoke.js";import{buildAppProcessEnv as H}from"../../../core/runtime/spawn-env-rows.js";import{compileLaunch as N}from"../../../core/spaces/mounts.js";import{appProcessSandboxed as M,launchAppProcess as R}from"../../../core/spaces/process.js";import{requireCurrentExecution as B}from"./broker-recovery.js";import{actsAsPerson as C}from"../router.js";import{launchSub as W}from"../../../core/runs/node-sub.js";async function k(o,n,i){const t=o.params.id;if(t===void 0?!C(o.principal):!A(t)||o.principal.class!=="broker"||o.principal.node!==t)throw new r(403,"permission_error","hook execution requires its current node, or the person for the global route");const e=t===void 0?null:await T(t);if(t!==void 0&&!e)throw new r(404,"not_found","node not found");if(t!==void 0&&await B(t,n),typeof i!="string"||!y(i))throw new r(400,"invalid_request","hook cwd must be absolute");if(!M())throw new r(400,"invalid_request","hook routes require the root launcher");let d;try{d=E(i)}catch(u){throw u.code==="ENOENT"?new r(400,"invalid_request","hook cwd does not exist"):u}if(e){if(e.isolated===!0){const a=O(t,e.grantee??"app:terminal"),s=_(a,d);if(s===".."||s.startsWith(`..${h}`)||s.startsWith(h))throw new r(403,"permission_error","hook cwd is outside the isolated node folder")}const u=await N({nodeId:t,app:o.principal.class==="broker"?o.principal.app:"app:terminal",sub:W(e.sub,t),grantId:e.grant_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,command:[],env:{},auditMissing:p(()=>{},"auditMissing")}),f=p(a=>{const s=_(a,d);return s===""||s!==".."&&!s.startsWith(`..${h}`)&&!y(s)},"within");if(!u.mounts.some(a=>f(a.source)))throw new r(403,"permission_error","hook cwd is outside the node mounts")}return{id:t,node:e,cwd:d,app:e&&o.principal.class==="broker"?o.principal.app:"app:terminal"}}p(k,"checkedContext");async function b(o,n){const i=S(await P(),o,n);if(!i.valid)throw new r(422,"hook_registry_invalid","the effective hook registry is invalid");return i}p(b,"currentRegistry");async function $(o){const{node:n,cwd:i}=await k(o,o.query.get("expected_execution_id"),o.query.get("cwd"));return{status:200,body:{hooks:(await b(i,n.profile_id??null)).hooks.filter(e=>e.plugin.scope==="user").map(e=>({id:e.id,plugin:e.plugin.name,target:e.target,phase:e.phase,op:e.op,description:e.description,effects:e.effects,declarationIndex:e.declarationIndex}))}}}p($,"handleHookPlan");async function v(o){const n=o.body;if(!n||typeof n!="object"||Array.isArray(n))throw new r(400,"invalid_request","hook execution requires a JSON body");const i=n,{id:t,node:e,cwd:d,app:u}=await k(o,i.expected_execution_id,i.cwd);if(typeof i.hook_id!="string"||typeof i.request!="string")throw new r(400,"invalid_request","hook execution requires hook_id and request");const a=(await b(d,e?.profile_id??null)).hooks.find(c=>c.id===i.hook_id);if(!a)throw new r(404,"hook_not_registered","hook id is not registered for this cwd");const s=await H(d,e?.profile_id??null,u),m=await R({...t===void 0?{}:{nodeId:t},app:u,command:[a.executable,"--crtr-hook-protocol","1"],cwd:d,pluginRoot:a.plugin.root,env:s,stdin:i.request,stdoutBytes:10*1024*1024,stderrBytes:64*1024});let l,w=!1;try{const c=await Promise.race([m.completion,new Promise((D,g)=>{l=setTimeout(()=>{w=!0,m.stop().then(()=>g(new r(504,"hook_timeout","hook executable timed out")),q=>g(q))},I)})]);if(w)throw new r(504,"hook_timeout","hook executable timed out");if(c.stdoutTruncated)throw new r(502,"hook_output_limit","hook stdout exceeded the 10 MiB cap");return{status:200,body:{stdout:c.stdout,status:c.exitCode,signal:c.signal}}}finally{l&&clearTimeout(l)}}p(v,"handleHookExec");const te=[{method:"GET",pattern:"/v1/nodes/:id/hooks/plan",handler:$},{method:"POST",pattern:"/v1/nodes/:id/hooks/exec",handler:v},{method:"POST",pattern:"/v1/hooks/exec",handler:v}];export{te as hookExecRoutes};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var R=Object.defineProperty;var d=(t,e)=>R(t,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as T}from"../../../core/llm/body-limits.js";import{llmCallerOf as k,parseLlmRequest as
|
|
2
|
-
`)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,l,await
|
|
3
|
-
`),{status:200}}const u=E(r.details,
|
|
1
|
+
var R=Object.defineProperty;var d=(t,e)=>R(t,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as T}from"../../../core/llm/body-limits.js";import{environmentPayerOfNode as x}from"../../../core/ledger/index.js";import{llmCallerOf as k,parseLlmRequest as I,runLlm as N}from"../../../core/llm/run.js";import{RunError as i}from"../../../core/runs/operations.js";import{errorCodes as P}from"../../../api/error-codes.js";import{getNode as $}from"../../../core/canvas/canvas.js";import{emitEvent as G}from"../../../core/events/emit.js";import{boundedCause as H}from"../map.js";import{socketPrincipal as c}from"../server.js";import{activeGrant as L,activeGrantForApp as A,grantFor as M,grantsSource as S,payerOfGrant as j}from"../../../core/grants/mirror.js";import{parseUsageMonth as B,usageFor as C}from"../../../core/ledger/index.js";import{admit as D}from"../../../core/llm/breaker.js";function E(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:n,...a}=t;return a}d(E,"operatorDetails");const F="app:terminal";async function O(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run,environmentPayer:await x(t.node)};if(t?.class==="app"){const n=await S();if(n===null||n==="local")return{grantee:t.app};let a;try{a=await A(t.app)}catch{throw new i(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!a)throw new i(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:a.sub}}return{grantee:F}}d(O,"spendTarget");async function U(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await L(t.grant):await M(t.app,t.sub);if(!e&&await j(t.grant)==="app")throw new i(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return k(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await S();return e===null||e==="local"?void 0:k(await A(t.app))}}d(U,"llmCaller");function q(t){const e=P[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}d(q,"errorType");function J(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const n=t.details?.payment;return n===void 0?{}:{payment:n}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}d(J,"capFields");const se=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:T,handler:d(async({body:t,res:e,req:n,causedBy:a})=>{const f=v();e.setHeader("Request-Id",f);const p=new AbortController,h=d(()=>p.abort(),"abort");e.on("close",h);let g,b,y="none",w=!1;try{const o=I(t),s=o.model===void 0?void 0:D(o.model);if(typeof s=="number")return e.setHeader("Retry-After",String(s)),{status:503,body:{error:{code:"upstream_model_unavailable",message:`${o.model} is unavailable: the gateway's breaker is open`,details:{breaker:"open"},type:"server_error",origin:"runtime",retryable:!0,request_id:f}}};b=s;const r=c(n),u=r?.class==="broker"?await $(r.node):null;if(r?.class==="broker"&&!u)throw new i(401,"unauthorized","node not found");const l={...await O(r,u??void 0),request:f};w=!0;const _=await N(o,p.signal,o.stream?m=>{typeof m.served_model=="string"&&(g=m.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(m)}
|
|
2
|
+
`)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,l,await U(r),a);return y=p.signal.aborted?"none":"ok",o.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:_.completion}}catch(o){o instanceof i||G({event:"api.request.failed",level:"error",error:o instanceof Error?o:new Error(String(o)),...c(n)?.class==="broker"?{node_id:c(n).node}:{},fields:{method:"POST",path:"/v1/llm"}});const s=o instanceof i?o:new i(503,"upstream_model_unavailable",H(o));w&&s.code==="upstream_model_unavailable"&&!p.signal.aborted&&(y="fail");const r=y==="fail"&&b?.test?new i(503,s.code,s.message,s.param,{...s.details,breaker:"test"}):s;if(e.headersSent){const _=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:{},m=E(g!==void 0&&typeof _.served_model!="string"?{..._,served_model:g}:r.details,c(n)?.class);return e.end(`${JSON.stringify({error:{code:r.code,message:r.message,...m===void 0?{}:{details:m},type:"server_error",origin:"runtime",retryable:r.retryable,request_id:f}})}
|
|
3
|
+
`),{status:200}}const u=E(r.details,c(n)?.class),l=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return l!==void 0&&e.setHeader("Retry-After",String(l)),{status:r.status,body:{error:{code:r.code,message:r.message,...u===void 0?{}:{details:u},type:q(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:f,...l!==void 0?{retry_after_s:l}:{},...J(r)}}}}finally{e.off("close",h),b?.settle(y)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:d(async({req:t})=>{const e=v(),n={"Request-Id":e};try{const a=await O(c(t));return{status:200,headers:n,body:await C(a.grantee,B(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof i))throw a;return{status:a.status,headers:n,body:{error:{code:a.code,message:a.message,type:q(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{J as capFields,se as llmRoutes,O as spendTarget};
|
|
@@ -43,6 +43,8 @@ export interface ProviderCallInput {
|
|
|
43
43
|
approval?: string;
|
|
44
44
|
/** Which device machine takes the call (a `machine_id`, `runtime:` prefix optional); only a provider served by a machine accepts it. */
|
|
45
45
|
machine?: string;
|
|
46
|
+
/** The principal the call acts for (`--as`): carried through, not yet resolved. */
|
|
47
|
+
as?: string;
|
|
46
48
|
}
|
|
47
49
|
export declare function parseProvider(value: unknown): string;
|
|
48
50
|
export declare function parseCallInput(body: unknown): ProviderCallInput;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{
|
|
1
|
+
var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{parsePrincipal as G}from"@north-light/identity";import{randomUUID as N}from"node:crypto";import{cloudPersonScope as T}from"../../../core/runs/operations.js";import{directoryIssuer as F}from"../../../core/directory/issuer.js";import{activeGrantForApp as k,grantFor as x,grantsOfPerson as C,localGrants as j,providerIdsFromGrants as S}from"../../../core/grants/mirror.js";import{getNode as B}from"../../../core/canvas/canvas.js";import{scopeAllowed as D}from"../../../core/scopes.js";import{ProviderError as f,providerErrorBody as M,scopeMissing as U}from"../../../core/providers/errors.js";import{callProvider as z,providerTools as L}from"../../../core/providers/call.js";import{providerInstallState as V}from"../../../core/providers/bundles.js";import{installedProviderPlugins as Z,providerRootClaims as W,resolveProviderRef as J}from"../../../core/providers/roots.js";import{isCloudRole as h}from"../../../core/canvas/person-state.js";import{listAudit as X,writeProviderAudit as H}from"../../../core/providers/audit.js";import{emitEvent as P}from"../../../core/events/emit.js";import{resolvedScopes as _}from"../router.js";const Re=new Set(["provider.tools","provider.call","audit.list"]);async function K(e){if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null,origin:{node:null,run:null,machine:e.via}};const r=await x(e.actor.app,e.sub);if(!r)throw new f("grant_revoked",`app ${e.actor.app} has no active grant`);return{class:"app",sub:e.sub,grantee:e.actor.app,client_id:null,resolved:r.resolved,nodeScopes:e.actor.node_scopes,run_id:null,node_id:null,origin:{node:e.actor.node,run:e.actor.place?.run??null,machine:e.via}}}if(e.class==="machine"||e.class==="import")throw new f("permission_error","this operation is not available to the caller");if(e.class==="person"&&e.sub!==void 0){if(!h())throw new f("permission_error","provider calls are made by the install's person, a node or an app");return{class:"person",sub:e.sub,grantee:null,client_id:null,resolved:await _(e),nodeScopes:null,run_id:null,node_id:null}}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=await k(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:await _(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:await _(e),nodeScopes:e.scopes,run_id:e.run??(await B(e.node))?.run_id??null,node_id:e.node}}s(K,"callerFromRequest");function Ie(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(Ie,"callerFromApp");const Q=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function Y(e){const r=Q.exec(e);return r!==null&&r[1]!=="crtr"}s(Y,"isProviderScope");const A=new WeakMap;function ee(e){let r=A.get(e);return r===void 0&&(r=new Set(e),A.set(e,r)),r}s(ee,"heldSet");function E(e,r){return e===null?!0:Y(r)?ee(e).has(r):D(e,r)}s(E,"holds");function R(e,r){return e.class==="person"&&e.resolved===null?!0:E(e.resolved??[],r)&&E(e.nodeScopes,r)}s(R,"callerAllows");function Oe(e,r,n){const o=`${r}:${n}`;if(!R(e,o))throw U(o)}s(Oe,"requireGroup");function re(){return!!F()}s(re,"providerOperationsEnabled");const oe=/^[A-Za-z0-9_-]{1,64}$/;function p(e,r){return new f("invalid_request",e,{param:r})}s(p,"invalid");function I(e){if(typeof e!="string"||!oe.test(e)||e==="crtr")throw p("provider must be a provider id","provider");return e}s(I,"parseProvider");function te(e){if(!e||typeof e!="object"||Array.isArray(e))throw new f("invalid_request","a JSON object is required");const r=e,n=I(r.provider),o=r.tool;if(typeof o!="string"||!o.trim())throw p("tool must be a non-empty string","tool");const d=r.arguments??{};if(!d||typeof d!="object"||Array.isArray(d))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 u=r.approval;if(u!==void 0&&(typeof u!="string"||!u))throw p("approval must be a question id","approval");const l=r.machine;if(l!==void 0&&(typeof l!="string"||!l.trim()))throw p("machine must be a machine id","machine");const i=r.as;if(i!==void 0&&(typeof i!="string"||G(i)===null))throw p("as must be a principal like user:<id> or app:<id>/<path>","as");return{provider:n,tool:o.trim(),arguments:d,...a===void 0?{}:{version:a},...u===void 0?{}:{approval:u},...l===void 0?{}:{machine:l.trim()},...i===void 0?{}:{as:i}}}s(te,"parseCallInput");async function ne(e,r=new URLSearchParams){const n=s((i,v,b)=>{const m=r.get(i);if(m===null)return v;if(!/^\d+$/.test(m)||Number(m)>b||Number(m)<1)throw p(`invalid ${i}`,i);return Number(m)},"numeric"),o=r.has("after")?n("after",0,Number.MAX_SAFE_INTEGER):void 0,d=n("limit",100,1e3),a=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(i=>r.has(i)).map(i=>[i,r.get(i)])),u=T(e.sub),l=u===void 0?{}:{sub:u};return{status:200,body:await X(e.class==="person"?null:e.grantee,{after:o,limit:d,...l,...a})}}s(ne,"auditList");async function se(e,r,n){let o=r;const d=performance.now(),a=Z(),{skipped:u}=W(a),l=h()?e.sub?await C(e.sub):[]:await j(),i=h()?new Set(S(l.filter(t=>t.sub===e.sub))):null,v=s(t=>!u.has(t)&&(i===null||i.has(t)),"shown"),b=new Set(a.filter(t=>t.enabled&&t.manifest.provider?.id===t.name&&v(t.name)).map(t=>t.name)),m=S(l).filter(v),g=[...new Set([...b,...m])].sort();if(o!==void 0){const t=J(o);if(t===null)throw new f("not_found",`provider "${o}" is not available`);o=t}if(o!==void 0&&!g.includes(o))throw new f("not_found",`provider "${o}" is not available`);const O=o===void 0?g:[o],$=e.class==="person"?l.flatMap(t=>t.status==="active"&&(!h()||t.sub===e.sub)?t.resolved_scopes.map(({scope:c})=>c):[]):e.resolved??[],w=await Promise.all(O.map(async t=>{if(b.has(t))return L(e,t);if(!$.some(y=>y.startsWith(`${t}:`)&&R(e,y)))return null;const c=V(t);return c===void 0?null:{provider:t,display_name:t,status:c.status,...c.error?{error:c.error}:{},groups:[],commands:[]}})).then(t=>t.filter(c=>c!==null));if(P({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-d,fields:{caller:e.class,provider:o??null,providers:w.length}}),o!==void 0){if(w.length===0)throw new f("not_found",`provider "${o}" is not available`);return{status:200,body:w[0]}}return{status:200,body:{providers:w}}}s(se,"providerTools");async function ie(e,r,n){return z(e,r,n)}s(ie,"providerCall");async function de(e,r,n,o){if(!re())throw new f("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return await ne(r,n.query);if(e==="provider.tools")return se(r,n.params.provider===void 0?void 0:I(n.params.provider),o);if(e==="provider.call"){let d;try{d=te(n.body)}catch(a){const u=n.body&&typeof n.body=="object"&&!Array.isArray(n.body)?n.body:{};throw await H({request_id:o.requestId,caller:r,provider:typeof u.provider=="string"?u.provider:"",tool:typeof u.tool=="string"?u.tool:"",outcome:`refused:${a instanceof f?a.code:"invalid_request"}`}),a}return ie(r,d,o)}throw new f("not_found","unknown operation")}s(de,"handleProviderOperation");function ae(e){const r=new AbortController,n=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",n),{signal:r.signal,release:s(()=>e.off("close",n),"release")}}s(ae,"abortOnClose");function ue(e,r,n,o){const d=M(e,r,n,o??void 0);return d.status>=500&&!(e instanceof f)&&P({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),d}s(ue,"providerFailure");const $e=[{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:n})=>({method:e,pattern:r,handler:s(async o=>{const d=N(),{signal:a,release:u}=ae(o.res);let l=null;try{return l=await K(o.principal),{...await de(n,l,{params:o.params,body:o.body,query:new URL(o.req.url??"/","http://runtime.local").searchParams},{requestId:d,signal:a,...o.causedBy===void 0?{}:{causedBy:o.causedBy}}),headers:{"Request-Id":d}}}catch(i){return ue(i,d,!1,l?.run_id)}finally{u()}},"handler")}));export{Re as PROVIDER_OPERATIONS,ae as abortOnClose,R as callerAllows,Ie as callerFromApp,K as callerFromRequest,de as handleProviderOperation,te as parseCallInput,I as parseProvider,ue as providerFailure,re as providerOperationsEnabled,$e as providerRoutes,Oe as requireGroup};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CallLink, type CallToken } from '@north-light/identity';
|
|
2
2
|
import { type GrantSync } from '../../core/grants/cover.js';
|
|
3
3
|
import { type ActiveGrant } from '../../core/grants/mirror.js';
|
|
4
4
|
import type { ForwardedPrincipal, MachinePrincipal } from '../api/router.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var c=(n,e)=>m(n,"name",{value:e,configurable:!0});import{parsePrincipal as l}from"@north-light/identity";import{decodeEnvelope as v,EnvelopeError as w}from"../../core/peer/envelope.js";import{coverGrant as g}from"../../core/grants/cover.js";import{grantFor as z}from"../../core/grants/mirror.js";import{RunError as p}from"../../core/runs/operations.js";const t=c((n,e,i)=>({status:n,code:e,message:i}),"refuse"),b="the envelope does not match its token";function q(n){return async(e,i)=>{const a=c(()=>new p(403,"app_not_granted",`${e.sub} holds no active grant for ${i} on this machine`),"notGranted");if(e.grant===void 0){const o=await z(e.sub,i);if(o===null)throw a();return o}try{return await g(e.grant,e.rev??1,i,e.sub,n)}catch(o){throw o instanceof p&&o.status===401?a():o}}}c(q,"mirrorGrantLink");async function x(n,e,i){const a=n.chain[0];if(a===void 0||!a.sub.startsWith("runtime:"))return t(401,"unauthorized","not a machine's token");if(a.sub===i.self())return t(401,"unauthorized","a machine does not call itself");if(n.scope!==void 0)return t(401,"unauthorized","a provider token does not authorize on a machine");const o=i.relation(n.sub);if(o===null)return t(403,"forbidden","no relation reaches this machine");let u;if(e!==void 0){try{u=v(e)}catch(r){return t(400,"invalid_request",r instanceof w?r.message:"invalid envelope")}if(u.act.sub!==a.sub||u.sub!==n.sub)return t(401,"unauthorized",b);if(u.act.act!==void 0&&u.act.act.place===null)return t(400,"invalid_request","the envelope names an app with no run place")}const s=u?.act.act;if(n.chain.slice(1).some(r=>l(r.sub)?.kind!=="app"))return t(401,"unauthorized","the token chain names a link that is not an app principal");const f=n.chain.slice(1).filter(r=>l(r.sub)?.kind==="app");if(f.length>1)return t(401,"unauthorized","the token names more than one app");const d=f[0];if(d!==void 0&&(s===void 0||s.sub!==d.sub))return t(401,"unauthorized",b);const h=d??(s===void 0?void 0:{sub:s.sub});if(h!==void 0)try{await i.grantLink(h,n.sub)}catch(r){if(r instanceof p)return t(r.status,r.code,r.message);throw r}return u===void 0?{principal:{class:"machine",via:a.sub,sub:n.sub}}:s!==void 0?{principal:{class:"forwarded",via:a.sub,sub:n.sub,actor:{kind:"app",app:s.sub,node:s.node,node_scopes:s.node_scopes,place:s.place}}}:o!=="owner"?t(403,"forbidden","only the owner acts as the person"):{principal:{class:"forwarded",via:a.sub,sub:n.sub,actor:{kind:"person"}}}}c(x,"peerAuthority");export{q as mirrorGrantLink,x as peerAuthority};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.749",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -109,7 +109,7 @@
|
|
|
109
109
|
"build:plugin": "tsc -p packages/crouter-plugin/tsconfig.json",
|
|
110
110
|
"typecheck": "tsc --noEmit && tsc -p src/doc-editor/tsconfig.json",
|
|
111
111
|
"typecheck:pi-packages": "npx tsc -p src/builtin-pi-packages/pi-crtr-extensions/tsconfig.json",
|
|
112
|
-
"test:runtime-packaging": "node --test scripts/runtime-smoke.test.mjs scripts/pack-args.test.mjs scripts/ensure-native-linux.test.mjs scripts/release-version.test.mjs scripts/sandbox-start.test.mjs",
|
|
112
|
+
"test:runtime-packaging": "node --test scripts/runtime-smoke.test.mjs scripts/pack-args.test.mjs scripts/ensure-native-linux.test.mjs scripts/release-version.test.mjs scripts/sandbox-start.test.mjs scripts/install-source.test.mjs",
|
|
113
113
|
"check:consumer-resolution": "node scripts/check-consumer-resolution.mjs",
|
|
114
114
|
"contract:check": "node scripts/contract.mjs check",
|
|
115
115
|
"contract:surface": "node scripts/contract.mjs generate",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.749",
|
|
162
|
+
"@north-light/plugin": "0.3.749",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.75';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -263,5 +263,23 @@ export async function buildCanvasPanelLines(nodeId, asks, palette, source, crons
|
|
|
263
263
|
line: ` ${eye} ${muted(`${summary} · ↵ details`)}${RESET}`,
|
|
264
264
|
});
|
|
265
265
|
}
|
|
266
|
-
|
|
266
|
+
// What this node itself waits on: the person first, then named children, then other waits.
|
|
267
|
+
const waits = [];
|
|
268
|
+
if ((asks[nodeId] ?? 0) > 0)
|
|
269
|
+
waits.push('you');
|
|
270
|
+
if (live.length > 0) {
|
|
271
|
+
const first = navLabel((await detail(live[0])) ?? (await node(live[0])), live[0]);
|
|
272
|
+
waits.push(live.length === 1 ? first : `${first} +${live.length - 1}`);
|
|
273
|
+
}
|
|
274
|
+
if (reviews.length > 0)
|
|
275
|
+
waits.push('review');
|
|
276
|
+
if (bashSummary !== undefined)
|
|
277
|
+
waits.push(jobs.length === 1 ? 'a bash job' : `${jobs.length} bash jobs`);
|
|
278
|
+
if (cronSummary !== undefined)
|
|
279
|
+
waits.push(crons.length === 1 ? 'a cron' : `${crons.length} crons`);
|
|
280
|
+
for (const wait of roster?.object_waits ?? [])
|
|
281
|
+
if (wait.node_id === nodeId)
|
|
282
|
+
waits.push(wait.object_name);
|
|
283
|
+
const waiting = waits.length === 0 ? undefined : waits.join(', ');
|
|
284
|
+
return { reports: items.map((item) => item.line), reportIds, items, ...(waiting === undefined ? {} : { waiting }) };
|
|
267
285
|
}
|
|
@@ -76,6 +76,7 @@ export function createRoster(s, hooks) {
|
|
|
76
76
|
const others = remote ? undefined : { crons, reviews: openReviews, jobsOf: async (id) => (await cliClient().listBashJobs(id)).map(toBashJobStatus) };
|
|
77
77
|
const built = await buildCanvasPanelLines(s.nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others, view ?? await canvasSource.panelView?.(s.nodeId));
|
|
78
78
|
items = built.items;
|
|
79
|
+
hooks.onWaiting?.(built.waiting);
|
|
79
80
|
// After an in-place swap, land on the previously open node, which has taken
|
|
80
81
|
// the swapped-to node's place in this self-excluding roster.
|
|
81
82
|
if (autoSelect !== undefined) {
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// chrome/run-facts.ts — the gray fact line above the recap: how long the agent
|
|
2
|
+
// ran since the person's last message, when it finished, and what it waits on.
|
|
3
|
+
//
|
|
4
|
+
// Run time and finish time come from message timestamps on the broker stream
|
|
5
|
+
// (the welcome snapshot, then live message events). What the node waits on comes
|
|
6
|
+
// from the roster refresh, which already reads asks, children, reviews, jobs,
|
|
7
|
+
// crons and object waits for the wait rows below the editor.
|
|
8
|
+
import { formatBashElapsed } from '../../../core/bash-jobs.js';
|
|
9
|
+
import { isTrueUserMessage } from '../../../shared/tool-groups.js';
|
|
10
|
+
function stamp(message) {
|
|
11
|
+
return typeof message.timestamp === 'number' && Number.isFinite(message.timestamp) ? message.timestamp : undefined;
|
|
12
|
+
}
|
|
13
|
+
/** `2:31 PM` today, `Nov 18, 2:31 PM` on another day. */
|
|
14
|
+
export function finishLabel(atMs, nowMs) {
|
|
15
|
+
const at = new Date(atMs);
|
|
16
|
+
const time = at.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
|
|
17
|
+
if (at.toDateString() === new Date(nowMs).toDateString())
|
|
18
|
+
return time;
|
|
19
|
+
return `${at.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}, ${time}`;
|
|
20
|
+
}
|
|
21
|
+
export function createRunFacts(onChange) {
|
|
22
|
+
let lastUserAt;
|
|
23
|
+
let finishedAt;
|
|
24
|
+
let waiting;
|
|
25
|
+
const take = (message) => {
|
|
26
|
+
const at = stamp(message);
|
|
27
|
+
if (at === undefined)
|
|
28
|
+
return;
|
|
29
|
+
if (isTrueUserMessage(message)) {
|
|
30
|
+
lastUserAt = at;
|
|
31
|
+
finishedAt = undefined;
|
|
32
|
+
}
|
|
33
|
+
else if (message.role === 'assistant') {
|
|
34
|
+
finishedAt = at;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
observe(frame) {
|
|
39
|
+
if (frame.type === 'welcome') {
|
|
40
|
+
lastUserAt = undefined;
|
|
41
|
+
finishedAt = undefined;
|
|
42
|
+
for (const message of frame.snapshot.messages)
|
|
43
|
+
take(message);
|
|
44
|
+
onChange();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (frame.type === 'agent_start' || frame.type === 'agent_end' || frame.type === 'agent_settled') {
|
|
48
|
+
onChange();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (frame.type === 'message_end' || (frame.type === 'message_start' && frame.message.role === 'user')) {
|
|
52
|
+
take(frame.message);
|
|
53
|
+
onChange();
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
setWaiting(label) {
|
|
57
|
+
if (label === waiting)
|
|
58
|
+
return;
|
|
59
|
+
waiting = label;
|
|
60
|
+
onChange();
|
|
61
|
+
},
|
|
62
|
+
line(streaming, nowMs = Date.now()) {
|
|
63
|
+
if (streaming)
|
|
64
|
+
return undefined;
|
|
65
|
+
const parts = [];
|
|
66
|
+
if (finishedAt !== undefined) {
|
|
67
|
+
if (lastUserAt !== undefined && finishedAt >= lastUserAt)
|
|
68
|
+
parts.push(`ran ${formatBashElapsed(finishedAt - lastUserAt)}`);
|
|
69
|
+
parts.push(`finished ${finishLabel(finishedAt, nowMs)}`);
|
|
70
|
+
}
|
|
71
|
+
if (waiting !== undefined)
|
|
72
|
+
parts.push(`waiting on ${waiting}`);
|
|
73
|
+
return parts.length === 0 ? undefined : parts.join(' · ');
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
// widgets in their fixed cockpit slots, and the queued-steering panel above
|
|
3
3
|
// the editor. Both read the folded `SessionState` the orchestrator owns, so it
|
|
4
4
|
// arrives as a getter rather than a captured value.
|
|
5
|
-
import { Text, truncateToWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
5
|
+
import { Spacer, Text, truncateToWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
6
6
|
import { splitRecapLines } from './recap.js';
|
|
7
|
-
export function createChromeWidgets(ctx, state
|
|
7
|
+
export function createChromeWidgets(ctx, state,
|
|
8
|
+
/** The gray fact line (run time, finish time, waiting on), painted above the recap. */
|
|
9
|
+
factLine = () => undefined) {
|
|
8
10
|
const { tui, pal } = ctx;
|
|
9
11
|
const { aboveWidgets, belowWidgets, queued } = ctx.containers;
|
|
10
12
|
/** Paint serializable extension widgets into their fixed cockpit slots. */
|
|
@@ -12,10 +14,17 @@ export function createChromeWidgets(ctx, state) {
|
|
|
12
14
|
const session = state();
|
|
13
15
|
aboveWidgets.clear();
|
|
14
16
|
belowWidgets.clear();
|
|
15
|
-
// The recap widget is split: its goal line is
|
|
16
|
-
// header, while its state line lands here in the
|
|
17
|
-
// slot, label stripped and
|
|
17
|
+
// The fact line comes first. The recap widget is split: its goal line is
|
|
18
|
+
// painted by the pinned header, while its state line lands here in the
|
|
19
|
+
// widget's own cockpit slot, label stripped, faint, and never cut short.
|
|
18
20
|
const span = Math.max(1, (process.stdout.columns ?? 80) - 2);
|
|
21
|
+
const facts = factLine();
|
|
22
|
+
if (facts !== undefined) {
|
|
23
|
+
for (const wrapped of wrapTextWithAnsi(pal.faint(facts), span))
|
|
24
|
+
aboveWidgets.addChild(new Text(wrapped, 1, 0));
|
|
25
|
+
if (session.display.widgets['crtr-recap'] !== undefined)
|
|
26
|
+
aboveWidgets.addChild(new Spacer(1));
|
|
27
|
+
}
|
|
19
28
|
for (const [key, widget] of Object.entries(session.display.widgets)) {
|
|
20
29
|
const recap = key === 'crtr-recap';
|
|
21
30
|
const lines = recap ? splitRecapLines(widget.lines).state : widget.lines;
|
|
@@ -34,6 +34,7 @@ import { createTicketPanel } from './chrome/ticket-panel.js';
|
|
|
34
34
|
import { createPaneFocus } from './session/pane-focus.js';
|
|
35
35
|
import { createStatusLine } from './chrome/status-line.js';
|
|
36
36
|
import { createChromeWidgets } from './chrome/widgets.js';
|
|
37
|
+
import { createRunFacts } from './chrome/run-facts.js';
|
|
37
38
|
import { createRecapHeader } from './chrome/header.js';
|
|
38
39
|
import { createChromeRefresh, isTransientDaemonFailure } from './session/chrome-refresh.js';
|
|
39
40
|
import { createTeardown } from './session/teardown.js';
|
|
@@ -357,7 +358,9 @@ onConnected) {
|
|
|
357
358
|
editorChrome.syncContextBadge();
|
|
358
359
|
// The two broker-fed container painters: extension widgets in their cockpit
|
|
359
360
|
// slots, and the queued-steering panel.
|
|
360
|
-
|
|
361
|
+
// The gray fact line above the recap: run time, finish time, what the node waits on.
|
|
362
|
+
const runFacts = createRunFacts(() => renderExtensionWidgets());
|
|
363
|
+
const { renderExtensionWidgets, renderQueued } = createChromeWidgets(ctx, () => sync.state(), () => runFacts.line(sync.state().engine?.isStreaming === true));
|
|
361
364
|
// The OWNER of the folded SessionState and of what each delta repaints.
|
|
362
365
|
sync = createSessionStateSync(role, {
|
|
363
366
|
setEngineState: (engine) => input.setState(engine),
|
|
@@ -424,6 +427,7 @@ onConnected) {
|
|
|
424
427
|
openInspector,
|
|
425
428
|
openObject,
|
|
426
429
|
syncCursor: () => paneFocus.sync(),
|
|
430
|
+
onWaiting: (label) => runFacts.setWaiting(label),
|
|
427
431
|
});
|
|
428
432
|
// The one hollow-cursor owner: pane focus AND neither list holding the highlight.
|
|
429
433
|
const paneFocus = createPaneFocus(editor, [roster.active, strip.active, ticketPanel.active]);
|
|
@@ -714,6 +718,7 @@ onConnected) {
|
|
|
714
718
|
if (frame.type === 'welcome' && !welcomed)
|
|
715
719
|
mark('viewer.welcome_received');
|
|
716
720
|
handleBrokerFrame(frame);
|
|
721
|
+
runFacts.observe(frame);
|
|
717
722
|
if (frame.type === 'welcome' && !welcomed)
|
|
718
723
|
onFirstWelcome();
|
|
719
724
|
},
|
|
@@ -726,6 +731,7 @@ onConnected) {
|
|
|
726
731
|
scheduleTmuxBindingInstall();
|
|
727
732
|
chatView.settleRun();
|
|
728
733
|
sync.patchLocal({ isStreaming: false });
|
|
734
|
+
renderExtensionWidgets();
|
|
729
735
|
},
|
|
730
736
|
onReconnecting: () => chatView.setPendingUndelivered(true),
|
|
731
737
|
// A message sent on a connection that had already died never reached the broker: send it again now that one answers.
|
|
@@ -36,7 +36,8 @@ export const listLeaf = defineLeaf({
|
|
|
36
36
|
outputKind: 'object',
|
|
37
37
|
effects: ['None. Listing records no watch.'],
|
|
38
38
|
},
|
|
39
|
-
|
|
39
|
+
actingAs: true,
|
|
40
|
+
run: async (input, context) => {
|
|
40
41
|
const query = {
|
|
41
42
|
...(input['type'] ? { type: input['type'] } : {}),
|
|
42
43
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
@@ -46,6 +47,7 @@ export const listLeaf = defineLeaf({
|
|
|
46
47
|
...(input['deleted'] === true ? { deleted: true } : {}),
|
|
47
48
|
...(input['shared'] === true ? { shared: true } : {}),
|
|
48
49
|
...(input['machine'] ? { machine: input['machine'] } : {}),
|
|
50
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
49
51
|
limit: input['limit'] ?? 50,
|
|
50
52
|
...(input['cursor'] ? { cursor: input['cursor'] } : {}),
|
|
51
53
|
};
|
|
@@ -80,9 +80,11 @@ export const readLeaf = defineLeaf({
|
|
|
80
80
|
outputKind: 'object',
|
|
81
81
|
effects: ['A live read records a watch on the object for you (every event subject) and publishes a read event to its other watchers. A deleted or remote answer records nothing.'],
|
|
82
82
|
},
|
|
83
|
-
|
|
83
|
+
actingAs: true,
|
|
84
|
+
run: async (input, context) => {
|
|
84
85
|
try {
|
|
85
|
-
|
|
86
|
+
const query = { ...(input['fields'] === true ? { fields: true } : {}), ...(context?.as === undefined ? {} : { as: context.as }) };
|
|
87
|
+
return { ...(await cliClient().objects.read(input['ref'], Object.keys(query).length === 0 ? undefined : query)) };
|
|
86
88
|
}
|
|
87
89
|
catch (err) {
|
|
88
90
|
rethrowAsCliError(err);
|
|
@@ -23,7 +23,8 @@ export const searchLeaf = defineLeaf({
|
|
|
23
23
|
outputKind: 'object',
|
|
24
24
|
effects: ['None. Searching records no watch.'],
|
|
25
25
|
},
|
|
26
|
-
|
|
26
|
+
actingAs: true,
|
|
27
|
+
run: async (input, context) => {
|
|
27
28
|
const request = {
|
|
28
29
|
text: input['text'],
|
|
29
30
|
...(input['body'] === true ? { body: true } : {}),
|
|
@@ -32,6 +33,7 @@ export const searchLeaf = defineLeaf({
|
|
|
32
33
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
33
34
|
...(input['owner'] ? { owner: input['owner'] } : {}),
|
|
34
35
|
...(input['limit'] ? { limit: input['limit'] } : {}),
|
|
36
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
35
37
|
};
|
|
36
38
|
try {
|
|
37
39
|
return { ...(await cliClient().objects.search(request)) };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The canvas data-access layer. Nodes, their sessions, executions, and managed
|
|
2
2
|
// worktrees are SQL-authoritative. Node directories hold only artifacts.
|
|
3
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
3
4
|
import { loadExactProfileManifest } from '../profiles/manifest.js';
|
|
4
5
|
import { envNodeId } from '../../shared/env.js';
|
|
5
6
|
import { lstatSync, realpathSync, rmdirSync, rmSync, statSync } from 'node:fs';
|
|
@@ -61,7 +62,7 @@ async function seedRow(meta, db) {
|
|
|
61
62
|
const profile = meta.profile_id ? await profileObjectFor(db, meta.profile_id, app, meta.grantee ?? 'app:terminal') : null;
|
|
62
63
|
await createObject(db, { id: meta.node_id, type: 'node', kind: meta.kind, owner: (profile ?? app).id, privacy: 'public', name: meta.name, preview: '' });
|
|
63
64
|
// A node directly under an app is readable by the person it was made for.
|
|
64
|
-
if (profile === null && meta.sub)
|
|
65
|
+
if (profile === null && meta.sub && parsePrincipal(meta.sub)?.kind === 'user')
|
|
65
66
|
await writeActsFor(db, meta.node_id, meta.sub);
|
|
66
67
|
await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill('?').join(', ')})`)
|
|
67
68
|
.run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 36;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|