@north-light/cli 0.3.687 → 0.3.689
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/core/conversation-store/row-store.js +11 -11
- package/dist/core/grants/mirror.js +7 -7
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/router.d.ts +3 -0
- package/dist/daemon/api/router.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +13 -6
- package/packages/crouter-api/dist/core/grants/mirror.js +5 -4
- package/packages/crouter-api/dist/daemon/api/router.js +18 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).join(""),"encode")
|
|
3
|
-
`).filter(Boolean).map(t=>JSON.parse(t)),"decode"),h=_(()=>new Date().toISOString(),"at");async function g(o,t,r=!1){const
|
|
4
|
-
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(t,t);return{parts:r.filter(
|
|
5
|
-
`).subarray(
|
|
6
|
-
`).filter(Boolean).length-1),h())||!e?.run_id||e.event_offset===null)return;const f=e.source_session_id?[]:await T(p,e.run_id,e.node_id,
|
|
7
|
-
`);
|
|
8
|
-
`))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}
|
|
9
|
-
`);d.pop();const p=Math.max(0,
|
|
1
|
+
var U=Object.defineProperty;var _=(o,t)=>U(o,"name",{value:t,configurable:!0});import{randomUUID as O}from"node:crypto";import{existsSync as W,readFileSync as q,rmSync as B}from"node:fs";import{join as j}from"node:path";import{SessionManager as J}from"@earendil-works/pi-coding-agent";import{blobStore as E}from"../blobs/index.js";import{openDb as w,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as x}from"../layout.js";import{appendConversationEvents as T,rootRepromptPending as L}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as R}from"./index.js";const N="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",D=_((o,t,r)=>`conversations/${o}/${t}/${r}.jsonl`,"keyFor"),C=_(o=>o.map(t=>JSON.stringify(t)+`
|
|
2
|
+
`).join(""),"encode"),H=_(o=>o.split(`
|
|
3
|
+
`).filter(Boolean).map(t=>JSON.parse(t)),"decode"),h=_(()=>new Date().toISOString(),"at");async function g(o,t,r=!1){const a=await o.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${N} LIMIT 1${r?" FOR UPDATE OF s":""}`).get(t);if(!a)throw new R(t);return a}_(g,"binding");async function b(o,t){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(t)}_(b,"parts");async function Y(o,t){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(t)}_(Y,"tail");async function M(o,t){const r=await o.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
|
|
4
|
+
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(t,t);return{parts:r.filter(a=>a.kind==="part").map(({seq:a,blob_key:n,bytes:s,entries:e,created:i})=>({seq:Number(a),blob_key:n,bytes:Number(s),entries:Number(e),created:i})),tail:r.filter(a=>a.kind==="tail").map(({seq:a,body:n,bytes:s,created:e})=>({seq:Number(a),body:n,bytes:Number(s),created:e}))}}_(M,"snapshot");const I=4*1024*1024,V=4,P=16;async function*$(o,t,r){const a=[];let n=0;const s=_(()=>{for(;n<o&&a.length<r;){const e=t(n++);e.catch(()=>{}),a.push(e)}},"fill");for(s();a.length>0;){const e=await a.shift();s(),yield e}}_($,"readAhead");async function S(o,t,r){const a=[];let n=0;const s=await E(),e=[];for(const i of o.parts){const c=Math.max(t,n),d=Math.min(r,n+i.bytes);c<d&&e.push({key:i.blob_key,range:{start:c-n,length:d-c}}),n+=i.bytes}for await(const i of $(e.length,async c=>{const d=await s.get(e[c].key,e[c].range);if(!d)throw new Error(`missing conversation object: ${e[c].key}`);return d},P))a.push(i);for(const i of o.tail){const c=Math.max(t,n),d=Math.min(r,n+i.bytes);c<d&&a.push(Buffer.from(i.body+`
|
|
5
|
+
`).subarray(c-n,d-n)),n+=i.bytes}return Buffer.concat(a)}_(S,"bytesOf");const k=new Map;async function A(o,t,r){const a=await w();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!W(r))return;let n=q(r);const s=n.lastIndexOf(10);if(s<0)return;n=n.subarray(0,s+1);const e=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+N+" LIMIT 1").get(o);let i=[];if(e?.run_id&&e.event_offset!==null){const p=Number(e.event_offset);if(n.length<p)throw new Error(`conversation shorter than indexed offset: ${o}`);i=H(n.subarray(p).toString("utf8")).filter(u=>u.type!=="session")}const c=e?.run_id?await L(e.run_id,e.node_id,i):!1,d=D(t,o,0);await(await E()).put(d,n),await y(async p=>{if(!await p.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(o,d,n.length,Math.max(0,n.toString("utf8").split(`
|
|
6
|
+
`).filter(Boolean).length-1),h())||!e?.run_id||e.event_offset===null)return;const f=e.source_session_id?[]:await T(p,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(n.length,i.at(-1)?.id??null,JSON.stringify(f),e.binding_id)})}_(A,"importOne");async function m(o,t){const r=await t.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${N} LIMIT 1`).get(o),a=k.get(o);if(!r&&!a)throw new R(o);let n=(await b(t,o))[0];if(!n){const c=a?.path??r?.transcript_path??void 0;c&&await A(o,a?.node??r.node_id,c),n=(await b(t,o))[0]}if(!n||n.seq!==0)throw new R(o);const s=await(await E()).get(n.blob_key,{start:0,length:Math.min(n.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${n.blob_key}`);const e=s.indexOf(10);if(e<0)throw new Error(`invalid conversation header: ${o}`);const i=JSON.parse(s.subarray(0,e).toString("utf8"));if(i.type!=="session"||i.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:i,path:r?.transcript_path??a?.path??"",binding:r}}_(m,"initial");function at(){const o={async create(t,r,a,n){const e=await(await w()).prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(t);if(!e)throw new Error(`missing conversation owner ${t}`);const i=r.id,c=j(x(e.grantee).conversations,t,`${r.timestamp.replace(/[:.]/g,"-")}_${i}.jsonl`),d=C([r,...a]),p=D(t,i,0),u=e.run_id?await L(e.run_id,t,a):!1;return await(await E()).put(p,d),await y(async f=>{if(await f.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(i))throw new Error(`conversation already exists: ${i}`);const l=h(),v=r.parentSession?await f.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(r.parentSession):void 0;if(await f.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(O(),i,t,c,v?v.session_id:null,l,l,l),await f.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(i,p,Buffer.byteLength(d),a.length,l),e.run_id&&!v){const F=await T(f,e.run_id,t,a,[],u);await f.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(F),i,t)}}),{conversation_id:i,path:c}},async append(t,r){if(!r.length)return;const a=await g(await w(),t),n=a.run_id?await L(a.run_id,a.node_id,r):!1;await y(async s=>{const e=await g(s,t,!0);if(!(await b(s,t)).length)throw new R(t);const i=[];for(const c of r){const d=JSON.stringify(c);await s.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(t,c.id,d,Buffer.byteLength(d)+1,h())&&i.push(c)}if(e.run_id&&i.length){const c=await T(s,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json??"[]"),n);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(i.at(-1).id,JSON.stringify(c),e.binding_id)}})},async readLines(t){const r=await w(),{path:a}=await m(t,r),n=await M(r,t),s=n.parts.reduce((i,c)=>i+c.bytes,0)+n.tail.reduce((i,c)=>i+c.bytes,0);async function*e(){let i="";for await(const c of $(Math.ceil(s/I),d=>S(n,d*I,Math.min(s,(d+1)*I)),V)){const d=i+c.toString("latin1"),p=d.lastIndexOf(`
|
|
7
|
+
`);i=d.slice(p+1);for(const u of d.slice(0,p+1).split(`
|
|
8
|
+
`))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}i&&(yield Buffer.from(i,"latin1").toString("utf8"))}return _(e,"lines"),{path:a,lines:e()}},async read(t,r){const a=await w(),{header:n,path:s}=await m(t,a),e=await M(a,t),i=e.parts.reduce((f,l)=>f+l.bytes,0)+e.tail.reduce((f,l)=>f+l.bytes,0),c=_(f=>H(f).filter(l=>l.type!=="session"),"entriesOf");if(!r||i<=r.head+r.tail)return{header:n,entries:c((await S(e,0,i)).toString("utf8")),path:s};const d=(await S(e,0,Math.max(0,r.head))).toString("utf8").split(`
|
|
9
|
+
`);d.pop();const p=Math.max(0,i-r.tail),u=(await S(e,p>0?p-1:0,i)).toString("utf8").split(`
|
|
10
10
|
`);return p>0&&u.shift(),{header:n,entries:c(d.join(`
|
|
11
11
|
`)),tail:c(u.join(`
|
|
12
|
-
`)),path:s}},async header(t){const r=await w(),{header:
|
|
13
|
-
`).join("");return await(await
|
|
12
|
+
`)),path:s}},async header(t){const r=await w(),{header:a,path:n}=await m(t,r),s=await M(r,t);return{header:a,path:n,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((e,i)=>e+i.bytes,0)+s.tail.reduce((e,i)=>e+i.bytes,0)}},async list(t){const a=await(await w()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${N}`).all(),n=[];for(const s of a){if(t&&s.node_id!==t)continue;const e=await o.header(s.session_id);n.push({conversation_id:s.session_id,node_id:s.node_id,...e})}return n.sort((s,e)=>e.mtime-s.mtime)},async replace(t,r,a){if(r.id!==t)throw new Error("replacement header id differs from conversation id");const n=await w(),s=await g(n,t);if(s.run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const e=`conversations/${s.node_id}/${t}/0-${O()}.jsonl`,i=C([r,...a]);await(await E()).put(e,i);const c=await y(async d=>{if((await g(d,t,!0)).run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const u=await b(d,t);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(t,e,Buffer.byteLength(i),a.length,h()),u});for(const d of c)await(await E()).delete(d.blob_key)},async fork(t,r,a,n){const s=await o.read(t);let e=s.entries;if(a!==void 0){const i=J.inMemory(s.header.cwd,void 0,[s.header,...e]);i.createBranchedSession(a),e=i.getEntries()}return(await o.create(r??(await m(t,await w())).binding?.node_id??k.get(t).node,{...s.header,id:O(),timestamp:h(),cwd:n??s.header.cwd,parentSession:s.path},e)).conversation_id},async delete(t,r){const a=await w(),n=await b(a,t);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(t)});for(const s of n)await(await E()).delete(s.blob_key);r&&B(r,{force:!0})},async commit(t){return await y(async r=>{const a=await g(r,t,!0),n=await Y(r,t),s=await b(r,t);if(!n.length)return s.at(-1)?.seq??0;const e=(s.at(-1)?.seq??0)+1,i=D(a.node_id,t,e),c=n.map(d=>d.body+`
|
|
13
|
+
`).join("");return await(await E()).put(i,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await r.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(t,e,i,Buffer.byteLength(c),n.length,h()),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(t,n.at(-1).seq),e})},async importLegacy(t){const a=await(await w()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${t?"AND n.run_id = ?":""} ORDER BY s.session_id, ${N}`).all(...t?[t]:[]);for(const n of a)await A(n.session_id,n.node_id,n.transcript_path)},recover(t){for(const r of t)r.transcript_path&&k.set(r.session_id,{node:r.node_id,path:r.transcript_path})}};return o}_(at,"createRowStore");function G(o,t,r){const a=o.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${t}`);const n=JSON.parse(o.subarray(0,a).toString("utf8"));if(n.type!=="session"||n.id!==t)throw new Error(`invalid conversation header: ${t}`);const s=r(n.cwd);return s===n.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...n,cwd:s})),o.subarray(a)])}_(G,"withHeaderCwd");async function it(o,t,r){const a=await w(),n=await g(a,o),s=(await b(a,o))[0];if(!s||s.seq!==0)return!1;const e=await(await E()).get(s.blob_key);if(!e)throw new Error(`missing conversation object: ${s.blob_key}`);const i=G(e,o,p=>p===t?r:p);if(i===null)return!1;const c=`conversations/${n.node_id}/${o}/0-${O()}.jsonl`;await(await E()).put(c,i);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ? WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,i.length,o,s.blob_key)!==void 0);if(await(await E()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(it,"relocateConversationHeader");export{at as createRowStore,$ as readAhead,it as relocateConversationHeader,G as withHeaderCwd};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
SELECT DISTINCT e->>'scope' AS scope FROM
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=U(s);a&&(r[n]=a)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of F){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=H.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
|
+
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
3
|
+
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
|
|
4
|
+
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
5
5
|
CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
|
|
6
|
-
WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
|
|
7
7
|
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
|
-
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return
|
|
8
|
+
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(be,"teamsOf");async function Re(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await T(async o=>{let E=0;const g=[...a];E+=Number((await(g.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):o.prepareUncached("DELETE FROM grants").run())).changes);const w=o.prepare(`INSERT INTO grants
|
|
9
9
|
(id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
10
10
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -19,4 +19,4 @@ var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});i
|
|
|
19
19
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
20
20
|
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
21
21
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
22
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)
|
|
22
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(o,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(R=>({resourceId:c,subject:C(R)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(Re,"replaceGrants");async function he(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(he,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,he as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,Re as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var r=(e,n)=>g(e,"name",{value:n,configurable:!0});import{ApiError as t}from"../../../api/index.js";import{inboxPageProjection as y}from"./inbox-page.js";import{getRequestByInboxTicket as b}from"../../../core/human/requests.js";import{readableTicketIds as m}from"../router.js";import{readPageManifest as T}from"../../../core/human/page.js";import{scanInbox as q,scanPageHistory as I}from"../../../core/human/scan.js";import{readPageTicket as h,readTicketResult as k,selectedPageDir as x,validatePageTicketResponses as A,writePageProgress as P}from"../../../core/human/tickets.js";import{describePageAnswer as E}from"../../../core/human/answer.js";import{cancelHumanTicket as R,resolvePageTicket as S}from"../../human/finish.js";const O="Canceled from the inbox.",C=1e3,D=/^[a-f0-9]{64}$/;async function d(e){const n=await b(e);return n===null?null:{ticketId:n.request_id,dir:n.request_dir,kind:n.kind}}r(d,"resolveTicket");function l(e){const n=e.ticket_id;if(n===void 0||!D.test(n))throw new t(400,"invalid_request","invalid ticket id");return n}r(l,"requireTicketId");function u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}r(u,"isPlainObject");function f(e,n){for(const o of Object.keys(e))if(!n.includes(o))throw new t(400,"invalid_request",`unexpected field: ${o}`)}r(f,"requireNoExtraKeys");function N(e){if(!u(e))throw new t(400,"invalid_request","respond body is required");if(f(e,["responses"]),!u(e.responses))throw new t(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}r(N,"validateRespondRequest");function j(e){if(!u(e))throw new t(400,"invalid_request","progress body is required");if(f(e,["responses"]),!u(e.responses))throw new t(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}r(j,"validateProgressRequest");function G(e){if(e===void 0)return{};if(!u(e))throw new t(400,"invalid_request","cancel body must be an object");if(f(e,["reason"]),e.reason===void 0)return{};const n=e.reason;if(typeof n!="string")throw new t(400,"invalid_request","`reason` must be a string");if(n.trim()===""||n.length>C)throw new t(400,"invalid_request","`reason` must be nonempty after trim and at most 1000 characters");return{reason:n}}r(G,"validateCancelRequest");const L=[/^slot ".*?" /,/^response names unknown or non-response-bearing slot id/,/^final page response is missing response-bearing slot id/];function _(e){return e instanceof Error&&L.some(n=>n.test(e.message))}r(_,"isSlotValidationError");function v(e){const n={request_id:e.id,request_dir:e.dir,ticket_id:e.inboxTicketId,kind:"page",title:e.title,placement:e.placement,dialect:e.dialect,steps:e.steps,emitted_at:e.emittedAt,source:e.source,slot_kinds:e.slotKinds,inbox:e.inbox,awaits_response:e.awaitsResponse,state:e.state};return e.subtitle!==""&&(n.subtitle=e.subtitle),e.answerDigest!==void 0&&(n.answer_digest=e.answerDigest),e.recommendedOptions.length>0&&(n.recommended_options=e.recommendedOptions.map(o=>({slot_id:o.slotId,option_id:o.optionId,label:o.label}))),e.fastAction!==void 0&&(n.fast_action={kind:e.fastAction.kind,responses:e.fastAction.responses}),n}r(v,"pageSummaryToDTO");async function H(e){const n=await q(),o=await m(e.principal,n.map(i=>i.inboxTicketId));return{status:200,body:{tickets:n.filter(i=>o.has(i.inboxTicketId)).map(i=>{if(i.kind==="page")return v(i);if(i.kind==="review")return{request_id:i.id,request_dir:i.dir,ticket_id:i.inboxTicketId,kind:"review",title:i.title,subtitle:i.subtitle,blocked_since:i.blockedSince,source:i.source};throw new Error(`unknown ticket kind: ${i.kind}`)}).sort((i,a)=>{const p=r(w=>w.kind==="page"?w.emitted_at:w.blocked_since,"pageTime"),c=Date.parse(p(a))-Date.parse(p(i));return c!==0?c:i.ticket_id.localeCompare(a.ticket_id)})}}}r(H,"handleList");const K=new Set(["pending","resolved","canceled","passive"]);async function $(e){const n=e.query.get("node_id");if(n==="")throw new t(400,"invalid_request","node_id must be nonempty when present");const o=e.query.get("state");if(o!==null&&!K.has(o))throw new t(400,"invalid_request","state must be one of pending, resolved, canceled, passive");const s=await I(n??void 0,o??void 0),i=await m(e.principal,s.map(c=>c.inboxTicketId));return{status:200,body:{tickets:s.filter(c=>i.has(c.inboxTicketId)).map(v)}}}r($,"handleHistory");async function M(e){const n=l(e.params),o=await d(n);if(o===null)throw new t(404,"ticket_not_found","no matching ticket");if(o.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets have no page read operation");const s=await b(n);if(s===null||s.kind!=="page")throw new t(404,"ticket_not_found","no matching ticket");try{return{status:200,body:await y(s)}}catch{throw new t(500,"internal","the ticket could not be read")}}r(M,"handleGetPage");async function V(e){const n=l(e.params),o=N(e.body),s=await d(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets submit through their own path");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const i=await k(s.dir);if(i!==null&&i.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");if(i?.kind==="canceled")throw new t(409,"ticket_canceled","canceled tickets cannot be answered");try{await A(s.dir,o.responses)}catch(a){throw _(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","validation failed")}try{const a=await S(s.ticketId,o.responses);if(a.kind!=="page")throw new t(409,"ticket_kind_mismatch","unexpected result kind");return{status:200,body:a}}catch(a){throw a instanceof t?a:_(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","the ticket could not be finalized")}}r(V,"handleRespond");async function z(e){const n=l(e.params),o=j(e.body),s=await d(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets do not support progress autosave");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const i=await k(s.dir);if(i!==null&&i.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");try{return await P(s.dir,o.responses),{status:200,body:{}}}catch(a){throw _(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","progress could not be saved")}}r(z,"handleProgress");async function B(e){const n=l(e.params),o=G(e.body),s=await d(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets have their own cancel path");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");try{const i=await R(s.ticketId,{reason:o.reason??O,actor:"human",disposition:"dismissed"});if(i.outcome==="already_settled"||i.result.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");return{status:200,body:i.result}}catch(i){throw i instanceof t?i:new t(500,"internal","the ticket could not be canceled")}}r(B,"handleCancel");async function F(e){const n=l(e.params),o=await d(n);if(o===null)throw new t(404,"ticket_not_found","no matching ticket");if(o.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets fetch responses through their own path");const s=await k(o.dir);if(s===null)throw new t(404,"ticket_pending","ticket has no response yet");if(s.kind==="canceled")throw new t(404,"ticket_canceled","canceled tickets have no response");if(s.kind!=="page")throw new t(409,"ticket_kind_mismatch","unexpected result kind");try{const i=await T(await x(o.dir));return{status:200,body:{...s,answer:E(i,s.responses,{completedAt:s.completedAt})}}}catch{throw new t(500,"internal","the ticket answer could not be read")}}r(F,"handleGetResponse");const ie=[{method:"GET",pattern:"/v1/human/inbox",handler:H},{method:"GET",pattern:"/v1/human/inbox/history",handler:$},{method:"GET",pattern:"/v1/human/inbox/:ticket_id",handler:M},{method:"GET",pattern:"/v1/human/inbox/:ticket_id/response",handler:F},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/respond",handler:V},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/progress",handler:z},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/cancel",handler:B}];export{ie as inboxRoutes,l as requireTicketId,d as resolveTicket};
|
|
@@ -100,6 +100,9 @@ export declare function runCallerApp(principal: RequestPrincipal | AppPrincipal)
|
|
|
100
100
|
export declare function mayOnNode(principal: RequestPrincipal | AppPrincipal, permission: 'read' | 'edit' | 'message', nodeId: string): Promise<boolean>;
|
|
101
101
|
/** The ids of the nodes the caller may read, in one query that embeds the evaluator's condition; null when the caller reads every node (the person). */
|
|
102
102
|
export declare function readableNodeIds(principal: RequestPrincipal): Promise<Set<string> | null>;
|
|
103
|
+
/** The inbox tickets in `ticketIds` whose requester node the caller may read, decided in one query per chunk with the evaluator's condition.
|
|
104
|
+
* Same answer per ticket as `getRequestByInboxTicket` → `getNode` → `mayOnNode(read)`: a ticket with no requester node, or whose node row or object is missing, is not readable. */
|
|
105
|
+
export declare function readableTicketIds(principal: RequestPrincipal, ticketIds: readonly string[]): Promise<Set<string>>;
|
|
103
106
|
export declare function canReadRun(principal: RequestPrincipal | AppPrincipal, grantee: string, target?: string): Promise<boolean>;
|
|
104
107
|
export declare function requireRun(principal: RequestPrincipal | AppPrincipal, id: string, acting?: boolean, allowDeleting?: boolean): Promise<import("../../index.js").NodeMeta>;
|
|
105
108
|
export declare function canReadNode(principal: RequestPrincipal, grantee: string, target?: string): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var d=(e,t)=>j(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as D}from"../../core/events/emit.js";import{scopeAllowed as _,ScopeDeniedError as I}from"../../core/scopes.js";import{coveredByAny as L}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as F}from"../../core/canvas/person.js";import{activeGrant as J,activeGrantsOfPerson as M,grantFor as B}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as Y,RunError as b}from"../../core/runs/operations.js";import{openDb as x}from"../../core/canvas/db.js";import{check as Z,permits as V}from"../../core/permissions/evaluator.js";import{readerFor as R}from"./reader.js";import{checkCronFire as X}from"../cron/authority.js";import{operationFor as K}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{getRequest as A,getRequestByInboxTicket as O}from"../../core/human/requests.js";import{requireVisibleReview as g}from"../../core/review/store.js";import{getComment as v}from"../../core/review/comments.js";import{getStructuredRequest as ee}from"../../core/canvas/structured-requests.js";async function te(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){const i=r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id,c=r==="/v1/human/requests"&&i==null;if(i!==t.node&&!c)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const h=a.source;if(h&&typeof h=="object"&&"nodeId"in h&&h.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await v(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function y(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(y,"actsAsPerson");async function $(e){const t=await B(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d($,"forwardedGrant");async function T(e){if(e.class==="person"&&e.sub!==void 0)return(await M(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await $(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>L(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await X({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await J(e.grant):await B(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;throw new u(401,"grant_revoked","the node grant is not active")}d(T,"resolvedScopes");function p(e){return"class"in e?k(e):e.grantee}d(p,"runCallerApp");function N(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(N,"asRequestPrincipal");async function f(e,t,o){const n=N(e);if(y(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await x();return await Z(s,await R(s,{principal:n}),t,o)}d(f,"mayOnNode");async function ze(e){if(y(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await x(),o=await V(t,await R(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(ze,"readableNodeIds");async function P(e,t,o){const n=N(e);return y(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:_(await T(n),o)&&(!C(n)||_(n.scopes,o))}d(P,"mayReadApp");async function Ge(e,t,o){return o===void 0?await P(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(Ge,"canReadRun");async function Ue(e,t,o=!1,n=!1){const s=await w(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new b(404,"not_found","run not found");if(!await f(e,"read",t))throw new b(404,"not_found","run not found");if(o&&p(e)!==null&&p(e)!==s.grantee)throw new b(403,"other_app_run","cannot change another app's run");return await Y(t,s.grantee,n)}d(Ue,"requireRun");async function oe(e,t,o){return o===void 0?await P(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const W=new Set(["messages.post.58","messages.post.59"]);async function ne(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&F())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await $(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||y(t))return;if(t.class==="person")return await re(e,t,o);const n=await T(t);if(e.scope&&(!_(n,e.scope)||C(t)&&!_(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ue(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await w(r);if(!a)return;if(e.resource==="node-write"){const i=W.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(ne,"authorizeOperation");async function re(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await se(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ae(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await w(n))&&!await f(t,W.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(re,"authorizePersonNode");async function se(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await A(o.request_id):o.ticket_id?await O(o.ticket_id):null,r=o.comment_id?await v(o.comment_id):null,a=o.review_id?await g(o.review_id).catch(()=>null):r?await g(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await w(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(se,"authorizePersonHuman");async function ae(e,t,o){const n=await ee(o);if(n!==null&&(n.node_id===null||!await w(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ae,"authorizePersonStructuredRequest");async function de(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await w(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await w(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(de,"authorizePersonBody");async function ue(e,t,o,n){if(e.resource==="daemon-bash"&&(!_(n,"crtr:files:rw:user:.")||!_(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await A(o.request_id):o.ticket_id?await O(o.ticket_id):null,c=o.comment_id?await v(o.comment_id):null,h=o.review_id?await g(o.review_id):c?await g(c.review_id):null,m=i?.requester_node_id??h?.origin_node_id;if(m!=null){const l=await w(m);if(l&&(a?!await oe(t,l.grantee??"app:terminal",m):l.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(l&&!a&&!await f(t,"read",m))throw new u(404,"not_found","human request not found")}else if(i||h)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ue,"authorizeBrokerOnly");function ie(e,t){if(!_(e,t))throw new I("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",he=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function we(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&he.test(t)?t:void 0}d(we,"causedByOf");function je(e){return e.map(t=>({...t,ownerOnly:!0}))}d(je,"ownerOnly");class He{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:z(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??Q}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=z(o);for(const r of this.routes){if(r.method!==n)continue;const a=me(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){U(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await ne(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ce();i.operation.scope&&ie(n,i.operation.scope)}let c;try{c=await _e(t,i.maxBodyBytes)}catch(E){const S=E instanceof G?"payload_too_large":"invalid_request";U(o,S==="payload_too_large"?413:400,S,E.message);return}s.class==="person"&&s.sub!==void 0&&await de(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await te(i.operation,s,i.params,r.searchParams,c);const h=we(t.headers),m={...h===void 0?{}:{causedBy:h},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},l=await i.handler(m);o.writableEnded||le(o,l)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){q(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=H(r);a>=500&&D({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),q(o,a,i)}}}function z(e){return e.split("/").filter(t=>t.length>0)}d(z,"splitPath");function me(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(me,"matchSegments");class G extends Error{static{d(this,"BodyTooLargeError")}}async function _e(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new G(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(_e,"readJsonBody");function le(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(le,"writeResult");function q(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(q,"writeJson");function U(e,t,o,n){q(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(U,"writeError");export{fe as CAUSED_BY_HEADER,He as Router,y as actsAsPerson,k as appOf,ie as assertCeiling,oe as canReadNode,Ge as canReadRun,we as causedByOf,f as mayOnNode,je as ownerOnly,ce as ownerOnlyError,ze as readableNodeIds,Ue as requireRun,T as resolvedScopes,p as runCallerApp};
|
|
1
|
+
var H=Object.defineProperty;var d=(e,t)=>H(e,"name",{value:t,configurable:!0});import{toErrorBody as D}from"./map.js";import{emitEvent as I}from"../../core/events/emit.js";import{scopeAllowed as _,ScopeDeniedError as J}from"../../core/scopes.js";import{coveredByAny as L}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as F}from"../../core/canvas/person.js";import{activeGrant as M,activeGrantsOfPerson as Y,grantFor as O}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as Z,RunError as b}from"../../core/runs/operations.js";import{openDb as v}from"../../core/canvas/db.js";import{check as V,permits as R}from"../../core/permissions/evaluator.js";import{readerFor as q}from"./reader.js";import{checkCronFire as X}from"../cron/authority.js";import{operationFor as K}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{getRequest as A,getRequestByInboxTicket as N}from"../../core/human/requests.js";import{requireVisibleReview as y}from"../../core/review/store.js";import{getComment as E}from"../../core/review/comments.js";import{getStructuredRequest as ee}from"../../core/canvas/structured-requests.js";async function te(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){const i=r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id,c=r==="/v1/human/requests"&&i==null;if(i!==t.node&&!c)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const h=a.source;if(h&&typeof h=="object"&&"nodeId"in h&&h.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await E(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function g(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(g,"actsAsPerson");async function $(e){const t=await O(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d($,"forwardedGrant");async function T(e){if(e.class==="person"&&e.sub!==void 0)return(await Y(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await $(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>L(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await X({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await M(e.grant):await O(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;throw new u(401,"grant_revoked","the node grant is not active")}d(T,"resolvedScopes");function W(e){return"class"in e?k(e):e.grantee}d(W,"runCallerApp");function p(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(p,"asRequestPrincipal");async function f(e,t,o){const n=p(e);if(g(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await v();return await V(s,await q(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Ue(e){if(g(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await v(),o=await R(t,await q(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(Ue,"readableNodeIds");async function je(e,t){if(g(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await v(),n=await R(o,await q(o,{principal:e}),"read"),s=new Set;for(let r=0;r<t.length;r+=500){const a=t.slice(r,r+500),i=await o.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${a.map(()=>"?").join(",")}) AND ${n.sql}`).all(...a,...n.params);for(const c of i)s.add(c.id)}return s}d(je,"readableTicketIds");async function P(e,t,o){const n=p(e);return g(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:_(await T(n),o)&&(!C(n)||_(n.scopes,o))}d(P,"mayReadApp");async function ze(e,t,o){return o===void 0?await P(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(ze,"canReadRun");async function Ge(e,t,o=!1,n=!1){const s=await w(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new b(404,"not_found","run not found");if(!await f(e,"read",t))throw new b(404,"not_found","run not found");if(o&&W(e)!==null&&W(e)!==s.grantee)throw new b(403,"other_app_run","cannot change another app's run");return await Z(t,s.grantee,n)}d(Ge,"requireRun");async function oe(e,t,o){return o===void 0?await P(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const U=new Set(["messages.post.58","messages.post.59"]);async function ne(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&F())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await $(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||g(t))return;if(t.class==="person")return await re(e,t,o);const n=await T(t);if(e.scope&&(!_(n,e.scope)||C(t)&&!_(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ue(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await w(r);if(!a)return;if(e.resource==="node-write"){const i=U.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(ne,"authorizeOperation");async function re(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await se(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ae(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await w(n))&&!await f(t,U.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(re,"authorizePersonNode");async function se(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await A(o.request_id):o.ticket_id?await N(o.ticket_id):null,r=o.comment_id?await E(o.comment_id):null,a=o.review_id?await y(o.review_id).catch(()=>null):r?await y(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await w(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(se,"authorizePersonHuman");async function ae(e,t,o){const n=await ee(o);if(n!==null&&(n.node_id===null||!await w(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ae,"authorizePersonStructuredRequest");async function de(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await w(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await w(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(de,"authorizePersonBody");async function ue(e,t,o,n){if(e.resource==="daemon-bash"&&(!_(n,"crtr:files:rw:user:.")||!_(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await A(o.request_id):o.ticket_id?await N(o.ticket_id):null,c=o.comment_id?await E(o.comment_id):null,h=o.review_id?await y(o.review_id):c?await y(c.review_id):null,m=i?.requester_node_id??h?.origin_node_id;if(m!=null){const l=await w(m);if(l&&(a?!await oe(t,l.grantee??"app:terminal",m):l.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(l&&!a&&!await f(t,"read",m))throw new u(404,"not_found","human request not found")}else if(i||h)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ue,"authorizeBrokerOnly");function ie(e,t){if(!_(e,t))throw new J("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",he=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function we(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&he.test(t)?t:void 0}d(we,"causedByOf");function He(e){return e.map(t=>({...t,ownerOnly:!0}))}d(He,"ownerOnly");class De{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:j(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??Q}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=j(o);for(const r of this.routes){if(r.method!==n)continue;const a=me(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){G(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await ne(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ce();i.operation.scope&&ie(n,i.operation.scope)}let c;try{c=await _e(t,i.maxBodyBytes)}catch(x){const B=x instanceof z?"payload_too_large":"invalid_request";G(o,B==="payload_too_large"?413:400,B,x.message);return}s.class==="person"&&s.sub!==void 0&&await de(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await te(i.operation,s,i.params,r.searchParams,c);const h=we(t.headers),m={...h===void 0?{}:{causedBy:h},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},l=await i.handler(m);o.writableEnded||le(o,l)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){S(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=D(r);a>=500&&I({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),S(o,a,i)}}}function j(e){return e.split("/").filter(t=>t.length>0)}d(j,"splitPath");function me(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(me,"matchSegments");class z extends Error{static{d(this,"BodyTooLargeError")}}async function _e(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new z(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(_e,"readJsonBody");function le(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(le,"writeResult");function S(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(S,"writeJson");function G(e,t,o,n){S(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{fe as CAUSED_BY_HEADER,De as Router,g as actsAsPerson,k as appOf,ie as assertCeiling,oe as canReadNode,ze as canReadRun,we as causedByOf,f as mayOnNode,He as ownerOnly,ce as ownerOnlyError,Ue as readableNodeIds,je as readableTicketIds,Ge as requireRun,T as resolvedScopes,W as runCallerApp};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.689",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.689",
|
|
160
|
+
"@north-light/plugin": "0.3.689",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -38,6 +38,8 @@ const CHUNK = 4 * 1024 * 1024;
|
|
|
38
38
|
/** Ranges a streaming read keeps in flight. Each range of a conversation object is its own R2 request, which costs seconds from the
|
|
39
39
|
* cloud, so one range at a time made a 35 MB conversation take two minutes and a broker starting on it time out. */
|
|
40
40
|
const READ_AHEAD = 4;
|
|
41
|
+
/** Part objects of one range fetched at once. */
|
|
42
|
+
const PART_FETCHES = 16;
|
|
41
43
|
/** `fetch(0)`, `fetch(1)`, … `fetch(count - 1)` in order, keeping up to `depth` of them running ahead of the consumer. */
|
|
42
44
|
export async function* readAhead(count, fetch, depth) {
|
|
43
45
|
const running = [];
|
|
@@ -62,16 +64,21 @@ async function bytesOf(snap, start, end) {
|
|
|
62
64
|
const out = [];
|
|
63
65
|
let offset = 0;
|
|
64
66
|
const blobs = await blobStore();
|
|
67
|
+
const fetches = [];
|
|
65
68
|
for (const part of snap.parts) {
|
|
66
69
|
const from = Math.max(start, offset), to = Math.min(end, offset + part.bytes);
|
|
67
|
-
if (from < to)
|
|
68
|
-
|
|
69
|
-
if (!data)
|
|
70
|
-
throw new Error(`missing conversation object: ${part.blob_key}`);
|
|
71
|
-
out.push(data);
|
|
72
|
-
}
|
|
70
|
+
if (from < to)
|
|
71
|
+
fetches.push({ key: part.blob_key, range: { start: from - offset, length: to - from } });
|
|
73
72
|
offset += part.bytes;
|
|
74
73
|
}
|
|
74
|
+
// A conversation is one small object per commit, and each get is a round trip, so the parts are fetched PART_FETCHES at a time.
|
|
75
|
+
for await (const data of readAhead(fetches.length, async (i) => {
|
|
76
|
+
const got = await blobs.get(fetches[i].key, fetches[i].range);
|
|
77
|
+
if (!got)
|
|
78
|
+
throw new Error(`missing conversation object: ${fetches[i].key}`);
|
|
79
|
+
return got;
|
|
80
|
+
}, PART_FETCHES))
|
|
81
|
+
out.push(data);
|
|
75
82
|
for (const row of snap.tail) {
|
|
76
83
|
const from = Math.max(start, offset), to = Math.min(end, offset + row.bytes);
|
|
77
84
|
if (from < to)
|
|
@@ -154,12 +154,13 @@ export function providerIdsFromGrants(grants) {
|
|
|
154
154
|
* `JSON.stringify` of lists `entries()` accepted, and `entries()` refuses the strings jsonb rejects (`jsonbSafe`). */
|
|
155
155
|
export async function activeProviderIds() {
|
|
156
156
|
const scope = runtimeScope();
|
|
157
|
-
//
|
|
157
|
+
// Identical grant texts are deduplicated before the cast (rows repeat one text), and each text is cast once (`OFFSET 0` keeps the planner from
|
|
158
|
+
// inlining the cast into both uses). The scope strings are deduplicated before the pattern runs: the same few thousand scopes repeat across rows, and matching each of
|
|
158
159
|
// them (hundreds of thousands) cost about twenty times as long as matching the distinct ones.
|
|
159
160
|
const rows = await (await openDb()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
160
|
-
SELECT DISTINCT e->>'scope' AS scope FROM
|
|
161
|
-
|
|
162
|
-
|
|
161
|
+
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
162
|
+
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${ACTIVE_COMPUTED}${localOnly()}${scope.sql}) d OFFSET 0) p
|
|
163
|
+
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
163
164
|
CROSS JOIN LATERAL regexp_match(s.scope, '^(${ID}):${ID}$') m
|
|
164
165
|
WHERE m[1] <> 'crtr'`).all(...scope.args);
|
|
165
166
|
return rows.map((row) => row.id).sort();
|
|
@@ -139,6 +139,24 @@ export async function readableNodeIds(principal) {
|
|
|
139
139
|
const rows = await db.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${may.sql}`).all(...may.params);
|
|
140
140
|
return new Set(rows.map((r) => r.id));
|
|
141
141
|
}
|
|
142
|
+
/** The inbox tickets in `ticketIds` whose requester node the caller may read, decided in one query per chunk with the evaluator's condition.
|
|
143
|
+
* Same answer per ticket as `getRequestByInboxTicket` → `getNode` → `mayOnNode(read)`: a ticket with no requester node, or whose node row or object is missing, is not readable. */
|
|
144
|
+
export async function readableTicketIds(principal, ticketIds) {
|
|
145
|
+
if (actsAsPerson(principal))
|
|
146
|
+
return new Set(ticketIds);
|
|
147
|
+
if (principal.class === 'anonymous' || principal.class === 'machine' || principal.class === 'import' || ticketIds.length === 0)
|
|
148
|
+
return new Set();
|
|
149
|
+
const db = await openDb();
|
|
150
|
+
const may = await permits(db, await readerFor(db, { principal }), 'read');
|
|
151
|
+
const readable = new Set();
|
|
152
|
+
for (let i = 0; i < ticketIds.length; i += 500) {
|
|
153
|
+
const chunk = ticketIds.slice(i, i + 500);
|
|
154
|
+
const rows = await db.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${chunk.map(() => '?').join(',')}) AND ${may.sql}`).all(...chunk, ...may.params);
|
|
155
|
+
for (const row of rows)
|
|
156
|
+
readable.add(row.id);
|
|
157
|
+
}
|
|
158
|
+
return readable;
|
|
159
|
+
}
|
|
142
160
|
/** An app-wide question that names no node: own app, or the app-wide objects (`conversations`) read scope. */
|
|
143
161
|
async function mayReadApp(principal, grantee, scope) {
|
|
144
162
|
const caller = asRequestPrincipal(principal);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.689",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.689",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.689",
|
|
31
|
+
"@north-light/identity": "0.3.689"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.689",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.689",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.689",
|
|
32
|
+
"@north-light/plugin": "0.3.689",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -10667,17 +10667,17 @@
|
|
|
10667
10667
|
},
|
|
10668
10668
|
"packages/crouter-api": {
|
|
10669
10669
|
"name": "@north-light/api",
|
|
10670
|
-
"version": "0.3.
|
|
10670
|
+
"version": "0.3.689",
|
|
10671
10671
|
"license": "UNLICENSED"
|
|
10672
10672
|
},
|
|
10673
10673
|
"packages/crouter-env-docker": {
|
|
10674
10674
|
"name": "@north-light/env-docker",
|
|
10675
|
-
"version": "0.3.
|
|
10675
|
+
"version": "0.3.689",
|
|
10676
10676
|
"license": "UNLICENSED"
|
|
10677
10677
|
},
|
|
10678
10678
|
"packages/crouter-identity": {
|
|
10679
10679
|
"name": "@north-light/identity",
|
|
10680
|
-
"version": "0.3.
|
|
10680
|
+
"version": "0.3.689",
|
|
10681
10681
|
"license": "UNLICENSED",
|
|
10682
10682
|
"dependencies": {
|
|
10683
10683
|
"jose": "^6.2.1"
|
|
@@ -10685,21 +10685,21 @@
|
|
|
10685
10685
|
},
|
|
10686
10686
|
"packages/crouter-plugin": {
|
|
10687
10687
|
"name": "@north-light/plugin",
|
|
10688
|
-
"version": "0.3.
|
|
10688
|
+
"version": "0.3.689",
|
|
10689
10689
|
"license": "UNLICENSED",
|
|
10690
10690
|
"dependencies": {
|
|
10691
|
-
"@north-light/api": "0.3.
|
|
10692
|
-
"@north-light/identity": "0.3.
|
|
10691
|
+
"@north-light/api": "0.3.689",
|
|
10692
|
+
"@north-light/identity": "0.3.689"
|
|
10693
10693
|
}
|
|
10694
10694
|
},
|
|
10695
10695
|
"packages/crouter-sdk": {
|
|
10696
10696
|
"name": "@north-light/sdk",
|
|
10697
|
-
"version": "0.3.
|
|
10697
|
+
"version": "0.3.689",
|
|
10698
10698
|
"license": "UNLICENSED",
|
|
10699
10699
|
"dependencies": {
|
|
10700
|
-
"@north-light/api": "0.3.
|
|
10701
|
-
"@north-light/identity": "0.3.
|
|
10702
|
-
"@north-light/plugin": "0.3.
|
|
10700
|
+
"@north-light/api": "0.3.689",
|
|
10701
|
+
"@north-light/identity": "0.3.689",
|
|
10702
|
+
"@north-light/plugin": "0.3.689",
|
|
10703
10703
|
"jose": "^6.2.1"
|
|
10704
10704
|
},
|
|
10705
10705
|
"bin": {
|