@north-light/cli 0.3.748 → 0.3.750
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/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/core/canvas/canvas.js +16 -16
- 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.d.ts +1 -1
- package/dist/core/command.js +6 -6
- package/dist/core/grants/owner.d.ts +7 -0
- package/dist/core/grants/owner.js +1 -0
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/import/load/bind.d.ts +1 -1
- package/dist/core/import/load/bind.js +11 -8
- 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/runtime/recap.js +6 -6
- package/dist/core/spaces/permissions.js +1 -1
- package/dist/core/spaces/process.js +1 -1
- 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/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/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.js +4 -3
- package/packages/crouter-api/dist/core/grants/owner.js +15 -0
- package/packages/crouter-api/dist/core/graph/reader.js +9 -6
- 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 +13 -4
- package/packages/crouter-api/dist/core/spaces/permissions.js +10 -4
- package/packages/crouter-api/dist/core/spaces/process.js +5 -3
- 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,9 +1,9 @@
|
|
|
1
|
-
var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as
|
|
2
|
-
UNION ALL SELECT 'grants' FROM ${
|
|
3
|
-
UNION ALL SELECT 'nodes' FROM ${
|
|
4
|
-
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,
|
|
5
|
-
WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(
|
|
6
|
-
AND ${f(
|
|
1
|
+
var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as w}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as Y}from"./rewrite.js";import{ImportLaneError as F}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(n=>n.replace(/^user:/,""),"bare"),g=c((n,t)=>`${f(n)}.${f(t)}`,"sq"),N=c(async(n,t,...a)=>await n.prepareUncached(t).all(...a),"all");function T(n,t){return new F("bind","person_mismatch",n,t)}c(T,"mismatch");function se(n,t,a,p){if(n===t||n===a)return a;throw T(`${p} names ${n}, which is neither the bundle's person nor the importing person`,{where:p,value:n})}c(se,"boundSub");async function ne(n,t,a,p){if(!K.test(a))throw T(`the bundle's person ${JSON.stringify(a)} is not a user:<id> principal`,{where:"source.json person",value:a});if(a===p)return;const u=c(r=>g(t,r),"T"),o=await n.prepareUncached(`SELECT 'identities' AS tbl FROM ${u("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
|
|
2
|
+
UNION ALL SELECT 'grants' FROM ${u("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${u("profiles")} WHERE person = ?
|
|
3
|
+
UNION ALL SELECT 'nodes' FROM ${u("nodes")} WHERE sub = ? LIMIT 1`).get(a,a,a,a);if(o!==void 0)throw T(`the bundle's person ${a} is already a person in the target (${o.tbl}), not the importing person ${p}`,{where:`${o.tbl}`,value:a})}c(ne,"checkSourcePerson");const B=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],z=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function re(n){const{db:t,schema:a,sourcePerson:p,targetPerson:u}=n,o=c(s=>g(a,s),"S"),r=c((s,d)=>{throw T(`${s} names ${d.join(", ")}, who is neither the bundle's person ${p} nor the importing person ${u}`,{where:s,values:d})},"refuse");for(const[s,d]of B){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}for(const[s,d]of z){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}const b=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,p,u);b.length>0&&r("identities.external_id",b.map(s=>s.v));const h=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
|
|
4
|
+
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,u);h.length>0&&r("daemon_actions principal.sub",h.map(s=>s.v));const l=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(p),C(u));l.length>0&&r("relations acts_for subject",l.map(s=>s.v));const E=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return E>0?{relations:E}:{}}c(re,"checkStagedPersons");async function G(n,t){return(await N(n,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
|
|
5
|
+
WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(u=>u[0]))}c(G,"earlierImportedObjects");async function ae(n,t){const{db:a,schema:p,catalog:u,targetPerson:o}=n,r=await H(n,t);if(r.length>0)throw T(`the bundle refers to objects that are not ${o}'s: ${r.slice(0,10).map(b=>`${b.tbl}.${b.col}=${b.value}`).join(", ")}`,{references:r.slice(0,10)});await V(n)}c(ae,"checkStagedReferences");async function ie(n,t){const{db:a,schema:p,catalog:u}=n;if(!u.tables.has("messages"))return{};const o=c(s=>g(p,s),"S"),r=[...new Set((await H(n,t)).filter(s=>s.tbl==="messages").map(s=>s.value))];if(r.length===0)return{};const b="(object_id = ANY(?::text[]) OR actor_id = ANY(?::text[]))",h=`(SELECT message_id FROM ${o("messages")} WHERE ${b})`,l={};for(const[s,d]of[["deliveries","message_id"],["message_causes","message_id"]]){if(!u.tables.has(s))continue;const _=Number((await a.prepareUncached(`DELETE FROM ${o(s)} WHERE ${d} IN ${h}`).run(r,r)).changes);_>0&&(l[s]=_)}const E=Number((await a.prepareUncached(`DELETE FROM ${o("messages")} WHERE ${b}`).run(r,r)).changes);return E>0&&(l.messages=E),l}c(ie,"dropRefusedMessages");async function H(n,t){const{db:a,schema:p,target:u,catalog:o,targetPerson:r}=n,b=c(_=>g(p,_),"S"),h=c(_=>g(u,_),"T"),l=C(r);await a.exec(`CREATE TABLE ${b("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const E=[];for(const[_,$]of Y(o))if(!(!o.tables.has(_)||_==="relations"))for(const m of $)!(_==="nodes"&&m==="profile_id")&&!(_==="crons"&&m==="profile")&&E.push([_,m,""]);E.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[_,$,m]of E)await a.prepareUncached(`INSERT INTO ${b("_refs")} SELECT ?, ?, ${f($)}::text FROM ${b(_)} ${m===""?"WHERE":`${m} AND`} ${f($)} IS NOT NULL
|
|
6
|
+
AND ${f($)}::text NOT IN (SELECT id FROM ${b("objects")}) AND ${f($)}::text IN (SELECT id FROM ${h("objects")})`).run(_,$);const s=await G(a,t),d=await N(a,`WITH RECURSIVE chain(start, id) AS (
|
|
7
7
|
SELECT DISTINCT value, value FROM ${b("_refs")}
|
|
8
8
|
UNION SELECT c.start, o.owner FROM chain c JOIN ${h("objects")} o ON o.id = c.id JOIN ${h("objects")} up ON up.id = o.owner AND up.type <> 'app'),
|
|
9
9
|
ok(id) AS (
|
|
@@ -11,7 +11,10 @@ var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});i
|
|
|
11
11
|
UNION SELECT d.object FROM ${h("documents")} d WHERE d.source_path IS NOT NULL
|
|
12
12
|
UNION SELECT i.object FROM ${h("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
|
|
13
13
|
UNION SELECT r.resource_id FROM ${h("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
|
|
14
|
+
UNION SELECT r.resource_id FROM ${h("relations")} r JOIN ${h("relations")} m ON m.resource_type = 'crtr/group' AND m.relation = 'member' AND m.resource_id = r.subject_id
|
|
15
|
+
AND m.subject_type = 'user' AND m.subject_id = ?
|
|
16
|
+
WHERE r.resource_type = 'crtr/object' AND r.relation IN ('reader', 'editor', 'messenger', 'user_of') AND r.subject_type = 'crtr/group' AND r.subject_relation = 'member'
|
|
14
17
|
UNION SELECT unnest(?::text[]))
|
|
15
18
|
SELECT r.tbl, r.col, r.value FROM ${b("_refs")} r
|
|
16
|
-
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),
|
|
17
|
-
JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,
|
|
19
|
+
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),d}c(H,"foreignReferences");async function V(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(l=>g(a,l),"S"),r=c(l=>g(p,l),"T"),b=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[l,E]of b){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names profiles that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}for(const[l,E]of[["nodes","grant_id"],["crons","grant_id"]]){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names grants that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}const h=await N(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${o("daemon_actions")} d
|
|
20
|
+
JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,u);if(h.length>0)throw T(`a queued action names grants that belong to another person: ${h.map(l=>l.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:h.map(l=>l.v)})}c(V,"checkStagedProfilesAndGrants");const k=c((n,t)=>new F("bind","bundle_invalid",n,t),"bundleInvalid");async function ce(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(e=>g(a,e),"S"),r=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),b=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),h=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),l=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),E=c(e=>e.split("/")[1]??"","jobOwner"),s=c((e,i,S,O)=>{const D=w(i);if(D===null||D.kind!==S||O!==void 0&&i!==O)throw k(`${e} holds ${JSON.stringify(i)}, which is not a ${S} blob key${O===void 0?"":` of the shape ${O}`}`,{where:e,value:i})},"shaped");for(const e of b)if(s("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of h)s("upload_uses.blob_key",e.blob_key,"attachment");for(const e of l)s("jobs.output_key",e.output_key,"job",`jobs/${E(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of b){const i=w(e);i!==null&&i.kind==="conversation"&&!r.has(i.owner)&&d.add(i.owner)}for(const{blob_key:e}of h){const i=w(e);i!==null&&i.kind==="attachment"&&!r.has(i.owner)&&d.add(i.owner)}for(const{output_key:e}of l)r.has(E(e))||d.add(E(e));const _=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(p,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),$=c(e=>r.has(e)||_.get(e)===u,"held"),m=c(e=>!r.has(e)&&!_.has(e),"gone"),A={},I=c((e,i)=>{i>0&&(A[e]=(A[e]??0)+i)},"count"),R=c(async(e,...i)=>Number((await t.prepareUncached(e).run(...i)).changes),"drop"),W=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),L=new Map;for(const{conversation_id:e,blob_key:i}of b){const S=w(i),O=L.get(e);O!==null&&(S===null||S.kind!=="conversation"?L.set(e,null):L.set(e,[...O??[],S.owner]))}const v=[...L].filter(([e,i])=>i!==null&&!W.has(e)&&i.every(m)).map(([e])=>e);v.length>0&&(I("conversation_parts",await R(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,v)),I("conversation_entries",await R(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,v)));const U=new Set(v),j=c((e,i)=>{const S=w(i).owner;if(!$(S))throw T(`${e} holds ${i}, which belongs to node ${S}, who is not in the bundle`,{where:e,value:i})},"owned");for(const e of b)U.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const y=h.filter(e=>{const i=w(e.blob_key);return i!==null&&i.kind==="attachment"&&m(i.owner)&&!r.has(e.run_id)});y.length>0&&I("upload_uses",await R(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,y.map(e=>e.run_id),y.map(e=>e.path)));const x=new Set(y);for(const e of h)x.has(e)||j("upload_uses.blob_key",e.blob_key);const M=l.filter(e=>e.output_key===`jobs/${E(e.output_key)}/${e.object}/output`&&m(E(e.output_key)));M.length>0&&I("jobs",await R(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,M.map(e=>e.object)));const q=new Set(M);for(const e of l)q.has(e)||j("jobs.output_key",e.output_key);return A}c(ce,"checkStagedBlobKeys");async function ue(n){const{db:t,schema:a}=n;for(const p of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(a,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=p[u];if(o===null||!o.startsWith("requests/"))continue;const r=w(o.includes("/",9)?o:`${o}/x`);if(r===null||r.kind!=="request")throw k(`human_requests.${u} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${u}`,value:o});if(r.owner!==p.request_id)throw T(`human_requests.${u} of ${p.request_id} holds ${o}, which belongs to request ${r.owner}`,{where:`human_requests.${u}`,value:o})}}c(ue,"checkStagedRequestKeys");export{se as boundSub,ne as checkSourcePerson,ce as checkStagedBlobKeys,re as checkStagedPersons,ae as checkStagedReferences,ue as checkStagedRequestKeys,ie as dropRefusedMessages};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var a=(e,o)=>w(e,"name",{value:o,configurable:!0});import{
|
|
1
|
+
var w=Object.defineProperty;var a=(e,o)=>w(e,"name",{value:o,configurable:!0});import{parsePrincipal as m}from"@north-light/identity";import{joinedOwner as E}from"../directory/join.js";import{nodePlace as d}from"../permissions/ceiling.js";import{openDb as f}from"../canvas/db.js";import{ownMachineId as p}from"./directory.js";const P="Crtr-Envelope",v=16*1024,h=12*1024;class r extends Error{static{a(this,"EnvelopeError")}constructor(o){super(o),this.name="EnvelopeError"}}async function $(e,o={}){return b(await y(e,o))}a($,"envelopeFor");async function y(e,o){const n=o.via??p(),t=e.class==="person"?"":e.sub,s=o.owner??(t.startsWith("user:")?t:E());if(s==null)throw new r("this machine has no account owner to make a peer call for");if(e.class==="person")return{sub:s,act:{sub:n}};if(e.class==="broker"){const c=await(o.placeOf??(async u=>await d(await f(),u)))(e.node);return{sub:s,act:{sub:n,act:{sub:e.app,node:e.node,node_scopes:e.scopes===null?null:[...e.scopes],place:c}}}}return{sub:s,act:{sub:n,act:{sub:e.app,node:e.anchor,node_scopes:e.scopes===null?null:[...e.scopes],place:{run:e.origin_run??"",isolated:e.isolated}}}}}a(y,"buildEnvelope");function b(e){const o=_(e).length;if(o>h){const n=e.act.act?.node_scopes?.length;throw new r(`the call's identity is ${o} bytes, over the ${h}-byte limit for a call to another machine${n===void 0?"":` (the node holds ${n} scopes)`}; narrow the node's scopes`)}return e}a(b,"fits");function _(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}a(_,"encodeEnvelope");const i=a(e=>typeof e=="string"&&e!=="","isString"),l=a(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord");function B(e){if(e.length>v)throw new r("the envelope is too large");if(!/^[A-Za-z0-9_-]+$/.test(e))throw new r("the envelope is not base64url");let o;try{o=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new r("the envelope is not JSON")}if(!l(o)||!i(o.sub)||!o.sub.startsWith("user:"))throw new r("the envelope names no user");const n=o.act;if(!l(n)||!i(n.sub)||!n.sub.startsWith("runtime:"))throw new r("the envelope names no calling machine");const t=n.act;if(t===void 0)return{sub:o.sub,act:{sub:n.sub}};if(!l(t)||!i(t.sub)||m(t.sub)?.kind!=="app")throw new r("the envelope names no calling app");const{node:s,node_scopes:c,place:u}=t;if(s!==null&&!i(s))throw new r("the envelope node is not a node id");if(c!==null&&!(Array.isArray(c)&&c.every(i)))throw new r("the envelope node_scopes is not a list of scopes");if(u!==null&&!(l(u)&&typeof u.run=="string"&&typeof u.isolated=="boolean"))throw new r("the envelope place is malformed");return{sub:o.sub,act:{sub:n.sub,act:{sub:t.sub,node:s,node_scopes:c,place:u===null?null:{run:u.run,isolated:u.isolated}}}}}a(B,"decodeEnvelope");async function k(e,o,n={}){const t=n.via??p();if(e.class==="person"||e.grantee===null)return{sub:o,act:{sub:t}};const s=e.node_id===null?null:await(n.placeOf??(async c=>await d(await f(),c)))(e.node_id);return b({sub:o,act:{sub:t,act:{sub:e.grantee,node:e.node_id,node_scopes:e.nodeScopes===null?null:[...e.nodeScopes],place:s}}})}a(k,"envelopeForProviderCaller");export{P as ENVELOPE_HEADER,r as EnvelopeError,v as MAX_ENVELOPE_BYTES,h as MAX_SENT_ENVELOPE_BYTES,B as decodeEnvelope,_ as encodeEnvelope,$ as envelopeFor,k as envelopeForProviderCaller};
|
package/dist/core/peer/stubs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var T=Object.defineProperty;var r=(n,e)=>T(n,"name",{value:e,configurable:!0});import{createObject as
|
|
1
|
+
var T=Object.defineProperty;var r=(n,e)=>T(n,"name",{value:e,configurable:!0});import{parsePrincipal as A}from"@north-light/identity";import{createObject as g,getById as p,ownerForGrantee as f,ownerLockKey as N}from"../graph/objects.js";import{readLegacyPrivacy as L}from"../graph/types.js";import{upsertKind as $}from"../graph/custom.js";import{CrtrError as y}from"../errors.js";import{ExitCode as m}from"../../types.js";import{normalizeMachineId as b}from"./names.js";import{personId as d,personIdAsync as I}from"../canvas/person.js";import{writeActsFor as W}from"../permissions/facts.js";const H=["public","private"],C=r(n=>{const e=n.act.act;return e===void 0?{sub:n.sub,app:null,node:null,node_scopes:null,place:null}:{sub:n.sub,app:e.sub,node:e.node,node_scopes:e.node_scopes,place:e.place}},"identityOfEnvelope");async function S(n,e){const t=typeof e=="string"?await p(n,e):e;if(t===null)return null;const i=await n.prepare("SELECT home_machine, envelope_json FROM peer_stubs WHERE object = ?").get(t.id);return i?{object:t,home_machine:i.home_machine,identity:i.envelope_json===null?null:JSON.parse(i.envelope_json)}:null}r(S,"stubOf");const Z=r(async(n,e)=>await n.prepare("SELECT 1 FROM peer_stubs WHERE object = ?").get(e.id)!==void 0,"isStub");async function D(n){return await f(n,d())}r(D,"localPerson");async function P(n,e){return await f(n,e)}r(P,"localApp");async function ee(n,e){return e.type==="app"?await P(n,`app:${e.name}`):e.type==="person"?await D(n):null}r(ee,"localOwnerActor");function h(n,e){return n!==null?n.app===null?d():n.app:e?.type==="app"?e.external_id??`app:${e.handle}`:d()}r(h,"ownerGrantee");async function k(n,e,t){return await f(n,h(e,t?.owner))}r(k,"ownerFor");const U=["ingest:","stub:","owner:","kind:"],O=r(n=>{const e=U.findIndex(t=>n.startsWith(t));if(e<0)throw new Error(`lockInOrder: ${JSON.stringify(n)} is not a known lock key`);return e},"rankOf");async function K(n,e){const t=[...new Set(e)];if(t.length===0)return;const c=(await n.prepareUncached(t.map((a,o)=>`SELECT ${o} AS i, hashtext(?) AS h`).join(" UNION ALL ")).all(...t)).map(a=>({key:t[Number(a.i)],hash:Number(a.h)})).sort((a,o)=>O(a.key)-O(o.key)||a.hash-o.hash);for(const{key:a}of c)await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(a)}r(K,"lockInOrder");async function E(n,e){const t=A(e);if(t===null)throw new Error(`grantee ${JSON.stringify(e)} is not a principal`);const[i,c]=t.kind==="app"?["app",t.namespace]:["user",e];return await n.prepare("SELECT 1 FROM identities WHERE scheme = ? AND external_id = ?").get(i,c)===void 0?[N(i,c)]:[]}r(E,"missingOwnerKey");async function v(n,e,t,i,c){const a=[`stub:${e}`],o=c?.kind_decl;return o!==void 0&&o.name===t&&a.push(`kind:${t}`,...await E(n,h(null,o.owner))),await p(n,e)===null&&a.push(...await E(n,h(i,c?.owner))),a}r(v,"stubLockKeys");async function ne(n,e){return e.type==="app"?await E(n,`app:${e.name}`):e.type==="person"?await E(n,d()):await v(n,e.id,e.type,null,e)}r(ne,"actorLockKeys");async function F(n,e,t,i,c,a){const o=c===void 0?null:C(c),u=L(a?.privacy??"public");if(!H.includes(u))throw new y("invalid_event",`invalid privacy ${JSON.stringify(u)}`,m.GENERAL,{id:e});await K(n,await v(n,e,t,o,a));const s=await p(n,e);if(s!==null){const w=await S(n,s);if(w===null)throw new y("conflict",`${e} is a local ${s.type}, not a stub of ${i}`,m.GENERAL,{id:e});if(w.home_machine!==i)throw new y("conflict",`${e} is already a stub of ${w.home_machine}, not ${i}`,m.GENERAL,{id:e,home_machine:w.home_machine});return o!==null&&(await n.prepare("UPDATE peer_stubs SET envelope_json = ? WHERE object = ?").run(JSON.stringify(o),s.id),await n.prepare("UPDATE objects SET reception = 2 WHERE id = ?").run(s.id)),a!==void 0&&(await x(n,t,a),a.privacy!==void 0&&s.privacy!==u)?(await n.prepare("UPDATE objects SET privacy = ? WHERE id = ?").run(u,s.id),await p(n,s.id)):s}const _=await k(n,o,a);await x(n,t,a);const l=await g(n,{id:e,type:t,kind:a?.kind??null,owner:_.id,privacy:u,name:a?.name??e,preview:a?.preview??"",home_machine:i});return await n.prepare("INSERT INTO peer_stubs (object, home_machine, envelope_json, created_at) VALUES (?, ?, ?, ?)").run(l.id,i,o===null?null:JSON.stringify(o),new Date().toISOString()),_.type==="app"&&await W(n,l.id,await I()),o!==null&&await n.prepare("UPDATE objects SET reception = 2 WHERE id = ?").run(l.id),await p(n,l.id)}r(F,"ensureStub");async function x(n,e,t){const i=t?.kind_decl;i===void 0||i.name!==e||await $(n,{name:i.name,owner:await k(n,null,{...t,owner:i.owner}),description:i.description,events:i.events,read:null,source:"peer"})}r(x,"holdKind");async function te(n,e,t){const i=await F(n,e,"node",b(t));return await n.prepare("UPDATE objects SET reception = 2 WHERE id = ?").run(i.id),await p(n,i.id)}r(te,"ensureNodeStub");async function ie(n,e,t){const i=await S(n,e);i===null||i.home_machine===t||(await n.prepare("UPDATE peer_stubs SET home_machine = ? WHERE object = ?").run(t,i.object.id),await n.prepare("UPDATE objects SET home_machine = ? WHERE id = ?").run(t,i.object.id))}r(ie,"rehomeStub");async function ae(n,e){const t=await R(n,e.owner===null?null:await p(n,e.owner)),i=await j(n,e.type);return{id:e.id,type:e.type,kind:e.kind,name:e.name,preview:e.preview,owner:t,privacy:e.privacy,...i===null?{}:{kind_decl:i}}}r(ae,"describeObject");async function R(n,e){if(e===null||e.type!=="person"&&e.type!=="app"&&e.type!=="repo"&&e.type!=="profile"&&e.type!=="group")return null;const t=await n.prepare("SELECT scheme, external_id FROM identities WHERE object = ?").get(e.id);return{id:e.id,type:e.type,scheme:t?.scheme??null,external_id:t?.external_id??null,handle:e.name}}r(R,"ownerRefOf");async function j(n,e){const t=await n.prepare("SELECT owner, description, events_json FROM object_kinds WHERE name = ?").get(e),i=t===void 0?null:await R(n,await p(n,t.owner));return t===void 0||i===null?null:{name:e,description:t.description,events:JSON.parse(t.events_json),owner:i}}r(j,"kindDeclarationOf");async function re(n,e,t){const i=await j(n,e.type);return i===null?t:{...t,kind_decl:i}}r(re,"withKindDecl");export{ne as actorLockKeys,ae as describeObject,te as ensureNodeStub,F as ensureStub,C as identityOfEnvelope,Z as isStub,j as kindDeclarationOf,ee as localOwnerActor,K as lockInOrder,ie as rehomeStub,v as stubLockKeys,S as stubOf,re as withKindDecl};
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var j=Object.defineProperty;var s=(t,e)=>j(t,"name",{value:e,configurable:!0});import{covers as
|
|
2
|
-
WHERE g.resolved_scopes_json::jsonb @> '[{"scope":"crtr:memory:manage:user","mode":"always"}]'::jsonb`).all()).map(n=>n.id)}s(
|
|
1
|
+
var j=Object.defineProperty;var s=(t,e)=>j(t,"name",{value:e,configurable:!0});import{parsePrincipal as x}from"@north-light/identity";import{covers as R}from"@north-light/identity";import{isCloudRole as F}from"../canvas/person-state.js";import{eligiblePackageApps as M}from"../packages/eligibility.js";import{subjectSet as U}from"./evaluator.js";import{FALSE as g,TRUE as H,and as k,f as h,or as T,raw as c}from"./sql.js";const J=s(t=>({ownApp:t,roots:[],namespaces:[],place:null,predicates:{allNodes:!1,spaces:!1},authorApps:[],packageApps:null}),"empty");async function L(t,e){return(await t.prepare("SELECT external_id FROM identities WHERE object = ? ORDER BY scheme LIMIT 1").get(e))?.external_id??null}s(L,"externalId");async function D(t,e,n){return(await t.prepare("SELECT o.id FROM identities i JOIN objects o ON o.id = i.object WHERE i.scheme = ? AND i.external_id = ? AND o.deleted_at IS NULL").get(e,n))?.id??null}s(D,"objectOf");async function P(t){return(await t.prepare("SELECT id FROM objects WHERE type = 'person' AND home_machine IS NULL AND deleted_at IS NULL ORDER BY created_at").all()).map(n=>n.id)}s(P,"personObjectIds");async function X(t){return(await t.prepare(`SELECT DISTINCT i.object AS id FROM grants g JOIN identities i ON i.external_id = g.grantee AND i.scheme = 'app'
|
|
2
|
+
WHERE g.resolved_scopes_json::jsonb @> '[{"scope":"crtr:memory:manage:user","mode":"always"}]'::jsonb`).all()).map(n=>n.id)}s(X,"firstPartyApps");function I(t,e){return z(t).has(e.replace(/^app:/,""))}s(I,"holdsProviderGroup");const W=new WeakMap;function z(t){let e=W.get(t);if(e===void 0){e=new Set;for(const n of t){const o=n.indexOf(":");o>=0&&!n.includes(":",o+1)&&e.add(n.slice(0,o))}W.set(t,e)}return e}s(z,"providerGroupHolders");function Y(t){return t.class==="object"?t.repos.map(e=>e.id):t.class!=="node"?[]:[...new Set([...t.repos,...t.projectRepos].map(e=>e.id))]}s(Y,"repoRoots");async function Z(t,e){return e===null?[]:(await U(t,e)).groupIds.filter(n=>n.startsWith("group:")).map(n=>n.slice(6))}s(Z,"memberGroups");async function V(t,e,n){if(e.class==="person")return null;const o=e.scopes;return await M(t,{holdsProvider:s(f=>o!==null&&I(o,f),"holdsProvider"),cloud:F(),ownExt:await L(t,e.app.id),user:n})}s(V,"readablePackageApps");async function ie(t,e,n,o,f={}){if(e.class==="person")return null;const a=J(e.app.id),r=e.scopes,E=s(i=>r!==null&&r.some(p=>R(p,i)),"has"),l=await L(t,e.app.id),w=e.class==="node"?await _(t,e.node.id):e.place??null;a.place=w,a.authorApps=[e.app.id];const N=o==="write"?"rw":"read",m=e.launched,d=s((i,p,u=!0)=>{a.roots.push({id:i,private:u,match:p})},"own");if(o==="message"||m===void 0||m===null||l===null||m.some(i=>R(i,`crtr:memory:${N}:${l}`)))d(e.app.id,"any"),l!==null&&(a.namespaces=await G(t,l));else{d(e.app.id,"non-document"),o==="read"&&w!==null&&d(e.app.id,"run-report");for(const i of await t.prepare("SELECT o.id, i.external_id FROM objects o JOIN identities i ON i.object = o.id AND i.scheme = 'profile' WHERE o.owner = ? AND o.type = 'profile' AND o.deleted_at IS NULL").all(e.app.id))m.some(p=>R(p,`crtr:memory:${N}:${l}:profile:${i.external_id}`))&&d(i.id,"no-node")}if(o==="read"&&(a.packageApps=await V(t,e,n)??[]),o==="read"&&w===null&&d(e.app.id,"run-node",!1),r===null)return a;a.predicates.spaces=!0;const A=await P(t),y=E("crtr:memory:manage:user"),C=y||E("crtr:memory:read_private:user"),S=s((i,p)=>{for(const u of A)u!==e.app.id&&a.roots.push({id:u,private:p,match:i})},"addPerson");if(o==="write")if(y)S("any",!0);else{E("crtr:memory:rw:user")&&(S("self",!0),S("authored:*",!0));for(const i of r){const p=/^crtr:memory:rw:user:(.+)$/.exec(i);p!==null&&S(`authored:${p[1]}`,!0)}E("crtr:objects:write:user")&&S("any",!0),a.roots.some(i=>i.match.startsWith("authored:"))&&a.authorApps.push(...await X(t))}else o==="read"&&(y?S("any",!0):S("direct-doc",C),E(`crtr:objects:${f.verb??"read"}:user`)&&S("any",C));const v=o==="write"?"write":f.verb??"read",b=e.class==="object"&&e.object.type.includes("."),$=s(async(i,p)=>{const u=x(i);if(u?.kind!=="app"||u.path.length>0)return;const O=await D(t,"app",i);O===null||O===e.app.id||a.roots.push({id:O,private:I(r,i),match:p})},"appRoot");for(const i of r){if(!i.startsWith("crtr:"))continue;let p=/^crtr:memory:(read|rw):app:([A-Za-z0-9_-]{1,64})(?::profile:([A-Za-z0-9_-]{1,64}))?$/.exec(i);if(p!==null&&(o==="read"||o==="write"&&p[1]==="rw")){if(p[3]===void 0)await $(`app:${p[2]}`,"no-node");else{const u=await D(t,"profile",p[3]);u!==null&&a.roots.push({id:u,private:!1,match:"no-node"})}continue}if(p=/^crtr:objects:(read|watch|link|write):(user|node|profile:[A-Za-z0-9_-]+|app:[A-Za-z0-9_-]+)$/.exec(i),p!==null&&o!=="message"&&(p[1]===v||o==="read"&&b&&p[1]==="watch")){const u=p[2];if(u==="node")a.predicates.allNodes=!0;else if(u.startsWith("profile:")){const O=await D(t,"profile",u.slice(8));O!==null&&a.roots.push({id:O,private:!1,match:"below"})}else u.startsWith("app:")&&await $(u,"objects-app");continue}if(p=/^crtr:conversations:read:(app:[A-Za-z0-9_-]+)$/.exec(i),p!==null&&o==="read"){await $(p[1],"node-report"),await $(p[1],"run-node");continue}p=/^crtr:objects:message:(app:[A-Za-z0-9_-]+)$/.exec(i),p!==null&&o==="message"&&await $(p[1],"node-tree")}if(o==="read"){for(const i of a.packageApps??[])i!==e.app.id&&a.roots.push({id:i,private:!1,match:"shipped"});for(const i of await t.prepare("SELECT o.id, i.external_id FROM objects o JOIN identities i ON i.object = o.id AND i.scheme = 'app' WHERE o.type = 'app' AND o.deleted_at IS NULL").all())i.id!==e.app.id&&a.roots.push({id:i.id,private:I(r,i.external_id),match:"custom"})}if(o!=="message")for(const i of[...Y(e),...await Z(t,n)])a.roots.push({id:i,private:o==="read",match:"any"});return a}s(ie,"resolveCeiling");async function G(t,e){return(await t.prepare("SELECT namespace FROM schemas WHERE app = ?").all(e)).map(n=>n.namespace)}s(G,"ownNamespaces");async function _(t,e){const n=await t.prepare("SELECT run_id, isolated FROM nodes WHERE node_id = ?").get(e);if(n!==void 0)return{run:n.run_id??e,isolated:n.isolated===1};const o=await t.prepare("SELECT run_id FROM deleted_isolated_nodes WHERE node_id = ?").get(e);return o?{run:o.run_id,isolated:!0}:null}s(_,"nodePlace");async function ae(t,e){const n=await _(e,t);n?.isolated&&await e.prepare("INSERT INTO deleted_isolated_nodes (node_id, run_id) VALUES (?, ?) ON CONFLICT (node_id) DO UPDATE SET run_id = excluded.run_id").run(t,n.run)}s(ae,"rememberDeletedIsolated");function pe(t){return t.class==="person"?t:{...t,launched:null}}s(pe,"asRuntimeWriter");async function se(t,e,n,o,f=!1){if(e.class==="person"||e.launched===void 0||e.launched===null)return null;const a=await t.prepare(`WITH RECURSIVE c(id, owner, type, kind, depth) AS (
|
|
3
3
|
SELECT id, owner, type, kind, 0 FROM objects WHERE id = ? UNION ALL
|
|
4
4
|
SELECT p.id, p.owner, p.type, p.kind, c.depth + 1 FROM c JOIN objects p ON p.id = c.owner WHERE c.depth < 12)
|
|
5
|
-
SELECT c.id, c.type, c.kind FROM c ORDER BY c.depth`).all(n);if(a[a.length-1]?.id!==e.app.id)return null;const r=await
|
|
6
|
-
SELECT ${
|
|
5
|
+
SELECT c.id, c.type, c.kind FROM c ORDER BY c.depth`).all(n);if(a[a.length-1]?.id!==e.app.id)return null;const r=await L(t,e.app.id);if(r===null)return null;if(a.length===1)return f?e.launched.some(N=>R(N,`crtr:memory:${o}:${r}`))?null:`crtr:memory:${o}:${r}`:null;if(!f&&a[0].type!=="document")return null;const E=a.slice(0,-1).reverse();if(o==="read"&&!f&&a[0].kind==="report"&&E[0].type==="node"&&e.class!=="object"){const N=e.class==="node"?await _(t,e.node.id):e.place??null,m=await _(t,E[0].id);if(N!==null&&m!==null&&N.run===m.run)return null}const l=E[0],w=l.type==="profile"?`crtr:memory:${o}:${r}:profile:${await L(t,l.id)}`:`crtr:memory:${o}:${r}`;return e.launched.some(N=>R(N,w))?null:w}s(se,"missingMemoryScope");function ce(t,e){const n=[];t.roots.length>0&&n.push(K(t,e)),t.namespaces.length>0&&n.push(h`split_part(${c(e)}.schema_type, '/', 1) = ANY(${t.namespaces}::text[])`),t.predicates.allNodes&&n.push(c(`(${e}.type = 'node' AND ${e}.privacy = 'public')`)),t.predicates.spaces&&n.push(c(`(${e}.owner IS NULL AND ${e}.type IN ('app','person','repo','group'))`));const o=t.packageApps===null?H:h`(NOT EXISTS (SELECT 1 FROM documents sd WHERE sd.object = ${c(e)}.id AND sd.source_path IS NOT NULL) OR ${c(e)}.owner = ANY(${t.packageApps}::text[]))`;return k([T(n),B(t,e),o])}s(ce,"ceilingFrag");function B(t,e){if(t.place===null)return H;const n=t.place.isolated?1:0;return h`NOT EXISTS (WITH RECURSIVE ca(id, owner, depth, near_node) AS (
|
|
6
|
+
SELECT ${c(e)}.id, ${c(e)}.owner, 0, CASE WHEN ${c(e)}.type = 'node' THEN ${c(e)}.id END
|
|
7
7
|
UNION ALL
|
|
8
8
|
SELECT p.id, p.owner, ca.depth + 1, COALESCE(ca.near_node, CASE WHEN p.type = 'node' THEN p.id END)
|
|
9
9
|
FROM ca JOIN objects p ON p.id = ca.owner WHERE ca.depth < 12)
|
|
10
10
|
SELECT 1 FROM ca LEFT JOIN nodes cn ON cn.node_id = ca.near_node LEFT JOIN deleted_isolated_nodes cd ON cd.node_id = ca.near_node
|
|
11
11
|
WHERE ca.id = ${t.ownApp} AND ca.depth > 0 AND ca.near_node IS NOT NULL
|
|
12
12
|
AND NOT (CASE WHEN cn.node_id IS NOT NULL THEN COALESCE(cn.run_id, cn.node_id) = ${t.place.run} OR (cn.isolated = 0 AND ${n} = 0)
|
|
13
|
-
WHEN cd.node_id IS NOT NULL THEN cd.run_id = ${t.place.run} ELSE ${n} = 0 END))`}s(
|
|
14
|
-
WHERE rv.document = ${
|
|
15
|
-
AND (au.type = 'person' OR COALESCE((SELECT app FROM nodes WHERE node_id = au.id), au.owner) = ANY(${t.authorApps}::text[]))))`)}const w=
|
|
16
|
-
WHERE rn.node_id = ${
|
|
17
|
-
SELECT ${
|
|
13
|
+
WHEN cd.node_id IS NOT NULL THEN cd.run_id = ${t.place.run} ELSE ${n} = 0 END))`}s(B,"placeFrag");function K(t,e){const n=t.roots.map(d=>d.id),o=t.roots.map(d=>d.private?1:0),f=t.roots.map(d=>d.match),a=new Set(t.roots.map(d=>d.match)),r=s(d=>`${e}.${d}`,"O"),E=[],l=s((d,A)=>{a.has(d)&&E.push(h`(r.match = ${d} AND ${typeof A=="string"?c(A):A})`)},"t");l("any","TRUE"),l("below","ca.depth > 0"),l("direct-doc",`(ca.depth = 0 OR (ca.depth = 1 AND ${r("type")} = 'document'))`),l("no-node","NOT ca.node_below"),l("node-tree","ca.node_below"),l("objects-app",`(ca.node_below OR ${r("type")} LIKE '%.%')`),l("node-report",`(ca.node_below AND ${r("type")} = 'document' AND ${r("kind")} = 'report')`),l("custom",`${r("type")} LIKE '%.%'`),l("shipped",`(ca.depth > 0 AND EXISTS (SELECT 1 FROM documents sd WHERE sd.object = ${r("id")} AND sd.source_path IS NOT NULL))`),l("non-document",`(${r("type")} <> 'document')`),l("self","ca.depth = 0"),a.has("run-report")&&E.push(t.place===null?g:h`(r.match = 'run-report' AND ${c(r("type"))} = 'document' AND ${c(r("kind"))} = 'report' AND EXISTS (SELECT 1 FROM nodes rn WHERE rn.node_id = ca.near_node AND COALESCE(rn.run_id, rn.node_id) = ${t.place.run}))`);for(const d of a)if(d.startsWith("authored:")){const A=d.slice(9);E.push(h`(r.match = ${d} AND ca.depth = 1 AND ${c(r("type"))} = 'document' AND ${A==="*"?c("TRUE"):h`${c(r("name"))} = ${A}`} AND EXISTS (SELECT 1 FROM revisions rv JOIN objects au ON au.id = rv.author
|
|
14
|
+
WHERE rv.document = ${c(r("id"))} AND rv.number = (SELECT min(number) FROM revisions WHERE document = ${c(r("id"))})
|
|
15
|
+
AND (au.type = 'person' OR COALESCE((SELECT app FROM nodes WHERE node_id = au.id), au.owner) = ANY(${t.authorApps}::text[]))))`)}const w=T(E),N=a.has("run-node")?h`EXISTS (SELECT 1 FROM nodes rn JOIN unnest(${n}::text[], ${o}::int[], ${f}::text[]) AS r(id, priv, match) ON r.match = 'run-node' AND r.id = rn.app
|
|
16
|
+
WHERE rn.node_id = ${c(r("id"))} AND rn.run_id IS NOT NULL AND ${c(r("type"))} = 'node' AND (${c(r("privacy"))} = 'public' OR r.priv = 1))`:g,m=h`EXISTS (WITH RECURSIVE ca(id, owner, type, depth, node_below, near_node) AS (
|
|
17
|
+
SELECT ${c(r("id"))}, ${c(r("owner"))}, ${c(r("type"))}, 0, FALSE, CASE WHEN ${c(r("type"))} = 'node' THEN ${c(r("id"))} END
|
|
18
18
|
UNION ALL
|
|
19
19
|
SELECT p.id, p.owner, p.type, ca.depth + 1, ca.node_below OR ca.type = 'node', COALESCE(ca.near_node, CASE WHEN p.type = 'node' THEN p.id END)
|
|
20
20
|
FROM ca JOIN objects p ON p.id = ca.owner WHERE ca.depth < 12)
|
|
21
21
|
SELECT 1 FROM ca JOIN unnest(${n}::text[], ${o}::int[], ${f}::text[]) AS r(id, priv, match) ON r.id = ca.id
|
|
22
|
-
WHERE (CASE WHEN ca.id = r.id THEN (${
|
|
22
|
+
WHERE (CASE WHEN ca.id = r.id THEN (${c(r("privacy"))} = 'public' OR r.priv = 1) ELSE FALSE END) AND ${w})`;return T([m,N])}s(K,"rootsFrag");export{pe as asRuntimeWriter,ce as ceilingFrag,I as holdsProviderGroup,se as missingMemoryScope,_ as nodePlace,P as personObjectIds,V as readablePackageApps,ae as rememberDeletedIsolated,ie as resolveCeiling};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var a=(s,e)=>L(s,"name",{value:e,configurable:!0});import{parsePrincipal as x}from"@north-light/identity";import{isCloudRole as _,personIdAsync as H}from"../canvas/person.js";import{requestPersonId as W}from"../canvas/person-state.js";import{OBJECT_TYPE as k,GROUP_TYPE as m}from"./builtin.js";import{ceilingFrag as M,resolveCeiling as U}from"./ceiling.js";import{compilePermission as w}from"./compile.js";import{PermissionError as j}from"./errors.js";import{loadDefinitions as y}from"./schemas.js";import{TRUE as D,and as F,f as d,or as P,raw as u}from"./sql.js";const q=["read","edit","message","use","share"],v={read:"read",use:"read",edit:"write",share:"write",message:"message"},f=a(s=>s.replace(/^user:/,""),"bareUser"),S=a(s=>{const e=x(s);return e?.kind==="user"?f(e.namespace):null},"personSub");async function J(s,e){const t=await A(s,e);if(t!==null)return t;const n=e.class==="app"&&e.sub===void 0;if(e.class==="app"&&!(n&&!_()))throw new j(403,"no_person","an app reader that names no person acts for no one");return f(await H())}a(J,"userOf");async function A(s,e){if(e.class==="person"){const r=await s.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(e.person.id);return r===void 0?null:f(r.external_id)}if(e.class==="app")return e.sub===void 0?null:S(e.sub);if(e.class==="object"&&e.sub!==void 0)return S(e.sub);const t=e.class==="node"?e.node.id:e.object.id,n=await s.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(t);return n?.sub==null?null:S(n.sub)}a(A,"namedUserOf");async function O(s,e){const t=[e,"*"],n=await s.prepareUncached(`WITH RECURSIVE g(id) AS (
|
|
2
2
|
SELECT resource_id FROM relations WHERE resource_type = ? AND relation = 'member' AND subject_type = 'user' AND subject_id = ANY(?::text[])
|
|
3
3
|
UNION
|
|
4
4
|
SELECT r.resource_id FROM relations r JOIN g ON r.subject_type = ? AND r.subject_id = g.id AND r.subject_relation = 'member'
|
|
5
5
|
WHERE r.resource_type = ? AND r.relation = 'member')
|
|
6
|
-
SELECT id FROM g`).all(m,
|
|
6
|
+
SELECT id FROM g`).all(m,t,m,m);return{userIds:t,groupIds:n.map(r=>r.id)}}a(O,"subjectSet");const p=new WeakMap,ce=a(s=>(p.has(s)||p.set(s,null),s),"shareReads");function Y(s,e){const t=p.get(e);if(t)return t;const n=(async()=>{const r=_()&&W()===void 0?await A(s,e):await J(s,e);return{reader:e,userId:r,subjects:r===null?{userIds:["*"],groupIds:[]}:await O(s,r),defs:await y(s)}})();return t===null&&(p.set(e,n),n.catch(()=>p.set(e,null))),n}a(Y,"resolveReader");const B=a(s=>"subjects"in s,"isEval");async function G(s,e,t,n="o",r={}){if(!q.includes(t))throw new j(400,"unknown_permission",`unknown permission ${t}`);const o=B(e)?e:await Y(s,e),{defs:c}=o,E=u(`${n}.id`),N=w(c,o.subjects,k,t,E),h=t==="read"?P([N,u(`${n}.type = 'app'`)]):N,g=o.reader.class==="person"?null:o.reader.app.id,T=o.reader.class==="app"&&o.reader.place===void 0&&g!==null?await z(s,g):new Set,l=[];for(const[i,I]of c){if(i.startsWith("crtr/")||i==="user"||i==="app"||!(t in I.permissions)&&!(t in I.relations))continue;const C=i.split("/")[0];l.push(d`WHEN ${u(n)}.schema_type = ${i} THEN ${T.has(C)?D:w(c,o.subjects,i,t,E)}`)}const b=l.length===0?d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${h} ELSE FALSE END)`:d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${h} ${{sql:l.map(i=>i.sql).join(" "),params:l.flatMap(i=>i.params)}} ELSE FALSE END)`,R=await V(s,o,v[t],r);return R===null?b:F([M(R,n),b])}a(G,"permits");const $=new WeakMap;function V(s,e,t,n={}){let r=$.get(e.reader);r===void 0&&$.set(e.reader,r=new Map);const o=`${t} ${n.verb??""} ${e.userId} ${e.subjects.groupIds.join(",")}`;let c=r.get(o);return c===void 0&&(c=U(s,e.reader,e.userId,t,n),r.set(o,c),c.catch(()=>r.delete(o))),c}a(V,"ceilingOf");async function z(s,e){const t=await s.prepare("SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?").all(e);return new Set(t.map(n=>n.namespace))}a(z,"ownNamespaceTypes");async function ie(s,e,t,n,r={}){const o=await G(s,e,t,"o",r);return(await s.prepareUncached(`SELECT ${o.sql} AS ok FROM objects o WHERE o.id = ?`).get(...o.params,n))?.ok===!0}a(ie,"check");async function ue(s,e,t,n){const r=await O(s,f(e)),o=await y(s),c=w(o,r,n.type,t,d`${n.id}::text`);return(await s.prepareUncached(`SELECT ${c.sql} AS ok`).get(...c.params))?.ok===!0}a(ue,"checkUser");export{q as PERMISSIONS,V as ceilingOf,ie as check,ue as checkUser,G as permits,Y as resolveReader,ce as shareReads,O as subjectSet,J as userOf};
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
var l=Object.defineProperty;var n=(t,e)=>l(t,"name",{value:e,configurable:!0});import{headlessText as
|
|
1
|
+
var l=Object.defineProperty;var n=(t,e)=>l(t,"name",{value:e,configurable:!0});import{headlessText as d}from"./headless-pi.js";import{envRecapModelOverride as c}from"../../shared/env.js";const m=25e3,u="anthropic/claude-haiku-5-5",p=`You brief a developer returning to a paused coding-agent conversation. They run many agent sessions in parallel and have lost this one's thread: they no longer know what this conversation is about or what they originally asked for. The brief exists to solve exactly that \u2014 pinned above their input box, it must tell them at a glance what this conversation is FOR and where it actually stands. You are given the first and most recent messages of the literal user/agent back-and-forth (tool output omitted), and the agent's roadmap file when one exists.
|
|
2
2
|
|
|
3
3
|
Output EXACTLY two plain-text lines, nothing else:
|
|
4
4
|
Goal: <what was requested \u2014 the original ask / what this conversation is for>
|
|
5
5
|
State: <catch-them-up: what is ACTUALLY going on right now>
|
|
6
6
|
|
|
7
|
-
Both lines are extremely short \u2014 telegraphic fragments, roughly 8-15 words, no filler. The State line must NOT restate the most recent message \u2014 the last message is often mid-progress, a question, or noise; instead synthesize the real position: what has landed, what is in flight, and the live blocker or needed answer.
|
|
7
|
+
Both lines are extremely short \u2014 telegraphic fragments, roughly 8-15 words, no filler. The State line must NOT restate the most recent message \u2014 the last message is often mid-progress, a question, or noise; instead synthesize the real position: what has landed, what is in flight, and the live blocker or needed answer. Do NOT say what the agent is waiting on or who it waits for \u2014 the viewer already shows that on its own line. Be concrete (real file names, branches, SHAs, error messages \u2014 one specific anchor beats abstractions). Never narrate turn by turn, hedge, or pad. If the conversation has barely started, still emit your best two lines.
|
|
8
8
|
|
|
9
9
|
Examples of the shape (from other conversations):
|
|
10
10
|
Goal: Validate + commit the Unit 3 attach-keybinding migration in this worktree.
|
|
11
11
|
State: Done \u2014 17/17 tests green, committed and rebased onto main.
|
|
12
12
|
|
|
13
13
|
Goal: Build the trimmed-v1 command-plugin seam (orchestrating phases).
|
|
14
|
-
State: Phase 1 landed;
|
|
14
|
+
State: Phase 1 landed; core-seam worker building phase 2.
|
|
15
15
|
|
|
16
16
|
Goal: Standing personal assistant \u2014 iMessage wakes, Reddit scans, small tasks.
|
|
17
|
-
State:
|
|
17
|
+
State: Reddit scan shipped; hook, map export and Omi timing still open.`;function g(t,e){return`${e!==void 0&&e.trim()!==""?`<roadmap>
|
|
18
18
|
${e.trim()}
|
|
19
19
|
</roadmap>
|
|
20
20
|
|
|
@@ -22,6 +22,6 @@ ${e.trim()}
|
|
|
22
22
|
${t}
|
|
23
23
|
</conversation>
|
|
24
24
|
|
|
25
|
-
Write the two-line Goal:/State: briefing for the conversation above. Output JUST the two lines.`}n(g,"recapUserPrompt");function f(t){const e=
|
|
25
|
+
Write the two-line Goal:/State: briefing for the conversation above. Output JUST the two lines.`}n(g,"recapUserPrompt");function f(t){const e=c();return e!==void 0?e:t!==void 0&&t.trim()!==""?t.trim():u}n(f,"recapModel");function w(t){return t.split(`
|
|
26
26
|
`).map(e=>e.replace(/\s+/g," ").trim()).filter(e=>e!=="").join(`
|
|
27
|
-
`)}n(w,"parseRecap");function
|
|
27
|
+
`)}n(w,"parseRecap");function T(t,e,a,r,o){const i=(t??"").trim();i!==""&&d({systemPrompt:p,userPrompt:g(i,r),modelSpec:f(a),timeoutMs:m,...o===void 0?{}:{causedBy:o}}).then(h=>{const s=w(h);if(s!=="")try{e(s)}catch{}}).catch(()=>{})}n(T,"generateRecap");export{T as generateRecap};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var f=(r,n)=>b(r,"name",{value:n,configurable:!0});import{parseScope as A}from"@north-light/identity";import{coveredByAny as p}from"../../shared/env.js";import{activeGrant as E,grantFor as F}from"../grants/mirror.js";import{isNamespaceOwner as j,ownerScopes as z}from"../grants/owner.js";import{appSpace as h,userFilesRoot as N}from"../layout.js";import{contains as y}from"./file-root.js";import{join as R,resolve as l}from"node:path";import{lstatSync as Z,realpathSync as d}from"node:fs";async function D(r,n,o,t){const e=o?await E(o):await F(r,n);if(o&&!e)throw new Error(`no active grant for ${r}`);return _(r,n,e,t)}f(D,"permissionsForRun");function _(r,n,o,t){if(o?o.grantee!==r||o.sub!==n:!j(r,n))throw new Error(`no active grant for ${r}`);if(t!==null&&!Array.isArray(t))throw new Error("invalid launched scopes");const e=[],s=[];let c=t===null;const m=o?o.resolved:z(r),$=t??m;for(const i of $){if(typeof i!="string")throw new Error("invalid launched scope");A(i);const v=i===`crtr:memory:read:${r}`||i===`crtr:memory:rw:${r}`||i.startsWith(`crtr:memory:read:${r}:`)||i.startsWith(`crtr:memory:rw:${r}:`);if(t!==null&&!v&&!p(m,i))throw new Error(`launched scope not in grant: ${i}`);const w=/^crtr:files:(read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(i);if(w){const[,x,u,S]=w;if(u===r)throw new Error(`own-app files cannot narrow a run: ${i}`);e.push({holder:u,path:S,writable:x==="rw"})}const a=/^crtr:objects:read:(app:[A-Za-z0-9_-]{1,64})$/.exec(i);a&&a[1]!==r&&s.push(a[1])}return{app:r,ownNodes:c,otherFiles:e,otherNodes:s}}f(_,"permissionsForGrant");function k(r,n){const o=l(r);for(const t of n){const e=l(t);if(y(e,o))try{if(d(o)!==o||d(e)!==e)continue;let s=o;for(;y(e,s)&&!Z(s).isSymbolicLink();){if(s===e)return!0;s=l(s,"..")}}catch{}}return!1}f(k,"readableProject");function H(r,n,o,t){const e=[h(n).files];for(const s of t??o){if(t!==null&&!p(o,s))continue;const c=/^crtr:files:(?:read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(s);c&&e.push(R(c[1]==="user"?N():h(c[1]).files,c[2]==="."?"":c[2]))}return k(r,e)}f(H,"readableProjectForScopes");import{fileRoot as M}from"./file-root.js";export{M as fileRoot,_ as permissionsForGrant,D as permissionsForRun,k as readableProject,H as readableProjectForScopes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var N=Object.defineProperty;var u=(e,r)=>N(e,"name",{value:r,configurable:!0});import{existsSync as R}from"node:fs";import{assertGranteeRunsHere as O}from"../runtime/unsandboxed.js";import{randomUUID as k}from"node:crypto";import{join as h}from"node:path";import{getNode as S}from"../canvas/canvas.js";import{nodeAgentDir as H,nodeHome as K,nodeRunDir as B}from"../canvas/paths.js";import{appSpace as F}from"../layout.js";import{activeGrant as g,activeGrantForApp as y,grantFor as I,grantsGeneration as G}from"../grants/mirror.js";import{ownsWithoutRow as b}from"../grants/owner.js";import{emitEvent as A}from"../events/emit.js";import{ensureAppSpace as M}from"./space.js";import{compileLaunch as D,launchStillGranted as j}from"./mounts.js";import{pinSandboxRuntimeHome as q}from"./runtime-home.js";import{sandboxCacheEnv as U}from"./cache-env.js";import{launcherRequest as E}from"../../launcher/client.js";import{LAUNCHER_SOCKET as L}from"../../launcher/spec.js";import{isCloudRole as W}from"../canvas/person.js";import{launchSub as x}from"../runs/node-sub.js";function z(e){return`cron-${e}`}u(z,"cronLaunchId");function we(){if(process.platform!=="linux")return!1;if(R(L))return!0;throw new Error("root launcher socket is unavailable; refusing an unsandboxed app process")}u(we,"appProcessSandboxed");function pe(){return P??(process.platform==="linux"&&R(L))}u(pe,"appProcessesSandboxed");let P;function he(e){P=e}u(he,"__setAppProcessesSandboxedForTest");async function ge(e,r,n,o=!1,i,d){const a=n===void 0?null:await S(n),s=d!==void 0?d.grantId?await g(d.grantId):await I(e,d.sub):a?null:await y(e);if(d!==void 0?!s&&!b(e,d.sub,d.grantId):!a&&!s)throw new Error(`no active grant for ${e}`);return(await D({nodeId:n??"proc-cwd-check",app:e,...d!==void 0?{sub:d.sub,grantId:s?.id??null,scopes:d.scopes}:{sub:a?x(a.sub,a.node_id):s.sub,grantId:a?a.grant_id??null:s.id,scopes:a?.scopes??null},command:["true"],env:{},...n===void 0?{withoutNode:!0}:{},...i===void 0?{}:{folder:i},isolated:a?.isolated===!0||o,auditMissing:u(()=>{},"auditMissing")})).mounts.some(({source:c})=>r===c||r.startsWith(c==="/"?"/":`${c}/`))}u(ge,"cwdIsMounted");async function C(e,r="SIGKILL",n){if(!("ok"in await E({operation:"stop",pid:e,signal:r,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}u(C,"stopAppProcess");function J(e,r,n,o,i){return o?i??H(e,r):n}u(J,"appProcessCwd");async function Ie(e){if(W())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 S(e.nodeId);if(e.nodeId!==void 0&&!r)throw new Error(`missing node ${e.nodeId}`);const n=r?.grantee??e.app??"app:terminal";if(O(n),e.app!==void 0&&e.app!==n)throw new Error("app does not match node");const o=e.principal;let i=null;if(o!==void 0){if(i=o.grantId?await g(o.grantId):await I(n,o.sub),i?i.grantee!==n||i.sub!==o.sub:!b(n,o.sub,o.grantId))throw new Error(`no active grant for ${n}`)}else if(r){const t=x(r.sub,r.node_id);if(n!=="app:terminal"&&!b(n,t,r.grant_id)&&!(r.grant_id?await g(r.grant_id):await I(n,t)))throw new Error(`no active grant for ${n}`)}else if(i=await y(n),!i)throw new Error(`no active grant for ${n}`);await M(n);const d=e.cron===void 0?e.nodeId??`proc-${k()}`:z(e.cron.executionId),a=r?.isolated===!0||e.isolated===!0;if(a&&!r&&e.folder===void 0)throw new Error("isolated process requires a live node");const s=F(n),m=J(d,n,e.cwd,a,e.folder),c=r?K(d,n,a):a&&e.folder!==void 0?h(e.folder,"home"):s.home,T=q(Object.fromEntries(Object.entries({...e.env,...process.platform==="linux"?U(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(B(d),"cli.sock")}}).filter(t=>t[1]!==void 0))),v=o!==void 0?{nodeId:d,app:n,sub:o.sub,grantId:i?.id??null,scopes:o.scopes}:{nodeId:d,app:n,sub:r?x(r.sub,r.node_id):i.sub,grantId:r?r.grant_id??null:i.id,scopes:r?.scopes??null},$=u(async()=>{const t=await D({...v,command:e.command,env:T,...e.nodeId===void 0?{withoutNode:!0}:{},isolated:a,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(p=>A({level:"warn",event:"process.mount.missing",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{source:p}}),"auditMissing")});if(e.pluginRoot!==void 0&&(t.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 t.capture={stdoutBytes:e.stdoutBytes??256*1024,stderrBytes:e.stderrBytes??256*1024,...e.stderrTail?{stderrTail:!0}:{},...e.stdin===void 0?{}:{stdin:e.stdin}};return t},"compile");let f;for(let t=0;t<2&&f===void 0;t++){const p=await G(),_=await $(),l=await E({operation:"launch",spec:_});if(!("pid"in l))throw new Error("launcher did not return a process id");if(await G()===p||await j(v,_)){f=l.pid;break}A({level:"info",event:"process.launch.regranted",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{pid:l.pid}}),await C(l.pid,"SIGKILL").catch(()=>{})}if(f===void 0)throw new Error("grant changed during every launch attempt");const w=f;return{pid:w,get completion(){return E({operation:"wait",pid:w}).then(t=>{if(!("result"in t))throw new Error("launcher did not return process completion");return t.result})},stop:u((t="SIGKILL")=>C(w,t,e.cron===void 0?e.nodeId:d),"stop")}}u(Ie,"launchAppProcess");export{he as __setAppProcessesSandboxedForTest,J as appProcessCwd,we as appProcessSandboxed,pe as appProcessesSandboxed,z as cronLaunchId,ge as cwdIsMounted,Ie as launchAppProcess,C as stopAppProcess};
|
|
@@ -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.750",
|
|
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.750",
|
|
162
|
+
"@north-light/plugin": "0.3.750",
|
|
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",
|
|
@@ -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) {
|