@north-light/cli 0.3.659 → 0.3.661
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 +5 -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/broker-ops.d.ts +33 -1
- package/dist/api/dto/files.d.ts +20 -0
- package/dist/api/dto/run-events.d.ts +9 -1
- package/dist/api/routes.d.ts +3 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +12 -6
- package/dist/clients/attach/viewer.js +471 -471
- package/dist/commands/push.js +6 -4
- package/dist/core/canvas/deliveries.d.ts +2 -0
- package/dist/core/canvas/deliveries.js +19 -18
- package/dist/core/canvas/export-sqlite.js +1 -1
- package/dist/core/canvas/migrations.js +1 -1
- package/dist/core/canvas/person.js +3 -3
- package/dist/core/canvas/schema-pg/019-outbound-files.sql +26 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/remove.js +1 -1
- package/dist/core/import/bundle/layout.d.ts +1 -1
- package/dist/core/import/bundle/layout.js +3 -3
- package/dist/core/import/load/bind.js +8 -8
- package/dist/core/providers/files.js +1 -1
- package/dist/core/runs/operations.js +4 -4
- package/dist/core/runtime/broker/daemon-ops.d.ts +2 -1
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/broker/frame-session.js +3 -3
- package/dist/core/runtime/broker/held-deferred-inbox.d.ts +6 -0
- package/dist/core/runtime/broker/held-deferred-inbox.js +1 -1
- package/dist/core/runtime/broker/rebind.d.ts +5 -2
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/launch-recipe.d.ts +13 -0
- package/dist/core/runtime/launch-recipe.js +1 -0
- package/dist/core/runtime/revive.d.ts +2 -0
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/storage/download.d.ts +0 -1
- package/dist/core/storage/download.js +1 -1
- package/dist/core/storage/media-types.d.ts +1 -0
- package/dist/core/storage/media-types.js +1 -0
- package/dist/core/storage/shares.d.ts +15 -6
- package/dist/core/storage/shares.js +1 -1
- package/dist/core/storage/tables.d.ts +31 -1
- package/dist/core/storage/tables.js +4 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/node-files.d.ts +2 -0
- package/dist/daemon/api/handlers/node-files.js +1 -0
- package/dist/daemon/api/handlers/transfer.d.ts +2 -2
- package/dist/daemon/api/handlers/transfer.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/reconcilers/ledger-storage.js +3 -3
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/docs/apps/guides/files-and-documents.md +11 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
package/dist/commands/push.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
- code: ${r.code} (${r.retryable?"retryable":"not retryable"})`;return`${
|
|
1
|
+
var P=Object.defineProperty;var d=(e,r)=>P(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{closeSync as $,constants as _,createReadStream as k,fstatSync as N,openSync as R}from"node:fs";import{basename as T}from"node:path";import{Readable as A}from"node:stream";import{envNodeId as E}from"../shared/env.js";import{defineBranch as F,defineLeaf as g}from"../core/command.js";import{InputError as a,readStdinRaw as q}from"../core/io.js";import{ApiError as L}from"../api/index.js";import{cliClient as w,rethrowAsCliError as f}from"./api-client.js";import{contentTypeFor as U}from"../core/storage/media-types.js";const v=100*1024*1024;function y(){const e=E();if(e===void 0||e.trim()==="")throw new a({error:"no_node_context",message:"CRTR_NODE_ID is not set \u2014 push runs inside a canvas node.",next:"Run push from a node process spawned by the runtime."});return e.trim()}d(y,"requireCallerNode");const x={update:"report progress to subscribers",final:"finish: write the canonical result, mark the node done, close its window"},I={update:"you have progress worth surfacing to your managers while work remains in flight. Use normal delivery unless it can wait for their next real wake (--tier deferred) or needs immediate attention (--tier urgent); use push final only when the work is actually done.",final:"the work this node was spawned to do is complete and you are ready to hand back the canonical result \u2014 this writes that result, marks the node done, and closes its window, so it is the LAST thing you do here, not a progress note. Use push update while work is still in flight, and do not reach for final on a node working directly with the user: it has no manager to report up to and would close mid-conversation (the guard blocks it unless you pass --force after the user confirms)."};function j(){return g({name:"result",description:"answer a pending structured-output request with the required JSON result, or decline it",whenToUse:'your system prompt names a pending structured-output request you must answer. The value is validated against the required schema server-side; a mismatch rejects with field errors and records nothing, so fix and rerun. When the schema cannot be honestly satisfied (blocked, unavailable, bad input), pass `--decline "<reason>" --code <token>` (plus `--retryable` when the same request could succeed later) instead of inventing a value; your requester names the code tokens it accepts. For a terminal request either path IS how the node finishes \u2014 never call `crtr push final` alongside it.',help:{name:"push result",summary:"answer a pending structured-output request",params:[{kind:"stdin",name:"value",required:!1,constraint:"The JSON result. Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes. Required unless `--decline` is passed."},{kind:"flag",name:"request",type:"string",required:!0,constraint:"The request id from the structured-output instruction. It binds this result to that exact request; crouter never selects a pending request implicitly."},{kind:"flag",name:"decline",type:"string",required:!1,constraint:"Decline instead of answering: one plain sentence on why the schema cannot be honestly satisfied (blocked, unavailable, bad input). Requires `--code`. Records a failure outcome with reason `declined` carrying the reason, code, and retryable flag, and clears the request; for a terminal request this finishes the node."},{kind:"flag",name:"code",type:"string",required:!1,constraint:"With `--decline`: one whitespace-free token (\u2264 64 chars) naming the decline class. crouter carries it verbatim; the requester validates it against the tokens it documented for you."},{kind:"flag",name:"retryable",type:"bool",required:!1,default:!1,constraint:"With `--decline`: the same request could succeed if issued again later (a transient block). Omit when the decline is final for this input."}],output:[{name:"mode",type:"string",required:!0,constraint:"Which request this answered: `terminal` finished the node; `oneoff` left it working."},{name:"declined",type:"object",required:!1,constraint:"Present only when the request was declined: { reason, code, retryable } as recorded."},{name:"report",type:"string",required:!0,constraint:"Name of the report document pushed alongside the result, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},{name:"transitioned",type:"object",required:!1,constraint:"Present only for a terminal request that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."}],outputKind:"object",effects:["Validates the value against the pending schema server-side; a mismatch records nothing and the request stays pending.","Records the accepted result (or the decline) on the pending request and clears it.","A terminal decline records a `failure` outcome with reason `declined` whose `declined` field carries { reason, code, retryable }; the requester sees no value.","Pushes the mode-matched report: final for a terminal request (the node finishes \u2014 same effects as `push final`), update for a one-off request (the node keeps working)."]},run:d(async e=>{const r=y(),n=typeof e.request=="string"?e.request.trim():"";if(n==="")throw new a({error:"request_id_required",message:"a structured result needs its request id",field:"request",next:"Copy the request id named in the structured-output instruction and rerun with `--request <request-id>`."});const o=typeof e.decline=="string"?e.decline.trim():"",i=typeof e.code=="string"?e.code.trim():"";let s;if(o!==""){if(i==="")throw new a({error:"missing_decline_code",message:"a decline needs a code",field:"code",next:"Pass `--code <token>` \u2014 the whitespace-free token your requester documented for this decline class."});s={request_id:n,decline:o,code:i,retryable:e.retryable===!0}}else{if(i!==""||e.retryable===!0)throw new a({error:"decline_flags_without_decline",message:"--code and --retryable only apply with --decline",next:'Pass `--decline "<reason>"` alongside them, or drop them and submit the JSON result.'});let t=typeof e.value=="string"?e.value.trim():"";if(t===""&&(t=(await q()).trim()),t==="")throw new a({error:"missing_value",message:"no result value",field:"value",next:'Pass the JSON result as an argument or on stdin, or `--decline "<reason>" --code <token>` when the schema cannot be honestly satisfied.'});let h;try{h=JSON.parse(t)}catch(u){throw new a({error:"bad_result_json",message:`the result is not valid JSON: ${u.message}`,field:"value",next:"Pass one valid JSON value matching the requested schema."})}s={request_id:n,value:h}}try{const t=await w().submitResult(r,s);return{mode:t.mode,report:t.report,notified:t.notified,...t.declined===void 0?{}:{declined:t.declined},...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(t){f(t)}},"run"),render:d(e=>{const r=e.declined,n=e.mode==="terminal"?`${r?"Decline recorded":"Result recorded"} \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.`:`${r?"One-off request declined":"One-off result recorded"} and pushed \u2014 the structured-output gate is cleared; continue working normally.`,o=r===void 0?"":`
|
|
2
|
+
- code: ${r.code} (${r.retryable?"retryable":"not retryable"})`;return`${n}
|
|
3
3
|
|
|
4
|
-
- report: ${e.report}${o}`},"render")})}
|
|
4
|
+
- report: ${e.report}${o}`},"render")})}d(j,"makeResultLeaf");function z(){return g({name:"file",description:"hand a file from this node\u2019s machine to the person you work for",whenToUse:"you produced a file the person should have \u2014 a report, export, image, spreadsheet \u2014 and the person works through an app or chat, not in your shell. Writing a path into a message does not give them the file; this does. One file per call, up to 100 MiB. The file is copied when you run this, so later edits are not sent; run it again for a new version. The node must belong to an app run (a conversation someone started through an app); otherwise there is no one to give it to.",help:{name:"push file",summary:"hand a file to the person",params:[{kind:"positional",name:"path",required:!0,constraint:"Path of one regular file, at most 100 MiB. A symbolic link is refused. The file name shown to the person is its base name."}],output:[{name:"file_id",type:"string",required:!0,constraint:"Id of the stored file; the app downloads or shares it by this id."},{name:"name",type:"string",required:!0,constraint:"File name as the person sees it."},{name:"media_type",type:"string",required:!0,constraint:"Media type chosen from the file extension (`application/octet-stream` when unknown)."},{name:"size",type:"number",required:!0,constraint:"Size in bytes."}],outputKind:"object",effects:["Uploads a copy of the file to storage and records it against this node\u2019s app run.","Appends a `file.sent` event to the run, which the app sees.","Fails without recording anything when the stored bytes do not match the file as read, or the node belongs to no app run."]},run:d(async e=>{const r=y(),n=typeof e.path=="string"?e.path:"";if(n==="")throw new a({error:"missing_path",message:"no file path",field:"path",next:"Pass the path of the file to hand over."});let o;try{o=R(n,_.O_RDONLY|_.O_NOFOLLOW)}catch(i){throw new a({error:"file_unreadable",message:`cannot open ${n}: ${i.code==="ELOOP"?"it is a symbolic link":i.message}`,field:"path",next:"Pass the path of a regular file you can read, not a link."})}try{const i=N(o);if(!i.isFile())throw new a({error:"not_a_file",message:`${n} is not a regular file`,field:"path",next:"Pass one regular file; zip a directory first."});if(i.size>v)throw new a({error:"file_too_large",message:`${n} is ${i.size} bytes; the limit is ${v}`,field:"path",next:"Split or compress the file below 100 MiB."});const s=T(n),t=U(s),h=O("sha256");let u=0;for await(const l of k("",{fd:o,autoClose:!1,start:0}))h.update(l),u+=l.length;if(u!==i.size)throw new a({error:"file_changed",message:`${n} changed while it was read`,field:"path",next:"Rerun when nothing is writing to the file."});const b=w();try{const l=await b.createNodeFile(r,{name:s,media_type:t,size:u,sha256:h.digest("hex")});let c;try{c=await fetch(l.upload_link,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":t,"Content-Length":String(u)},body:u===0?new Uint8Array(0):A.toWeb(k("",{fd:o,autoClose:!1,start:0,end:u-1})),duplex:"half"})}catch(m){throw new a({error:"upload_failed",message:`storage could not be reached: ${m instanceof Error?m.message:String(m)}`,next:"Rerun `crtr push file` to try again."})}if(await c.body?.cancel().catch(()=>{}),!c.ok)throw new a({error:"upload_failed",message:`storage answered ${c.status} to the upload`,next:"Rerun `crtr push file` to try again."});const p=await b.completeNodeFile(r,l.file_id);return{file_id:p.file_id,name:p.name,media_type:p.media_type,size:p.size}}catch(l){if(l instanceof a)throw l;f(l)}}finally{$(o)}},"run"),render:d(e=>`File handed over: ${String(e.name)} (${String(e.size)} bytes, ${String(e.media_type)}).
|
|
5
|
+
|
|
6
|
+
- file_id: ${String(e.file_id)}`,"render")})}d(z,"makeFileLeaf");function S(e){return g({name:e,description:x[e],whenToUse:I[e],help:{name:`push ${e}`,summary:x[e],params:[{kind:"stdin",name:"body",required:!0,constraint:"Report body (markdown). Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes."},...e==="update"?[{kind:"flag",name:"tier",type:"enum",choices:["deferred","normal","urgent"],required:!1,default:"normal",constraint:"Delivery urgency: deferred holds for the receiver\u2019s next non-deferred wake; normal wakes normally; urgent steers a live receiver and wakes an idle receiver."}]:[{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Override the guard that blocks `push final` on a node the user is attending (a resident with no one to report up to). Only pass this after the user explicitly confirms they want this node finished."}]],output:[{name:"report",type:"string",required:!0,constraint:"Name of the written report document, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},...e==="final"?[{name:"transitioned",type:"object",required:!1,constraint:"Present only for a final that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."},{name:"worktree_auto_dropped",type:"boolean",required:!1,constraint:"Present only when the server closed this node\u2019s managed-worktree record without requiring `node worktree close`; cleanup of an existing checkout remains pending (see worktree_auto_dropped_path)."},{name:"worktree_auto_dropped_path",type:"string",required:!1,constraint:"Present only alongside worktree_auto_dropped: the closed worktree path; an existing checkout remains until pending cleanup."}]:[]],outputKind:"object",effects:["Creates the report document `<node-id>/reports/<compact-ts>-<uuid8>-<kind>` (server-side).","Appends one inbox pointer per subscriber.",...e==="final"?["Marks the node done (status + intent) server-side; its engine shuts down on next stop.","When this node owns a clean managed worktree already contained in its local base, the server closes its record with cleanup pending instead of blocking on `node worktree close`. A clean worktree whose exact tip exists on any branch on origin may also finalize while retaining its branch and checkout; uncommitted changes or a tip absent from origin still block with open_managed_worktree."]:[]]},run:d(async r=>{const n=y();let o=typeof r.body=="string"?r.body.trim():"";if(o===""&&(o=(await q()).trim()),o==="")throw new a({error:"missing_body",message:"no report body",field:"body",next:"Pass the body as an argument or on stdin."});const i=w();if(e==="final"&&r.force!==!0){let s=null;try{s=await i.getNode(n)}catch(t){t instanceof L&&t.status===404||f(t)}if(s!==null&&s.lifecycle==="resident"&&s.edges.subscribers.length===0)throw new a({error:"no_final_recipient",message:"This node is working directly with the user \u2014 it has no manager to submit a final result to. `push final` would end the conversation mid-stream.",next:'You almost certainly do NOT need to finish here \u2014 just keep working with the user. If the user has explicitly asked you to finish and close this node, confirm with them first, then rerun with `crtr push final --force "<result>"`.'})}try{const s=r.tier,t=await i.pushReport(n,{tier:e,body:o,...s===void 0?{}:{delivery_tier:s}});return{report:t.report,notified:t.notified,...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(s){f(s)}},"run"),render:d(r=>{const n=Array.isArray(r.notified)?r.notified.length:0,o=e==="final"?'Result recorded \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.':`Progress report fanned to ${n} subscriber(s).`,i=r.worktree_auto_dropped===!0?`
|
|
5
7
|
|
|
6
8
|
Closed a clean managed-worktree record at ${String(r.worktree_auto_dropped_path)} \u2014 nothing to land; cleanup remains pending if the checkout still exists.`:"";return`${o}
|
|
7
9
|
|
|
8
|
-
- report: ${r.report}${
|
|
10
|
+
- report: ${r.report}${i}`},"render")})}d(S,"makePushLeaf");function G(){return F({name:"push",rootEntry:{concept:"the one verb up the graph \u2014 a node reports to whoever subscribes to it",desc:"push an update or final report to your subscribers",useWhen:"sharing progress, raising an alert, or finishing your work"},help:{name:"push",summary:"push a report to your subscribers",model:"A push writes a report document the node owns and fans a lightweight pointer to every subscriber's inbox. Delivery inlines reports under 1,000 characters; a longer report is read with `crtr canvas read <name>`. Point at documents you wrote as `[[<node-id>/<name>]]`, never as a file path. Nothing is pushed automatically \u2014 the feed contains only what a node pushes explicitly, so push whenever you want a manager to see something. Pipe markdown via a single-quoted heredoc so it reaches the report literally. `push final` is how ANY node finishes: write the canonical result, mark done, close the window."},children:[S("update"),S("final"),j(),z()]})}d(G,"registerPush");export{G as registerPush};
|
|
@@ -109,6 +109,8 @@ export declare function resetHandedOffDeliveries(now: number): Promise<number>;
|
|
|
109
109
|
/** The lane checks the claim immediately before launching the action. An action
|
|
110
110
|
* superseded after claim but before dispatch must not start with stale input. */
|
|
111
111
|
export declare function pushDeliveryClaimIsCurrent(delivery: DeliveryRecord, owner: string): Promise<boolean>;
|
|
112
|
+
/** Return the mail an execution claimed but has not acknowledged to pending, so the next claim (its next cycle's kickoff) carries it. */
|
|
113
|
+
export declare function releaseExecutionMail(nodeId: string, executionId: string, now?: number): Promise<number>;
|
|
112
114
|
/** Reset mail held by an execution that is no longer this node's one live execution.
|
|
113
115
|
* Push receiver deliveries have a due timestamp and are claimed by the daemon lane. */
|
|
114
116
|
export declare function resetStaleExecutionMail(now: number): Promise<number>;
|
|
@@ -1,46 +1,47 @@
|
|
|
1
|
-
var x=Object.defineProperty;var
|
|
2
|
-
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,
|
|
1
|
+
var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as O}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{inboxPath as w,passivePath as D}from"./paths.js";import{withRetryBudget as X}from"./delivery-contract.js";import{emitEvent as H}from"../events/emit.js";import{mapAsync as F}from"../async-array.js";function R(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(R,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
|
|
2
|
+
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function A(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
|
|
3
3
|
m.sender_node_id, m.sender_name, m.kind, m.label, m.body_ref, m.body_json, m.disposition
|
|
4
4
|
FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
5
5
|
WHERE d.destination_id = ? AND d.wake = ?
|
|
6
6
|
${E?"AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'":d===0?"AND NOT (m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')":""}
|
|
7
7
|
AND d.canceled_at IS NULL
|
|
8
8
|
AND d.state = 'handed_off' AND d.claim_owner = ?
|
|
9
|
-
ORDER BY m.seq`).all(a,d,
|
|
9
|
+
ORDER BY m.seq`).all(a,d,r)).map(i=>({...R(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(A,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
10
10
|
WHERE d.destination_id = ? AND d.wake = ? AND d.state = 'pending' AND d.canceled_at IS NULL
|
|
11
11
|
AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')`,M=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
|
|
12
|
-
WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function Z(e,a,
|
|
12
|
+
WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function Z(e,a,r,d=Date.now()){const s=r==="wake"?1:0;if(r==="deferred_run")return await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=await c.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
13
13
|
WHERE d.destination_id = ? AND d.wake = 0 AND d.canceled_at IS NULL
|
|
14
14
|
AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'
|
|
15
15
|
AND (d.state = 'pending' OR (d.state = 'handed_off' AND d.claim_owner = ?))`).all(e,a),t=new Set(i.length===0?[]:(await c.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
|
|
16
|
-
WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await A(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(M).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,s,i)}})}
|
|
17
|
-
WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,
|
|
16
|
+
WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await A(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(M).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,s,i)}})}o(Z,"claimNodeMail");async function ee(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
|
|
17
|
+
WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await A(d,e,a,1,s)})}o(ee,"claimKickoffMail");function W(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(W,"normalizedSettlement");async function j(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:W(d),l=X(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
|
|
18
18
|
SET state = ?, next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL,
|
|
19
19
|
acknowledged_at = ?, failed_at = ?, last_failure_json = ?, updated_at = ?
|
|
20
|
-
WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,
|
|
20
|
+
WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,r)).changes)===1;if(f&&l.exhausted&&_.state==="permanent_failed"){const y=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:y.destination_id,messageId:y.message_id})}return f});for(const i of E)H({level:"error",event:"delivery.exhausted",outcome:"failed",attempt:a,fields:{delivery_id:e,destination_id:i.destinationId,message_id:i.messageId,failure:i.failure,retry:`crtr sys retry-delivery ${e}`}});return c}o(j,"settleDelivery");async function te(e,a=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries
|
|
21
21
|
SET state = 'pending', attempts = 0, next_attempt_at = ?, failed_at = NULL, updated_at = ?
|
|
22
|
-
WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}
|
|
23
|
-
WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}
|
|
22
|
+
WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}o(te,"retryFailedDelivery");async function ae(e,a,r,d=Date.now()){return await T(async s=>await L(s,e,a,!1)?{action:"acknowledged",results:await F(r,async c=>{const i=await s.prepare("SELECT 1 FROM deliveries WHERE delivery_id = ? AND destination_id = ?").get(c.deliveryId,e)!==void 0;return{deliveryId:c.deliveryId,outcome:i&&await j(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ae,"acknowledgeNodeMail");async function ne(e){const a=await(await N()).prepare(`SELECT m.body_json FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
23
|
+
WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}o(ne,"messageBodyForDelivery");async function ie(e){return(await(await N()).prepare(`SELECT * FROM deliveries
|
|
24
24
|
WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?
|
|
25
|
-
ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(R)}
|
|
25
|
+
ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(R)}o(ie,"duePushDeliveries");async function de(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
|
|
26
26
|
WHERE d.delivery_id = ? AND d.state = 'pending' AND d.canceled_at IS NULL AND d.next_attempt_at <= ?
|
|
27
27
|
AND NOT EXISTS (SELECT 1 FROM deliveries old JOIN messages prior ON prior.message_id = old.message_id
|
|
28
28
|
JOIN messages next ON next.message_id = d.message_id
|
|
29
29
|
WHERE old.destination_id = d.destination_id AND old.delivery_id != d.delivery_id
|
|
30
30
|
AND old.state = 'handed_off' AND old.canceled_at IS NOT NULL
|
|
31
|
-
AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,
|
|
31
|
+
AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:R(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(de,"claimPushDelivery");async function se(e){return await T(async a=>{const r=await a.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
|
|
32
32
|
claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
|
|
33
33
|
WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL`).run(e,e),d=await a.prepare(`UPDATE deliveries SET state = 'pending', next_attempt_at = CASE WHEN next_attempt_at IS NOT NULL THEN ?::bigint ELSE NULL END,
|
|
34
34
|
claimed_at = NULL, claim_owner = NULL, updated_at = ?
|
|
35
|
-
WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)`).run(e,e);return Number(
|
|
36
|
-
AND attempts = ? AND claim_owner = ? AND canceled_at IS NULL`).get(e.deliveryId,e.attempts,a)!==void 0}
|
|
35
|
+
WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)`).run(e,e);return Number(r.changes)+Number(d.changes)})}o(se,"resetHandedOffDeliveries");async function re(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE delivery_id = ? AND state = 'handed_off'
|
|
36
|
+
AND attempts = ? AND claim_owner = ? AND canceled_at IS NULL`).get(e.deliveryId,e.attempts,a)!==void 0}o(re,"pushDeliveryClaimIsCurrent");async function oe(e,a,r=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
|
|
37
|
+
WHERE destination_id = ? AND claim_owner = ? AND state = 'handed_off' AND next_attempt_at IS NULL`).run(r,e,a)).changes)}o(oe,"releaseExecutionMail");async function le(e){return Number((await(await N()).prepare(`UPDATE deliveries AS d SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
|
|
37
38
|
WHERE d.state = 'handed_off' AND d.next_attempt_at IS NULL
|
|
38
39
|
AND NOT EXISTS (
|
|
39
40
|
SELECT 1 FROM executions e WHERE e.node_id = d.destination_id AND e.execution_id = d.claim_owner AND e.state != 'exited'
|
|
40
|
-
)`).run(e)).changes)}
|
|
41
|
-
AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}
|
|
42
|
-
`).filter(
|
|
43
|
-
`).map(a=>a.trim()).filter(Boolean)):new Set}
|
|
41
|
+
)`).run(e)).changes)}o(le,"resetStaleExecutionMail");const $=o((e,a)=>`${e}.wake = 1 AND ${e}.canceled_at IS NULL AND ${e}.urgency != 'deferred' AND ${e}.state IN (${a})`,"WAKE_MAIL_SQL"),b=o(e=>$(e,"'pending', 'handed_off'"),"UNSEEN_WAKE_MAIL_SQL");async function _e(e){return await(await N()).prepare(`SELECT 1 FROM deliveries d WHERE d.destination_id = ? AND ${b("d")} LIMIT 1`).get(e)!==void 0}o(_e,"hasUnseenWakeMail");async function ce(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE destination_id = ? AND wake = 1
|
|
42
|
+
AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(ce,"hasWakeMailSince");async function Ee(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ee,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=O(e,"utf8");return a.trim()===""?[]:a.split(`
|
|
43
|
+
`).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function q(e){return I(e)?new Set(O(e,"utf8").split(`
|
|
44
|
+
`).map(a=>a.trim()).filter(Boolean)):new Set}o(q,"readCanceled");function me(e){e.exec(`
|
|
44
45
|
CREATE TABLE IF NOT EXISTS messages (
|
|
45
46
|
message_id TEXT PRIMARY KEY,
|
|
46
47
|
seq INTEGER NOT NULL UNIQUE,
|
|
@@ -94,4 +95,4 @@ CREATE TABLE IF NOT EXISTS waits (
|
|
|
94
95
|
);
|
|
95
96
|
CREATE UNIQUE INDEX IF NOT EXISTS waits_live ON waits(node_id) WHERE satisfied_at IS NULL;
|
|
96
97
|
CREATE INDEX IF NOT EXISTS waits_node ON waits(node_id);
|
|
97
|
-
`);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=q(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${D(n)}.draining`],[1,D(n)]])U(f).forEach((y,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:y,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const
|
|
98
|
+
`);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=q(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${D(n)}.draining`],[1,D(n)]])U(f).forEach((y,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:y,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(me,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{b as UNSEEN_WAKE_MAIL_SQL,$ as WAKE_MAIL_SQL,ae as acknowledgeNodeMail,Ee as acknowledgedNodeMailCount,ee as claimKickoffMail,Z as claimNodeMail,de as claimPushDelivery,R as deliveryFrom,ie as duePushDeliveries,_e as hasUnseenWakeMail,ce as hasWakeMailSince,ne as messageBodyForDelivery,me as migrateMessagingState,W as normalizedSettlement,re as pushDeliveryClaimIsCurrent,oe as releaseExecutionMail,se as resetHandedOffDeliveries,le as resetStaleExecutionMail,te as retryFailedDelivery,j as settleDelivery};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let M=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),k=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${k===void 0?"":` ORDER BY ${k}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),M+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:M,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
|
|
1
|
+
var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","files","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let M=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),k=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${k===void 0?"":` ORDER BY ${k}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),M+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:M,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
|
|
2
2
|
${s.join(`
|
|
3
3
|
`)}`)}d(pe,"verify");export{Re as exportPostgresToSqlite};
|
|
@@ -1052,7 +1052,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
|
|
|
1052
1052
|
name TEXT NOT NULL,
|
|
1053
1053
|
PRIMARY KEY (src, name)
|
|
1054
1054
|
) WITHOUT ROWID;
|
|
1055
|
-
`),ce,e=>e.exec("ALTER TABLE uploads ADD COLUMN sub TEXT")];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
|
|
1055
|
+
`),ce,e=>e.exec("ALTER TABLE uploads ADD COLUMN sub TEXT"),e=>e.exec("ALTER TABLE shares ADD COLUMN sub TEXT")];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
|
|
1056
1056
|
CREATE TABLE waits_new (
|
|
1057
1057
|
wait_id TEXT PRIMARY KEY,
|
|
1058
1058
|
node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as
|
|
1
|
+
var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as f,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new f;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["files","sub"],["files","grantee"],["shares","sub"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
|
|
2
2
|
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
3
3
|
AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
|
|
4
4
|
AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
|
|
5
5
|
AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+s(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,a)),t["relations.written_by"]=s(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=s(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of ne)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of ee){const d=s(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+s(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));d!==0&&(t[`${o}.person`]=d)}const u=s(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await re(n,e))&&(await z(n,e,r),t["charge_totals.rebuilt"]=1),t}c(U,"substitutePerson");async function te(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
|
|
6
6
|
WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?s(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await G(n,"app:terminal")).id)):0)+s(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+s(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(te,"rewriteLegacyGrantees");async function ae(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),a=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=s(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t)),p["node_tokens.grant"]=s(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${a})`).run(r,...t)),p["crons.grant_id"]=s(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=s(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
|
|
7
7
|
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
8
|
-
AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[R
|
|
8
|
+
AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[N,R]of Object.entries(w))R!==0&&(r[T+N]=(r[T+N]??0)+R)},"add");let a=await m(e,l);if(a===null)throw new f;let p=null;const u=h();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
|
|
9
9
|
WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${w} LIMIT 1`).get()!==void 0){const T=await J(e,"person","user",a,"user");t({repaired_stubs:s(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${w})`).run(T.id))})}t({"nodes.sub_null_terminal":s(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
|
|
10
10
|
SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
|
|
11
|
-
WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,
|
|
11
|
+
WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,f as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-- 019-outbound-files.sql — a file an agent hands to the person (`crtr push file`), and the person a share belongs to. One transaction,
|
|
2
|
+
-- additions only: `schema_min_reader` is not touched, so the previous release (version 18) still opens the result: it never names the new
|
|
3
|
+
-- table or column, so its `shares` inserts leave `sub` null and its `SELECT *` reads ignore it.
|
|
4
|
+
--
|
|
5
|
+
-- `files` is one row per handed-over file. Its bytes are the storage upload with the same id (`file_id` = `uploads.upload_id`), so storage
|
|
6
|
+
-- deletes and app removal reach them through `uploads` and `upload_uses`. `sub` is the person a cloud role's run belongs to (null on a Mac);
|
|
7
|
+
-- an app reads a file only when its app, its person and the run's read rule all match. `completed_at` is set once the API has read the stored
|
|
8
|
+
-- object back and found the size and sha256 the agent declared.
|
|
9
|
+
--
|
|
10
|
+
-- `shares.sub` is the person a cloud role's share was made for; null on a Mac and on every row written before this step.
|
|
11
|
+
CREATE TABLE files (
|
|
12
|
+
file_id text PRIMARY KEY,
|
|
13
|
+
run_id text NOT NULL,
|
|
14
|
+
node_id text NOT NULL,
|
|
15
|
+
grantee text NOT NULL,
|
|
16
|
+
sub text,
|
|
17
|
+
name text NOT NULL,
|
|
18
|
+
media_type text NOT NULL,
|
|
19
|
+
size bigint NOT NULL,
|
|
20
|
+
sha256 text NOT NULL,
|
|
21
|
+
created_at text NOT NULL,
|
|
22
|
+
completed_at text
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX idx_files_run ON files(run_id);
|
|
25
|
+
|
|
26
|
+
ALTER TABLE shares ADD COLUMN sub text;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 19;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=19;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var d=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as L}from"../canvas/worktrees.js";import{withCanvasWrite as
|
|
1
|
+
var h=Object.defineProperty;var d=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as L}from"../canvas/worktrees.js";import{withCanvasWrite as p,openDb as l}from"../canvas/db.js";import{cancelCron as W}from"../canvas/crons.js";import{emitEvent as w}from"../events/emit.js";import{appSpace as N,appsRoot as u,secretsDir as H}from"../layout.js";import{notifyRunDeleted as y}from"../runs/events.js";import{cancelOpenQuestions as M}from"../runs/questions.js";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{deleteRunFiles as A,markGranteeUploadsDeletePending as U,releaseRunUploads as q,turnSharesOffFor as I}from"../storage/tables.js";import{stopNodeSandboxes as P}from"../spaces/stop.js";import{activeAppUser as k,markAppUserRemoved as j}from"../spaces/users.js";import{launcherRequest as B}from"../../launcher/client.js";import{LaunchRefused as b}from"../../launcher/spec.js";import{otherLiveGrantOfApp as G}from"./mirror.js";import{launcherPresent as g,listSandboxes as Y,stopSandboxPid as x}from"./sandboxes.js";import{filterAsync as R}from"../async-array.js";async function pe(r,o){if(r==="app:terminal")throw new Error("app:terminal cannot be removed");const s=o===void 0||!await G(r,o);await _(r,o,s)}d(pe,"removeApp");async function we(r,o){await _(r,o,!1,!0)}d(we,"removePersonData");async function _(r,o,s,v=!1){const f=N(r),i=s?await k(r):null;w({level:"info",event:"daemon.grants.removal_started",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null}});const t=o===void 0?{sql:"grantee = ?",args:[r]}:{sql:"grantee = ? AND sub = ?",args:[r,o]};for(const{node_id:e}of await(await l()).prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args))await M({node_id:e},"the app was removed");const a=await p(async e=>(await e.prepare(`UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id IN (SELECT node_id FROM node_rows WHERE ${t.sql})`).run(new Date().toISOString(),...t.args),(await e.prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args)).map(n=>n.node_id)));for(const{cron_id:e}of await(await l()).prepare(`SELECT cron_id FROM crons WHERE ${t.sql}`).all(...t.args))await W(e);const m=(await Promise.all(a.map(e=>P(e,"app_removed",{deleting:!0})))).filter(e=>!e.confirmed);if(m.length)throw new Error(`sandbox teardown could not be confirmed for ${m.length} node(s) of ${r}`);if(i&&g())for(const e of await Y())e.uid===i.uid&&await x(e.pid);const c=await R(a,async e=>(await(await l()).prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(e))?.run_id===e);if(await p(async e=>{if(s&&await I(r,e),await q(a,e),await A(c,e),s&&await U(r,e),!a.length)return;const n=a.map(()=>"?").join(","),S=await e.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${n}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${n})`).all(...a,...a);await e.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${n})`).run(...a);for(const{message_id:E}of S)await e.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(E,E)}),v){const e=await R(a,L);if(e.length)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${e.join(", ")}`);for(const n of a)await F(await C(n))}await T(a);for(const e of c)y(e);if(s&&(O(D(H(),"env",f.root.slice(u().length+1)),{recursive:!0,force:!0}),$(u(),f.root)),i&&g())try{await B({operation:"user.delete",uid:i.uid})}catch(e){if(!(e instanceof b&&e.refusal==="invalid_uid"))throw e}i&&await j(i.uid),w({level:"info",event:"daemon.grants.removal_completed",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null,nodes:a.length}})}d(_,"cascade");export{pe as removeApp,we as removePersonData};
|
|
@@ -4,7 +4,7 @@ export declare const BODIES_TABLE = "bodies";
|
|
|
4
4
|
/** Tables whose rows are dumped, staged and (after rewrites) copied, in no particular order: the lane computes the copy
|
|
5
5
|
* order from the target's foreign-key catalog. A table's part files, read in order, hold its rows in primary-key order (identity-ordered
|
|
6
6
|
* tables in source `seq` order). */
|
|
7
|
-
export declare const COPIED_TABLES: readonly ["objects", "documents", "revisions", "revision_parents", "identities", "jobs", "custom_objects", "context_sessions", "environments", "object_kinds", "edges", "watches", "watch_subscriptions", "exposures", "rules", "unresolved_links", "nodes", "sessions", "worktrees", "node_faults", "waits", "structured_requests", "memory_reads", "deleted_isolated_nodes", "node_outcome_deliveries", "run_events", "messages", "message_causes", "deliveries", "crons", "cron_runs", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "audit_rows", "idempotency_keys", "uploads", "upload_uses", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
|
|
7
|
+
export declare const COPIED_TABLES: readonly ["objects", "documents", "revisions", "revision_parents", "identities", "jobs", "custom_objects", "context_sessions", "environments", "object_kinds", "edges", "watches", "watch_subscriptions", "exposures", "rules", "unresolved_links", "nodes", "sessions", "worktrees", "node_faults", "waits", "structured_requests", "memory_reads", "deleted_isolated_nodes", "node_outcome_deliveries", "run_events", "messages", "message_causes", "deliveries", "crons", "cron_runs", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "audit_rows", "idempotency_keys", "uploads", "upload_uses", "files", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
|
|
8
8
|
/** Dumped and staged so rewrite 2 can map them, never inserted into the target (`grants`: the directory writes them). */
|
|
9
9
|
export declare const STAGED_ONLY_TABLES: readonly ["grants"];
|
|
10
10
|
/** Every table the exporter dumps. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var c=Object.defineProperty;var n=(
|
|
1
|
+
var c=Object.defineProperty;var n=(s,e)=>c(s,"name",{value:e,configurable:!0});import{once as a}from"node:events";import{createWriteStream as d}from"node:fs";import{pipeline as u}from"node:stream/promises";import{createZstdCompress as f,createZstdDecompress as m,zstdDecompressSync as l}from"node:zlib";const E="bodies",p=["objects","documents","revisions","revision_parents","identities","jobs","custom_objects","context_sessions","environments","object_kinds","edges","watches","watch_subscriptions","exposures","rules","unresolved_links","nodes","sessions","worktrees","node_faults","waits","structured_requests","memory_reads","deleted_isolated_nodes","node_outcome_deliveries","run_events","messages","message_causes","deliveries","crons","cron_runs","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","audit_rows","idempotency_keys","uploads","upload_uses","files","shares","provider_approvals","relations","charges","limits","conversation_parts","conversation_entries","profiles","bodies"],_=["grants"],S=[...p,..._],b={audit_rows:"id",review_comment_events:"seq"},z=["objects","revisions","watches","watch_subscriptions","sessions","waits","structured_requests","deliveries","run_events"],h={prefix:n(s=>`imports/${s}/`,"prefix"),rowPart:n((s,e,t)=>`imports/${s}/rows/${e}/${t}.jsonl.zst`,"rowPart"),source:n(s=>`imports/${s}/source.json`,"source"),manifest:n(s=>`imports/${s}/manifest.jsonl.zst`,"manifest"),nodeFiles:n((s,e)=>`imports/${s}/node-files/${e}.tar.zst`,"nodeFiles"),request:n((s,e)=>`requests/${s}/${e}`,"request")};function $(s,e,t){return(t.rowParts[e]??[]).map(r=>h.rowPart(s,e,r))}n($,"rowKeys");function L(s,e){let t;for(const r of s)(e===r.from||e.startsWith(r.from.endsWith("/")?r.from:`${r.from}/`))&&(t===void 0||r.from.length>t.from.length)&&(t=r);return t===void 0?e:t.to+e.slice(t.from.length)}n(L,"mapPath");function B(s){const e=l(s).toString("utf8");if(e==="")return[];if(!e.endsWith(`
|
|
2
2
|
`))throw new Error("row file is truncated: the last line is not newline-terminated");return e.slice(0,-1).split(`
|
|
3
|
-
`).map(
|
|
4
|
-
`}n(P,"rowLine");class j{static{n(this,"RowFileWriter")}zst=f();finished;written=0;constructor(e){this.finished=u(this.zst,d(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,
|
|
3
|
+
`).map(t=>JSON.parse(t))}n(B,"decodeRows");function P(s){return`${JSON.stringify(s)}
|
|
4
|
+
`}n(P,"rowLine");class j{static{n(this,"RowFileWriter")}zst=f();finished;written=0;constructor(e){this.finished=u(this.zst,d(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,t=Buffer.byteLength(e,"utf8")){this.written+=t,this.zst.write(e,"utf8")||await Promise.race([a(this.zst,"drain"),this.finished])}async close(){this.zst.end(),await this.finished}destroy(){this.zst.destroy()}}async function*A(s){const e=m({chunkSize:1048576});e.end(s);let t=[];for await(const r of e){let o=0;for(let i=r.indexOf(10,o);i!==-1;i=r.indexOf(10,o))t.push(r.subarray(o,i)),yield(t.length===1?t[0]:Buffer.concat(t)).toString("utf8"),t=[],o=i+1;o<r.length&&t.push(r.subarray(o))}if(t.length>0)throw new Error("row file is truncated: the last line is not newline-terminated")}n(A,"rowLines");export{E as BODIES_TABLE,p as COPIED_TABLES,S as DUMPED_TABLES,b as KEY_MAPPED_TABLES,j as RowFileWriter,z as SEQ_TABLES,_ as STAGED_ONLY_TABLES,h as bundleKeys,B as decodeRows,L as mapPath,$ as rowKeys,P as rowLine,A as rowLines};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as P}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(a=>a.replace(/^user:/,""),"bare"),g=c((a,t)=>`${f(a)}.${f(t)}`,"sq"),N=c(async(a,t,...r)=>await a.prepareUncached(t).all(...r),"all");function I(a,t){return new D("bind","person_mismatch",a,t)}c(I,"mismatch");function te(a,t,r,l){if(a===t||a===r)return r;throw I(`${l} names ${a}, which is neither the bundle's person nor the importing person`,{where:l,value:a})}c(te,"boundSub");async function oe(a,t,r,l){if(!K.test(r))throw I(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===l)return;const
|
|
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`,l,
|
|
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(l=>J(l.inserted_keys).map(
|
|
6
|
-
AND ${f(
|
|
1
|
+
var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as P}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(a=>a.replace(/^user:/,""),"bare"),g=c((a,t)=>`${f(a)}.${f(t)}`,"sq"),N=c(async(a,t,...r)=>await a.prepareUncached(t).all(...r),"all");function I(a,t){return new D("bind","person_mismatch",a,t)}c(I,"mismatch");function te(a,t,r,l){if(a===t||a===r)return r;throw I(`${l} names ${a}, which is neither the bundle's person nor the importing person`,{where:l,value:a})}c(te,"boundSub");async function oe(a,t,r,l){if(!K.test(r))throw I(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===l)return;const u=c(i=>g(t,i),"T"),o=await a.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(r,r,r,r);if(o!==void 0)throw I(`the bundle's person ${r} is already a person in the target (${o.tbl}), not the importing person ${l}`,{where:`${o.tbl}`,value:r})}c(oe,"checkSourcePerson");const Y=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],B=[["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 ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:u}=a,o=c(p=>g(r,p),"S"),i=c((p,d)=>{throw I(`${p} names ${d.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${u}`,{where:p,values:d})},"refuse");for(const[p,d]of Y){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,S.map(O=>O.v))}for(const[p,d]of B){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,S.map(O=>O.v))}const h=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`,l,u);h.length>0&&i("identities.external_id",h.map(p=>p.v));const _=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`,l,u);_.length>0&&i("daemon_actions principal.sub",_.map(p=>p.v));const m=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(l),C(u));m.length>0&&i("relations acts_for subject",m.map(p=>p.v));const $=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return $>0?{relations:$}:{}}c(ne,"checkStagedPersons");async function z(a,t){return(await N(a,`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(l=>J(l.inserted_keys).map(u=>u[0]))}c(z,"earlierImportedObjects");async function se(a,t){const{db:r,schema:l,target:u,catalog:o,targetPerson:i}=a,h=c(n=>g(l,n),"S"),_=c(n=>g(u,n),"T"),m=C(i);await r.exec(`CREATE TABLE ${h("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const $=[];for(const[n,b]of P(o))if(!(!o.tables.has(n)||n==="relations"))for(const E of b)!(n==="nodes"&&E==="profile_id")&&!(n==="crons"&&E==="profile")&&$.push([n,E,""]);$.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,b,E]of $)await r.prepareUncached(`INSERT INTO ${h("_refs")} SELECT ?, ?, ${f(b)}::text FROM ${h(n)} ${E===""?"WHERE":`${E} AND`} ${f(b)} IS NOT NULL
|
|
6
|
+
AND ${f(b)}::text NOT IN (SELECT id FROM ${h("objects")}) AND ${f(b)}::text IN (SELECT id FROM ${_("objects")})`).run(n,b);const p=await z(r,t),d=await N(r,`WITH RECURSIVE chain(start, id) AS (
|
|
7
7
|
SELECT DISTINCT value, value FROM ${h("_refs")}
|
|
8
8
|
UNION SELECT c.start, o.owner FROM chain c JOIN ${_("objects")} o ON o.id = c.id JOIN ${_("objects")} up ON up.id = o.owner AND up.type <> 'app'),
|
|
9
9
|
ok(id) AS (
|
|
@@ -13,5 +13,5 @@ var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});i
|
|
|
13
13
|
UNION SELECT r.resource_id FROM ${_("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
|
|
14
14
|
UNION SELECT unnest(?::text[]))
|
|
15
15
|
SELECT r.tbl, r.col, r.value FROM ${h("_refs")} r
|
|
16
|
-
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(
|
|
17
|
-
JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:
|
|
16
|
+
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(d.length>0)throw I(`the bundle refers to objects that are not ${i}'s: ${d.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:d});const S=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,b]of S){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("profiles")} p ON p.id = s.${f(b)} WHERE p.person <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names profiles that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}for(const[n,b]of[["nodes","grant_id"],["crons","grant_id"]]){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("grants")} g ON g.id = s.${f(b)} WHERE g.sub <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names grants that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}const O=await N(r,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${h("daemon_actions")} d
|
|
17
|
+
JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:u}=a,o=c(e=>g(r,e),"S"),i=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),h=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),_=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),m=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=c(e=>e.split("/")[1]??"","jobOwner"),p=c((e,s,w,L)=>{const F=R(s);if(F===null||F.kind!==w||L!==void 0&&s!==L)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${L===void 0?"":` of the shape ${L}`}`,{where:e,value:s})},"shaped");for(const e of h)if(p("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 _)p("upload_uses.blob_key",e.blob_key,"attachment");for(const e of m)p("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of h){const s=R(e);s!==null&&s.kind==="conversation"&&!i.has(s.owner)&&d.add(s.owner)}for(const{blob_key:e}of _){const s=R(e);s!==null&&s.kind==="attachment"&&!i.has(s.owner)&&d.add(s.owner)}for(const{output_key:e}of m)i.has($(e))||d.add($(e));const S=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(l,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),O=c(e=>i.has(e)||S.get(e)===u,"held"),n=c(e=>!i.has(e)&&!S.has(e),"gone"),b={},E=c((e,s)=>{s>0&&(b[e]=(b[e]??0)+s)},"count"),T=c(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of h){const w=R(s),L=v.get(e);L!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...L??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(n)).map(([e])=>e);y.length>0&&(E("conversation_parts",await T(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),E("conversation_entries",await T(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=c((e,s)=>{const w=R(s).owner;if(!O(w))throw I(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of h)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=_.filter(e=>{const s=R(e.blob_key);return s!==null&&s.kind==="attachment"&&n(s.owner)&&!i.has(e.run_id)});M.length>0&&E("upload_uses",await T(`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`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of _)U.has(e)||j("upload_uses.blob_key",e.blob_key);const A=m.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&n($(e.output_key)));A.length>0&&E("jobs",await T(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,A.map(e=>e.object)));const x=new Set(A);for(const e of m)x.has(e)||j("jobs.output_key",e.output_key);return b}c(re,"checkStagedBlobKeys");async function ae(a){const{db:t,schema:r}=a;for(const l of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(r,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=l[u];if(o===null||!o.startsWith("requests/"))continue;const i=R(o.includes("/",9)?o:`${o}/x`);if(i===null||i.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(i.owner!==l.request_id)throw I(`human_requests.${u} of ${l.request_id} holds ${o}, which belongs to request ${i.owner}`,{where:`human_requests.${u}`,value:o})}}c(ae,"checkStagedRequestKeys");export{te as boundSub,oe as checkSourcePerson,re as checkStagedBlobKeys,ne as checkStagedPersons,se as checkStagedReferences,ae as checkStagedRequestKeys};
|