@north-light/cli 0.3.689 → 0.3.691
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/files.d.ts +17 -0
- package/dist/api/dto/reviews.d.ts +2 -0
- package/dist/api/routes.d.ts +2 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
- package/dist/clients/attach/viewer.js +498 -498
- package/dist/clients/inbox/review/review-client.js +1 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/permissions/ceiling.js +8 -7
- package/dist/core/providers/files.d.ts +2 -0
- package/dist/core/providers/files.js +1 -1
- package/dist/core/review/stage.d.ts +6 -0
- package/dist/core/review/stage.js +1 -1
- package/dist/core/storage/node-transfer.d.ts +6 -0
- package/dist/core/storage/node-transfer.js +1 -0
- package/dist/daemon/api/handlers/node-files.js +1 -1
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/docs/sdk/release-notes.md +4 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +6 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +2 -0
- package/packages/crouter-api/dist/clients/inbox/review/review-client.js +3 -1
- package/packages/crouter-api/dist/core/command-plugins/compose.js +16 -3
- package/packages/crouter-api/dist/core/permissions/ceiling.js +10 -2
- package/packages/crouter-api/dist/core/providers/files.js +80 -9
- package/packages/crouter-api/dist/core/storage/node-transfer.js +100 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +2 -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 +1 @@
|
|
|
1
|
-
var u=Object.defineProperty;var r=(e,
|
|
1
|
+
var u=Object.defineProperty;var r=(e,i)=>u(e,"name",{value:i,configurable:!0});import{randomUUID as l}from"node:crypto";import{ApiError as f}from"../../../api/errors.js";import{filesCrossByUpload as p,uploadNodeFile as w}from"../../../core/storage/node-transfer.js";import{cliClient as o}from"../../../commands/api-client.js";import{createCommentAuthority as m}from"./comments-client.js";class s extends Error{static{r(this,"ReviewTerminalError")}state;resultPath;reason;constructor(i,n){if(i==="approved"){if(n===void 0||n==="")throw new Error("approved review omitted its canonical result path");super(`review is already approved; see ${n}`),this.resultPath=n}else super(n===void 0||n===""?"review is already canceled":`review is already canceled: ${n}`),n!==void 0&&n!==""&&(this.reason=n);this.name="ReviewTerminalError",this.state=i}}function E(e={}){const i=r(async n=>{try{return await n()}catch(t){const a=_(t);throw a!==void 0&&e.onTerminalConflict?.(a),t}},"request");return{async byId(n){const t=await i(()=>o().getReview(n));return await d(t,t.companion_node_id,i)},async createInline(n){const t="file"in n&&p()?await w(n.file):void 0,a=await i(()=>o().createReview({origin_kind:"inline",origin_node_id:n.originNodeId,..."file"in n?t!==void 0?{file_upload_id:t}:{file:n.file}:{document:n.document},idempotency_key:l()}));return await d(a,a.companion_node_id,i)},comments(n){return m(n,i)},async submit(n){const t=await i(()=>o().submitReview(n));return t.outcome==="awaiting_companion"?{outcome:"awaiting_companion"}:{outcome:"approved",changed:v(t.review),resultPath:c(t.review)}},async cancel(n,t){await i(()=>o().cancelReview(n,{reason:t,actor:"human",disposition:"dismissed"}))}}}r(E,"createReviewClient");async function d(e,i,n){if(e.state!=="open")throw h(e);const t=await n(()=>o().getNode(i));return{reviewId:e.review_id,companionNodeId:i,file:e.file,cwd:t.cwd}}r(d,"resolveReview");function h(e){if(e.state!=="approved"&&e.state!=="canceled")throw new Error(`terminal review ${e.review_id} has invalid state ${e.state}`);return e.state==="approved"?new s("approved",c(e)):new s("canceled",e.cancel_reason)}r(h,"terminalError");function v(e){if(typeof e.changed!="boolean")throw new Error(`approved review ${e.review_id} omitted its changed disposition`);return e.changed}r(v,"requireChanged");function c(e){if(typeof e.result_path!="string"||e.result_path==="")throw new Error(`terminal review ${e.review_id} omitted its canonical result path`);return e.result_path}r(c,"requireResultPath");function C(e){return e.state==="approved"?`This review was already approved. Result: ${e.resultPath??"unknown"}`:e.reason===void 0||e.reason===""?"This review was canceled.":`This review was canceled: ${e.reason}`}r(C,"terminalRefusalNotice");function _(e){if(!(e instanceof f)||e.status!==409||e.code!=="review_terminal_conflict")return;const i=e.details?.review;if(i!==void 0){if(i.state==="approved")return i.result_path===void 0?"This review was already approved by someone else.":`This review was already approved by someone else. Result: ${i.result_path}`;if(i.state==="canceled")return i.cancel_reason===void 0||i.cancel_reason===""?"This review was canceled before this submission landed.":`This review was canceled before this submission landed: ${i.cancel_reason}`}}r(_,"terminalConflictNotice");export{s as ReviewTerminalError,E as createReviewClient,_ as terminalConflictNotice,C as terminalRefusalNotice};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var u=(n,e)=>j(n,"name",{value:e,configurable:!0});import{resolve as w}from"node:path";import{ExitCode as U}from"../../types.js";import{envNodeId as A}from"../../shared/env.js";import{cliClient as l}from"../../commands/api-client.js";import{apiErrorToCliError as g}from"../io.js";import{ApiError as m}from"../../api/index.js";import{defineBranch as E,defineLeaf as L}from"../command.js";import{qualifiedTopLevelCommandName as M,resolveCommandRegistry as S}from"../command-manifests/registry.js";import{executeExternalLeaf as P}from"./transport/exec-invoke.js";import{invokeHttpLeaf as H}from"./transport/http-invoke.js";import{downloadNodeUpload as R,filesCrossByUpload as k,uploadNodeFile as K}from"../storage/node-transfer.js";import{readPathParam as $}from"./transport/http-plan.js";import{sha256Hex as I,signedHeaderDigest as O}from"./transport/sign.js";import{needsAppToken as q}from"../plugin-objects-manifest.js";async function C(n){const e=await l().request("GET",`/v1/providers/${encodeURIComponent(n)}/tools`);return new Set(e.groups.flatMap(a=>a.leaves.map(t=>t.tool)))}u(C,"allowedProviderTools");function v(n,e,a){return n.children.some(t=>t.kind==="leaf"?a.has([...e,t.name].join(" ")):v(t,[...e,t.name],a))}u(v,"hasAllowedLeaf");function B(n,e,a){return n.children.filter(t=>t.tier!=="hidden"&&(t.kind==="leaf"?a.has([...e,t.name].join(" ")):v(t,[...e,t.name],a))).length}u(B,"visibleChildCount");function x(n,e,a){return async()=>{if(!A())return n.help;const t=await a();return{...n.help,listing:n.help.listing?.flatMap(d=>{const o=n.children.find(c=>c.name===d.name);if(o?.kind==="leaf")return t.has([...e,o.name].join(" "))?[d]:[];if(o?.kind!=="branch")return[];const s=[...e,o.name];if(!v(o,s,t))return[];const i=B(o,s,t);return[{...d,...d.subCount!==void 0?{subCount:i}:{}}]})}}}u(x,"providerHelp");const D="Runs on one of your devices. Add `--machine <machine_id>` to pick which; without it the call goes to your only device, and with several the answer is `machine_required` listing each one's machine_id. The `runtime:` prefix on the id is optional.";function T(n,e,a,t=!1){return{outputKind:"object",...t?{machineSelector:!0}:{},run:u(async(d,o)=>{const s={...d};for(const i of a.params){if(!("type"in i))continue;const c=i.name.replace(/-([a-z])/g,(p,f)=>f.toUpperCase()),r=s[c];i.type==="file"&&typeof r=="string"?s[c]=k()?{upload_id:await K(w(r))}:w(r):i.type==="path"&&r!==void 0&&(s[c]=$(`provider command \`${n} ${e}\``,i,r))}try{const i=await l({timeoutMs:0}).request("POST","/v1/provider/call",{provider:n,tool:e,arguments:s,...o?.machine===void 0?{}:{machine:o.machine}},{timeout:0});if(k())for(const c of a.output??[]){const r=i[c.name];if(c.type==="file"&&r&&typeof r=="object"&&typeof r.upload_id=="string"){const{upload_id:p,size:f,sha256:h}=r;i[c.name]=await R(p,c.name,f,h)}}return i}catch(i){throw i instanceof m?g(i,void 0,{providerCall:!0}):i}},"run")}}u(T,"providerLeafAdapter");function _(n,e){return/^[A-Za-z0-9_-]{1,64}$/.test(n)&&n!=="crtr"&&!e.has(n)}u(_,"validRootName");function se(n,e){const a=[],t=[];for(const o of n){const{provider:s,commands:i}=o;if(!Array.isArray(i)||o.status!=="available"&&!_(s,e))continue;if(o.status!=="available"){const r=o.error??"bundle installation pending",p=`Unavailable (${o.status}): ${r}`,f=E({name:s,rootEntry:{concept:o.display_name,desc:p,useWhen:p},help:{name:s,summary:p},children:[],refusal:{code:"provider_unavailable",message:p,exit:U.NETWORK,next:"The daemon retries bundle installation on grant sync; retry after the provider becomes available."}});t.push(f);continue}const c=u(r=>r.kind==="branch"?{...r,children:r.children.map(c)}:{...r,rest:{method:"GET",path:"/",params:{}}},"helpNode");for(const r of i){if(r.kind!=="branch"||!Array.isArray(r.children)||!_(r.name,e))continue;const p=c(r);a.push({contributor:{name:s,scope:"user"},manifestName:r.name,node:o.groups.length===0?{...p,rootEntry:void 0}:p,adaptLeaf:u((f,h)=>T(s,h.slice(1).join(" "),f,o.transport==="machine"),"adaptLeaf")})}}const d=F(S(a,e));for(const o of d){const s=n.find(r=>r.status==="available"&&r.commands.some(p=>p.name===o.name||M({name:r.provider},p.name)===o.name));if(s?.status!=="available")continue;const i=new Set(s.groups.flatMap(r=>r.leaves.map(p=>p.tool))),c=u((r,p)=>{r.effectiveHelp=x(r,p,async()=>i);for(const f of r.children)f.kind==="branch"&&c(f,[...p,f.name])},"attachHelp");c(o,[])}return[...d,...t]}u(se,"composeSandboxProviderSubtrees");async function z(n){try{const{token:e,socket:a}=await l().plugins.appToken(n);return{CRTR_APP_TOKEN:e,CRTR_DAEMON_SOCKET:a}}catch(e){if(e instanceof m&&(e.status===404||e.status===403))return;throw e instanceof m?g(e):e}}u(z,"appEnvFor");function b(n,e){return(a,t)=>{const d=n.transport,o=e(t);if(n.provider!==void 0)return T(n.provider.id,o.slice(1).join(" "),a,d.kind==="machine");if(d.kind==="exec"){const i=d.executable;if(i===void 0)throw new Error(`exec plugin "${n.plugin.name}" has an executable leaf without transport.executable`);return{outputKind:"object",run:u(async c=>{const r=q(n.plugin.manifest)?await z(n.plugin.name):void 0;return P({plugin:n.plugin,executable:i,commandPath:o,output:a.output,...r!==void 0?{appEnv:r}:{}},c)},"run")}}if(d.kind==="machine")throw new Error(`machine plugin "${n.plugin.name}" is not a capability provider`);const s=a;return{outputKind:s.rest.streaming===!0?"jsonl":"object",run:u((i,c)=>H({registration:{name:n.plugin.name,endpoint:d.endpoint,...d.authEnv!==void 0?{authEnv:d.authEnv}:{}},...n.manifest?.baseUrl!==void 0?{baseUrl:n.manifest.baseUrl}:{},...n.manifest?.timeouts!==void 0?{timeouts:n.manifest.timeouts}:{},params:s.params,rest:s.rest,output:s.output,commandPath:o},i,c,{callHeaders:u(r=>l().plugins.callHeaders(n.plugin.name,{method:r.method,url:r.url.href,body_sha256:I(r.body),...O(r.headers)}).then(p=>p.headers,p=>{throw p instanceof m?g(p):p}),"callHeaders")}),"run")}}}u(b,"adaptLeaf");function pe(n){return{contributions:n.map(e=>({contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,manifestName:e.manifestName,adaptLeaf:b(e,a=>[e.manifestName,...a.slice(1)]),...e.provider!==void 0?{provider:e.provider}:{}})),coreMounts:[],issues:[]}}u(pe,"adaptPluginContributions");function ue(n){return n.map(e=>({parent:e.parent,plugin:e.plugin.name,contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,...e.provider!==void 0?{provider:e.provider}:{},adaptLeaf:b({...e,manifestName:e.node.name},a=>e.provider===void 0?[...a]:[e.provider.id,...a.slice(e.parent.length)])}))}u(ue,"adaptPluginCoreMounts");function F(n,e=C){return n.contributions.map(a=>y(a,a.node,[a.node.name],1,e))}u(F,"composeExternalSubtrees");function de(n,e){return n.filter(a=>a.parent.join("\0")===e.join("\0")).map(a=>a.node.kind==="branch"?y(a,a.node,[...e,a.node.name],a.provider===void 0?1:e.length):N(a,a.node,[...e,a.node.name]))}u(de,"composeCoreBranchMounts");function y(n,e,a,t=1,d=C){const o=e.rootEntry===void 0?void 0:{concept:e.rootEntry.concept,desc:e.rootEntry.description,useWhen:e.rootEntry.whenToUse},s=E({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...o!==void 0?{rootEntry:o}:{},help:{name:a.join(" "),summary:e.summary,...e.model!==void 0?{model:e.model}:{},...a.length===1&&n.extensionIssue!==void 0?{extensionIssue:n.extensionIssue}:{}},...e.passthrough!==void 0?{passthrough:e.passthrough}:{},children:e.children.map(i=>i.kind==="branch"?y(n,i,[...a,i.name],t,d):N(n,i,[...a,i.name]))});return n.provider!==void 0&&(s.effectiveHelp=x(s,a.slice(t),()=>d(n.provider.id))),s}u(y,"buildBranch");function N(n,e,a){const t=n.adaptLeaf(e,a);return L({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...t.machineSelector===!0?{machineSelector:!0}:{},help:{name:a.join(" "),summary:e.summary,...t.machineSelector===!0?{guide:D}:{},params:e.params,output:e.output,outputKind:t.outputKind,effects:[...e.effects]},run:t.run})}u(N,"buildLeaf");export{pe as adaptPluginContributions,ue as adaptPluginCoreMounts,de as composeCoreBranchMounts,F as composeExternalSubtrees,se as composeSandboxProviderSubtrees};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE g.resolved_scopes_json::jsonb @> '[{"scope":"crtr:memory:manage:user","mode":"always"}]'::jsonb`).all()).map(n=>n.id)}s(P,"firstPartyApps");function
|
|
1
|
+
var j=Object.defineProperty;var s=(t,e)=>j(t,"name",{value:e,configurable:!0});import{covers as $}from"@north-light/identity";import{isCloudRole as x}from"../canvas/person-state.js";import{eligiblePackageApps as F}from"../packages/eligibility.js";import{subjectSet as M}from"./evaluator.js";import{FALSE as g,TRUE as H,and as U,f as h,or as y,raw as d}from"./sql.js";const k=s(t=>({ownApp:t,roots:[],namespaces:[],place:null,predicates:{allNodes:!1,spaces:!1},authorApps:[],packageApps:null}),"empty");async function R(t,e){return(await t.prepare("SELECT external_id FROM identities WHERE object = ? ORDER BY scheme LIMIT 1").get(e))?.external_id??null}s(R,"externalId");async function T(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(T,"objectOf");async function J(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(J,"personObjectIds");async function P(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(P,"firstPartyApps");function D(t,e){return X(t).has(e.replace(/^app:/,""))}s(D,"holdsProviderGroup");const W=new WeakMap;function X(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(X,"providerGroupHolders");function z(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(z,"repoRoots");async function Y(t,e){return e===null?[]:(await M(t,e)).groupIds.filter(n=>n.startsWith("group:")).map(n=>n.slice(6))}s(Y,"memberGroups");async function Z(t,e,n){if(e.class==="person")return null;const o=e.scopes;return await F(t,{holdsProvider:s(f=>o!==null&&D(o,f),"holdsProvider"),cloud:x(),ownExt:await R(t,e.app.id),user:n})}s(Z,"readablePackageApps");async function oe(t,e,n,o,f={}){if(e.class==="person")return null;const a=k(e.app.id),r=e.scopes,E=s(i=>r!==null&&r.some(p=>$(p,i)),"has"),l=await R(t,e.app.id),w=e.class==="node"?await L(t,e.node.id):e.place??null;a.place=w,a.authorApps=[e.app.id];const N=o==="write"?"rw":"read",m=e.launched,c=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=>$(i,`crtr:memory:${N}:${l}`)))c(e.app.id,"any"),l!==null&&(a.namespaces=await V(t,l));else{c(e.app.id,"non-document"),o==="read"&&w!==null&&c(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=>$(p,`crtr:memory:${N}:${l}:profile:${i.external_id}`))&&c(i.id,"no-node")}if(o==="read"&&(a.packageApps=await Z(t,e,n)??[]),o==="read"&&w===null&&c(e.app.id,"run-node",!1),r===null)return a;a.predicates.spaces=!0;const A=await J(t),_=E("crtr:memory:manage:user"),I=_||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(_)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 P(t))}else o==="read"&&(_?S("any",!0):S("direct-doc",I),E(`crtr:objects:${f.verb??"read"}:user`)&&S("any",I));const v=o==="write"?"write":f.verb??"read",b=e.class==="object"&&e.object.type.includes("."),O=s(async(i,p)=>{const u=await T(t,"app",i);u===null||u===e.app.id||a.roots.push({id:u,private:D(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 O(`app:${p[2]}`,"no-node");else{const u=await T(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 C=await T(t,"profile",u.slice(8));C!==null&&a.roots.push({id:C,private:!1,match:"below"})}else u.startsWith("app:")&&await O(u,"objects-app");continue}if(p=/^crtr:conversations:read:(app:[A-Za-z0-9_-]+)$/.exec(i),p!==null&&o==="read"){await O(p[1],"node-report"),await O(p[1],"run-node");continue}p=/^crtr:objects:message:(app:[A-Za-z0-9_-]+)$/.exec(i),p!==null&&o==="message"&&await O(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:D(r,i.external_id),match:"custom"})}if(o!=="message")for(const i of[...z(e),...await Y(t,n)])a.roots.push({id:i,private:o==="read",match:"any"});return a}s(oe,"resolveCeiling");async function V(t,e){return(await t.prepare("SELECT namespace FROM schemas WHERE app = ?").all(e)).map(n=>n.namespace)}s(V,"ownNamespaces");async function L(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(L,"nodePlace");async function re(t,e){const n=await L(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(re,"rememberDeletedIsolated");function ie(t){return t.class==="person"?t:{...t,launched:null}}s(ie,"asRuntimeWriter");async function ae(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
|
|
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 R(t,e.app.id);if(r===null)return null;if(a.length===1)return f?e.launched.some(N=>$(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 L(t,e.node.id):e.place??null,m=await L(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 R(t,l.id)}`:`crtr:memory:${o}:${r}`;return e.launched.some(N=>$(N,w))?null:w}s(ae,"missingMemoryScope");function pe(t,e){const n=[];t.roots.length>0&&n.push(B(t,e)),t.namespaces.length>0&&n.push(h`split_part(${d(e)}.schema_type, '/', 1) = ANY(${t.namespaces}::text[])`),t.predicates.allNodes&&n.push(d(`(${e}.type = 'node' AND ${e}.privacy = 'public')`)),t.predicates.spaces&&n.push(d(`(${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 = ${d(e)}.id AND sd.source_path IS NOT NULL) OR ${d(e)}.owner = ANY(${t.packageApps}::text[]))`;return U([y(n),G(t,e),o])}s(pe,"ceilingFrag");function G(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
6
|
SELECT ${d(e)}.id, ${d(e)}.owner, 0, CASE WHEN ${d(e)}.type = 'node' THEN ${d(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)
|
|
@@ -10,12 +10,13 @@ var v=Object.defineProperty;var s=(t,e)=>v(t,"name",{value:e,configurable:!0});i
|
|
|
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(G,"placeFrag");function B(t,e){const n=t.roots.map(c=>c.id),o=t.roots.map(c=>c.private?1:0),
|
|
13
|
+
WHEN cd.node_id IS NOT NULL THEN cd.run_id = ${t.place.run} ELSE ${n} = 0 END))`}s(G,"placeFrag");function B(t,e){const n=t.roots.map(c=>c.id),o=t.roots.map(c=>c.private?1:0),f=t.roots.map(c=>c.match),a=new Set(t.roots.map(c=>c.match)),r=s(c=>`${e}.${c}`,"O"),E=[],l=s((c,A)=>{a.has(c)&&E.push(h`(r.match = ${c} AND ${typeof A=="string"?d(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 ${d(r("type"))} = 'document' AND ${d(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 c of a)if(c.startsWith("authored:")){const A=c.slice(9);E.push(h`(r.match = ${c} AND ca.depth = 1 AND ${d(r("type"))} = 'document' AND ${A==="*"?d("TRUE"):h`${d(r("name"))} = ${A}`} AND EXISTS (SELECT 1 FROM revisions rv JOIN objects au ON au.id = rv.author
|
|
14
14
|
WHERE rv.document = ${d(r("id"))} AND rv.number = (SELECT min(number) FROM revisions WHERE document = ${d(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=
|
|
15
|
+
AND (au.type = 'person' OR COALESCE((SELECT app FROM nodes WHERE node_id = au.id), au.owner) = ANY(${t.authorApps}::text[]))))`)}const w=y(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 = ${d(r("id"))} AND rn.run_id IS NOT NULL AND ${d(r("type"))} = 'node' AND (${d(r("privacy"))} = 'public' OR r.priv = 1))`:g,m=h`EXISTS (WITH RECURSIVE ca(id, owner, type, depth, node_below, near_node) AS (
|
|
16
17
|
SELECT ${d(r("id"))}, ${d(r("owner"))}, ${d(r("type"))}, 0, FALSE, CASE WHEN ${d(r("type"))} = 'node' THEN ${d(r("id"))} END
|
|
17
18
|
UNION ALL
|
|
18
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)
|
|
19
20
|
FROM ca JOIN objects p ON p.id = ca.owner WHERE ca.depth < 12)
|
|
20
|
-
SELECT 1 FROM ca JOIN unnest(${n}::text[], ${o}::int[], ${
|
|
21
|
-
WHERE (CASE WHEN ca.id = r.id THEN (${d(r("privacy"))} = 'public' OR r.priv = 1) ELSE FALSE END) AND ${w})
|
|
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 (${d(r("privacy"))} = 'public' OR r.priv = 1) ELSE FALSE END) AND ${w})`;return y([m,N])}s(B,"rootsFrag");export{ie as asRuntimeWriter,pe as ceilingFrag,D as holdsProviderGroup,ae as missingMemoryScope,L as nodePlace,J as personObjectIds,Z as readablePackageApps,re as rememberDeletedIsolated,oe as resolveCeiling};
|
|
@@ -28,6 +28,8 @@ export interface FileArgumentCopy {
|
|
|
28
28
|
path: string;
|
|
29
29
|
name: string;
|
|
30
30
|
object_id: string;
|
|
31
|
+
/** Set when the argument was an upload the node's CLI made (`{upload_id}`): `object_id` is that upload, signed with `signDownload`. */
|
|
32
|
+
upload_id?: string;
|
|
31
33
|
/** The signed GET URL the provider receives, valid 15 minutes. */
|
|
32
34
|
url: string;
|
|
33
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as oe}from"node:crypto";import{closeSync as D,constants as ne,createWriteStream as ie}from"node:fs";import{basename as re,extname as ae,isAbsolute as se,join as C}from"node:path";import{Transform as de}from"node:stream";import{pipeline as ue}from"node:stream/promises";import{appSpace as M}from"../layout.js";import{RunError as F}from"../runs/operations.js";import{createFileBeneath as le,existsBeneath as q,openBeneath as ce,removeTreeBeneath as I,setModeBeneath as fe,unlinkBeneath as pe,withDirBeneath as he}from"../spaces/open-beneath.js";import{ensureAppSpace as we}from"../spaces/space.js";import{isCloudRole as me}from"../canvas/person-state.js";import{invalidStorageName as N,storageClient as T,StorageRefused as U,UPLOAD_MAX_BYTES as B}from"../storage/client.js";import{openCallerFile as _e}from"../storage/caller-file.js";import{contentTypeFor as ge}from"../storage/media-types.js";import{withCanvasWrite as ye}from"../canvas/db.js";import{deleteUploadUse as be,getUpload as $e,insertUpload as ve,insertUploadUses as Se,setUploadSize as Ue,uploadUseAt as ze}from"../storage/tables.js";import{ProviderError as d}from"./errors.js";const Ee=11e4,Ae="app:terminal";function H(e){if(e.class==="person")return e.grantee??Ae;if(!e.grantee)throw new d("server_error","provider caller has no grantee");return e.grantee}u(H,"grantee");function Ce(e){if(e.class==="person"&&e.sub)throw new d("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:H(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Ce,"fileCaller");function y(e){return e instanceof d?e:e instanceof U?new d("storage_unavailable",`storage refused: ${e.message}`):e instanceof F&&e.code==="storage_unavailable"&&e.retryable?new d("storage_unavailable",e.message):e}u(y,"storageFailure");const b=u(e=>new d("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!se(n)||n.includes("\0"))throw new d("invalid_request",`${t} must be an absolute runtime path`,{param:t});let r;try{r=_e(Ce(e),n)}catch(i){throw i instanceof F?i.code==="scope_missing"?new d("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new d("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(r.size>B)throw new d("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=re(r.path),o=N(i);if(o)throw new d("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:r,name:i,mediaType:ge(r.path)}}catch(i){throw D(r.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const r=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:r.url}}catch(n){throw y(n)}}u(Te,"copyOutbound");async function P(e,t,n,r){const i=[];try{for(const a of t)n[a]===void 0||n[a]===null||i.push(Fe(e,a,n[a]));if(!i.length)return[];let o;try{o=r()}catch(a){throw y(a)}const c=[];for(const a of i)c.push(await Te(o,a));return c}finally{for(const o of i)D(o.file.fd)}}u(P,"copyArguments");function k(e){const t=N(e);if(t)throw new d("server_error",`file output ${e} cannot name an upload: ${t}`)}u(k,"checkOutputField");async function W(e,t,n){k(t);const r=H(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:B})}catch(c){throw y(c)}return await ve({upload_id:o.upload_id,grantee:r,name:t,media_type:i,size:B,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:r}}u(W,"createResultUpload");function X(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(X,"uploadHeaders");function Y(e,t){const n={...e};for(const r of t)n[r.param]=r.url;return n}u(Y,"withUrls");async function Ke(e,t,n,r={}){const i=r.storage??T;if(t.output&&(k(t.output),me()))throw new d("invalid_request","this command returns a file, which cannot be delivered to your computer from here yet, so it is not available from a moved Mac");const o=await P(e,t.params,n,i),c=t.output?await W(e,t.output,i):null;return{arguments:Y(n,o),copies:o,upload:c,headers:X(c)}}u(Ke,"prepareFileCall");async function Qe(e,t,n,r,i={}){const o=i.storage??T,c=[];for(const s of r.copies)try{const p=await o().signOutbound(s.object_id);c.push({...s,url:p.url})}catch(p){if(!(p instanceof U))throw y(p);c.push(...await P(e,[s.param],n,o))}let a=r.upload;if(a)try{const s=await o().signUploadLink(a.upload_id);a={...a,upload_link:s.upload_link}}catch(s){if(!(s instanceof U))throw y(s);s.status===404&&(a=await W(e,t.output??a.field,o))}return{arguments:Y(n,c),copies:c,upload:a,headers:X(a)}}u(Qe,"resignForRetry");const Be=/^[0-9a-f]{64}$/i;function Re(e,t){if(t===1)return e;const n=ae(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Re,"candidate");async function Ve(e,t,n,r={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,a=c[o.field];if(a==null)return i;if(typeof a!="object"||Array.isArray(a))throw b(`${o.field} must be {upload_id, size, sha256}`);const s=a;if(typeof s.upload_id!="string"||typeof s.size!="number"||!Number.isSafeInteger(s.size)||s.size<0||typeof s.sha256!="string"||!Be.test(s.sha256))throw b(`${o.field} must be {upload_id, size, sha256}`);if(s.upload_id!==o.upload_id)throw b(`${o.field} names an upload other than Crtr-Upload-Id`);const p=s.size,G=s.sha256.toLowerCase(),z=AbortSignal.timeout(r.budgetMs??Ee),R=r.signal?AbortSignal.any([z,r.signal]):z;let h;try{h=await(r.storage??T)().fetchUpload(o.upload_id,R)}catch(m){throw m instanceof U?b(`${o.field} names an upload with nothing stored`):y(m)}if(h.size===null)throw h.body.destroy(),new d("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(h.size!==p)throw h.body.destroy(),b(`${o.field} claims ${p} bytes; storage holds ${h.size}`);const E=o.grantee,$=e.node_id!==null,J=await we(E),f=$?M(E).nodes:M(E).files,A=$?C(f,e.node_id):f,v=$?C(A,"attachments"):f,K={uid:process.getuid?.()??0,gid:J.gid},O=$&&!q(f,A),Q=$&&!O&&!q(f,v);let w=null,S=null,x=!1;const L=u(async()=>{if(!x){if(x=!0,S)try{await be(S)}catch{}if(w)try{pe(f,w)}catch{}try{O?I(f,A):Q&&I(f,v)}catch{}}},"cleanup");try{he(f,v,()=>{},!0);for(let l=1;;l++){const _=C(v,Re(o.field,l));if(!await ze(_))try{le(f,_,Buffer.alloc(0),432),w=_;break}catch(g){if(g.code!=="EEXIST")throw g}}let m=0;const j=oe("sha256"),V=new de({transform(l,_,g){m+=l.length,j.update(l),g(null,l)}}),Z=ce(f,w,ne.O_WRONLY);try{await ue(h.body,V,ie("",{fd:Z,autoClose:!0}),{signal:R})}catch(l){throw z.aborted?new d("storage_unavailable","the file result could not be fetched within 110 s"):l instanceof F?y(l):new d("storage_unavailable",`storage stopped sending ${o.field}: ${l instanceof Error?l.message:String(l)}`)}if(m!==p)throw new d("storage_unavailable",`storage sent ${m} of ${p} bytes of ${o.field}`);if(j.digest("hex")!==G)throw b(`${o.field}: the stored bytes do not match sha256`);fe(f,w,432,K);const ee=w;await ye(async l=>{const _=await $e(o.upload_id,l);if(!_||_.delete_pending_since)throw new d("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await Ue(o.upload_id,p,l),!e.run_id)return;const g=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!g||g.deleting_at)throw new d("not_found",`run ${e.run_id} was deleted while its file result was fetched`);S={upload_id:o.upload_id,run_id:e.run_id,path:ee},await Se([S],l)})}catch(m){throw h.body.destroy(),await L(),m}return{result:{...c,[o.field]:w},file:{path:w,upload_id:o.upload_id},cleanup:L}}u(Ve,"resolveFileResult");export{Ee as FILE_RESULT_FETCH_BUDGET_MS,Ke as prepareFileCall,Qe as resignForRetry,Ve as resolveFileResult};
|
|
1
|
+
var ue=Object.defineProperty;var u=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{closeSync as H,constants as le,createWriteStream as ce}from"node:fs";import{basename as fe,extname as pe,isAbsolute as he,join as F}from"node:path";import{Transform as we,Writable as _e}from"node:stream";import{pipeline as N}from"node:stream/promises";import{appSpace as W}from"../layout.js";import{RunError as T}from"../runs/operations.js";import{createFileBeneath as ge,existsBeneath as P,openBeneath as ye,removeTreeBeneath as I,setModeBeneath as me,unlinkBeneath as be,withDirBeneath as $e}from"../spaces/open-beneath.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{isCloudRole as O}from"../canvas/person-state.js";import{invalidStorageName as X,storageClient as B,StorageRefused as z,UPLOAD_MAX_BYTES as j}from"../storage/client.js";import{openCallerFile as Se}from"../storage/caller-file.js";import{contentTypeFor as Ee}from"../storage/media-types.js";import{withCanvasWrite as Y}from"../canvas/db.js";import{deleteUploadUse as G,getUpload as L,insertUpload as ze,insertUploadUses as J,setUploadSize as K,uploadUseAt as Ue}from"../storage/tables.js";import{ProviderError as s}from"./errors.js";const Ae=11e4,Ce="app:terminal";function Q(e){if(e.class==="person")return e.grantee??Ce;if(!e.grantee)throw new s("server_error","provider caller has no grantee");return e.grantee}u(Q,"grantee");function Re(e){if(e.class==="person"&&e.sub)throw new s("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:Q(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Re,"fileCaller");function m(e){return e instanceof s?e:e instanceof z?new s("storage_unavailable",`storage refused: ${e.message}`):e instanceof T&&e.code==="storage_unavailable"&&e.retryable?new s("storage_unavailable",e.message):e}u(m,"storageFailure");const S=u(e=>new s("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,o){if(typeof o!="string"||!o||!he(o)||o.includes("\0"))throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});let a;try{a=Se(Re(e),o)}catch(i){throw i instanceof T?i.code==="scope_missing"?new s("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new s("not_found",`no such file: ${o}`,{param:t}):i:i}try{if(a.size>j)throw new s("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=fe(a.path),n=X(i);if(n)throw new s("invalid_request",`${t}: file name cannot be sent: ${n}`,{param:t});return{param:t,file:a,name:i,mediaType:Ee(a.path)}}catch(i){throw H(a.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const o=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(o.upload_link,t.file.fd,t.file.size,t.mediaType);const a=await e.signOutbound(o.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:o.object_id,url:a.url}}catch(o){throw m(o)}}u(Te,"copyOutbound");function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Object.keys(e),o=e.upload_id;return t.length===1&&typeof o=="string"&&o!==""?o:null}u(Oe,"uploadRef");async function Be(e,t,o,a){if(!O())throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});const i=await L(o);if(!i||i.delete_pending_since||i.grantee!==e.grantee||i.sub!==null&&i.sub!==(e.sub??null))throw new s("not_found",`no such upload: ${o}`,{param:t});try{const n=await a().signDownload(o);return{param:t,path:"",name:i.name,object_id:o,upload_id:o,url:n.url}}catch(n){throw n instanceof z?new s("not_found",`upload ${o} holds no bytes`,{param:t}):m(n)}}u(Be,"uploadArgument");async function V(e,t,o,a){const i=[],n=[];try{for(const r of t){if(o[r]===void 0||o[r]===null)continue;const f=Oe(o[r]);if(f!==null){n.push(await Be(e,r,f,a));continue}i.push(Fe(e,r,o[r]))}if(!i.length)return n;let c;try{c=a()}catch(r){throw m(r)}const d=[...n];for(const r of i)d.push(await Te(c,r));return d}finally{for(const c of i)H(c.file.fd)}}u(V,"copyArguments");function Z(e){const t=X(e);if(t)throw new s("server_error",`file output ${e} cannot name an upload: ${t}`)}u(Z,"checkOutputField");async function ee(e,t,o){Z(t);const a=Q(e),i="application/octet-stream";let n;try{n=await o().createResultUpload({name:t,media_type:i,max_size:j})}catch(c){throw m(c)}return await ze({upload_id:n.upload_id,grantee:a,...O()&&e.sub?{sub:e.sub}:{},name:t,media_type:i,size:j,created_at:new Date().toISOString()}),{field:t,upload_id:n.upload_id,upload_link:n.upload_link,grantee:a}}u(ee,"createResultUpload");function te(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(te,"uploadHeaders");function oe(e,t){const o={...e};for(const a of t)o[a.param]=a.url;return o}u(oe,"withUrls");async function et(e,t,o,a={}){const i=a.storage??B;t.output&&Z(t.output);const n=await V(e,t.params,o,i),c=t.output?await ee(e,t.output,i):null;return{arguments:oe(o,n),copies:n,upload:c,headers:te(c)}}u(et,"prepareFileCall");async function tt(e,t,o,a,i={}){const n=i.storage??B,c=[];for(const r of a.copies)try{const f=r.upload_id?await n().signDownload(r.upload_id):await n().signOutbound(r.object_id);c.push({...r,url:f.url})}catch(f){if(!(f instanceof z))throw m(f);c.push(...await V(e,[r.param],o,n))}let d=a.upload;if(d)try{const r=await n().signUploadLink(d.upload_id);d={...d,upload_link:r.upload_link}}catch(r){if(!(r instanceof z))throw m(r);r.status===404&&(d=await ee(e,t.output??d.field,n))}return{arguments:oe(o,c),copies:c,upload:d,headers:te(d)}}u(tt,"resignForRetry");const je=/^[0-9a-f]{64}$/i;function Le(e,t){if(t===1)return e;const o=pe(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}u(Le,"candidate");async function ot(e,t,o,a={}){const i={result:o,file:null,cleanup:u(async()=>{},"cleanup")},n=t.upload;if(!n||!o||typeof o!="object"||Array.isArray(o))return i;const c=o,d=c[n.field];if(d==null)return i;if(typeof d!="object"||Array.isArray(d))throw S(`${n.field} must be {upload_id, size, sha256}`);const r=d;if(typeof r.upload_id!="string"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.sha256!="string"||!je.test(r.sha256))throw S(`${n.field} must be {upload_id, size, sha256}`);if(r.upload_id!==n.upload_id)throw S(`${n.field} names an upload other than Crtr-Upload-Id`);const f=r.size,U=r.sha256.toLowerCase(),_=AbortSignal.timeout(a.budgetMs??Ae),E=a.signal?AbortSignal.any([_,a.signal]):_;let l;try{l=await(a.storage??B)().fetchUpload(n.upload_id,E)}catch(y){throw y instanceof z?S(`${n.field} names an upload with nothing stored`):m(y)}if(l.size===null)throw l.body.destroy(),new s("storage_unavailable",`storage did not say how many bytes ${n.field} holds`);if(l.size!==f)throw l.body.destroy(),S(`${n.field} claims ${f} bytes; storage holds ${l.size}`);if(O())return await De(e,n,c,r,l,E,_);const b=n.grantee,w=e.node_id!==null,ne=await ve(b),h=w?W(b).nodes:W(b).files,R=w?F(h,e.node_id):h,A=w?F(R,"attachments"):h,ie={uid:process.getuid?.()??0,gid:ne.gid},D=w&&!P(h,R),re=w&&!D&&!P(h,A);let g=null,C=null,k=!1;const q=u(async()=>{if(!k){if(k=!0,C)try{await G(C)}catch{}if(g)try{be(h,g)}catch{}try{D?I(h,R):re&&I(h,A)}catch{}}},"cleanup");try{$e(h,A,()=>{},!0);for(let p=1;;p++){const $=F(A,Le(n.field,p));if(!await Ue($))try{ge(h,$,Buffer.alloc(0),432),g=$;break}catch(v){if(v.code!=="EEXIST")throw v}}let y=0;const M=x("sha256"),ae=new we({transform(p,$,v){y+=p.length,M.update(p),v(null,p)}}),se=ye(h,g,le.O_WRONLY);try{await N(l.body,ae,ce("",{fd:se,autoClose:!0}),{signal:E})}catch(p){throw _.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):p instanceof T?m(p):new s("storage_unavailable",`storage stopped sending ${n.field}: ${p instanceof Error?p.message:String(p)}`)}if(y!==f)throw new s("storage_unavailable",`storage sent ${y} of ${f} bytes of ${n.field}`);if(M.digest("hex")!==U)throw S(`${n.field}: the stored bytes do not match sha256`);me(h,g,432,ie);const de=g;await Y(async p=>{const $=await L(n.upload_id,p);if(!$||$.delete_pending_since)throw new s("not_found",`${n.field}: the upload was deleted while it was fetched`);if(await K(n.upload_id,f,p),!e.run_id)return;const v=await p.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!v||v.deleting_at)throw new s("not_found",`run ${e.run_id} was deleted while its file result was fetched`);C={upload_id:n.upload_id,run_id:e.run_id,path:de},await J([C],p)})}catch(y){throw l.body.destroy(),await q(),y}return{result:{...c,[n.field]:g},file:{path:g,upload_id:n.upload_id},cleanup:q}}u(ot,"resolveFileResult");async function De(e,t,o,a,i,n,c){const d=a.size,r=a.sha256.toLowerCase();if(!e.run_id)throw i.body.destroy(),new s("invalid_request","a file result needs a node to deliver it to");const f=e.run_id,U=x("sha256");let _=0;try{await N(i.body,new _e({write(l,b,w){U.update(l),_+=l.length,w()}}),{signal:n})}catch(l){throw i.body.destroy(),c.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):new s("storage_unavailable",`storage stopped sending ${t.field}: ${l instanceof Error?l.message:String(l)}`)}if(_!==d)throw new s("storage_unavailable",`storage sent ${_} of ${d} bytes of ${t.field}`);if(U.digest("hex")!==r)throw S(`${t.field}: the stored bytes do not match sha256`);const E={upload_id:t.upload_id,run_id:f,path:`upload:${t.upload_id}`};return await Y(async l=>{const b=await L(t.upload_id,l);if(!b||b.delete_pending_since)throw new s("not_found",`${t.field}: the upload was deleted while it was checked`);const w=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(f);if(!w||w.deleting_at)throw new s("not_found",`run ${f} was deleted while its file result was checked`);await K(t.upload_id,d,l),await J([E],l)}),{result:{...o,[t.field]:{upload_id:t.upload_id,size:d,sha256:r}},file:{path:"",upload_id:t.upload_id},cleanup:u(async()=>{try{await G(E)}catch{}},"cleanup")}}u(De,"keepCloudResult");export{Ae as FILE_RESULT_FETCH_BUDGET_MS,et as prepareFileCall,tt as resignForRetry,ot as resolveFileResult};
|
|
@@ -14,6 +14,12 @@ export interface StageReviewArgs {
|
|
|
14
14
|
origin_kind: ReviewOriginKind;
|
|
15
15
|
origin_node_id: string;
|
|
16
16
|
file?: string;
|
|
17
|
+
/** A cloud role's file review: the upload the caller's CLI made of the file, owned by this app and person. */
|
|
18
|
+
file_upload_id?: string;
|
|
19
|
+
file_upload_owner?: {
|
|
20
|
+
grantee: string;
|
|
21
|
+
sub: string;
|
|
22
|
+
} | undefined;
|
|
17
23
|
document?: ReviewedDocument;
|
|
18
24
|
idempotency_key: string;
|
|
19
25
|
subtitle?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var $=Object.defineProperty;var n=(e,i)=>$(e,"name",{value:i,configurable:!0});import{createHash as q}from"node:crypto";import{existsSync as D,realpathSync as U,rmSync as z,statSync as j}from"node:fs";import{isAbsolute as C}from"node:path";import{getNode as N}from"../canvas/index.js";import{conversationIdFromPath as P,conversationStore as A,ConversationNotFoundError as T}from"../conversation-store/index.js";import{ensureReviewDir as H,reviewDir as R}from"../canvas/paths.js";import{checkReviewableBytes as K,checkReviewableFile as L}from"../human/visible-paths.js";import{isCloudRole as p}from"../canvas/person.js";import{blobStore as M}from"../blobs/index.js";import{REQUEST_BLOB_PREFIX as Q,isBlobRequestPath as h,readRequestFile as S,writeRequestFile as k}from"../human/request-files.js";import{getUpload as X}from"../storage/tables.js";import{storageClient as G}from"../storage/client.js";import{newNodeId as F}from"../runtime/nodes.js";import{captureOrigin as J}from"./companion.js";import{materializeSessionBranch as V}from"../runtime/session-branch.js";import{getRequestByIdempotencyKey as W}from"../human/requests.js";import{ReviewOperationError as a}from"./types.js";function r(e,i){return new a("review_target_unreviewable","review target cannot be staged",{phase:"create",file:e,reason:i})}n(r,"targetError");function _(e){return p()?`${Q}${e}`:R(e)}n(_,"stagedReviewDir");function B(e){return e==="file is not UTF-8 text"?"binary":e==="file is too large to review (2 MB limit)"?"too_large":e==="file is too long to review (5,000 line limit)"?"too_many_lines":"not_a_file"}n(B,"unreviewableReason");async function x(e){const i=K(await S(e));if(!i.ok)throw r(e,B(i.reason));return e}n(x,"validateBlobReviewFile");function v(e){if(!C(e))throw r(e,"not_absolute");if(!D(e))throw r(e,"missing");try{if(!j(e).isFile())throw r(e,"not_a_file")}catch(t){throw t instanceof a?t:r(e,"missing")}const i=L(e);if(!i.ok)throw r(e,B(i.reason));try{return U(e)}catch{throw r(e,"missing")}}n(v,"validateReviewFile");function Y(e){return new a("review_branch_unavailable","review branch could not be materialized",{reason:"materialize_failed",origin_node_id:e})}n(Y,"branchUnavailable");async function Z(e){try{return await J(e)}catch(i){throw i instanceof a&&i.code==="review_origin_missing"?new a("review_origin_missing","review origin was not found",{origin_node_id:e,reason:"origin_missing"}):i}}n(Z,"captureStagedOrigin");async function ee(e,i){try{return await V(i)}catch{throw Y(e)}}n(ee,"materialize");async function ie(e,i){if(i!==void 0){const t=P(i);if(t===null)throw new Error(`invalid staged conversation path: ${i}`);try{await A().delete(t)}catch(c){if(!(c instanceof T))throw c}}try{await te(e)}catch{}}n(ie,"discardStaging");async function te(e){if(p()){const i=await M();for(const t of await i.list(`${_(e)}/`))await i.delete(t)}else z(R(e),{recursive:!0,force:!0})}n(te,"deleteReviewFiles");async function ge(e){const i=await W(e.idempotency_key);if(i!==null)return{existing:i};if(e.document===void 0&&e.file_upload_id===void 0&&p())throw r(e.file??"","cloud_unsupported");if(await N(e.origin_node_id)===null)throw new a("review_origin_missing","review origin was not found",{origin_node_id:e.origin_node_id,reason:"origin_missing"});const t=await F(),c=await F();let w,s=e.document===void 0&&e.file_upload_id===void 0?v(e.file??""):"";try{const d=_(t);if(h(d)||H(t),e.file_upload_id!==void 0){const o=await X(e.file_upload_id),f=e.file_upload_owner;if(!o||o.delete_pending_since||!f||o.grantee!==f.grantee||o.sub!==f.sub)throw r(e.file_upload_id,"missing");let b;try{b=await G().fetchUpload(o.upload_id)}catch{throw r(e.file_upload_id,"missing")}const g=[];for await(const O of b.body)g.push(O);const u=`${d}/document.md`;await k(u,Buffer.concat(g)),s=h(u)?await x(u):v(u)}else if(e.document!==void 0){const o=`${d}/document.md`;await k(o,e.document.body),s=h(o)?await x(o):v(o)}const l=await Z(e.origin_node_id),E=new Date().toISOString(),m=await S(s),y=q("sha256").update(m).digest("hex");w=await ee(e.origin_node_id,l);const I=new Date().toISOString();return{row:{review_id:t,idempotency_key:e.idempotency_key,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,companion_node_id:c,review_dir:_(t),file:s,origin_session_file:l.sourceFile,origin_session_id:l.sourceSessionId,origin_leaf_id:l.leafId,model_spec:l.modelSpec,branch_file:w,baseline_sha256:y,baseline_bytes:m.length,anchor_base_sha256:y,anchor_base_bytes:m,state:"binding",created:I,captured_at:E,opened_at:null,submit_requested_at:null,output_path:e.output_path??null,document_id:e.document?.id??null,document_name:e.document?.name??null,document_base:e.document?.base??null,subtitle:e.subtitle??null,approved_at:null,approved_sha256:null,changed:null,comments_total:null,comments_unresolved:null,result_json:null,canceled_at:null,cancel_reason:null,cancel_actor:null,delivery_entry_id:null,delivered_at:null,delivery_error:null,projected_at:null,projection_error:null},review_dir:_(t)}}catch(d){throw await ie(t,w),d}}n(ge,"stageReview");export{te as deleteReviewFiles,ie as discardStaging,ge as stageReview};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** True when this CLI's commands run on the control plane, which cannot read this node's disk. */
|
|
2
|
+
export declare function filesCrossByUpload(): boolean;
|
|
3
|
+
/** Upload one regular file the node can read; returns the upload id. */
|
|
4
|
+
export declare function uploadNodeFile(path: string): Promise<string>;
|
|
5
|
+
/** Download an upload the control plane holds for this node into its attachments folder, named after `field`; returns the local path. */
|
|
6
|
+
export declare function downloadNodeUpload(uploadId: string, field: string, size: number, sha256: string): Promise<string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var R=Object.defineProperty;var c=(e,o)=>R(e,"name",{value:o,configurable:!0});import{closeSync as O,constants as l,createReadStream as v,createWriteStream as C,fstatSync as L,mkdirSync as x,openSync as w}from"node:fs";import{basename as z,extname as E,join as $}from"node:path";import{Readable as S}from"node:stream";import{pipeline as N}from"node:stream/promises";import{createHash as T}from"node:crypto";import{cliClient as b}from"../../commands/api-client.js";import{InputError as U}from"../io.js";import{envNodeId as u,providerProjectionOverBrokerRelay as k}from"../../shared/env.js";import{contentTypeFor as A}from"./media-types.js";import{appSpace as I}from"../layout.js";import{envGrantee as P}from"../../shared/env.js";const W=100*1024*1024;function V(){return u()!==void 0&&k()}c(V,"filesCrossByUpload");function a(e,o,t){throw new U({error:e,message:o,next:t})}c(a,"fail");async function Z(e){const o=u();o||a("no_node","a file can be uploaded only from a node","Run this from a node.");let t;try{t=w(e,l.O_RDONLY|l.O_NOFOLLOW)}catch(n){return a("not_found",`no such file: ${e} (${n.code??n.message})`,"Pass the path of a regular file you can read.")}try{const n=L(t);n.isFile()||a("not_found",`${e} is not a regular file`,"Pass the path of a regular file."),n.size>W&&a("invalid_request",`${e} exceeds 100 MiB`,"Split or compress the file.");const s=z(e),f=A(s),i=await b().createNodeUpload(o,{name:s,media_type:f,size:n.size}),d=await fetch(i.upload_link,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":f,"Content-Length":String(n.size)},body:n.size===0?new Uint8Array(0):S.toWeb(v("",{fd:t,autoClose:!1,start:0,end:n.size-1})),duplex:"half"});return await d.body?.cancel().catch(()=>{}),d.ok||a("upload_failed",`storage answered ${d.status} to the upload of ${e}`,"Run the command again."),i.upload_id}finally{O(t)}}c(Z,"uploadNodeFile");function B(e,o){if(o===1)return e;const t=E(e);return t&&t!==e?`${e.slice(0,-t.length)}-${o}${t}`:`${e}-${o}`}c(B,"candidate");async function ee(e,o,t,n){const s=u();s||a("no_node","a file result can be saved only on a node","Run this from a node.");const f=await b().nodeUploadLink(s,e),i=await fetch(f.url,{signal:AbortSignal.timeout(11e4)});(!i.ok||!i.body)&&a("download_failed",`storage answered ${i.status} to the download of ${o}`,"Run the command again.");const d=$(I(P()??a("no_node","this node has no app assignment","Run this from a node.")).nodes,s,"attachments");x(d,{recursive:!0});for(let m=1;;m++){const p=$(d,B(o,m));let h;try{h=w(p,l.O_WRONLY|l.O_CREAT|l.O_EXCL,432)}catch(r){if(r.code==="EEXIST")continue;throw r}const y=T("sha256");let g=0;try{const r=S.fromWeb(i.body);r.on("data",_=>{y.update(_),g+=_.length}),await N(r,C("",{fd:h,autoClose:!0}))}catch(r){a("download_failed",`could not save ${o}: ${r instanceof Error?r.message:String(r)}`,"Run the command again.")}return(g!==t||y.digest("hex")!==n.toLowerCase())&&a("download_failed",`the downloaded ${o} does not match the size and sha256 the server verified`,"Run the command again."),p}}c(ee,"downloadNodeUpload");export{ee as downloadNodeUpload,V as filesCrossByUpload,Z as uploadNodeFile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var z=Object.defineProperty;var f=(n,t)=>z(n,"name",{value:t,configurable:!0});import{createHash as k}from"node:crypto";import{Writable as A}from"node:stream";import{pipeline as U}from"node:stream/promises";import{ApiError as i}from"../../../api/index.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{RunError as O,cloudPersonScope as m}from"../../../core/runs/operations.js";import{appendRunEvent as E}from"../../../core/runs/events.js";import{invalidStorageName as h,storageClient as c,StorageRefused as y,UPLOAD_MAX_BYTES as g}from"../../../core/storage/client.js";import{completeFile as T,fileUsePath as P,getFile as $,getUpload as C,insertFile as D,insertUploadUses as b,insertUpload as v}from"../../../core/storage/tables.js";const q=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(?:\s*;.{0,200})?$/,M=/^[0-9a-f]{64}$/,j=11e4;async function S(n){const t=n.params.id;if(n.principal.class!=="broker"||n.principal.node!==t)throw new i(403,"permission_error","only this node\u2019s broker may hand over a file");const e=await _(t),o=n.principal.run;if(e===null||o===null||e.run_id!==o||!e.grantee)throw new i(400,"invalid_request","this node belongs to no app run, so there is no one to hand a file to");const r=await _(o);if(r===null||r.event_cursor===null||r.event_cursor===void 0)throw new i(400,"invalid_request","this node\u2019s run has no event stream, so there is no app to hand a file to");return{nodeId:t,runId:o,grantee:e.grantee,person:m(n.principal.sub)}}f(S,"callerRun");function I(n){if(!n||typeof n!="object"||Array.isArray(n))throw new i(400,"invalid_request","a JSON object is required");return n}f(I,"object");async function N(n){const t=await S(n),e=I(n.body);for(const s of Object.keys(e))if(!["name","media_type","size","sha256"].includes(s))throw new i(400,"invalid_request",`unknown field ${s}`);const{name:o,media_type:r,size:d,sha256:l}=e;if(typeof o!="string")throw new i(400,"invalid_request","name is required");const u=h(o);if(u)throw new i(400,"invalid_request",u);if(typeof r!="string"||!q.test(r))throw new i(400,"invalid_request","media_type must be a media type");if(typeof d!="number"||!Number.isSafeInteger(d)||d<0)throw new i(400,"invalid_request","size must be a non-negative integer");if(d>g)throw new i(400,"invalid_request","file exceeds 100 MiB");if(typeof l!="string"||!M.test(l))throw new i(400,"invalid_request","sha256 must be 64 lowercase hex digits");const a=await c().createUpload({name:o,media_type:r,size:d}),p=new Date().toISOString();return await w(async s=>{await v({upload_id:a.upload_id,grantee:t.grantee,...t.person===void 0?{}:{sub:t.person},name:o,media_type:r,size:d,created_at:p},s),await b([{upload_id:a.upload_id,run_id:t.runId,path:P(a.upload_id)}],s),await D({file_id:a.upload_id,run_id:t.runId,node_id:t.nodeId,grantee:t.grantee,...t.person===void 0?{}:{sub:t.person},name:o,media_type:r,size:d,sha256:l,created_at:p},s)}),{status:201,body:{file_id:a.upload_id,upload_link:a.upload_link,expires_at:a.expires_at}}}f(N,"handleCreate");async function R(n){const t=await S(n),e=await $(n.params.fileId);if(!e||e.node_id!==t.nodeId)throw new i(404,"not_found","file not found");const o=f(()=>({status:200,body:{file_id:e.file_id,name:e.name,media_type:e.media_type,size:e.size}}),"done");if(e.completed_at)return o();const r=AbortSignal.timeout(j);let d;try{d=await c().fetchUpload(e.file_id,r)}catch(a){throw a instanceof y?new i(409,"file_not_uploaded","the file bytes have not been uploaded"):a}const l=k("sha256");let u=0;try{await U(d.body,new A({write(a,p,s){l.update(a),u+=a.length,s()}}),{signal:r})}catch(a){throw new O(503,"storage_unavailable",`storage stopped sending the file: ${a instanceof Error?a.message:String(a)}`,void 0,void 0,void 0,!0)}if(u!==e.size||l.digest("hex")!==e.sha256)throw new i(409,"file_mismatch","the stored bytes do not match the declared size and sha256; hand the file over again");return await w(async a=>{await T(e.file_id,void 0,a)&&await E(a,e.run_id,e.node_id,"file.sent",{file_id:e.file_id,name:e.name,media_type:e.media_type,size:e.size})}),o()}f(R,"handleComplete");async function B(n){const t=n.params.id;if(n.principal.class!=="broker"||n.principal.node!==t)throw new i(403,"permission_error","only this node\u2019s broker may upload");const e=await _(t);if(e===null||e.run_id===null||!e.grantee)throw new i(400,"invalid_request","this node belongs to no run, so it cannot upload");const o=I(n.body);for(const s of Object.keys(o))if(!["name","media_type","size"].includes(s))throw new i(400,"invalid_request",`unknown field ${s}`);const{name:r,media_type:d,size:l}=o;if(typeof r!="string")throw new i(400,"invalid_request","name is required");const u=h(r);if(u)throw new i(400,"invalid_request",u);if(typeof d!="string"||!q.test(d))throw new i(400,"invalid_request","media_type must be a media type");if(typeof l!="number"||!Number.isSafeInteger(l)||l<0)throw new i(400,"invalid_request","size must be a non-negative integer");if(l>g)throw new i(400,"invalid_request","file exceeds 100 MiB");const a=m(n.principal.sub),p=await c().createUpload({name:r,media_type:d,size:l});return await w(async s=>{await v({upload_id:p.upload_id,grantee:e.grantee,...a===void 0?{}:{sub:a},name:r,media_type:d,size:l,created_at:new Date().toISOString()},s),await b([{upload_id:p.upload_id,run_id:e.run_id,path:`upload:${p.upload_id}`}],s)}),{status:201,body:{upload_id:p.upload_id,upload_link:p.upload_link,expires_at:p.expires_at}}}f(B,"handleUploadCreate");async function F(n){const t=n.params.id;if(n.principal.class!=="broker"||n.principal.node!==t)throw new i(403,"permission_error","only this node\u2019s broker may read its uploads");const e=await _(t),o=await C(n.params.uploadId),r=m(n.principal.sub);if(!e||!o||o.delete_pending_since||o.grantee!==e.grantee||r!==void 0&&o.sub!==r)throw new i(404,"not_found","upload not found");try{return{status:200,body:await c().signDownload(o.upload_id)}}catch(d){throw d instanceof y?new i(404,"not_found","upload not found"):d}}f(F,"handleUploadLink");const x=[{method:"POST",pattern:"/v1/nodes/:id/uploads",handler:B},{method:"POST",pattern:"/v1/nodes/:id/uploads/:uploadId/link",handler:F},{method:"POST",pattern:"/v1/nodes/:id/files",handler:N},{method:"POST",pattern:"/v1/nodes/:id/files/:fileId/complete",handler:R}];export{x as nodeFileRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=Object.defineProperty;var s=(t,e)=>E(t,"name",{value:e,configurable:!0});import{ApiError as h}from"../../../api/index.js";import{isCloudRole as y}from"../../../core/canvas/person.js";import{withCanvasWrite as S}from"../../../core/canvas/db.js";import{isSafeNodeId as w}from"../../../core/canvas/paths.js";import{readDocument as T}from"../../../core/graph/documents.js";import{getById as C}from"../../../core/graph/objects.js";import{checkoutsForCwd as $}from"../../../core/graph/repo-sync/repos.js";import{getNode as g}from"../../../core/canvas/canvas.js";import{assertScope as I}from"../../../core/scopes.js";import{createReview as A}from"../../../core/review/birth.js";import{readAnchorBase as D,listReviews as O,requireVisibleReview as R}from"../../../core/review/store.js";import{cancelReview as F,submitReviewApproval as L}from"../../review/finish.js";import{toFeedbackResultDTO as P,toReviewDTO as j}from"../map.js";import{readerFor as B,resolveRef as N,warmReaderRepos as G}from"../reader.js";import{actsAsPerson as V,canReadNode as W}from"../router.js";import{invalidRequest as K,objectBody as b,optionalString as c,requireParam as M,requiredString as k}from"./validate.js";import{filterAsync as z}from"../../../core/async-array.js";const H=new Set(["open","approved","canceled"]),J=["origin_kind","origin_node_id","document","file","file_upload_id","idempotency_key","subtitle","output_path"],Q=["reason","actor","disposition"];function f(t){K("review request",t)}s(f,"invalidRequest");function v(t,e){return M(t,"review_id","must be a safe review id",w,e)}s(v,"requireReviewId");function p(t){return{...j(t,t.state==="approved"?{result_path:`${t.review_dir}/result.json`}:{}),review_dir:t.review_dir}}s(p,"toReviewResponseDTO");function U(t){const e=[],n=b(t.body,J,e),o=n.origin_kind,i=o==="ticket"||o==="inline"?o:void 0;i===void 0&&e.push({field:"origin_kind",problem:"must be ticket or inline",...o===void 0?{}:{received:o}});const d=k(n,"origin_node_id",e);d!==void 0&&!w(d)&&e.push({field:"origin_node_id",problem:"must be a safe node id",received:d});const r=c(n,"document",e),a=c(n,"file",e),l=c(n,"file_upload_id",e);l!==void 0&&(a!==void 0||r!==void 0||!y())&&e.push({field:"file_upload_id",problem:"is only for a cloud role and excludes file and document"}),i==="ticket"&&(r===void 0||a!==void 0)&&e.push({field:"document",problem:"is required for ticket reviews, and file is not allowed"}),i==="inline"&&[a,r,l].filter(q=>q!==void 0).length!==1&&e.push({field:"file",problem:"inline reviews take exactly one of file or document"});const u=k(n,"idempotency_key",e);u!==void 0&&u.length>128&&e.push({field:"idempotency_key",problem:"must be at most 128 characters",received:u});const _=c(n,"subtitle",e),m=c(n,"output_path",e);return i==="ticket"&&_===void 0&&n.subtitle===void 0&&e.push({field:"subtitle",problem:"is required for ticket reviews"}),i==="inline"&&n.subtitle!==void 0&&e.push({field:"subtitle",problem:"is only allowed for ticket reviews",received:n.subtitle}),i==="inline"&&n.output_path!==void 0&&e.push({field:"output_path",problem:"is only allowed for ticket reviews",received:n.output_path}),m!==void 0&&y()&&e.push({field:"output_path",problem:"is not supported on the cloud: a review result is projected only to its own request files",received:m}),(e.length>0||i===void 0||d===void 0||!w(d)||u===void 0||u.length>128)&&f(e),{origin_kind:i,origin_node_id:d,...r===void 0?{}:{document:r},...a===void 0?{}:{file:a},...l===void 0?{}:{file_upload_id:l},idempotency_key:u,..._===void 0?{}:{subtitle:_},...m===void 0?{}:{output_path:m}}}s(U,"parseCreate");function X(t){const e=[],n={},o=new Set(["state","origin_node_id","file"]);for(const[i,d]of t.query.entries())o.has(i)||e.push({field:i,problem:"is not allowed",received:d});for(const i of o){const d=t.query.getAll(i);if(d.length>1){e.push({field:i,problem:"must appear at most once",received:d});continue}const r=d[0];r!==void 0&&(i==="state"?H.has(r)?n.state=r:e.push({field:i,problem:"must be open, approved, or canceled",received:r}):i==="origin_node_id"?w(r)?n.origin_node_id=r:e.push({field:i,problem:"must be a safe node id",received:r}):r===""?e.push({field:i,problem:"must be a non-empty string",received:r}):n.file=r)}return e.length>0&&f(e),n}s(X,"parseList");function Y(t,e){const n=t.body===void 0?{}:b(t.body,Q,e),o=c(n,"reason",e),i=c(n,"actor",e),d=c(n,"disposition",e);return d!==void 0&&d!=="canceled"&&d!=="dismissed"&&e.push({field:"disposition",problem:'must be "canceled" or "dismissed"',received:d}),{...o===void 0?{}:{reason:o},...i===void 0?{}:{actor:i},...d==="canceled"||d==="dismissed"?{disposition:d}:{}}}s(Y,"parseCancel");function Z(t,e){b(t.body,[],e)}s(Z,"requireEmptyBody");async function x(t){const e=U(t),n=await g(e.origin_node_id);n!==null&&I(n,"crtr:act");const{document:o,file:i,file_upload_id:d,...r}=e,a=await A({...r,...d!==void 0?{file_upload_id:d,file_upload_owner:t.principal.class==="broker"?{grantee:t.principal.app,sub:t.principal.sub}:void 0}:o===void 0?{file:i??""}:{document:await ee(t,o)}});return{status:200,body:p(a)}}s(x,"handleCreate");async function ee(t,e){return await G(t.principal),await S(async n=>{const o=await B(n,t),i=await N(n,o,e);if("remote"in i)throw new h(404,"not_found",`no document named ${i.remote} on this runtime`,{next:"Check the name with `crtr canvas search`."});if("deleted"in i)throw new h(404,"not_found",`${i.deleted.name} is deleted`,{id:i.deleted.id,deleted:!0});if(i.type!=="document")throw new h(400,"invalid_request",`${e} is a ${i.type}, not a document`);const d=await T(n,o,i,async(l,u)=>await $(n,l,u));if(d.needsMerge)throw new h(409,"needs_merge",`${i.name} has ${d.heads.length} heads; merge them before a review`,{id:i.id,next:`Read it with \`crtr canvas read ${i.id}\` and write the merged body with \`crtr doc edit\`.`});const r=i.owner===null?null:await C(n,i.owner),a=r===null?"":r.type==="node"?r.id:r.name;return{id:i.id,name:a===""?i.name:`${a}/${i.name}`,base:d.record.heads_key,body:d.heads[0].body}})}s(ee,"reviewedDocument");async function ie(t){const e=X(t);return{status:200,body:{reviews:(await z(await O(e),async o=>{if(V(t.principal))return!0;const i=await g(o.origin_node_id);return i!==null&&await W(t.principal,i.grantee??"app:terminal",i.node_id)})).map(p)}}}s(ie,"handleList");async function ne(t){const e=[],n=v(t,e);return(e.length>0||n===void 0)&&f(e),{status:200,body:p(await R(n))}}s(ne,"handleRead");async function te(t){const e=[],n=v(t,e);Z(t,e),(e.length>0||n===void 0)&&f(e);const o=await L(n);return{status:200,body:o.outcome==="awaiting_companion"?{review:p(o.record),outcome:o.outcome}:{review:p(o.record),result:P(o.result),outcome:o.outcome}}}s(te,"handleSubmit");async function oe(t){const e=[],n=v(t,e),o=Y(t,e);(e.length>0||n===void 0)&&f(e);const i=await F(n,o);return{status:200,body:{review:p(i.record),outcome:i.outcome}}}s(oe,"handleCancel");async function de(t){const e=[],n=v(t,e);(e.length>0||n===void 0)&&f(e);const o=await R(n),i=await D(o.review_id);if(i===null)throw new Error(`review anchor base is missing: ${o.review_id}`);return{status:200,body:{review_id:o.review_id,anchor_base_sha256:i.sha256,anchor_base_text:new TextDecoder("utf-8",{fatal:!0}).decode(i.bytes),file:o.file}}}s(de,"handleDocument");const qe=[{method:"POST",pattern:"/v1/human/reviews",scope:"crtr:act",handler:x},{method:"GET",pattern:"/v1/human/reviews",handler:ie},{method:"GET",pattern:"/v1/human/reviews/:review_id",handler:ne},{method:"POST",pattern:"/v1/human/reviews/:review_id/submit",handler:te},{method:"POST",pattern:"/v1/human/reviews/:review_id/cancel",handler:oe},{method:"GET",pattern:"/v1/human/reviews/:review_id/document",handler:de}];export{U as parseCreate,qe as reviewRoutes};
|