@north-light/cli 0.3.546 → 0.3.548
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/builtin-memory/crouter-sdk/release-notes.md +4 -0
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/conversation-store/file-store.js +8 -8
- package/dist/core/conversation-store/index.d.ts +3 -1
- package/dist/core/conversation-store/index.js +1 -1
- package/dist/core/graph/access.js +2 -2
- package/dist/core/graph/events.js +8 -8
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/docs/sdk/release-notes.md +4 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -9,6 +9,10 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.548
|
|
13
|
+
|
|
14
|
+
`canvas.watch` with a `watcher` that is a node of your own app now works under `crtr:objects:link:node`. It answered `404 not_found` (`watcher not found`) before. The node must be reachable from the caller under run confinement and must itself be able to read the object. A watch on a node of another machine now forwards every event level, and that node's own listening config decides how each is delivered, where an event below level 3 was dropped before it left the object's machine.
|
|
15
|
+
|
|
12
16
|
## 0.3.546
|
|
13
17
|
|
|
14
18
|
`GET /v1/nodes/:id/broker/extension-state` no longer returns `report_nodes` (every node's id, name, created and grantee). Nothing has read it since 0.3.350, and returning it cost a query over every node on each model request of every broker. No SDK method reads it.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var te=Object.defineProperty;var i=(e,n)=>te(e,"name",{value:n,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{lstatSync as ae,realpathSync as W,rmdirSync as ie,rmSync as oe,statSync as re}from"node:fs";import{basename as se,dirname as F,isAbsolute as de,join as N,relative as ue,resolve as le,sep as ce}from"node:path";import{removeTreeBeneath as b}from"../spaces/open-beneath.js";import{emitEvent as _e}from"../events/emit.js";import{withCanvasWrite as p,openDb as r}from"./db.js";import{conversationStore as pe,ConversationNotFoundError as fe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Ee,UNSEEN_WAKE_MAIL_SQL as we}from"./deliveries.js";import{isAppRun as C}from"./app-run.js";import{registerOutcomeAction as H}from"./outcome-actions.js";import{publish as ye}from"../graph/events.js";import{nodeObject as me}from"../graph/objects.js";import{findNodeBySessionFileSql as Ne}from"./sessions.js";import{hydrateFault as Re}from"./recovery.js";import{hasUnreconciledWorktree as Se,openWorktree as he,readWorktree as Oe,worktreeFromRow as Le}from"./worktrees.js";import{isPidAlive as Te,isPidPresent as M,recordedPidLiveness as De}from"./pid.js";import{ensureHome as ve,jobDir as ge,nodeDir as Ae,nodeRunDir as P}from"./paths.js";import{appForNode as ke,ensureNodeDirs as xe,nodeAgentDir as Ue}from"./node-agent-paths.js";import{appSpace as O}from"../layout.js";import{createObject as Ie,getById as $,ownerForGrantee as je,setObjectKind as We,setObjectName as Fe}from"../graph/objects.js";import{deleteNodeWithOwned as be}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ce,SUBTREE_IDS_SQL as He}from"./tree.js";import{filterAsync as y,mapAsync as L}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Rn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Rn,"assertRunNotDeleting");async function Me(e,n){const t=await je(n,e.grantee??"app:terminal");await Ie(n,{id:e.node_id,type:"node",kind:e.kind,owner:t.id,privacy:"public",name:e.name,preview:""}),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at) VALUES (${Array(40).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null)}i(Me,"seedRow");function q(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return Re(Object.fromEntries(n))}i(q,"faultFrom");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=M(n.pi_pid),a=q(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}i(f,"rowFrom");async function B(e,n){return n??=await Oe(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(B,"metaFrom");async function Sn(e,n={}){return ve(),await p(async t=>{await Me(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await he(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await H(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await xe(e.node_id),await R(e.node_id)}i(Sn,"createNode");async function R(e){const n=await(await r()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await B(n)}i(R,"getNode");const Pe=1440*60*1e3;function z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(z,"createRequestRecord");async function hn(e){const n=await(await r()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:z(n)}i(hn,"findCreateRequest");async function On(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return a!==void 0?z(a):(await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved')").run(e,t+Pe),{requestKey:e,nodeId:null,state:"reserved"})})}i(On,"reserveCreateRequest");async function Ln(e=Date.now()){return Number((await(await r()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(Ln,"pruneExpiredCreateRequests");async function Tn(e,n){await(await r()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(Tn,"recordCreateRequestNode");async function Dn(e,n){await(await r()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ?").run(n,e)}i(Dn,"reserveCreateRequestNode");async function vn(e,n){await(await r()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(vn,"completeCreateRequest");async function gn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(gn,"abandonCreateRequest");function An(e){return le(e)}i(An,"canonicalSessionFile");async function kn(e){const n=await Ne(e);return n===null?null:await R(n)}i(kn,"findNodeBySessionFile");async function xn(e){const n=await(await r()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(xn,"getRow");async function Un(e){const n=await(await r()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(Un,"getRowByPane");async function In(e){return(await(await r()).prepare(`SELECT * FROM node_rows
|
|
2
2
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
|
|
3
3
|
AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
|
|
4
|
-
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}
|
|
5
|
-
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let s=0;for(const d of
|
|
4
|
+
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(In,"dueNodeDeadlines");async function jn(e,n){return Number((await(await r()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(jn,"setNodeDeadline");async function Wn(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
|
|
5
|
+
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let s=0;for(const d of a){const l=Date.parse(d.deadline_at);Number.isNaN(l)||(s+=Number((await o.run(new Date(l+n).toISOString(),d.node_id,d.deadline_at)).changes))}return s})}i(Wn,"shiftProfileNodeDeadlines");function T(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}i(T,"sqlInput");async function Fn(e,n){const t=[],a=i((s,d=s)=>{Object.prototype.hasOwnProperty.call(n,s)&&t.push([d,T(n[s],s)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",E(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",E(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",E(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",E(n.launch,"launch")]);const o=i(s=>Object.prototype.hasOwnProperty.call(n,s),"has");return await p(async s=>{const d=await $(s,e);if(d===null||d.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await Fe(s,d,T(n.name,"name")),o("kind")&&await We(s,d,T(n.kind,"kind")),t.length===0)return;if((await s.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await R(e)}i(Fn,"updateNode");async function bn(e,n){await(await r()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(bn,"setStatus");async function Cn(e,n){await(await r()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(Cn,"setIntent");async function Hn(e,n,t={}){if(t.outcome===void 0){const o=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const d=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(d.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&d.push("final_report IS NULL");const l=await(await r()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${d.join(" AND ")}`).run(...s);return Number(l.changes)}const a=t.outcome;return await p(async o=>{const s=[],d=[];Object.prototype.hasOwnProperty.call(n,"status")&&(s.push("status = ?"),d.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(s.push("intent = ?"),d.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(s.push("terminal_reason = ?"),d.push(n.terminal_reason??null));const l=i((I,w)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${w} END`,"outcomeValue");s.push(`outcome_kind = ${l(a.kind,"outcome_kind")}`,`outcome_reason = ${l(a.reason,"outcome_reason")}`,`outcome_detail_json = ${l(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${l(a.at,"outcome_at")}`),d.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];d.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),d.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await o.prepareUncached(`UPDATE nodes SET ${s.join(", ")} WHERE ${u.join(" AND ")}`).run(...d);if(Number(_.changes)===0)return 0;const h=await o.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||h.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await ye(o,{event:"outcome",object:await me(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(Hn,"transitionStatusIntent");async function Mn(e){return(await(await r()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(Mn,"getFinalReport");async function Pn(e,n){return(await(await r()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}i(Pn,"clearFinalReportIfMatches");async function $n(e,n){await(await r()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}i($n,"setPresence");async function qn(e,n){await(await r()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}i(qn,"recordLaunch");async function Bn(e,n){await(await r()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(Bn,"recordSettledTurn");async function zn(e,n){await(await r()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(zn,"setFrozen");async function Jn(e){await(await r()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(Jn,"clearFrozen");async function Yn(e,n){await(await r()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(Yn,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",J=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function $e(e){return e.worktree_state===null?null:Le(Object.fromEntries(J.map(n=>[n,e[`worktree_${n}`]])))}i($e,"worktreeFromProjection");async function Qn(e){const n=J.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await r()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await L(t,async a=>await B(a,$e(a)))}i(Qn,"listNodesByProfile");async function Vn(){return(await(await r()).prepare(`SELECT
|
|
6
6
|
node_id, name, description, kind, mode, lifecycle, status, cwd, profile_id,
|
|
7
7
|
grantee, parent, created, frozen_at, terminal_reason, final_report,
|
|
8
8
|
telemetry_tokens_in, telemetry_updated_at, pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -10,13 +10,13 @@ var ee=Object.defineProperty;var a=(e,n)=>ee(e,"name",{value:n,configurable:!0})
|
|
|
10
10
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
11
11
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
12
12
|
fault_provider_error_json
|
|
13
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}
|
|
13
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(Vn,"browseNodes");async function Kn(e,n){await(await r()).prepare(`UPDATE nodes
|
|
14
14
|
SET telemetry_tokens_in = ?,
|
|
15
15
|
telemetry_context_tokens = COALESCE(?, telemetry_context_tokens),
|
|
16
16
|
telemetry_last_activity = COALESCE(?, telemetry_last_activity),
|
|
17
17
|
telemetry_updated_at = ?
|
|
18
18
|
WHERE node_id = ?
|
|
19
|
-
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}
|
|
19
|
+
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(Kn,"updateNodeTelemetry");async function Gn(){return(await(await r()).prepare(`SELECT
|
|
20
20
|
node_id, name, description, cycles, kind, status, frozen_at,
|
|
21
21
|
telemetry_context_tokens, telemetry_last_activity,
|
|
22
22
|
pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -24,14 +24,14 @@ var ee=Object.defineProperty;var a=(e,n)=>ee(e,"name",{value:n,configurable:!0})
|
|
|
24
24
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
25
25
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
26
26
|
fault_provider_error_json
|
|
27
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,
|
|
27
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=M(t),o=q(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:n.turn_open_at!==null&&n.turn_closed_at===null&&a}})}i(Gn,"graphNodes");async function qe(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Ce}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${He})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,o=>`\\${o}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await r()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}i(qe,"listNodes");const Be=`SELECT
|
|
28
28
|
node_id, created, launched_at, last_settled_at, finalized_at,
|
|
29
29
|
outcome_at, last_activity_at, pane, "window", tmux_session
|
|
30
30
|
FROM nodes
|
|
31
31
|
WHERE ${m}
|
|
32
32
|
AND status IN ('done', 'canceled', 'dead')
|
|
33
33
|
AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
|
|
34
|
-
ORDER BY created`;async function
|
|
34
|
+
ORDER BY created`;async function Xn(){return await(await r()).prepare(Be).all()}i(Xn,"listTerminalPlacementResidue");const ze=`WITH candidates AS MATERIALIZED (
|
|
35
35
|
SELECT node_id FROM nodes WHERE status IN ('active', 'idle')
|
|
36
36
|
UNION
|
|
37
37
|
SELECT node_id FROM nodes
|
|
@@ -45,23 +45,23 @@ var ee=Object.defineProperty;var a=(e,n)=>ee(e,"name",{value:n,configurable:!0})
|
|
|
45
45
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
46
46
|
AND v.kind != 'human'
|
|
47
47
|
AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))
|
|
48
|
-
ORDER BY v.created`;async function
|
|
49
|
-
WHERE ${
|
|
50
|
-
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${
|
|
51
|
-
ORDER BY v.created`).all()).map(f)}
|
|
48
|
+
ORDER BY v.created`;async function Zn(){return(await(await r()).prepare(ze).all()).map(f)}i(Zn,"listNodesForSupervision");const Y=i(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),Je=i(e=>`(${e}.status IN ('active', 'idle') OR ${Y(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function et(e){return await(await r()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${Je("nodes")} AND node_id != ?`).all(e)}i(et,"resumableNodeCwds");async function nt(){return(await(await r()).prepare(`SELECT v.* FROM node_rows v
|
|
49
|
+
WHERE ${Y("v")}
|
|
50
|
+
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${we("d")}) AND v.kind != 'human' AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
51
|
+
ORDER BY v.created`).all()).map(f)}i(nt,"listParkedResidentsWithWakeMail");async function tt(e,n){await(await r()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}i(tt,"registerWarmSpare");async function at(e){return(await(await r()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(at,"unregisterWarmSpare");async function D(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
|
|
52
52
|
n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
|
|
53
|
-
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}
|
|
54
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}
|
|
53
|
+
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(D,"warmSpareRowsFor");async function it(){return await D(await r())}i(it,"listWarmSpares");async function ot(e){return await(await r()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(ot,"isWarmSpare");function Q(e){return e.status!=="active"&&e.status!=="idle"?!1:De(e.pi_pid,e.pi_pid_identity)==="alive"}i(Q,"spareIsClaimable");async function rt(e,n,t={}){return await p(async a=>{const o=(await D(a,e)).find(Q);return o===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await H(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(rt,"claimWarmSpare");async function st(e){return(await D(await r(),e)).filter(Q).length}i(st,"warmSpareCount");async function dt(e){return(await(await r()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(dt,"childrenOf");async function ut(){return(await(await r()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
|
|
54
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(ut,"rosterNodes");async function lt(e){return(await(await r()).prepareUncached(`SELECT * FROM node_rows
|
|
55
55
|
WHERE parent IS NULL AND kind != 'human'
|
|
56
56
|
AND status IN ('active','idle') AND cwd = ?
|
|
57
57
|
AND ${m}
|
|
58
|
-
ORDER BY created DESC`).all(e)).map(f)}
|
|
59
|
-
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const
|
|
58
|
+
ORDER BY created DESC`).all(e)).map(f)}i(lt,"listResumableRoots");export*from"./tree.js";async function ct(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ?").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(ct,"withFreshTerminalGuard");async function S(e){return await Se(e)}i(S,"hasUnreconciledManagedWorktree");async function V(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await S(e.node_id)||e.node_id===j()||C(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(V,"isCollectible");async function v(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await r()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:N(O(a.grantee).conversations,a.node_id)}])).values()]}i(v,"nodeConversationIds");async function g(e){const n=await r(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
|
|
59
|
+
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:s,dir:d}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&ae(s,{throwIfNoEntry:!1})!==void 0){if(!Ye(d,s)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${s}`);continue}try{await pe().delete(o,s)}catch(l){if(!(l instanceof fe))throw l}}}i(g,"deleteNodeConversations");function Ye(e,n){try{const t=ue(W(e),N(W(F(n)),se(n)));return t!==""&&t!==".."&&!t.startsWith(`..${ce}`)&&!de(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(Ye,"isBeneath");async function A(e,n){const t=await $(e,n);return t===null||t.deleted_at!==null?!1:(await be(e,t),!0)}i(A,"deleteNodeObject");async function k(e){return{nodeId:e,app:await R(e)===null?null:await ke(e)}}i(k,"nodeFiles");async function K({nodeId:e,app:n}){n!==null&&b(O(n).nodes,await Ue(e,n)),b(F(P(e)),P(e))}i(K,"removeNodeAppTrees");function G({nodeId:e}){return[Ae(e)]}i(G,"nodeOwnedDirs");function X({nodeId:e,app:n}){if(n!==null)try{ie(N(O(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(X,"removeNodeConversationDir");async function x(e){await K(e);for(const n of G(e))oe(n,{recursive:!0,force:!0});X(e)}i(x,"removeNodeFiles");async function _t(e){if(await S(e))return{deleted:!1};const n=await k(e),t=await v([e]),a=await p(async o=>(await A(o,e),{deleted:!0}));return await g(t),await x(n),a}i(_t,"deleteNode");async function pt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,S);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);const a=await L(n,k),o=await v(n),s=n.map(()=>"?").join(","),d=(await(await r()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${s}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),l=await y(d,async u=>await p(async _=>await A(_,u)));await g(o);for(const u of l){const _=a[n.indexOf(u)];await U(_,async()=>await x(_))}return l}i(pt,"deleteNodes");async function ft(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),s=j()??"",d=await r(),l=i(c=>ne(c)<a,"quiet"),u=i(c=>({node_id:c.node_id,status:c.status,created:c.created}),"toPruned"),_=await Qe(),h=(await y((await d.prepare(`SELECT * FROM node_rows
|
|
60
60
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
61
|
-
ORDER BY created`).all(o)).map(f),async c=>await
|
|
61
|
+
ORDER BY created`).all(o)).map(f),async c=>await V(c,{pastTtl:!0})&&l(c)&&!_.has(c.node_id)&&!await e.held(c.node_id))).map(u),I=t?(await y((await d.prepare(`SELECT * FROM node_rows
|
|
62
62
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
63
|
-
ORDER BY created`).all(o)).map(f),async c=>c.node_id!==s&&!
|
|
63
|
+
ORDER BY created`).all(o)).map(f),async c=>c.node_id!==s&&!Te(c.pi_pid??null)&&(c.frozen_at??null)===null&&(c.respawn_not_before??null)===null&&c.intent!=="idle-release"&&!C(c)&&!await Ee(c.node_id)&&!await S(c.node_id)&&l(c)&&!await e.held(c.node_id))).map(u):[],w=await Z([...h,...I]);return n||w.length===0?{pruned:w,dryRun:n}:(await ee(w,e.removeDirs),{pruned:w,dryRun:n})}i(ft,"pruneNodes");async function Qe(){const e=await(await r()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
|
|
64
64
|
JOIN objects d ON d.id = w.object AND d.type = 'document' AND d.deleted_at IS NULL
|
|
65
65
|
JOIN objects o ON o.id = w.watcher AND o.deleted_at IS NULL
|
|
66
66
|
LEFT JOIN nodes n ON n.node_id = w.watcher
|
|
67
|
-
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}
|
|
67
|
+
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(Qe,"ownersOfWatchedDocuments");async function Z(e){const t=(await r()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(s=>a.has(s.node_id)))}i(Z,"retainRunRootsWithMembers");async function ee(e,n){if(e.length===0)return;const t=await L(e,async o=>await k(o.node_id)),a=await v(e.map(o=>o.node_id));for(const o of e)await p(async s=>await A(s,o.node_id));if(await g(a),n!==void 0){for(const o of t)await U(o,async()=>{await K(o),X(o)});n(t.flatMap(G));return}for(const o of t)await U(o,async()=>await x(o))}i(ee,"deletePrunedNodes");async function U(e,n){try{n()}catch(t){_e({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(U,"eachNodeBestEffort");function ne(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=re(N(ge(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(ne,"lastActivityMs");async function Et(e){const n=e.dryRun??!1,t=await qe(),a=await y(t,async u=>await V(u)&&!await e.held(u.node_id)),o=t.length-a.length,s=Math.max(0,e.maxNodes-o),d=a.map(u=>({row:u,recency:ne(u)})).sort((u,_)=>_.recency-u.recency).slice(s).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),l=await Z(d);return n||l.length===0?{pruned:l,dryRun:n}:(await ee(l),{pruned:l,dryRun:n})}i(Et,"pruneToLimit");export{Y as PARKED_RESIDENT_SQL,Je as RESUMABLE_NODE_SQL,gn as abandonCreateRequest,Rn as assertRunNotDeleting,Vn as browseNodes,An as canonicalSessionFile,dt as childrenOf,rt as claimWarmSpare,Pn as clearFinalReportIfMatches,Jn as clearFrozen,vn as completeCreateRequest,Sn as createNode,_t as deleteNode,pt as deleteNodes,In as dueNodeDeadlines,hn as findCreateRequest,kn as findNodeBySessionFile,Mn as getFinalReport,R as getNode,xn as getRow,Un as getRowByPane,Gn as graphNodes,V as isCollectible,ot as isWarmSpare,ne as lastActivityMs,qe as listNodes,Qn as listNodesByProfile,Zn as listNodesForSupervision,nt as listParkedResidentsWithWakeMail,lt as listResumableRoots,Xn as listTerminalPlacementResidue,it as listWarmSpares,k as nodeFiles,ze as nodesForSupervisionSql,Ln as pruneExpiredCreateRequests,ft as pruneNodes,Et as pruneToLimit,Tn as recordCreateRequestNode,qn as recordLaunch,Yn as recordRespawnAttempt,Bn as recordSettledTurn,tt as registerWarmSpare,x as removeNodeFiles,On as reserveCreateRequest,Dn as reserveCreateRequestNode,et as resumableNodeCwds,ut as rosterNodes,zn as setFrozen,Cn as setIntent,jn as setNodeDeadline,$n as setPresence,bn as setStatus,Wn as shiftProfileNodeDeadlines,Be as terminalPlacementResidueSql,Hn as transitionStatusIntent,at as unregisterWarmSpare,Fn as updateNode,Kn as updateNodeTelemetry,st as warmSpareCount,ct as withFreshTerminalGuard};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var G=Object.defineProperty;var u=(l,o)=>G(l,"name",{value:o,configurable:!0});import{randomUUID as J}from"node:crypto";import{closeSync as v,createReadStream as K,existsSync as $,fsyncSync as
|
|
2
|
-
`))if(w.trim())try{o.push(JSON.parse(w))}catch{}return o}u(E,"parseLines");function
|
|
3
|
-
`);for(;
|
|
4
|
-
`)}}}finally{v(o)}}u(
|
|
5
|
-
`).join("")}u(
|
|
6
|
-
`)},"slice"),s=a(0,
|
|
1
|
+
var G=Object.defineProperty;var u=(l,o)=>G(l,"name",{value:o,configurable:!0});import{randomUUID as J}from"node:crypto";import{closeSync as v,createReadStream as K,existsSync as $,fsyncSync as M,mkdirSync as L,openSync as z,readFileSync as C,readSync as k,renameSync as Q,rmSync as T,statSync as S,unlinkSync as O,writeFileSync as j}from"node:fs";import{createInterface as V}from"node:readline";import{dirname as X,join as F,relative as Y,resolve as b}from"node:path";import{SessionManager as Z}from"@earendil-works/pi-coding-agent";import{ConversationNotFoundError as I}from"./index.js";function E(l){const o=[];for(const w of l.split(`
|
|
2
|
+
`))if(w.trim())try{o.push(JSON.parse(w))}catch{}return o}u(E,"parseLines");function ee(l){const o=z(l,"r");try{const w=Buffer.allocUnsafe(4096);let f="";for(;;){const h=k(o,w,0,w.length,null);f+=w.toString("utf8",0,h);let d=f.indexOf(`
|
|
3
|
+
`);for(;d!==-1||h===0;){const m=d===-1?f:f.slice(0,d),[y]=E(m);if(y!==void 0)return y;if(d===-1)return;f=f.slice(d+1),d=f.indexOf(`
|
|
4
|
+
`)}}}finally{v(o)}}u(ee,"firstLine");function te(l,o){const w=z(l,"r");try{const f=Buffer.alloc(1);return k(w,f,0,1,o-1),f[0]}finally{v(w)}}u(te,"lastByte");function P(l,o){return[l,...o].map(w=>`${JSON.stringify(w)}
|
|
5
|
+
`).join("")}u(P,"lines");function W(l,o){const w=`--${b(o).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return F(l,w)}u(W,"sessionDirectory");function A(l){return`${l.timestamp.replace(/[:.]/g,"-")}_${l.id}.jsonl`}u(A,"fileName");function fe(l,o){const{appendSection:w}=o,f=new Map,h=new Map;L(l,{recursive:!0,mode:448});const d=new Set;async function m(t){if(d.has(t))return;const e=await y(t);if(await o.repair?.(t,e),!$(e)){f.delete(t),h.delete(t);return}d.add(t)}u(m,"repair");async function y(t){const e=f.get(t)??await o.pathFor?.(t);if(!e)throw new I(t);return f.set(t,e),e}u(y,"pathFor");async function x(t){await m(t);const e=await y(t),r=E(C(e,"utf8")),n=r.shift();if(n?.type!=="session"||n.id!==t)throw new Error(`invalid conversation: ${t}`);return{header:n,entries:r,path:e}}u(x,"read");function B(t,e){const r=ee(e);return r?.type==="session"&&r.id===t?r:void 0}u(B,"validHeader");async function N(t){const e=await y(t),r=B(t,e);if(!r)throw new Error(`invalid conversation: ${t}`);return{header:r,path:e}}u(N,"headerOf");async function H(t,e){await m(t);const{header:r,path:n}=await N(t),c=S(n).size;if(c<=e.head+e.tail)return await x(t);const i=z(n,"r");try{const a=u((R,_)=>{if(_<=0)return[];const U=Buffer.allocUnsafe(_),q=k(i,U,0,_,R);return U.subarray(0,q).toString("utf8").split(`
|
|
6
|
+
`)},"slice"),s=a(0,e.head),p=a(c-e.tail,e.tail);s.pop(),p.shift();const g=E(s.join(`
|
|
7
7
|
`));return g[0]?.type==="session"&&g.shift(),{header:r,entries:g,tail:E(p.join(`
|
|
8
|
-
`)),path:n}}finally{v(i)}}u(H,"readWindow");async function D(e,
|
|
9
|
-
`).join("")),
|
|
8
|
+
`)),path:n}}finally{v(i)}}u(H,"readWindow");async function D(t,e,r,n,c){if(f.has(e.id))throw new Error(`conversation already exists: ${e.id}`);const i=Y(l,n);if(i.startsWith("..")||i===""||b(n)===b(l))throw new Error("conversation path outside store root");if(L(X(n),{recursive:!0,mode:448}),$(n))throw new Error(`conversation file already exists: ${n}`);let a=!1;try{const s=u(()=>{const p=z(n,"wx",384);a=!0;try{return j(p,P(e,r)),M(p),a=!1,S(n).size}finally{v(p)}},"write");return t===void 0?s():await w(e.id,{kind:"create",nodeId:t,path:n,entries:r,...c?{sourceId:c}:{}},s),f.set(e.id,n),e.id}catch(s){throw a||!$(n)?($(n)&&O(n),await o.abortCreate?.(e.id)):f.set(e.id,n),s}}return u(D,"createAt"),{recover(t){for(const e of t){if(!e.transcript_path)continue;const r=f.get(e.session_id);if(r&&r!==e.transcript_path)throw new Error(`conflicting conversation paths: ${e.session_id}`);f.set(e.session_id,e.transcript_path)}},repair:m,async readLines(t){await m(t);const e=await y(t),r=V({input:K(e),crlfDelay:1/0});return{path:e,lines:r}},async create(t,e,r,n){return await D(t,e,r,await o.createPath?.(t,e)??n??F(W(l,e.cwd),A(e)))},async append(t,e,r){if(e.length===0)return;await m(t);const n=await y(t);if(r?.dedupe){const i=new Set((await x(t)).entries.map(a=>a.id));if(e=e.filter(a=>!i.has(a.id)),e.length===0)return}const c=S(n).size;if(c>0&&te(n,c)!==10)throw new Error(`incomplete conversation tail: ${t}`);try{await w(t,{kind:"append",entries:e},()=>{const i=z(n,"a");try{return j(i,e.map(a=>`${JSON.stringify(a)}
|
|
9
|
+
`).join("")),M(i),S(n).size}finally{v(i)}})}catch(i){throw d.delete(t),i}},async replace(t,e,r){await m(t);const n=await y(t);if(e.id!==t)throw new Error("replacement header id differs from conversation id");const c=C(n),i=u(s=>{const p=`${n}.${J()}.tmp`;try{j(p,s,{flag:"wx",mode:384});const g=z(p,"r");try{M(g)}finally{v(g)}Q(p,n)}finally{$(p)&&O(p)}},"swap");let a=!1;try{await w(t,{kind:"replace"},()=>(i(P(e,r)),a=!0,S(n).size))}catch(s){throw a&&i(c),s}finally{h.delete(t)}},async read(t,e){return e?await H(t,e):await x(t)},async header(t){await m(t);const{header:e,path:r}=await N(t),n=S(r);return{header:e,path:r,mtime:n.mtimeMs,size:n.size}},async fork(t,e,r,n){const c=await x(t);let i=c.entries;if(r!==void 0){const p=Z.inMemory(c.header.cwd,void 0,[c.header,...i]);p.createBranchedSession(r),i=p.getEntries()}const a=new Date().toISOString(),s={...c.header,id:J(),timestamp:a,cwd:n??c.header.cwd,parentSession:c.path};return await D(e,s,i,e&&o.createPath?await o.createPath(e,s):F(W(l,s.cwd),A(s)),t)},async list(t){const e=[],r=await o.owners();for(const n of new Set([...f.keys(),...r.keys()])){const c=r.get(n);if(t!==void 0&&c!==t||(await m(n),!f.has(n)))continue;const i=await y(n),a=S(i);let s=h.get(n);(!s||s.mtime!==a.mtimeMs||s.size!==a.size)&&(s={mtime:a.mtimeMs,size:a.size,header:B(n,i)},h.set(n,s)),s.header&&e.push({conversation_id:n,...c?{node_id:c}:{},header:s.header,mtime:a.mtimeMs,size:a.size,path:i})}return e.sort((n,c)=>c.mtime-n.mtime)},async delete(t,e){e===void 0?O(await y(t)):T(e,{force:!0}),await o.delete?.(t),f.delete(t),d.delete(t),h.delete(t)}}}u(fe,"createFileStore");export{fe as createFileStore,W as sessionDirectory};
|
|
@@ -78,7 +78,9 @@ export interface ConversationStore {
|
|
|
78
78
|
}>;
|
|
79
79
|
fork(id: string, nodeId?: string, leafId?: string, cwd?: string): Promise<string>;
|
|
80
80
|
list(nodeId?: string): Promise<ConversationInfo[]>;
|
|
81
|
-
|
|
81
|
+
/** `path` names the transcript when its sessions row is already gone (the in-process store only;
|
|
82
|
+
* the socket client resolves from the row and ignores it). A file already missing there is not an error. */
|
|
83
|
+
delete(id: string, path?: string): Promise<void>;
|
|
82
84
|
}
|
|
83
85
|
export declare function conversationIdFromPath(path: string): string | null;
|
|
84
86
|
export declare function defaultConversationRoot(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var o=(e,r)=>c(e,"name",{value:r,configurable:!0});import{appsRoot as i,socketDir as p}from"../layout.js";import{join as d}from"node:path";import{createStoreClient as f}from"./client.js";import{currentNodeToken as u}from"../runtime/broker/node-token.js";class l extends Error{static{o(this,"ConversationNotFoundError")}code="not_found";constructor(r){super(`conversation not found: ${r}`)}}function h(e){return e instanceof l}o(h,"isConversationNotFound");function k(e){return/(?:^|\/)[^/]+_([0-9a-f-]{36})\.jsonl$/i.exec(e)?.[1]??null}o(k,"conversationIdFromPath");function R(){return i()}o(R,"defaultConversationRoot");function m(){return process.env.CRTR_STORE_ADDRESS||d(p(),"store.sock")}o(m,"storeAddress");let t,s;function A(e){t=e}o(A,"installConversationStore");function F(){if(t)return t;const e=a();return{create:o(async(...r)=>e.create(...r),"create"),append:o(async(...r)=>e.append(...r),"append"),replace:o(async(...r)=>e.replace(...r),"replace"),read:o(async(...r)=>e.read(...r),"read"),header:o(async(...r)=>e.header(...r),"header"),fork:o(async(...r)=>e.fork(...r),"fork"),list:o(async(...r)=>e.list(...r),"list"),delete:o(async
|
|
1
|
+
var c=Object.defineProperty;var o=(e,r)=>c(e,"name",{value:r,configurable:!0});import{appsRoot as i,socketDir as p}from"../layout.js";import{join as d}from"node:path";import{createStoreClient as f}from"./client.js";import{currentNodeToken as u}from"../runtime/broker/node-token.js";class l extends Error{static{o(this,"ConversationNotFoundError")}code="not_found";constructor(r){super(`conversation not found: ${r}`)}}function h(e){return e instanceof l}o(h,"isConversationNotFound");function k(e){return/(?:^|\/)[^/]+_([0-9a-f-]{36})\.jsonl$/i.exec(e)?.[1]??null}o(k,"conversationIdFromPath");function R(){return i()}o(R,"defaultConversationRoot");function m(){return process.env.CRTR_STORE_ADDRESS||d(p(),"store.sock")}o(m,"storeAddress");let t,s;function A(e){t=e}o(A,"installConversationStore");function F(){if(t)return t;const e=a();return{create:o(async(...r)=>e.create(...r),"create"),append:o(async(...r)=>e.append(...r),"append"),replace:o(async(...r)=>e.replace(...r),"replace"),read:o(async(...r)=>e.read(...r),"read"),header:o(async(...r)=>e.header(...r),"header"),fork:o(async(...r)=>e.fork(...r),"fork"),list:o(async(...r)=>e.list(...r),"list"),delete:o(async r=>e.delete(r),"delete")}}o(F,"conversationStore");function a(){const e=m();return s?.address!==e&&(s={address:e,store:f(e,u())}),s.store}o(a,"conversationClient");async function D(e,r){if(t)return t.read(e,r);const n=a();return n.readAsync?n.readAsync(e,r):n.read(e,r)}o(D,"readConversationAsync");import{createFileStore as _,sessionDirectory as N}from"./file-store.js";import{installSessionManagerStorePatch as T}from"./patch.js";import{findOrphanedParents as $,relinkOrphanedParents as g,repairConversationFile as I}from"./repair.js";export{l as ConversationNotFoundError,a as conversationClient,k as conversationIdFromPath,F as conversationStore,_ as createFileStore,R as defaultConversationRoot,$ as findOrphanedParents,A as installConversationStore,T as installSessionManagerStorePatch,h as isConversationNotFound,D as readConversationAsync,g as relinkOrphanedParents,I as repairConversationFile,N as sessionDirectory,m as storeAddress};
|
|
@@ -2,7 +2,7 @@ var R=Object.defineProperty;var s=(n,t)=>R(n,"name",{value:t,configurable:!0});i
|
|
|
2
2
|
SELECT owner, 1 FROM objects WHERE id = ? AND owner IS NOT NULL
|
|
3
3
|
UNION ALL
|
|
4
4
|
SELECT o.owner, c.depth + 1 FROM objects o JOIN chain c ON o.id = c.id WHERE o.owner IS NOT NULL
|
|
5
|
-
) SELECT o.* FROM chain c CROSS JOIN objects o WHERE o.id = c.id ORDER BY c.depth`).all(t.id)}s(C,"ownerChain");async function P(n,t){return(await o(n,t)).space}s(P,"spaceOf");async function o(n,t){const a=await C(n,t),i=a.length?a[a.length-1]:t,e=g[i.type];if(!e)throw new Error(`${t.type} ${t.id} has no space: its owner chain ends at ${i.type} ${i.id}`);const p=a.length?[...a.slice(0,-1).reverse(),t]:[];return{space:i,path:p,impl:e}}s(o,"locate");async function y(n,t){return t.type!=="document"?!1:(await n.prepare("SELECT source_path FROM documents WHERE object = ?").get(t.id))?.source_path!=null}s(y,"isShipped");async function
|
|
5
|
+
) SELECT o.* FROM chain c CROSS JOIN objects o WHERE o.id = c.id ORDER BY c.depth`).all(t.id)}s(C,"ownerChain");async function P(n,t){return(await o(n,t)).space}s(P,"spaceOf");async function o(n,t){const a=await C(n,t),i=a.length?a[a.length-1]:t,e=g[i.type];if(!e)throw new Error(`${t.type} ${t.id} has no space: its owner chain ends at ${i.type} ${i.id}`);const p=a.length?[...a.slice(0,-1).reverse(),t]:[];return{space:i,path:p,impl:e}}s(o,"locate");async function y(n,t){return t.type!=="document"?!1:(await n.prepare("SELECT source_path FROM documents WHERE object = ?").get(t.id))?.source_path!=null}s(y,"isShipped");async function v(n,t){return(await n.prepare(`SELECT a.* FROM objects a WHERE a.type = 'app' AND a.deleted_at IS NULL AND EXISTS (
|
|
6
6
|
SELECT 1 FROM objects o JOIN documents d ON d.object = o.id
|
|
7
7
|
WHERE o.owner = a.id AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL)
|
|
8
|
-
ORDER BY a.name = 'crtr', a.name`).all()).filter(i=>f(n,t,i))}s(
|
|
8
|
+
ORDER BY a.name = 'crtr', a.name`).all()).filter(i=>f(n,t,i))}s(v,"toolApps");function f(n,t,a){return a.type==="app"}s(f,"mayUseTools");const T=s(n=>n.class!=="app"||n.place!==void 0,"isRun");async function A(n,t,a){const i=`${(await l(n,a)).external_id.replace(/^app:/,"")}:`;return t.some(e=>e.startsWith(i)&&!e.slice(i.length).includes(":"))}s(A,"holdsProviderGroup");async function I(n,t,a){return t.class==="person"?!0:t.class==="object"?t.owner.id===a.id:t.class==="app"?t.app.id===a.id||a.type==="profile"&&a.owner===t.app.id:t.app.id===a.id||a.type==="profile"&&t.profile?.id===a.id||a.type==="repo"&&await L(n,t,a,"rw")}s(I,"mayActAs");async function _(n,t,a){if(t.class!=="node"&&!(t.class==="app"&&t.place!==void 0))return!0;const i=t.class==="app"?t.place:await x(t.node.id,n);if(i===null)return!0;const e=await O(a.id,n);return e===null?!i.isolated:N(i,e)}s(_,"customReachable");const h=s(n=>n.type.includes("."),"isCustom");async function J(n,t,a){return await E(n,await o(n,t),t,a)}s(J,"objectsTargets");async function E(n,{space:t,path:a},i,e){const p=[];if(t.type==="person")p.push("user");else if(t.type==="app"&&a.length>0){const c=a[0];if(c.type==="profile")a.length>1&&p.push(`profile:${(await l(n,c)).external_id}`);else if(c.type==="node"||h(c)){const r=(await l(n,t)).external_id;r!==e&&p.push(r)}}return i.type==="node"&&p.push("node"),p}s(E,"targetsOf");async function u(n,t,a,i,e){if(t.class==="person"||t.scopes===null)return!1;const p=t.scopes;if(p.length===0||a!=="link"&&i.space.type==="app"&&t.app.id===i.space.id)return!1;const c=(await l(n,t.app)).external_id;return(await E(n,i,e,c)).some(r=>{const m=`crtr:objects:${a}:${r}`;return p.some(d=>S(d,m))})}s(u,"holdsInLocated");async function M(n,t,a,i){return t.class==="person"||t.scopes===null?!1:await u(n,t,a,await o(n,i),i)}s(M,"holdsObjectsScope");async function B(n,t,a,i,e){const p=i.owner===null?null:await n.prepareUncached("SELECT * FROM objects WHERE id = ?").get(i.owner)??null;if(p===null)return!1;const c={class:"app",app:t,scopes:a??[]};return await I(n,c,p)?a===null||await M(n,c,"link",e):!1}s(B,"linkAuthorizes");async function Y(n,t,a){return(await U(n,a))(t)}s(Y,"canRead");async function U(n,t){let a=null,i=null;return async e=>{if(e.class==="person")return!0;if(a??=await o(n,t),a.space.type==="app"&&a.path.length>0){if(i??=await y(n,t),i&&f(n,e,a.space))return!0;if(h(t)){if(e.app.id===a.space.id&&!await _(n,e,t))return!1;if(e.app.id!==a.space.id&&e.scopes!==null&&f(n,e,a.space)&&(t.privacy==="public"||T(e)&&await A(n,e.scopes,a.space)))return!0}}return await u(n,e,"read",a,t)||e.class==="object"&&h(e.object)&&await u(n,e,"watch",a,t)?!0:await a.impl.canRead(n,e,a.space,a.path,t)}}s(U,"readCheck");async function z(n,t,a){if(await y(n,a))return!1;const i=await o(n,a);if(await u(n,t,"write",i,a))return!0;const{space:e,path:p,impl:c}=i;return await c.canChange(n,t,e,p,a)}s(z,"canChange");async function G(n,t,a,i){if(t.class==="person")return null;const{space:e,path:p}=await o(n,a);return e.type==="app"&&t.app.id===e.id?await w(n,t,e,p,a,i):null}s(G,"missingMemoryScope");async function V(n,t,a,i){if(t.class==="person")return null;const e=await o(n,a),{space:p}=e;return p.type!=="app"||t.app.id!==p.id?null:await w(n,t,p,e.path.length===0?[a]:[...e.path],null,i)}s(V,"missingMemoryScopeUnder");export{z as canChange,Y as canRead,_ as customReachable,M as holdsObjectsScope,A as holdsProviderGroup,y as isShipped,B as linkAuthorizes,I as mayActAs,f as mayUseTools,G as missingMemoryScope,V as missingMemoryScopeUnder,J as objectsTargets,C as ownerChain,U as readCheck,P as spaceOf,v as toolApps};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND name = ? AND id != ? LIMIT 1`).get(e.name,e.id)?`${e.type}:${e.name}`:e.name}d(oe,"ownerHandleOf");async function ie(n,e,o){const i=e.object.owner===null?null:await n.prepare("SELECT * FROM objects WHERE id = ?").get(e.object.owner),t=i?.id??null,
|
|
3
|
-
`)[0]:`${e.event} ${e.object.type} ${e.object.name}`),...l?.bodyRef===void 0?{}:{bodyRef:l.bodyRef},...l?.disposition===void 0?{}:{disposition:l.disposition},senderNodeId:e.actor?.type==="node"?e.actor.id:null,senderName:e.actor===null||e.actor===void 0?null:e.actor.home_machine?`${e.actor.name} on ${M(e.actor.home_machine)}`:e.actor.name,bodyJson:f}}d(se,"messageInput");async function re(n,e,o,i,t){if(!o.supersedes)return[{attrs:e.attrs,destinations:[...i]}];const
|
|
1
|
+
var x=Object.defineProperty;var d=(n,e)=>x(n,"name",{value:e,configurable:!0});import{EventEmitter as H}from"node:events";const v=new H;v.setMaxListeners(0);async function pe(n,e){const o=d(i=>e(i),"listener");return v.on(n,o),()=>v.off(n,o)}d(pe,"subscribeDocumentEvents");import{evalCondition as $}from"../predicate.js";import{finalizeNodeMail as B,insertMessage as J}from"../feed/messages.js";import{linkAuthorizes as K,ownerChain as U,readCheck as G}from"./access.js";import{getById as q}from"./objects.js";import{appScopesNow as z,publishLookups as P,readerForObject as V}from"./reader.js";import{configFromJson as k}from"./watches.js";import{CrtrError as L}from"../errors.js";import{ExitCode as A}from"../../types.js";import{eventSpec as X,kindOf as C}from"./kinds/registry.js";import{machineNameOf as M}from"../peer/names.js";import{settleObjectWaits as Y}from"../canvas/waits.js";import{RECEIVERS as F}from"./receivers.js";import{DEFAULT_LISTEN as D}from"./types.js";import{afterCommit as Q}from"../canvas/db.js";function Z(n,e){if(n.level===void 0||n.level===e.level||e.levels?.includes(n.level))return n.level??e.level;const o=[e.level,...e.levels??[]].filter((i,t,r)=>r.indexOf(i)===t).sort((i,t)=>i-t);throw new L("invalid_level",`${n.object.type} ${n.event} publishes at level ${o.join(", ")}, not ${n.level}`,A.USAGE,{kind:n.object.type,event:n.event,level:n.level,allowed:o})}d(Z,"resolveLevel");function ee(n,e){const o=n.split("."),i=e.split(".");for(let t=0;t<o.length;t++){if(o[t]===">")return t===o.length-1&&i.length>t;if(t>=i.length||o[t]!=="*"&&o[t]!==i[t])return!1}return o.length===i.length}d(ee,"matchSubject");const W={"next-turn":1,"after-turn":2,steer:3,interrupt:4};function te(n,e){let o=null;for(const i of n){let t=null;for(const r of i)r.threshold<=e&&(!t||r.threshold>t.threshold)&&(t=r);t&&(!o||W[t.delivery]>W[o])&&(o=t.delivery)}return o}d(te,"resolveDelivery");async function ve(n,e,o){if(e.config)return e.config;const i=await n.prepare("SELECT listen_json FROM objects WHERE id = ?").get(o.id);return i?.listen_json?k(i.listen_json):D}d(ve,"listenConfigFor");function ne(n,e){return e.inboxKind??(n.level>=7?"urgent":"update")}d(ne,"inboxKind");async function oe(n,e){return e.type==="node"?e.id:await n.prepare(`SELECT 1 FROM objects WHERE type IN ('person','app','repo','profile')
|
|
2
|
+
AND name = ? AND id != ? LIMIT 1`).get(e.name,e.id)?`${e.type}:${e.name}`:e.name}d(oe,"ownerHandleOf");async function ie(n,e,o){const i=e.object.owner===null?null:await n.prepare("SELECT * FROM objects WHERE id = ?").get(e.object.owner),t=i?.id??null,r=i?await oe(n,i):null;return{event:e.event,level:e.level,object:{id:e.object.id,type:e.object.type,kind:e.object.kind,owner:t,owner_handle:r,name:e.object.name,...e.object.home_machine?{machine:M(e.object.home_machine),machine_id:e.object.home_machine}:{}},actor:e.actor?.id??null,...e.actor?.home_machine?{actor_machine:M(e.actor.home_machine),actor_machine_id:e.actor.home_machine}:{},attrs:o,...e.pointer===void 0?{}:{pointer:e.pointer}}}d(ie,"pushFields");async function se(n,e,o,i){const t=await ie(n,e,i),r=e.messageBody!==void 0&&o.carriesBody===!0,f=r?typeof e.messageBody=="object"&&e.messageBody!==null&&!Array.isArray(e.messageBody)?{...e.messageBody,push:t}:{body:e.messageBody,push:t}:{push:t},c=r?e.messageBody:null,l=c?.bodyRef===void 0?null:c;return{kind:ne(e,o),label:l?.label??(typeof c?.label=="string"?c.label:e.object.type.includes(".")&&typeof e.messageBody?.summary=="string"?e.messageBody.summary.split(`
|
|
3
|
+
`)[0]:`${e.event} ${e.object.type} ${e.object.name}`),...l?.bodyRef===void 0?{}:{bodyRef:l.bodyRef},...l?.disposition===void 0?{}:{disposition:l.disposition},senderNodeId:e.actor?.type==="node"?e.actor.id:null,senderName:e.actor===null||e.actor===void 0?null:e.actor.home_machine?`${e.actor.name} on ${M(e.actor.home_machine)}`:e.actor.name,bodyJson:f}}d(se,"messageInput");async function re(n,e,o,i,t){if(!o.supersedes)return[{attrs:e.attrs,destinations:[...i]}];const r=n.prepare(`SELECT d.delivery_id, d.message_id, d.state, m.body_json FROM deliveries d
|
|
4
4
|
JOIN messages m ON m.message_id = d.message_id
|
|
5
5
|
WHERE d.destination_id = ? AND d.state IN ('pending', 'handed_off')
|
|
6
6
|
AND d.canceled_at IS NULL AND m.event = ? AND m.object_id = ?
|
|
7
|
-
ORDER BY m.seq`),f=n.prepare("DELETE FROM deliveries WHERE delivery_id = ?"),c=n.prepare("SELECT * FROM objects WHERE id = ?"),l=new Map,
|
|
8
|
-
UNION ALL SELECT depth FROM message_causes WHERE message_id = ? LIMIT 1`).get(
|
|
9
|
-
COALESCE(s.config_json, o.listen_json) AS config_json, w.link_app`,
|
|
10
|
-
JOIN objects o ON o.id = w.watcher WHERE w.object = ? AND w.watcher != ? AND o.reception >= 1`:`SELECT ${
|
|
11
|
-
WHERE o.reception = 2 AND w.object = ? AND w.watcher != ?`).all(t.object.id,t.actor?.id??"");if(
|
|
7
|
+
ORDER BY m.seq`),f=n.prepare("DELETE FROM deliveries WHERE delivery_id = ?"),c=n.prepare("SELECT * FROM objects WHERE id = ?"),l=new Map,E=new Set;for(const m of i){const g=t(m),O=await c.get(g),I=O===void 0?void 0:await C(n,O.type),_=await r.all(g,e.event,e.object.id),j=new Set;for(const a of _)a.state==="handed_off"?await I?.supersedeClaimed?.(n,a.delivery_id)&&j.add(a.delivery_id):(await f.run(a.delivery_id),E.add(a.message_id));const h=_.filter(a=>a.state==="pending"||j.has(a.delivery_id)).at(-1),b=h?.message_id??null,s=l.get(b)??{prior:h?.body_json?JSON.parse(h.body_json).push?.attrs??null:null,destinations:[]};s.destinations.push(m),l.set(b,s)}const N=n.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)");for(const m of E)await N.run(m,m);return[...l.values()].map(m=>({attrs:o.merge?o.merge(m.prior,e):e.attrs,destinations:m.destinations}))}d(re,"supersede");async function ae(n,e,o,i,t){const r=await q(n,i);if(r===null||r.type!=="app")return!1;const f=await n.prepare("SELECT 1 FROM peer_stubs WHERE object = ?").get(e.id)!==void 0,c=f?null:await z(n,r,t);return(f||c!==null)&&await K(n,r,c,e,o)}d(ae,"linkDelivers");const T=8;class ce extends L{static{d(this,"HopLimitError")}constructor(e){super("hop_limit",`event depth ${e} exceeds ${T}`,A.GENERAL,{depth:e,limit:T})}}async function Ie(n,e,o=async()=>[]){const i=await X(n,e.object.type,e.event),t={...e,level:Z(e,i)};t.object.type==="document"&&(t.event==="edited"||t.event==="deleted")&&Q(()=>v.emit(t.object.id,t.event));const r=e.cause??null,f=r===null?null:await n.prepare(`SELECT depth FROM messages WHERE message_id = ?
|
|
8
|
+
UNION ALL SELECT depth FROM message_causes WHERE message_id = ? LIMIT 1`).get(r,r);if(r!==null&&f===void 0)throw new L("unknown_cause",`no message ${r}`,A.USAGE,{cause:r});const c=f===null?0:f.depth+1;if(c>T)throw new ce(c);(i.endsWait===!0||t.event==="deleted")&&await Y(n,t.object.id);const l=await U(n,t.object),E=`w.watcher, o.id AS watcher_id, o.type AS watcher_type, o.reception, s.pattern, s.filter_json,
|
|
9
|
+
COALESCE(s.config_json, o.listen_json) AS config_json, w.link_app`,N=await n.prepareUncached(i.durable?`SELECT ${E} FROM watches w JOIN watch_subscriptions s ON s.watch = w.watch_id
|
|
10
|
+
JOIN objects o ON o.id = w.watcher WHERE w.object = ? AND w.watcher != ? AND o.reception >= 1`:`SELECT ${E} FROM objects o JOIN watches w ON w.watcher = o.id JOIN watch_subscriptions s ON s.watch = w.watch_id
|
|
11
|
+
WHERE o.reception = 2 AND w.object = ? AND w.watcher != ?`).all(t.object.id,t.actor?.id??"");if(N.length===0)return{delivered:0,message_id:null,depth:c};const m={event:t.event,level:t.level,id:t.object.id,type:t.object.type,kind:t.object.kind,actor:t.actor?.id??null,...t.attrs},g=new Map;for(const s of N){if(t.onlyWatchers!==void 0&&!t.onlyWatchers.includes(s.watcher_id)||!ee(s.pattern,t.event)||s.filter_json!==null&&!$(JSON.parse(s.filter_json),m))continue;const a=g.get(s.watcher)??{id:s.watcher_id,type:s.watcher_type,reception:s.reception,configs:[],configured:!1,linkApp:s.link_app};a.configs.push(s.config_json?k(s.config_json):D),a.configured||=s.config_json!==null,g.set(s.watcher,a)}const O=(l.length?l[l.length-1]:t.object).type==="repo",I=d(async()=>[],"noRepos"),_=await G(n,t.object),j=P(n),h=[];for(const s of g.values()){const a=await n.prepare("SELECT * FROM objects WHERE id = ?").get(s.id),u=await C(n,a.type),R=u.receiverFor?await u.receiverFor(n,a):u.receiver;if(R===void 0)continue;const w=R==="peer"&&!s.configured?"next-turn":te(s.configs,t.level);if(w===null)continue;const y=await V(n,a,O?o:I,j);if(y.scopes===null&&(y.class==="node"||y.owner.type!=="person"))continue;const p=s.linkApp!==null&&!await _(y)&&await ae(n,t.object,a,s.linkApp,j);!p&&!await _(y)||h.push({id:s.id,reception:s.reception,delivery:w,receiver:R,...p?{linked:p}:{}})}if(h.length===0)return{delivered:0,message_id:null,depth:c};let b=null;for(const s of await re(n,t,i,h,a=>a.id)){const a=new Map;for(const p of s.destinations)a.set(p.receiver,[...a.get(p.receiver)??[],p]);const u=await se(n,t,i,s.attrs),R=[...a].map(([p,S])=>F[p].bodyOwner(S)).find(p=>p!==null)??null,w=B({...u,urgency:"normal"},R),y=await J(n,{operationId:w.operationId,createdAt:w.createdAt,senderNodeId:u.senderNodeId,senderName:u.senderName,kind:u.kind,label:u.label,bodyRef:w.bodyRef,bodyJson:w.bodyJson,disposition:u.disposition??null,event:{event:t.event,objectId:t.object.id,level:t.level,actorId:t.actor?.id??null},causeMessageId:r,depth:c});b??=y;for(const[p,S]of a)await F[p].enqueue(n,{messageId:y,event:t.event,level:t.level,senderNodeId:u.senderNodeId,elevatesTier:i.elevatesTier===!0,...t.idempotencyKey===void 0?{}:{idempotencyKey:t.idempotencyKey}},S)}return{delivered:h.length,message_id:b,depth:c}}d(Ie,"publish");export{T as HOP_LIMIT,ce as HopLimitError,ve as listenConfigFor,ee as matchSubject,Ie as publish,te as resolveDelivery,Z as resolveLevel,pe as subscribeDocumentEvents,re as supersede};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var l=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import{ApiError as p}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as $e}from"../../../api/dto/objects.js";import{openDb as E,withCanvasWrite as j}from"../../../core/canvas/db.js";import{actorOf as
|
|
2
|
-
content unavailable: ${r.unavailable}`,data:{...w,content:"markdown"in r?"live":"unavailable"}}})}l(et,"read");function Y(e,t,a,n){if(e!=null){if(!a.includes(e)){n.push({field:t,problem:`must be one of ${a.join(", ")}`,received:e});return}return e}}l(Y,"oneOf");async function ge(e,t,a){if(t!=null){if(typeof t!="string"||!await Ce(e,t)){a.push({field:"type",problem:`must be a kind: one of ${(await De(e)).join(", ")}`,received:t});return}return t}}l(ge,"kindName");function je(e,t,a,n){if(e==null)return n;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(a.push({field:t,problem:"must be an integer from 1 to 100",received:e}),n):i}l(je,"limitOf");async function _e(e){const t=e.query,a=[],n=await ge(await E(),t.get("type"),a),i=Y(t.get("privacy"),"privacy",$e,a),o=je(t.get("limit"),"limit",a,50),r=t.get("cursor");r!==null&&!/^\d+$/.test(r)&&a.push({field:"cursor",problem:"is not a cursor from a previous page",received:r});const s=t.get("deleted");return s!==null&&!["0","1","true","false"].includes(s)&&a.push({field:"deleted",problem:"must be true or false",received:s}),a.length>0&&C("object list request",a),await j(async c=>{const u=await v(c,e),w={...n?{type:n}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{}},h=t.get("owner");if(h!==null){const m=await he(c,u,h);if(m===null)return{items:[],next_cursor:null};w.owner=m}const y=t.get("name"),g=[];let k=r===null?0:Number(r),f=!0;for(;g.length<o&&f;){const m=await Me(c,u,w,{limit:100,after_seq:k});f=m.length===100;for(const q of m)if(k=q.seq,(y===null||q.name.startsWith(y))&&g.push(q),g.length===o)break}const d=g.at(-1);return{items:await we(g,async m=>await me(c,m)),next_cursor:g.length===o&&d?String(d.seq):null}})}l(_e,"listLocal");const tt={ms:3e4},nt="self",X=l((e,t)=>e.map(a=>({...a,machine:t})),"labelItems");async function ke(e,t,a,n){const i=W.current;try{const o=await i.call(t.id,{method:"GET",path:"/v1/objects",query:a},await i.envelope(e.principal),n);if(Ye(o))return{state:"unreachable",items:[],next:null};if(o.status===426)return{state:"too_old",items:[],next:null};const r=o.body;return o.status!==200||!Array.isArray(r?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:X(r.items,t),next:r.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(ke,"remotePage");async function at(e){const t=new Promise(a=>e.addEventListener("abort",()=>a(null),{once:!0}));return Promise.race([W.current.machines().catch(()=>null),t])}l(at,"machinesWithin");async function it(e){const t=e.query.get("machine");if(!fe(e.principal)||!W.current.joined()||t===nt)return await _e(ve(e));const n=W.current.self(),i=t!==null&&A(t)!==n,o=i?null:await _e(ve(e)),r=new AbortController,s=setTimeout(()=>r.abort(),tt.ms);s.unref?.();try{const c=await at(r.signal);if(c===null){if(i)throw new p(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return o}const u=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),w=u(n),h=c.filter(d=>d.machine_id!==n&&d.kind!=="device"),y=D(e);if(t!==null){if(!i)return{items:X(o.items,w),next_cursor:o.next_cursor,machines:[{machine_id:n,name:w.name,state:"ok",more:o.next_cursor!==null}]};const d=A(t);if(!h.some(q=>q.machine_id===d))throw new p(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await ke(e,u(d),y,r.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:u(d).name,state:m.state,more:m.next!==null}]}}const{cursor:g,...k}=y,f=await Promise.all(h.map(d=>ke(e,u(d.machine_id),k,r.signal)));return{items:[...X(o.items,w),...f.flatMap(d=>d.items)],next_cursor:o.next_cursor,machines:[{machine_id:n,name:w.name,state:"ok",more:o.next_cursor!==null},...h.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:f[m].state,more:f[m].next!==null}))]}}finally{clearTimeout(s)}}l(it,"list");function ve(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(ve,"withoutMachine");async function rt(e){const t=[],a=N(e.body)?e.body:{};N(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const n=a.text;(typeof n!="string"||n.trim()==="")&&t.push({field:"text",problem:"is required",received:n});const i=a.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(f){t.push({field:"grep",problem:`is not a valid regular expression: ${f.message}`,received:i})}a.body!==void 0&&typeof a.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:a.body});const o=await ge(await E(),a.type,t);a.kind!==void 0&&typeof a.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:a.kind}),a.owner!==void 0&&typeof a.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:a.owner});const r=je(a.limit,"limit",t,50);t.length>0&&C("object search request",t);const s=await j(async f=>{const d=await v(f,e),m=typeof a.owner=="string"?await he(f,d,a.owner):null;return{reader:d,owner:m}}),{reader:c,owner:u}=s;if(typeof a.owner=="string"&&u===null)return{items:[]};const w=await E(),h=await se(w,c,{text:n,body:a.body===!0||typeof i=="string"}),y=new Set(h.map(f=>f.object.id)),k=(typeof i=="string"?(await se(w,c,{text:i,grep:!0})).filter(f=>y.has(f.object.id)):h).filter(f=>(!o||f.object.type===o)&&(a.kind===void 0||f.object.kind===a.kind)&&(!u||f.object.owner===u.id));return{items:await we(k.slice(0,r),async f=>({object:await me(w,f.object),...f.line!==void 0?{matches:[{line:f.line,text:f.text??""}]}:{}}))}}l(rt,"search");const Oe=["interrupt","steer","after-turn","next-turn"],ot=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function st(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"||!ot.test(a)||a.includes(">")&&!a.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(st,"patternsOf");function ut(e,t){if(e===void 0)return;if(!N(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const a=[];for(const[n,i]of Object.entries(e)){const o=Number(n);!Number.isInteger(o)||o<1||o>10?t.push({field:`config.${n}`,problem:"level must be an integer from 1 to 10"}):Oe.includes(i)?a.push({threshold:o,delivery:i}):t.push({field:`config.${n}`,problem:`delivery must be one of ${Oe.join(", ")}`,received:i})}return a.sort((n,i)=>i.threshold-n.threshold)}l(ut,"configOf");async function qe(e){const t=await ye(e);if(t!==null)throw new p(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(qe,"refuseStubWatch");async function x(e,t){const a=await T(e,t)??await(async()=>{const n=await Fe(e,await Ae(e,{class:"person"},async()=>[]),t);return"object"in n?n.object:null})();return a===null||a.deleted_at!==null||!(a.type.includes(".")||a.type==="node")?null:a}l(x,"findWatcher");const O=l(()=>{throw new p(404,"not_found","watcher not found")},"watcherNotFound");async function Ee(e,t,a){if(typeof t!="string"||a===void 0||a===null)return null;if(typeof a!="string")throw new p(400,"invalid_request","invalid watcher_machine");if(await x(e,t)!==null)return null;const n=W.current;let i;try{i=await n.machines()}catch{throw new p(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const o=A(a);return(o===n.self()||!i.some(r=>A(r.machine_id)===o))&&O(),o}l(Ee,"remoteWatcherMachine");async function Te(e,t,a,n){if(t.publishToken||t.principal.class==="anonymous")return O();const i=await v(e,t);if(i.class==="person")return O();let o;try{o=await R(e,i,n)}catch{return O()}const r=o.owner===null?null:await T(e,o.owner);return r===null||!await ie(e,i,r)||!await Le(e,i,"link",a)?O():(await z(e,t,a),{actor:i.app,object:o})}l(Te,"linkWatcher");async function Re(e,t,a){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!a.type.includes("."))return!1;const n=await v(e,t),i=a.owner===null?null:await T(e,a.owner);return i!==null&&await ie(e,n,i)&&await We(e,n,a)}l(Re,"ownsWatcher");async function ct(e){const t=_(e),a=N(e.body)?e.body:{};if(typeof a.watcher=="string"&&await qe(t),typeof a.watcher!="string"){const i=await Q(e,t,{method:"POST",path:`${G(t)}/watch`,body:e.body});if(i.kind==="unknown")throw de(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw M(i.status,i.body);const o=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",o),Z(i.body,i.machine)}}const n=await Ee(await E(),a.watcher,a.watcher_machine);return await lt(e,n)}l(ct,"watch");async function lt(e,t=null){const a=[],n=e.body===void 0?{}:N(e.body)?e.body:(a.push({field:"body",problem:"must be an object"}),{}),i=st(n.patterns,a),o=ut(n.config,a);return n.filter!==void 0&&!N(n.filter)&&a.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&a.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),n.watcher_machine!==void 0&&typeof n.watcher_machine!="string"&&a.push({field:"watcher_machine",problem:"must be a machine id",received:n.watcher_machine}),a.length>0&&C("watch request",a),await j(async r=>{const s=typeof n.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new p(404,"not_found","watcher not found");const c=i??[">"],u={patterns:c,...o?{config:o}:{},...n.filter!==void 0?{filter:n.filter}:{}};if(s){const g=n.watcher,k=t===null?null:await ft(r,e,g,t),f=k??(e.publishToken?await re(r,g):await x(r,g));if(f===null)return O();if(k===null&&await Re(r,e,f)){const q=await oe(r,e,f);await z(r,e,f);const ee=await U(r,f),I=await R(r,ee,_(e));if(!await ae(r,ee,I))throw new p(404,"not_found","object not found");return await L(r,f,I,"act",u),await P(r,f,I),await H(r,{event:"watched",object:I,actor:q,attrs:{}},await F(r)),{object:await $(r,I,await b(r,I)),patterns:c}}const{actor:d,object:m}=await Te(r,e,f,_(e));return await L(r,f,m,"act",{...u,linkApp:d}),await P(r,f,m),await H(r,{event:"watched",object:m,actor:d,attrs:{}},await F(r)),{object:await $(r,m,await b(r,m)),patterns:c}}const w=await v(r,e),h=await K(r,e)??te(w),y=await R(r,w,_(e));return await L(r,h,y,"ask",u),await P(r,h,y),await H(r,{event:"watched",object:y,actor:h,attrs:{}},await F(r)),{object:await $(r,y,await b(r,y)),patterns:c}})}l(lt,"watchLocal");async function ft(e,t,a,n){return t.publishToken||t.principal.class==="anonymous"?O():await Je(e,a,n)}l(ft,"ensureNodeStubFor");async function Ie(e,t,a,n){const i=l(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
-
WHERE w.watcher = ? AND w.object = ?`).get(t.id,
|
|
1
|
+
var Ne=Object.defineProperty;var l=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import{ApiError as p}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as $e}from"../../../api/dto/objects.js";import{openDb as E,withCanvasWrite as j}from"../../../core/canvas/db.js";import{actorOf as ne}from"../../../core/graph/documents.js";import{readerForObject as L,readerFor as Ae}from"../../../core/graph/reader.js";import{resolveName as Fe,stubsNamed as Se,unwrapRef as ae}from"../../../core/graph/names.js";import{canRead as P,customReachable as We,holdsObjectsScope as Le,mayActAs as ie,spaceOf as Pe}from"../../../core/graph/access.js";import{customObjectRef as re,authorizeCustom as oe,fenceArgv as H}from"./custom-objects.js";import{edgesOf as Ce}from"../../../core/graph/edges.js";import{publish as V}from"../../../core/graph/events.js";import{objectDTO as b}from"../../../core/graph/kinds/dto.js";import{isKind as De,kindNames as Me,kindOf as B}from"../../../core/graph/kinds/registry.js";import{listObjects as Ge,searchObjects as se}from"../../../core/graph/objects.js";import{checkoutsForCwd as Ue}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as C,unwatch as ze,watchersOf as He,watchesOf as Ve}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as D,settleObjectWaitForUnwatch as Be}from"../../../core/graph/object-waits.js";import{readerFor as O,resolveRef as K}from"../reader.js";import{readDelegationFor as ue,runReadLeaf as Ke}from"../../plugin-objects/read-leaf.js";import{invalidRequest as M,isRecord as N}from"./validate.js";import{callerNode as ce,callerStub as Z,forwardNamed as Ze,forwardVerb as le,originates as fe,queryWithoutMachine as G,relayError as U,remoteStub as Je,unknownError as de,forwarding as W,withMachine as J}from"../../peer/forward.js";import{getById as T}from"../../../core/graph/objects.js";import{ensureNodeStub as Qe,isStub as Q,stubOf as Ye,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as Xe}from"../../../core/peer/client.js";import{normalizeMachineId as A}from"../../../core/peer/directory.js";import{mapAsync as we}from"../../../core/async-array.js";const F=l(async e=>async t=>await Ue(e,t),"reposFnFor");async function me(e,t){return{...await b(e,t),...await(await B(e,t.type)).listItem?.(e,t)}}l(me,"listItem");function xe(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}l(xe,"remoteMessage");async function he(e,t,n){try{return await R(e,t,n)}catch(a){if(a instanceof p&&a.code==="not_found"&&!a.details?.deleted)return null;throw a}}l(he,"ownerFilter");async function R(e,t,n){const a=await K(e,t,n);if("remote"in a)throw new p(404,"not_found",xe(a.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in a)throw new p(404,"not_found",`${a.deleted.name} is deleted`,{id:a.deleted.id,deleted:!0});return a}l(R,"liveRef");const _=l(e=>decodeURIComponent(e.params.ref),"refParam"),pe=l(e=>{const t=ae(e),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");async function ye(e){const t=await T(await E(),pe(e));return t!==null&&await Q(await E(),t)?t.id:null}l(ye,"stubIdOf");async function et(e,t){const n=await ye(e);return n!==null?{stub:n,hit:!0}:await j(async a=>{try{const i=await O(a,t),o=l(async()=>{const s=await Se(a,i,e);if(s.length>1)throw new p(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:s.map(c=>c.id),next:"Read one by its object id."});return{stub:s[0]?.id??null,hit:!1}},"named");let r;try{r=await K(a,i,e)}catch(s){if(s instanceof p&&s.code==="not_found")return await o();throw s}if("remote"in r)return await o();if("deleted"in r){const s=await o();return s.stub===null?{stub:null,hit:!0}:s}return{stub:await Q(a,r)?r.id:null,hit:!0}}catch(i){if(i instanceof p&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}})}l(et,"resolvedLocally");async function Y(e,t,n){const a=await et(t,e);if(a.stub!==null)return le(e,a.stub,n);if(a.hit||!fe(e.principal))return{kind:"local"};const i=await le(e,pe(t),n);return i.kind==="local"&&ae(t).includes("/")?Ze(e,n,{method:"GET",path:z(t),query:G(e)}):i}l(Y,"forwardRef");const z=l(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,n,a,i){const o=t?.object;!o?.id||!o.type||await j(async r=>{const s=await ce(r,e);if(s===null)return;const c=await Je(r,o.id,o.type,n,{kind:o.kind??null,name:o.name??o.id,...o.preview===void 0?{}:{preview:o.preview},owner:o.owner??null,...o.kind_decl===void 0?{}:{kind_decl:o.kind_decl},...o.privacy===void 0?{}:{privacy:o.privacy}});await C(r,s,c,a,i===void 0?{}:{patterns:i}),a==="ask"&&await D(r,s,c)})}l(be,"watchRemote");async function tt(e){const t=_(e),n=["1","true"].includes(e.query.get("fields")??""),a=await Y(e,t,{method:"GET",path:z(t),query:G(e)});if(a.kind==="unknown")return{state:"unknown",ref:t,unreachable:a.unreachable};if(a.kind==="remote"){if(a.status>=400)throw U(a.status,a.body);return await be(e,a.body,a.machine.id,"read"),J(a.body,a.machine)}const i=l(async s=>{const c=await Z(s,e);return c===null?await O(s,e):await L(s,c,await F(s))},"readerOf"),o=await j(async s=>{const c=await i(s),u=await K(s,c,t);if("remote"in u)return{state:"remote",remote:u.remote};if("deleted"in u)return{state:"deleted",deleted:await b(s,u.deleted)};const w=await ue(s,u);if(w!==null)return{delegate:w,hitId:u.id};const{data:h,text:y}=await(await B(s,u.type)).read(s,c,u,{fields:n,reposFn:await F(s)});return{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:y,data:h}});if(!("delegate"in o))return o;const r=await Ke(o.delegate,e.principal);return await j(async s=>{const c=await i(s),u=await T(s,o.hitId);if(u===null)throw new p(404,"not_found","object not found");if(u.deleted_at!==null)return{state:"deleted",deleted:await b(s,u)};if(!await P(s,c,u))throw new p(404,"not_found","object not found");const{data:w,text:h}=await(await B(s,u.type)).read(s,c,u,{fields:n,reposFn:await F(s)});return await ue(s,u)===null?{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:h,data:w}:{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:"markdown"in r?r.markdown:`${h}
|
|
2
|
+
content unavailable: ${r.unavailable}`,data:{...w,content:"markdown"in r?"live":"unavailable"}}})}l(tt,"read");function X(e,t,n,a){if(e!=null){if(!n.includes(e)){a.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}l(X,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await De(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await Me(e)).join(", ")}`,received:t});return}return t}}l(ge,"kindName");function je(e,t,n,a){if(e==null)return a;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),a):i}l(je,"limitOf");async function _e(e){const t=e.query,n=[],a=await ge(await E(),t.get("type"),n),i=X(t.get("privacy"),"privacy",$e,n),o=je(t.get("limit"),"limit",n,50),r=t.get("cursor");r!==null&&!/^\d+$/.test(r)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:r});const s=t.get("deleted");return s!==null&&!["0","1","true","false"].includes(s)&&n.push({field:"deleted",problem:"must be true or false",received:s}),n.length>0&&M("object list request",n),await j(async c=>{const u=await O(c,e),w={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{}},h=t.get("owner");if(h!==null){const m=await he(c,u,h);if(m===null)return{items:[],next_cursor:null};w.owner=m}const y=t.get("name"),g=[];let v=r===null?0:Number(r),f=!0;for(;g.length<o&&f;){const m=await Ge(c,u,w,{limit:100,after_seq:v});f=m.length===100;for(const q of m)if(v=q.seq,(y===null||q.name.startsWith(y))&&g.push(q),g.length===o)break}const d=g.at(-1);return{items:await we(g,async m=>await me(c,m)),next_cursor:g.length===o&&d?String(d.seq):null}})}l(_e,"listLocal");const nt={ms:3e4},at="self",x=l((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function ke(e,t,n,a){const i=W.current;try{const o=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(Xe(o))return{state:"unreachable",items:[],next:null};if(o.status===426)return{state:"too_old",items:[],next:null};const r=o.body;return o.status!==200||!Array.isArray(r?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:x(r.items,t),next:r.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(ke,"remotePage");async function it(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([W.current.machines().catch(()=>null),t])}l(it,"machinesWithin");async function rt(e){const t=e.query.get("machine");if(!fe(e.principal)||!W.current.joined()||t===at)return await _e(ve(e));const a=W.current.self(),i=t!==null&&A(t)!==a,o=i?null:await _e(ve(e)),r=new AbortController,s=setTimeout(()=>r.abort(),nt.ms);s.unref?.();try{const c=await it(r.signal);if(c===null){if(i)throw new p(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return o}const u=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),w=u(a),h=c.filter(d=>d.machine_id!==a&&d.kind!=="device"),y=G(e);if(t!==null){if(!i)return{items:x(o.items,w),next_cursor:o.next_cursor,machines:[{machine_id:a,name:w.name,state:"ok",more:o.next_cursor!==null}]};const d=A(t);if(!h.some(q=>q.machine_id===d))throw new p(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await ke(e,u(d),y,r.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:u(d).name,state:m.state,more:m.next!==null}]}}const{cursor:g,...v}=y,f=await Promise.all(h.map(d=>ke(e,u(d.machine_id),v,r.signal)));return{items:[...x(o.items,w),...f.flatMap(d=>d.items)],next_cursor:o.next_cursor,machines:[{machine_id:a,name:w.name,state:"ok",more:o.next_cursor!==null},...h.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:f[m].state,more:f[m].next!==null}))]}}finally{clearTimeout(s)}}l(rt,"list");function ve(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(ve,"withoutMachine");async function ot(e){const t=[],n=N(e.body)?e.body:{};N(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const a=n.text;(typeof a!="string"||a.trim()==="")&&t.push({field:"text",problem:"is required",received:a});const i=n.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(f){t.push({field:"grep",problem:`is not a valid regular expression: ${f.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const o=await ge(await E(),n.type,t);n.kind!==void 0&&typeof n.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:n.kind}),n.owner!==void 0&&typeof n.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:n.owner});const r=je(n.limit,"limit",t,50);t.length>0&&M("object search request",t);const s=await j(async f=>{const d=await O(f,e),m=typeof n.owner=="string"?await he(f,d,n.owner):null;return{reader:d,owner:m}}),{reader:c,owner:u}=s;if(typeof n.owner=="string"&&u===null)return{items:[]};const w=await E(),h=await se(w,c,{text:a,body:n.body===!0||typeof i=="string"}),y=new Set(h.map(f=>f.object.id)),v=(typeof i=="string"?(await se(w,c,{text:i,grep:!0})).filter(f=>y.has(f.object.id)):h).filter(f=>(!o||f.object.type===o)&&(n.kind===void 0||f.object.kind===n.kind)&&(!u||f.object.owner===u.id));return{items:await we(v.slice(0,r),async f=>({object:await me(w,f.object),...f.line!==void 0?{matches:[{line:f.line,text:f.text??""}]}:{}}))}}l(ot,"search");const Oe=["interrupt","steer","after-turn","next-turn"],st=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function ut(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!st.test(n)||n.includes(">")&&!n.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(ut,"patternsOf");function ct(e,t){if(e===void 0)return;if(!N(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const n=[];for(const[a,i]of Object.entries(e)){const o=Number(a);!Number.isInteger(o)||o<1||o>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Oe.includes(i)?n.push({threshold:o,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Oe.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}l(ct,"configOf");async function qe(e){const t=await ye(e);if(t!==null)throw new p(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(qe,"refuseStubWatch");async function ee(e,t){const n=await T(e,t)??await(async()=>{const a=await Fe(e,await Ae(e,{class:"person"},async()=>[]),t);return"object"in a?a.object:null})();return n===null||n.deleted_at!==null||!(n.type.includes(".")||n.type==="node")?null:n}l(ee,"findWatcher");const k=l(()=>{throw new p(404,"not_found","watcher not found")},"watcherNotFound");async function Ee(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new p(400,"invalid_request","invalid watcher_machine");if(await ee(e,t)!==null)return null;const a=W.current;let i;try{i=await a.machines()}catch{throw new p(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const o=A(n);return(o===a.self()||!i.some(r=>A(r.machine_id)===o))&&k(),o}l(Ee,"remoteWatcherMachine");async function Te(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return k();const i=await O(e,t);if(i.class==="person")return k();let o;try{o=await R(e,i,a)}catch{return k()}const r=o.owner===null?null:await T(e,o.owner);return r===null||!await ie(e,i,r)||!await Le(e,i,"link",n)||(await Pe(e,n)).id===i.app.id&&!(await P(e,i,n)&&await P(e,await L(e,n),o))?k():(await H(e,t,n),{actor:i.app,object:o})}l(Te,"linkWatcher");async function Re(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await O(e,t),i=n.owner===null?null:await T(e,n.owner);return i!==null&&await ie(e,a,i)&&await We(e,a,n)}l(Re,"ownsWatcher");async function lt(e){const t=_(e),n=N(e.body)?e.body:{};if(typeof n.watcher=="string"&&await qe(t),typeof n.watcher!="string"){const i=await Y(e,t,{method:"POST",path:`${z(t)}/watch`,body:e.body});if(i.kind==="unknown")throw de(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw U(i.status,i.body);const o=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",o),J(i.body,i.machine)}}const a=await Ee(await E(),n.watcher,n.watcher_machine);return await ft(e,a)}l(lt,"watch");async function ft(e,t=null){const n=[],a=e.body===void 0?{}:N(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=ut(a.patterns,n),o=ct(a.config,n);return a.filter!==void 0&&!N(a.filter)&&n.push({field:"filter",problem:"must be an object",received:a.filter}),a.watcher!==void 0&&typeof a.watcher!="string"&&n.push({field:"watcher",problem:"must be a custom-object ref",received:a.watcher}),a.watcher_machine!==void 0&&typeof a.watcher_machine!="string"&&n.push({field:"watcher_machine",problem:"must be a machine id",received:a.watcher_machine}),n.length>0&&M("watch request",n),await j(async r=>{const s=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new p(404,"not_found","watcher not found");const c=i??[">"],u={patterns:c,...o?{config:o}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(s){const g=a.watcher,v=t===null?null:await dt(r,e,g,t),f=v??(e.publishToken?await re(r,g):await ee(r,g));if(f===null)return k();if(v===null&&await Re(r,e,f)){const q=await oe(r,e,f);await H(r,e,f);const te=await L(r,f),I=await R(r,te,_(e));if(!await P(r,te,I))throw new p(404,"not_found","object not found");return await C(r,f,I,"act",u),await D(r,f,I),await V(r,{event:"watched",object:I,actor:q,attrs:{}},await F(r)),{object:await $(r,I,await b(r,I)),patterns:c}}const{actor:d,object:m}=await Te(r,e,f,_(e));return await C(r,f,m,"act",{...u,linkApp:d}),await D(r,f,m),await V(r,{event:"watched",object:m,actor:d,attrs:{}},await F(r)),{object:await $(r,m,await b(r,m)),patterns:c}}const w=await O(r,e),h=await Z(r,e)??ne(w),y=await R(r,w,_(e));return await C(r,h,y,"ask",u),await D(r,h,y),await V(r,{event:"watched",object:y,actor:h,attrs:{}},await F(r)),{object:await $(r,y,await b(r,y)),patterns:c}})}l(ft,"watchLocal");async function dt(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?k():await Qe(e,n,a)}l(dt,"ensureNodeStubFor");async function Ie(e,t,n,a){const i=l(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
+
WHERE w.watcher = ? AND w.object = ?`).get(t.id,n.id)).n,"count"),o=await i();await ze(e,t,n,a??void 0);const r=await i();return r===0&&await Be(e,t,n),{object:await b(e,n),removed:o-r}}l(Ie,"dropWatch");async function wt(e){const t=_(e);if(e.query.get("watcher")&&await qe(t),!e.query.get("watcher")){const a=await Y(e,t,{method:"DELETE",path:`${z(t)}/watch`,query:G(e)});if(a.kind==="unknown")throw de(t,a.unreachable);if(a.kind==="remote"){const i=a.status===404?a.body.error?.details:void 0,o=i?.deleted===!0?i.id:void 0;if(a.status>=400&&o===void 0)throw U(a.status,a.body);const r=o??a.body.object?.id,s=await j(async c=>{const u=await ce(c,e),w=r===void 0?null:await T(c,r);return u===null||w===null||!await Q(c,w)?null:await Ie(c,u,w,e.query.get("pattern"))});if(o!==void 0){if(s===null)throw U(a.status,a.body);return{...s,machine:a.machine}}return J(a.body,a.machine)}}const n=await Ee(await E(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await mt(e,n)}l(wt,"unwatchRoute");async function mt(e,t=null){const n=e.query.get("pattern"),a=e.query.get("watcher");return await j(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!a)throw new p(404,"not_found","watcher not found");const o=l(async(c,u)=>await Ie(i,c,u,n),"drop");if(a){const c=t===null?null:await(async()=>{const w=await T(i,a);return w!==null&&await Ye(i,w)!==null?w:null})();if(t!==null&&c===null)return k();const u=c??(e.publishToken?await re(i,a):await ee(i,a));return u===null?k():c===null&&await Re(i,e,u)?(await oe(i,e,u),await H(i,e,u),await o(u,await R(i,await L(i,u),_(e)))):await o(u,(await Te(i,e,u,_(e))).object)}const r=await O(i,e),s=await Z(i,e)??ne(r);return await o(s,await R(i,r,_(e)))})}l(mt,"unwatchLocal");async function ht(e){const t=[],n=X(e.query.get("type"),"type",["acted-on","links-to","watches"],t),a=X(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&M("edges request",t),await j(async i=>{const o=await O(i,e),r=await R(i,o,_(e)),s=[];if(n!=="watches")for(const c of await Ce(i,o,r,{...n?{type:n}:{},direction:a??"both"}))s.push({type:c.type,src:await b(i,c.src),dst:await b(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...a!=="in"?await Ve(i,o,r):[],...a!=="out"?await He(i,o,r):[]];for(const u of c)s.push({type:"watches",src:await b(i,u.watcher),dst:await b(i,u.object)})}return{items:s}})}l(ht,"edges");const S=l(e=>async t=>({status:200,body:await e(t)}),"ok"),Ut=[{method:"POST",pattern:"/v1/objects/search",handler:S(ot)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:S(ht)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:S(lt)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:S(wt)},{method:"GET",pattern:"/v1/objects/:ref",handler:S(tt)},{method:"GET",pattern:"/v1/objects",handler:S(rt)}];export{nt as listBudget,Ut as objectRoutes};
|
|
@@ -7,6 +7,10 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.548
|
|
11
|
+
|
|
12
|
+
`canvas.watch` with a `watcher` that is a node of your own app now works under `crtr:objects:link:node`. It answered `404 not_found` (`watcher not found`) before. The node must be reachable from the caller under run confinement and must itself be able to read the object. A watch on a node of another machine now forwards every event level, and that node's own listening config decides how each is delivered, where an event below level 3 was dropped before it left the object's machine.
|
|
13
|
+
|
|
10
14
|
## 0.3.546
|
|
11
15
|
|
|
12
16
|
`GET /v1/nodes/:id/broker/extension-state` no longer returns `report_nodes` (every node's id, name, created and grantee). Nothing has read it since 0.3.350, and returning it cost a query over every node on each model request of every broker. No SDK method reads it.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.548",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -140,7 +140,7 @@
|
|
|
140
140
|
},
|
|
141
141
|
"license": "UNLICENSED",
|
|
142
142
|
"dependencies": {
|
|
143
|
-
"@north-light/identity": "0.3.
|
|
143
|
+
"@north-light/identity": "0.3.548",
|
|
144
144
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
145
145
|
"@earendil-works/pi-ai": "1.1.0",
|
|
146
146
|
"@earendil-works/pi-coding-agent": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.548",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.548",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
25
25
|
"@milkdown/prose": "^7.22.3",
|
|
26
26
|
"@milkdown/utils": "^7.22.3",
|
|
27
|
-
"@north-light/identity": "0.3.
|
|
27
|
+
"@north-light/identity": "0.3.548",
|
|
28
28
|
"cron-parser": "^5.6.0",
|
|
29
29
|
"esbuild": "^0.27.7",
|
|
30
30
|
"jose": "^6.2.12",
|
|
@@ -12455,17 +12455,17 @@
|
|
|
12455
12455
|
},
|
|
12456
12456
|
"packages/crouter-api": {
|
|
12457
12457
|
"name": "@north-light/api",
|
|
12458
|
-
"version": "0.3.
|
|
12458
|
+
"version": "0.3.548",
|
|
12459
12459
|
"license": "UNLICENSED"
|
|
12460
12460
|
},
|
|
12461
12461
|
"packages/crouter-env-docker": {
|
|
12462
12462
|
"name": "@north-light/env-docker",
|
|
12463
|
-
"version": "0.3.
|
|
12463
|
+
"version": "0.3.548",
|
|
12464
12464
|
"license": "UNLICENSED"
|
|
12465
12465
|
},
|
|
12466
12466
|
"packages/crouter-identity": {
|
|
12467
12467
|
"name": "@north-light/identity",
|
|
12468
|
-
"version": "0.3.
|
|
12468
|
+
"version": "0.3.548",
|
|
12469
12469
|
"license": "UNLICENSED",
|
|
12470
12470
|
"dependencies": {
|
|
12471
12471
|
"jose": "^6.2.1"
|
|
@@ -12473,21 +12473,21 @@
|
|
|
12473
12473
|
},
|
|
12474
12474
|
"packages/crouter-plugin": {
|
|
12475
12475
|
"name": "@north-light/plugin",
|
|
12476
|
-
"version": "0.3.
|
|
12476
|
+
"version": "0.3.548",
|
|
12477
12477
|
"license": "UNLICENSED",
|
|
12478
12478
|
"dependencies": {
|
|
12479
|
-
"@north-light/api": "0.3.
|
|
12480
|
-
"@north-light/identity": "0.3.
|
|
12479
|
+
"@north-light/api": "0.3.548",
|
|
12480
|
+
"@north-light/identity": "0.3.548"
|
|
12481
12481
|
}
|
|
12482
12482
|
},
|
|
12483
12483
|
"packages/crouter-sdk": {
|
|
12484
12484
|
"name": "@north-light/sdk",
|
|
12485
|
-
"version": "0.3.
|
|
12485
|
+
"version": "0.3.548",
|
|
12486
12486
|
"license": "UNLICENSED",
|
|
12487
12487
|
"dependencies": {
|
|
12488
|
-
"@north-light/api": "0.3.
|
|
12489
|
-
"@north-light/identity": "0.3.
|
|
12490
|
-
"@north-light/plugin": "0.3.
|
|
12488
|
+
"@north-light/api": "0.3.548",
|
|
12489
|
+
"@north-light/identity": "0.3.548",
|
|
12490
|
+
"@north-light/plugin": "0.3.548",
|
|
12491
12491
|
"jose": "^6.2.1"
|
|
12492
12492
|
},
|
|
12493
12493
|
"bin": {
|