@north-light/cli 0.3.712 → 0.3.713
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/input/controller.d.ts +6 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/input/local-files.d.ts +16 -0
- package/dist/clients/attach/input/local-files.js +6 -0
- package/dist/clients/attach/session/editor-frame.d.ts +2 -2
- package/dist/clients/attach/session/editor-frame.js +1 -1
- package/dist/clients/attach/viewer.js +406 -402
- package/dist/commands/node/bash.js +1 -1
- package/dist/core/bash-guard.d.ts +10 -0
- package/dist/core/bash-guard.js +4 -4
- package/dist/core/broker-client/client.d.ts +2 -2
- package/dist/core/conversation-store/row-store.js +1 -1
- package/dist/core/graph/documents.d.ts +5 -5
- package/dist/core/graph/documents.js +9 -9
- package/dist/core/graph/kinds/custom.js +2 -2
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/environment.js +2 -2
- package/dist/core/graph/kinds/job.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +9 -1
- package/dist/core/graph/kinds/live-read.d.ts +4 -2
- package/dist/core/graph/kinds/live-read.js +1 -1
- package/dist/core/graph/kinds/node.js +5 -5
- package/dist/core/graph/kinds/owner.js +2 -2
- package/dist/core/runtime/bearings-render.d.ts +3 -0
- package/dist/core/runtime/bearings-render.js +7 -7
- package/dist/core/runtime/bearings.js +5 -5
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-read.d.ts +5 -1
- package/dist/core/runtime/broker/frame-read.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +37 -2
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/map.d.ts +6 -0
- package/dist/daemon/api/map.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/ci-runner.md +4 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
- package/packages/crouter-api/dist/clients/attach/input/local-files.js +97 -0
- package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
- package/packages/crouter-api/dist/commands/node/bash.js +2 -2
- package/packages/crouter-api/dist/core/bash-guard.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
- package/packages/crouter-api/dist/core/graph/documents.js +12 -24
- package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
- package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
- package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
- package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -5
- package/packages/crouter-api/dist/daemon/api/map.js +1 -1
- package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
- /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
- /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var q=Object.defineProperty;var i=(e,t)=>q(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as E,rmSync as I,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as N,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as M,newBashJobId as L,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as C}from"../../core/preview-result-path.js";import{contextDir as v}from"../../core/canvas/paths.js";import{nodeInPane as A}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=j()),o===void 0||o==="")throw new r({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}i(b,"resolveBashTarget");async function _(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new r({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}i(_,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:i(async e=>{const t=e.command,n=j(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new r({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{
|
|
1
|
+
var q=Object.defineProperty;var i=(e,t)=>q(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as E,rmSync as I,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as N,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as M,newBashJobId as L,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as C}from"../../core/preview-result-path.js";import{contextDir as v}from"../../core/canvas/paths.js";import{nodeInPane as A}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=j()),o===void 0||o==="")throw new r({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}i(b,"resolveBashTarget");async function _(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new r({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}i(_,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:i(async e=>{const t=e.command,n=j(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new r({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{destructiveCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new r({error:"refused",message:l,next:"Run a different command."});const a=y(o,L());E(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[C]:p,...$}=process.env;try{await m(n,a,o,s,$)}catch(f){throw I(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new r({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},R.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:i(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=N(v(n.node_id,n.grantee)),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(M(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:i(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,v(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>D(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:S(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:i(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${B(n.command)}${n.purpose===null?"":`
|
|
2
2
|
purpose: ${n.purpose}`}${n.deadline_at===null?"":`
|
|
3
3
|
cancels at: ${n.deadline_at}`}
|
|
4
4
|
${n.log_path===null?`log: not on this machine (its job files are not under this machine\u2019s crtr home \u2014 a sandbox or another computer); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
/** Seconds a leading `sleep ...` will block for, or null when the command does
|
|
2
2
|
* not open with a sleep (or its duration isn't statically knowable). */
|
|
3
3
|
export declare function leadingSleepSeconds(command: string): number | null;
|
|
4
|
+
/** Walk the line segment by segment, carrying the variable values and working
|
|
5
|
+
* directory the shell itself would carry, and refuse the first destructive
|
|
6
|
+
* segment aimed at a protected path.
|
|
7
|
+
*
|
|
8
|
+
* Carrying that state IS the guard's core distinction. `export HOME=/tmp/x`
|
|
9
|
+
* as its own command changes `$HOME` for everything after it, so a later
|
|
10
|
+
* `rm -rf "$HOME"` is a scratch directory and runs. A `HOME=/tmp/x cmd`
|
|
11
|
+
* PREFIX applies to that one command only, so a later `rm -rf "$HOME"` is the
|
|
12
|
+
* real home — which is precisely the mistake that destroyed one. */
|
|
13
|
+
export declare function destructiveCommandRefusal(command: string, cwd: string, home?: string): string | null;
|
|
4
14
|
/** The refusal this command earns before it runs, or null when it may run.
|
|
5
15
|
* `cwd` is the directory the command will execute in. */
|
|
6
16
|
export declare function bashCommandRefusal(command: string, cwd: string, home?: string): string | null;
|
package/dist/core/bash-guard.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var
|
|
1
|
+
var z=Object.defineProperty;var a=(t,n)=>z(t,"name",{value:n,configurable:!0});import{homedir as A,userInfo as N}from"node:os";import{isAbsolute as T,resolve as $,sep as R}from"node:path";import{commandSegments as q,stripHeredocs as H}from"./shell-segments.js";const v=10,P={s:1,m:60,h:3600,d:86400};function V(t){const n=/^\s*sleep(\s+[^;&|\n]+)/.exec(t);if(!n)return null;let e=0;for(const r of n[1].trim().split(/\s+/)){const s=/^([0-9]*\.?[0-9]+)([smhd]?)$/.exec(r);if(!s)return null;e+=Number(s[1])*P[s[2]||"s"]}return e}a(V,"leadingSleepSeconds");function Z(t){const n=V(t);return n===null||n<=v?null:`Refused: this command starts by sleeping ${n}s, over the ${v}s inline limit.
|
|
2
2
|
Holding a live window on a clock is never how you wait here. Instead:
|
|
3
3
|
- schedule the wake and end your turn: crtr cron -h (one-shot at a time, or recurring)
|
|
4
4
|
- race an inbox message against a deadline: crtr node wait deadline -h
|
|
5
5
|
- waiting on a command: crtr node bash run '<command>' starts it as a job and wakes you with its exit code
|
|
6
6
|
- waiting on a child, a reply from the user, or any spine event: just stop \u2014 the runtime wakes you.
|
|
7
|
-
If you truly need a short pause inline, sleep ${v}s or less.`}a(Z,"longSleepRefusal");const B=["/","/Applications","/bin","/dev","/etc","/home","/Library","/opt","/private","/private/etc","/private/tmp","/private/var","/sbin","/System","/tmp","/usr","/Users","/var","/Volumes"];function
|
|
7
|
+
If you truly need a short pause inline, sleep ${v}s or less.`}a(Z,"longSleepRefusal");const B=["/","/Applications","/bin","/dev","/etc","/home","/Library","/opt","/private","/private/etc","/private/tmp","/private/var","/sbin","/System","/tmp","/usr","/Users","/var","/Volumes"];function _(t,n){return t==="/"||t==="/Users"||t==="/home"||t==="/System/Volumes/Data"?"a filesystem root":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home (a multi-gigabyte canvas.db, every node directory and worktree)":null}a(_,"broadSearchReason");function U(t,n,e){return B.includes(t)?"a system directory":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home \u2014 every node\u2019s conversation and state":e===t||!e.startsWith(t.endsWith(R)?t:t+R)?null:`a directory containing your working directory (${e})`}a(U,"protectedReason");function G(t,n){const e=N().username;return new Map([["HOME",t],["PWD",n],["USER",e],["LOGNAME",e]])}a(G,"initialVariables");function C(t,n){let e=t;if(e==="~"||e.startsWith("~/")){const r=n.get("HOME");if(r===void 0)return null;e=r+e.slice(1)}else if(e.startsWith("~"))return null;return e=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(r,s,o)=>n.get(s??o)??r),/[$`*?[]/.test(e)?null:e}a(C,"expandText");function y(t,n,e){const r=C(t.replace(/\/+\*?\.?$/,"")||"/",n);return r===null?null:T(r)?$(r):e===null?null:$(e,r)}a(y,"resolveTarget");function p(t,n){for(const e of n){const r=e.indexOf("=");if(r<=0)continue;const s=e.slice(0,r);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;const o=C(e.slice(r+1),t);o===null?t.delete(s):t.set(s,o)}}a(p,"applyAssignments");const I=/^[0-9]*(&?>>?|<<?|>&|<&)/;function g(t){const n=[];let e=!1,r=!1;for(const s of t.slice(1)){if(r){r=!1;continue}const o=I.exec(s.text);if(o!==null&&!s.opaque){r=s.text===o[0];continue}if(!e&&s.text==="--"){e=!0;continue}!e&&s.text.startsWith("-")&&s.text!=="-"||n.push(s.text)}return n}a(g,"operands");function j(t){const n=new Set,e=new Set;for(const r of t.slice(1)){if(r.text==="--")break;if(r.text.startsWith("--"))e.add(r.text.slice(2));else if(r.text.startsWith("-")&&r.text.length>1)for(const s of r.text.slice(1))n.add(s)}return{letters:n,long:e}}a(j,"flagLetters");function b(t){const{letters:n,long:e}=j(t);return n.has("r")||n.has("R")||e.has("recursive")}a(b,"isRecursive");const F=/^\/dev\/r?(disk|sd[a-z]|nvme|hd[a-z]|vd[a-z]|mmcblk|md)/;function O(t){const n=[];let e=1;for(;e<t.length;){const r=t[e].text;if(r==="--"||/^-[HLPEdsx]$/.test(r))e+=1;else if(r==="-D"||r==="-O")e+=2;else if(r==="-f")e+1<t.length&&n.push(t[e+1].text),e+=2;else break}for(;e<t.length&&!t[e].text.startsWith("-");e+=1)n.push(t[e].text);return n}a(O,"findPaths");const X=new Set(["sudo","doas","command","env","nice","nohup","time","stdbuf","xargs","exec","builtin"]);function Y(t){let n=t;for(;n.length>0&&!n[0].opaque&&X.has(n[0].text);){let e=1;for(;e<n.length&&n[e].text.startsWith("-");){const r=/^-[nu]$/.test(n[e].text);e+=r?2:1}for(;e<n.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(n[e].text);)e+=1;if(e>=n.length)return[];n=n.slice(e)}return n}a(Y,"stripCommandPrefixes");function K(t){const n={targets:[],named:null},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=g(t);switch(r){case"rm":return b(t)?{targets:s,named:null}:n;case"mv":return s.length>=2?{targets:s.slice(0,-1),named:null}:n;case"chmod":case"chown":case"chgrp":return b(t)&&s.length>=2?{targets:s.slice(1),named:null}:n;case"find":return t.some(i=>!i.opaque&&(i.text==="-delete"||i.text==="-exec"||i.text==="-execdir"))?{targets:O(t),named:null}:n;case"dd":{const o=t.find(l=>l.text.startsWith("of="));if(o===void 0)return n;const i=o.text.slice(3);return F.test(i)?{targets:[],named:i}:i.startsWith("/dev/")?n:{targets:[i],named:null}}default:if(/^(mkfs|newfs)([.-].+)?$/.test(r))return{targets:[],named:r};if(r==="diskutil"){const o=s[0];if(o!==void 0&&/^(erase|reformat|partition|zeroDisk|randomDisk|secureErase)/i.test(o))return{targets:[],named:`diskutil ${o}`}}return n}}a(K,"destructiveTargets");const m={grep:new Set(["-e","-f","-A","-B","-C","-m","-d","-D","--regexp","--file","--max-count","--context","--after-context","--before-context","--include","--exclude","--exclude-dir","--directories","--devices","--label"]),rg:new Set(["-e","-f","-A","-B","-C","-m","-g","-t","-T","-j","-M","-E","-r","--regexp","--file","--max-count","--context","--after-context","--before-context","--glob","--iglob","--type","--type-not","--threads","--max-columns","--encoding","--replace","--max-depth","--max-filesize","--sort","--sortr","--type-add","--pre","--pre-glob","--ignore-file","--color","--colors","--engine"]),ag:new Set(["-A","-B","-C","-m","-G","-g","--depth","--ignore","--file-search-regex","--max-count","--context","--after","--before"])};function L(t,n){const e=[];let r=!1,s=!1;for(let o=1;o<t.length;o+=1){const i=t[o].text,l=I.exec(i);if(l!==null&&!t[o].opaque){i===l[0]&&(o+=1);continue}if(!s&&i==="--"){s=!0;continue}if(!s&&i.startsWith("-")&&i!=="-"){const c=i.includes("=")?i.slice(0,i.indexOf("=")):i;(c==="-e"||c==="-f"||c==="--regexp"||c==="--file"||/^-[^-]*[ef]/.test(i))&&(r=!0),!i.includes("=")&&n.has(i)&&(o+=1);continue}e.push(i)}return{words:e,patternGiven:r}}a(L,"searchOperands");function J(t){const n={roots:[],implicitCwd:!1},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=a(o=>{const{words:i,patternGiven:l}=L(t,o),c=l?i:i.slice(1);return{roots:c,implicitCwd:c.length===0}},"patternThenPaths");switch(r){case"grep":case"egrep":case"fgrep":return b(t)?s(m.grep):n;case"rgrep":return s(m.grep);case"rg":if(t.some(o=>o.text==="--files")){const{words:o}=L(t,m.rg);return{roots:o,implicitCwd:o.length===0}}return s(m.rg);case"ag":case"ack":return s(m.ag);case"find":{if(t.some(i=>i.text==="-maxdepth"))return n;const o=O(t);return{roots:o,implicitCwd:o.length===0}}case"du":{const o=g(t);return{roots:o,implicitCwd:o.length===0}}default:return n}}a(J,"searchRoots");function k(t,n,e){return`Refused: \`${t}\` searches ${n} recursively, which is ${e}.
|
|
8
8
|
A sweep that wide reads hundreds of gigabytes, starves crtrd of disk, and has crashed every open viewer on this machine before.
|
|
9
9
|
Search where the answer can actually be:
|
|
10
10
|
- a document (knowledge, preference, spec, report): crtr canvas search "<text>" or crtr canvas read <name> \u2014 documents live in canvas.db, never as files, so grep cannot find them.
|
|
11
11
|
- code: the one repo or directory you are working in, e.g. rg -l '<text>' <repo>.
|
|
12
12
|
- a node's files: its own context dir, e.g. ~/.crouter/apps/<app>/nodes/<id>/context.
|
|
13
|
-
If you believe a whole-tree search is genuinely required, ask the user \u2014 do not work around this refusal.`}a(
|
|
13
|
+
If you believe a whole-tree search is genuinely required, ask the user \u2014 do not work around this refusal.`}a(k,"broadSearchRefusalMessage");function Q(t,n,e=A()){const r=G(e,n);let s=[n];for(const o of q(H(t))){const i=Y(o.tokens),l=i[0];if(l!==void 0){const c=new Map(r);p(c,o.assignments);const f=s[s.length-1];f!==void 0&&c.set("PWD",f);const{targets:D,named:S}=K(i);if(S!==null)return W(o.text,S,"a whole disk or volume \u2014 never a task boundary");for(const d of D)for(const w of s.length===0?[null]:s){const u=y(d,c,w);if(u===null)continue;const h=U(u,e,n);if(h!==null)return W(o.text,u,h)}const E=J(i),M=s.length===0?[null]:s,x=s[s.length-1];if(E.implicitCwd&&x!==void 0){const d=_(x,e);if(d!==null)return k(o.text,x,d)}for(const d of E.roots)for(const w of M){const u=y(d,c,w);if(u===null)continue;const h=_(u,e);if(h!==null)return k(o.text,u,h)}}if(!o.background){if(l===void 0)p(r,o.assignments);else if(!l.opaque&&ee.has(l.text))p(r,o.assignments),p(r,g(i));else if(!l.opaque&&l.text==="cd"){const c=g(i)[0],f=c===void 0?r.get("HOME")??null:y(c,r,s[s.length-1]??null);s=f===null?[]:[...s,f]}}}return null}a(Q,"destructiveCommandRefusal");const ee=new Set(["export","declare","typeset","readonly"]);function W(t,n,e){return`Refused: \`${t}\` targets ${n}, which is ${e}.
|
|
14
14
|
Nothing an agent is asked to do requires destroying that path, and it cannot be undone.
|
|
15
15
|
If you meant somewhere else, name that path explicitly and run the command again. Two traps to check first:
|
|
16
16
|
- a \`VAR=value cmd\` prefix applies ONLY to that one command, so a later \`$VAR\` in the same line is the SHELL's value \u2014 this is exactly how a node deleted a home directory.
|
|
17
17
|
- \`~\` and \`$HOME\` are the real home directory, never a scratch dir; build scratch paths with mktemp -d and hold them in a variable of your own.
|
|
18
|
-
If you believe this path genuinely must be destroyed, ask the user \u2014 do not work around this refusal.`}a(
|
|
18
|
+
If you believe this path genuinely must be destroyed, ask the user \u2014 do not work around this refusal.`}a(W,"refusalMessage");function oe(t,n,e=A()){return Z(t)??Q(t,n,e)}a(oe,"bashCommandRefusal");export{oe as bashCommandRefusal,Q as destructiveCommandRefusal,V as leadingSleepSeconds};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from 'node:events';
|
|
2
2
|
import type { NodeRow } from '../canvas/types.js';
|
|
3
|
-
import type { BrokerDataFrame, BrokerToClient, ClientToBroker, DequeueFrame, GetHumanForkCoordinatesFrame, GetSettingsFrame, GetTreeFrame, ListMemoryRefsFrame, ListModelsFrame, ListScopedModelsFrame, ListSessionsFrame } from '../runtime/broker-protocol.js';
|
|
3
|
+
import type { BrokerDataFrame, BrokerToClient, ClientToBroker, DequeueFrame, GetHumanForkCoordinatesFrame, GetSettingsFrame, GetTreeFrame, ListMemoryRefsFrame, GetGitStatusFrame, UploadFileFrame, ListModelsFrame, ListScopedModelsFrame, ListSessionsFrame } from '../runtime/broker-protocol.js';
|
|
4
4
|
import { type RedialOptions, type Transport } from './transport.js';
|
|
5
5
|
export { BrokerUnavailableError, type Transport } from './transport.js';
|
|
6
6
|
export { SocketTransport } from './transport-socket.js';
|
|
@@ -9,7 +9,7 @@ export { RelayTransport, type RelayTarget } from './transport-relay.js';
|
|
|
9
9
|
* {@link BrokerClient.request} mints the `id`, sends the frame, and resolves
|
|
10
10
|
* with the matching `data` reply. The picker/operator code builds these; the
|
|
11
11
|
* client owns the correlation token so callers never hand-roll one. */
|
|
12
|
-
export type ReadOpRequest = Omit<ListModelsFrame, 'id'> | Omit<ListSessionsFrame, 'id'> | Omit<GetTreeFrame, 'id'> | Omit<GetSettingsFrame, 'id'> | Omit<ListScopedModelsFrame, 'id'> | Omit<DequeueFrame, 'id'> | Omit<GetHumanForkCoordinatesFrame, 'id'> | Omit<ListMemoryRefsFrame, 'id'>;
|
|
12
|
+
export type ReadOpRequest = Omit<ListModelsFrame, 'id'> | Omit<ListSessionsFrame, 'id'> | Omit<GetTreeFrame, 'id'> | Omit<GetSettingsFrame, 'id'> | Omit<ListScopedModelsFrame, 'id'> | Omit<DequeueFrame, 'id'> | Omit<GetHumanForkCoordinatesFrame, 'id'> | Omit<ListMemoryRefsFrame, 'id'> | Omit<GetGitStatusFrame, 'id'> | Omit<UploadFileFrame, 'id'>;
|
|
13
13
|
export interface BrokerClientOptions {
|
|
14
14
|
/** Where the frames go. Defaults to a {@link SocketTransport} against this
|
|
15
15
|
* node's local `view.sock` — the common case. Pass a {@link RelayTransport}
|
|
@@ -11,5 +11,5 @@ var J=Object.defineProperty;var f=(i,e)=>J(i,"name",{value:e,configurable:!0});i
|
|
|
11
11
|
`);_.pop();const l=Math.max(0,o-s.tail),w=(await O(n,l>0?l-1:0,o)).toString("utf8").split(`
|
|
12
12
|
`);return l>0&&w.shift(),{header:t,entries:c(_.join(`
|
|
13
13
|
`)),tail:c(w.join(`
|
|
14
|
-
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,o)=>n+o.bytes,0)+r.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${S}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await i.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,o=F([s,...a]);await(await y()).put(n,o);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await i.read(e);let n=r.entries;if(a!==void 0){const o=G.inMemory(r.header.cwd,void 0,[r.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(s??(await L(e,await E())).binding?.node_id??k.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM
|
|
14
|
+
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,o)=>n+o.bytes,0)+r.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${S}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await i.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,o=F([s,...a]);await(await y()).put(n,o);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await i.read(e);let n=r.entries;if(a!==void 0){const o=G.inMemory(r.header.cwd,void 0,[r.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(s??(await L(e,await E())).binding?.node_id??k.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await $(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,o=C(a.node_id,e,n),c=t.map(d=>d.body+`
|
|
15
15
|
`).join("");return await(await y()).put(o,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await s.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,o,Buffer.byteLength(c),t.length,N()),await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${S}`).all(...e?[e]:[]);for(const t of a)await j(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const s of e)s.transcript_path&&k.set(s.session_id,{node:s.node_id,path:s.transcript_path})}};return i}f(_e,"createRowStore");function Z(i,e,s){const a=i.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(i.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const r=s(t.cwd);return r===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:r})),i.subarray(a)])}f(Z,"withHeaderCwd");async function ue(i,e,s){const a=await E(),t=await m(a,i),r=(await h(a,i))[0];if(!r||r.seq!==0)return!1;const n=await(await y()).get(r.blob_key);if(!n)throw new Error(`missing conversation object: ${r.blob_key}`);const o=Z(n,i,_=>_===e?s:_);if(o===null)return!1;const c=`conversations/${t.node_id}/${i}/0-${v()}.jsonl`;await(await y()).put(c,o);const d=await b(async _=>await _.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,o.length,o.length,i,r.blob_key)!==void 0);if(await(await y()).delete(d?r.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${i}`);return!0}f(ue,"relocateConversationHeader");export{_e as createRowStore,q as readAhead,ue as relocateConversationHeader,Z as withHeaderCwd};
|
|
@@ -64,6 +64,9 @@ export interface DocumentRead {
|
|
|
64
64
|
export declare function actorOf(reader: Reader): ObjectRow;
|
|
65
65
|
/** Head revisions (no child), highest number first. More than one means the document needs a merge. */
|
|
66
66
|
export declare function heads(db: CanvasDb, doc: ObjectRow): Promise<Revision[]>;
|
|
67
|
+
export declare function headsKeyOf(revs: ReadonlyArray<{
|
|
68
|
+
rev_id: string;
|
|
69
|
+
}>): string;
|
|
67
70
|
export declare function documentRecord(db: CanvasDb, doc: ObjectRow): Promise<DocumentRecord>;
|
|
68
71
|
/** The `[[name]]` links a body names, in order, each once. */
|
|
69
72
|
export declare function linksIn(body: string): string[];
|
|
@@ -115,12 +118,9 @@ export declare function editDocument(db: CanvasDb, reader: Reader, doc: ObjectRo
|
|
|
115
118
|
* `acting_app`, `acting_for`) with the rationale. It descends from the highest head only, so a document that needs a merge still does. A caller
|
|
116
119
|
* that held the heads before keeps holding them; one that had not read the body does not gain a read base it never earned. */
|
|
117
120
|
export declare function setDocumentRecord(db: CanvasDb, reader: Reader | null, doc: ObjectRow, fields: DocumentFields, rationale?: string): Promise<ObjectRow>;
|
|
118
|
-
/** Record that the reader holds the document's current heads: a `read` watch with that read
|
|
119
|
-
* base, and a `read` push. Delivery's content load calls this without reading the body. */
|
|
120
|
-
export declare function recordRead(db: CanvasDb, reader: Reader, doc: ObjectRow, reposFn?: ReposFn): Promise<void>;
|
|
121
121
|
/** The document's record, each head with its body (several = needs merge) and its links under
|
|
122
|
-
* their current names
|
|
123
|
-
export declare function readDocument(db: CanvasDb, reader: Reader, doc: ObjectRow
|
|
122
|
+
* their current names. Records nothing. */
|
|
123
|
+
export declare function readDocument(db: CanvasDb, reader: Reader, doc: ObjectRow): Promise<DocumentRead>;
|
|
124
124
|
/** Every revision, newest first, with authors, rationales and parents. Records nothing. */
|
|
125
125
|
export declare function history(db: CanvasDb, reader: Reader, doc: ObjectRow): Promise<Revision[]>;
|
|
126
126
|
/** Rename and/or re-own a document. Only `objects` changes: links point at the id, so no body is
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var ue=Object.defineProperty;var c=(t,n)=>ue(t,"name",{value:n,configurable:!0});import{randomUUID as we}from"node:crypto";import{CrtrError as
|
|
1
|
+
var ue=Object.defineProperty;var c=(t,n)=>ue(t,"name",{value:n,configurable:!0});import{randomUUID as we}from"node:crypto";import{CrtrError as N,notFound as g,usage as d}from"../errors.js";import{ExitCode as R}from"../../types.js";import{get as pe,getMany as le,put as B}from"./bodies.js";import{dropUnresolved as me,linksOf as G,recordActedOn as S,setLinks as q,setUnresolved as de,unresolvedLinksCouldName as fe}from"./edges.js";import{publish as $}from"./events.js";import{readableOrDeleted as he,resolveNames as ye}from"./names.js";import{createObject as _e,getById as f}from"./objects.js";import{liveLookups as Ee,NoOwningAppError as ve,readerForNode as Ne,readerForObject as ge}from"./reader.js";import{replaceRules as K,setRulesOwner as Re}from"./rules.js";import{recordWatch as H}from"./watches.js";import{withCanvasWrite as h}from"../canvas/db.js";import{PURGE_RETENTION_MS as Se}from"../storage/purge.js";import{filterAsync as Oe,forEachAsync as Te,mapAsync as k}from"../async-array.js";import{check as A,resolveReader as De,userOf as V}from"../permissions/evaluator.js";import{missingMemoryScope as Y}from"../permissions/ceiling.js";import{deleteFact as xe,parseSubject as ke,writeActsFor as Ae,writeFact as je}from"../permissions/facts.js";import{PermissionError as Le}from"../permissions/errors.js";function v(t){return t.class==="node"?t.node:t.class==="app"?t.app:t.class==="object"?t.object:t.person}c(v,"actorOf");async function C(t,n){const e=`user:${await V(t,n)}`;return n.class==="person"?{app:null,for:e}:{app:(await t.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(n.app.id))?.external_id??null,for:e}}c(C,"actingOf");function Ie(t,n){return new N("conflict",t,R.GENERAL,n)}c(Ie,"conflict");function y(t){if(t.type!=="document")throw d(`${t.type} ${t.id} is not a document`)}c(y,"assertDocument");async function X(t,n){return await t.prepare(`WITH RECURSIVE chain(id, owner, type, depth) AS (
|
|
2
2
|
SELECT id, owner, type, 0 FROM objects WHERE id = ?
|
|
3
3
|
UNION ALL
|
|
4
4
|
SELECT o.id, o.owner, o.type, c.depth + 1 FROM objects o JOIN chain c ON o.id = c.owner WHERE c.depth < 12
|
|
5
|
-
) SELECT 1 AS hit FROM chain WHERE type = 'repo' LIMIT 1`).get(n.id)!==void 0}c(X,"inRepoSpace");async function M(t,n,e){if(e!=="public"&&await X(t,n))throw d(`a repo owns only public documents; ${n.name} cannot own a ${e} one`,{rule:"repo-public-only",next:"Write it as public, or give it another owner (your own documents can carry `if: {repo: <handle>}`)."})}c(M,"assertPublicInRepo");async function W(t,n,e,a){if(e.trim()===""||e!==e.trim())throw d(`invalid document name ${JSON.stringify(e)}`);const i=await t.prepare("SELECT id FROM objects WHERE (type = 'document' OR strpos(type, '.') > 0) AND owner = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(n.id,e);if(i&&i.id!==a?.id)throw Ie(`${n.name} already has a document named ${e}`,{name:e,holder:i.id})}c(W,"assertNameFree");async function U(t,n,e){if(!await
|
|
6
|
-
WHERE rp.child = ? ORDER BY p.rev_id`).all(n.rev_id);return{rev_id:n.rev_id,seq:n.seq,number:n.number,body_hash:n.body_hash,author:n.author,rationale:n.rationale,verbatim:n.verbatim===1,created_at:n.created_at,acting_app:n.acting_app,acting_for:n.acting_for,parents:e.map(a=>a.rev_id)}}c(Q,"toRevision");async function
|
|
7
|
-
AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id`).all(n.id);return await
|
|
8
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(n.id,e.rev_id??we(),e.number,e.body_hash,e.author?.id??null,e.rationale,e.verbatim?1:0,e.created_at??new Date().toISOString(),e.acting?.app??null,e.acting?.for??null),i=t.prepare("INSERT INTO revision_parents (child, parent) VALUES (?, ?)");for(const r of e.parents)await i.run(a.rev_id,r);return a}c(D,"insertRevision");function He(t){const n=new Set;for(const e of t.matchAll(/\[\[([^[\]\n]+?)\]\]/g))n.add(e[1].trim());return[...n]}c(He,"linksIn");async function Z(t,n,e){const a=[],i=[];for(const[r,o]of await ye(t,n,e))"object"in o?a.push({written_as:r,dst:o.object}):"deleted"in o?a.push({written_as:r,dst:o.deleted}):"remote"in o||i.push(r);return{links:a,unresolved:i}}c(Z,"resolveLinks");async function b(t,n,e,a,i){const r=He(a),o=await Z(t,await ee(t,e,i)??n,r),
|
|
5
|
+
) SELECT 1 AS hit FROM chain WHERE type = 'repo' LIMIT 1`).get(n.id)!==void 0}c(X,"inRepoSpace");async function M(t,n,e){if(e!=="public"&&await X(t,n))throw d(`a repo owns only public documents; ${n.name} cannot own a ${e} one`,{rule:"repo-public-only",next:"Write it as public, or give it another owner (your own documents can carry `if: {repo: <handle>}`)."})}c(M,"assertPublicInRepo");async function W(t,n,e,a){if(e.trim()===""||e!==e.trim())throw d(`invalid document name ${JSON.stringify(e)}`);const i=await t.prepare("SELECT id FROM objects WHERE (type = 'document' OR strpos(type, '.') > 0) AND owner = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(n.id,e);if(i&&i.id!==a?.id)throw Ie(`${n.name} already has a document named ${e}`,{name:e,holder:i.id})}c(W,"assertNameFree");async function U(t,n,e){if(!await A(t,n,"read",e.id))throw g(`no document ${e.id}`)}c(U,"readable");function z(t){return new N("scope_missing",`missing scope ${t}`,R.GENERAL,{scope:t})}c(z,"scopeMissing");async function O(t,n,e){await U(t,n,e);const{source_path:a}=await T(t,e);if(a!==null)throw new N("forbidden",`${e.name} is a built-in document shipped by a package; \`crtr doc\` cannot change it`,R.GENERAL,{id:e.id,next:"Edit it in the source repository of the package that ships it (for crtr's own documents, the crouter repo), not with `crtr doc`."});const i=await Y(t,n,e.id,"rw");if(i!==null)throw z(i);if(!await A(t,n,"edit",e.id))throw new N("forbidden",`you cannot change ${e.name}`,R.GENERAL,{id:e.id})}c(O,"changeable");async function Q(t,n){const e=await t.prepare(`SELECT p.rev_id FROM revision_parents rp JOIN revisions p ON p.rev_id = rp.parent
|
|
6
|
+
WHERE rp.child = ? ORDER BY p.rev_id`).all(n.rev_id);return{rev_id:n.rev_id,seq:n.seq,number:n.number,body_hash:n.body_hash,author:n.author,rationale:n.rationale,verbatim:n.verbatim===1,created_at:n.created_at,acting_app:n.acting_app,acting_for:n.acting_for,parents:e.map(a=>a.rev_id)}}c(Q,"toRevision");async function j(t,n){const e=await t.prepare(`SELECT * FROM revisions r WHERE r.document = ?
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id`).all(n.id);return await k(e,async a=>await Q(t,a))}c(j,"heads");function $e(t){return t.map(n=>n.rev_id).sort().join(",")}c($e,"headsKeyOf");async function T(t,n){const e=await t.prepare("SELECT * FROM documents WHERE object = ?").get(n.id);if(!e)throw g(`no document record for ${n.id}`);return{summary:e.summary,heads_key:e.heads_key,revision:e.revision,why_it_exists:e.why_it_exists,unlisted:e.unlisted===1,lint_ignore:e.lint_ignore_json===null?null:JSON.parse(e.lint_ignore_json),extensions:e.extensions_json===null?null:JSON.parse(e.extensions_json),source_path:e.source_path}}c(T,"documentRecord");async function D(t,n,e){const a=await t.prepare(`INSERT INTO revisions (document, rev_id, number, body_hash, author, rationale, verbatim, created_at, acting_app, acting_for)
|
|
8
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(n.id,e.rev_id??we(),e.number,e.body_hash,e.author?.id??null,e.rationale,e.verbatim?1:0,e.created_at??new Date().toISOString(),e.acting?.app??null,e.acting?.for??null),i=t.prepare("INSERT INTO revision_parents (child, parent) VALUES (?, ?)");for(const r of e.parents)await i.run(a.rev_id,r);return a}c(D,"insertRevision");function He(t){const n=new Set;for(const e of t.matchAll(/\[\[([^[\]\n]+?)\]\]/g))n.add(e[1].trim());return[...n]}c(He,"linksIn");async function Z(t,n,e){const a=[],i=[];for(const[r,o]of await ye(t,n,e))"object"in o?a.push({written_as:r,dst:o.object}):"deleted"in o?a.push({written_as:r,dst:o.deleted}):"remote"in o||i.push(r);return{links:a,unresolved:i}}c(Z,"resolveLinks");async function b(t,n,e,a,i){const r=He(a),o=await Z(t,await ee(t,e,i)??n,r),w=new Set(o.links.map(l=>l.written_as)),u=(await G(t,e)).filter(l=>r.includes(l.written_as)&&!w.has(l.written_as)),s=[...o.links,...u],p=new Set(u.map(l=>l.written_as)),m=o.unresolved.filter(l=>!p.has(l));return await oe(t,await q(t,e,s)),await de(t,e,m),m}c(b,"setRevisionLinks");async function ee(t,n,e){const a=n.owner==null?null:await f(t,n.owner);return n.deleted_at||n.home_machine!==null||!a||a.deleted_at?null:a.type==="node"?await Ne(t,a.id,e??(async()=>[]),Ee(t),!0):await ge(t,n,e).catch(i=>{if(i instanceof ve)return null;throw i})}c(ee,"ownerView");async function F(t,n,e){const a=new Map;for(const{src:i,name:r}of await fe(t,n.name,n.id))a.set(i,[...a.get(i)??[],r]);for(const[i,r]of a){const o=await f(t,i),w=o?await ee(t,o,e):null;if(!o||!w)continue;const u=(await Z(t,w,r)).links.filter(s=>s.dst.id===n.id);u.length!==0&&(await q(t,o,[...await G(t,o),...u]),await me(t,o,u.map(s=>s.written_as)))}}c(F,"linkNewlyNamed");async function Ce(t,n){const e=n.filter(r=>r.ownerType!=="node"),a=new Set,i=c((r,o,w)=>JSON.stringify([r,o,w]),"key");if(e.length>0){const r=await t.prepare(`SELECT DISTINCT v.owner_name, v.owner_type, v.name
|
|
9
9
|
FROM unnest(?::text[], ?::text[], ?::text[]) AS v(owner_name, owner_type, name)
|
|
10
10
|
JOIN objects o ON o.name = v.owner_name AND o.type <> v.owner_type AND o.type IN ('person','app','repo','profile','group')
|
|
11
11
|
JOIN objects d ON d.owner = o.id AND d.type = 'document' AND d.name = v.name AND d.deleted_at IS NULL`).all(e.map(o=>o.ownerName),e.map(o=>o.ownerType),e.map(o=>o.name));for(const o of r)a.add(i(o.owner_name,o.owner_type,o.name))}return n.map(r=>r.ownerType==="node"?r.ownerName:a.has(i(r.ownerName,r.ownerType,r.name))?`${r.ownerType}:${r.ownerName}`:r.ownerName)}c(Ce,"ownerPrefixes");async function te(t,n,e){const i=(await t.prepare(`SELECT e.written_as, o.*, w.type AS owner_type, CASE WHEN w.type = 'node' THEN w.id ELSE w.name END AS owner_handle
|
|
12
12
|
FROM edges e JOIN objects o ON o.id = e.dst LEFT JOIN objects w ON w.id = o.owner
|
|
13
|
-
WHERE e.type = 'links-to' AND e.src = ? AND e.written_as IS NOT NULL`).all(n.id)).filter(s=>!s.deleted_at&&s.written_as!==s.id&&!(!s.written_as.includes("/")&&s.name===s.written_as));if(i.length===0)return e;const r=i.filter(s=>s.owner_type!==null),o=await Ce(t,r.map(s=>({ownerType:s.owner_type,ownerName:s.owner_handle,name:s.name}))),
|
|
14
|
-
|
|
15
|
-
WHERE (resource_type = ? AND resource_id = ?) OR (subject_type = ? AND subject_id = ?)`).all(n.schema_type,n.id,n.schema_type,n.id);for(const a of e)await xe(t,{resourceType:a.resource_type,resourceId:a.resource_id,relation:a.relation,subject:{type:a.subject_type,id:a.subject_id,relation:a.subject_relation}})}c(
|
|
13
|
+
WHERE e.type = 'links-to' AND e.src = ? AND e.written_as IS NOT NULL`).all(n.id)).filter(s=>!s.deleted_at&&s.written_as!==s.id&&!(!s.written_as.includes("/")&&s.name===s.written_as));if(i.length===0)return e;const r=i.filter(s=>s.owner_type!==null),o=await Ce(t,r.map(s=>({ownerType:s.owner_type,ownerName:s.owner_handle,name:s.name}))),w=new Map(r.map((s,p)=>[s,o[p]])),u=new Map;for(const s of i){const p=!s.written_as.includes("/"),m=w.get(s),l=m!==void 0?`${m}/${s.name}`:s.name,_=p&&s.owner===n.owner?s.name:l;_!==s.written_as&&u.set(s.written_as,_)}return u.size===0?e:e.replace(/\[\[([^[\]\n]+?)\]\]/g,(s,p)=>{const m=u.get(p.trim());return m===void 0?s:`[[${m}]]`})}c(te,"withCurrentNames");async function J(t,n,e){if(e.preview!==void 0){if(e.preview.trim()==="")throw d("a document needs a preview",{field:"preview"});await t.prepare("UPDATE objects SET preview = ? WHERE id = ?").run(e.preview,n.id)}e.privacy!==void 0&&(await M(t,await f(t,n.owner),e.privacy),await t.prepare("UPDATE objects SET privacy = ? WHERE id = ?").run(e.privacy,n.id));const a=c(async(r,o)=>await t.prepareUncached(`UPDATE documents SET ${r} = ? WHERE object = ?`).run(o,n.id),"set");e.summary!==void 0&&await a("summary",e.summary),e.whyItExists!==void 0&&await a("why_it_exists",e.whyItExists),e.unlisted!==void 0&&await a("unlisted",e.unlisted?1:0),e.lintIgnore!==void 0&&await a("lint_ignore_json",e.lintIgnore===null?null:JSON.stringify(e.lintIgnore)),e.extensions!==void 0&&await a("extensions_json",e.extensions===null?null:JSON.stringify(e.extensions));const i=await f(t,n.id);return e.rules!==void 0&&await K(t,i,e.rules),i}c(J,"applyDocumentFields");async function ne(t,n,e,a="crtr"){if(n.owner.deleted_at)throw d(`${n.owner.name} is deleted`);if(n.relations?.length&&n.schemaType===void 0)throw new Le(400,"schema_type_required","relations need a schemaType: they are facts about a typed resource",{field:"relations"});if(n.preview.trim()==="")throw d("a document needs a preview",{field:"preview"});await M(t,n.owner,n.privacy),await W(t,n.owner,n.name);const i=await _e(t,{...n.id?{id:n.id}:{},type:"document",kind:n.kind,owner:n.owner.id,privacy:n.privacy,name:n.name,preview:n.preview,...n.schemaType!==void 0?{schema_type:n.schemaType}:{}});for(const{relation:o,subject:w}of n.relations??[])await je(t,{resourceType:n.schemaType,resourceId:i.id,relation:o,subject:ke(w),writtenBy:a});await t.prepare("INSERT INTO documents (object, heads_key, revision) VALUES (?, '', 0)").run(i.id);const r=await J(t,i,{...n,preview:void 0,privacy:void 0,rules:n.rules??[]});return await F(t,r,e),r}c(ne,"createDocument");async function L(t,n){const e=await j(t,n),a=$e(e),i=Math.max(0,...e.map(r=>r.number));return await t.prepare("UPDATE documents SET heads_key = ?, revision = ? WHERE object = ?").run(a,i,n.id),{heads_key:a,revision:i,headCount:e.length}}c(L,"setHeads");async function ot(t,n,e,a,i){return await h(async()=>{const r=await B(t,a),o=v(n),w=await Y(t,n,e.owner.id,"rw",!0);if(w!==null)throw z(w);const u=await C(t,n),s=await ne(t,e,i,u.app??u.for);e.owner.type==="app"&&e.schemaType===void 0&&await Ae(t,s.id,await V(t,n));const p=await D(t,s,{number:1,body_hash:r,author:o,rationale:null,parents:[],acting:u});if(!await A(t,n,"edit",s.id))throw g(`no owner ${e.owner.name} you can write to`);const{heads_key:m}=await L(t,s),l=await b(t,n,s,a,i);return await S(t,o,s),await H(t,o,s,"write",{readHeadsKey:m}),await $(t,{event:"created",object:s,actor:o,attrs:{revision:1},pointer:p.rev_id},i),{object:s,revision:1,unresolved:l}},{savepoint:!0})}c(ot,"writeDocument");async function Me(t,n,e){return(await t.prepare("SELECT read_heads_key FROM watches WHERE watcher = ? AND object = ?").get(v(n).id,e.id))?.read_heads_key??null}c(Me,"readBase");function We(t,n){let e=t;for(const[a,{old:i,new:r}]of n.entries()){if(i==="")throw d(`block ${a+1}: a replacement needs non-empty old text`,{field:"replace"});const o=e.indexOf(i);if(o<0)throw d(`block ${a+1}: old text not found: ${JSON.stringify(i.slice(0,120))}`,{field:"replace",old:i});if(e.indexOf(i,o+1)>=0)throw d(`block ${a+1}: old text occurs more than once: ${JSON.stringify(i.slice(0,120))}`,{field:"replace",old:i});e=e.slice(0,o)+r+e.slice(o+i.length)}return e}c(We,"applyReplacements");async function st(t,n,e,a,i,r,o={},w){if(y(e),await O(t,n,e),e.deleted_at)throw d(`${e.name} is deleted`);if(r===null)throw new N("read_first",`read ${e.name} before editing it`,R.GENERAL,{id:e.id});if(i.trim()==="")throw d("an edit needs a rationale",{field:"rationale"});const u=await T(t,e);if(u.heads_key!==r)return{stale:{heads_key:u.heads_key,revision:u.revision}};const s=await j(t,e);let p;if("body"in a)p=a.body;else{if(s.length!==1)throw d(`${e.name} has ${s.length} heads and needs a merge; pass the whole merged body`,{heads:s.length});p=We(await te(t,e,await pe(t,s[0].body_hash)),a.replace)}try{return await h(async()=>{const m=await B(t,p),l=v(n),_=1+Math.max(0,...s.map(E=>E.number)),P=await D(t,e,{number:_,body_hash:m,author:l,rationale:i,verbatim:a.verbatim===!0,parents:s.map(E=>E.rev_id),acting:await C(t,n)}),I=P.rev_id,se=await t.prepare("UPDATE documents SET heads_key = ?, revision = ? WHERE object = ? AND heads_key = ?").run(I,_,e.id,r);if(Number(se.changes)===0){const E=await T(t,e);throw new ae(E.heads_key,E.revision)}const x=await J(t,e,o),ce=await b(t,n,x,p,w);return await S(t,l,x),await H(t,l,x,"write",{readHeadsKey:I}),await $(t,{event:"edited",object:x,actor:l,pointer:P.rev_id,attrs:{revision:_,from_revision:u.revision,rationale:i}},w),{revision:_,heads_key:I,unresolved:ce}},{savepoint:!0})}catch(m){if(m instanceof ae)return{stale:{heads_key:m.heads_key,revision:m.revision}};throw m}}c(st,"editDocument");class ae extends Error{static{c(this,"StaleEdit")}heads_key;revision;constructor(n,e){super("stale"),this.heads_key=n,this.revision=e}}async function ct(t,n,e,a,i){if(y(e),n&&(await O(t,n,e),i===void 0||i.trim()===""))throw d("an edit needs a rationale",{field:"rationale"});return await h(async()=>{const r=await J(t,e,a);if(n){const o=v(n),w=await T(t,e),u=await Me(t,n,e),s=await j(t,e),p=s[0];await D(t,e,{number:1+Math.max(...s.map(l=>l.number)),body_hash:p.body_hash,author:o,rationale:i,parents:[p.rev_id],acting:await C(t,n)});const{heads_key:m}=await L(t,e);await S(t,o,r),await H(t,o,e,"write",u===w.heads_key?{readHeadsKey:m}:{})}return r},{savepoint:!0})}c(ct,"setDocumentRecord");async function ut(t,n,e){y(e),await U(t,n,e);const a=await T(t,e),i=await j(t,e),r=await le(t,i.map(p=>p.body_hash)),o=await k(i,async p=>({...p,body:await te(t,e,r.get(p.body_hash))})),w=await he(t,await De(t,n),"o"),s=(await t.prepareUncached(`SELECT e.written_as AS _written_as, o.* FROM edges e JOIN objects o ON o.id = e.dst
|
|
14
|
+
WHERE e.type = 'links-to' AND e.src = ? AND (${w.sql}) ORDER BY e.written_as`).all(e.id,...w.params)).map(({_written_as:p,...m})=>({written_as:p??"",object:m,deleted:m.deleted_at!==null}));return{object:e,record:a,heads:o,needsMerge:o.length>1,links:s}}c(ut,"readDocument");async function wt(t,n,e){y(e),await U(t,n,e);const a=await t.prepare("SELECT * FROM revisions WHERE document = ? ORDER BY number DESC, created_at DESC, seq DESC").all(e.id);return await k(a,async i=>await Q(t,i))}c(wt,"history");async function pt(t,n,e,a,i){if(y(e),e.deleted_at)throw d(`${e.name} is deleted`);return n&&await O(t,n,e),await h(async()=>{const r=a.owner??await f(t,e.owner),o=a.name??e.name;await W(t,r,o,e),await M(t,r,e.privacy),await t.prepare("UPDATE objects SET name = ?, owner = ? WHERE id = ?").run(o,r.id,e.id);const w=await f(t,e.id);if(r.id!==e.owner&&(await Re(t,w),n&&!await A(t,n,"edit",w.id)))throw g(`no owner ${r.name} you can move documents to`);return n&&await S(t,v(n),w),(o!==e.name||r.id!==e.owner)&&await F(t,w,i),w},{savepoint:!0})}c(pt,"moveDocument");async function lt(t,n,e,a,i){return y(e),e.deleted_at?e:(n&&await O(t,n,e),await h(async()=>{const r=await ie(t,n,e,a,i);return await Ue(t,e),await oe(t,await re(t,e.id),a),r},{savepoint:!0}))}c(lt,"deleteDocument");async function Ue(t,n){if(n.schema_type==null)return;const e=await t.prepare(`SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations
|
|
15
|
+
WHERE (resource_type = ? AND resource_id = ?) OR (subject_type = ? AND subject_id = ?)`).all(n.schema_type,n.id,n.schema_type,n.id);for(const a of e)await xe(t,{resourceType:a.resource_type,resourceId:a.resource_id,relation:a.relation,subject:{type:a.subject_type,id:a.subject_id,relation:a.subject_relation}})}c(Ue,"deleteFactsOf");async function Fe(t,n,e,a){return y(n),n.deleted_at?await h(async()=>{await W(t,await f(t,n.owner),e,n),await t.prepare("UPDATE objects SET deleted_at = NULL, name = ? WHERE id = ?").run(e,n.id);const i=await f(t,n.id);return await F(t,i,a),i},{savepoint:!0}):n}c(Fe,"restoreDocument");async function mt(t,n,e,a=Date.now()){if(y(e),!e.deleted_at)return e;if(Date.parse(e.deleted_at)<a-Se)throw d(`${e.name} was deleted over 30 days ago and can no longer be undeleted`,{id:e.id,deleted_at:e.deleted_at});const i=e.owner===null?null:await f(t,e.owner);if(i===null||i.deleted_at)throw d(`${e.name} cannot be undeleted while its owner is deleted`,{id:e.id});return await h(async()=>{const r=await Fe(t,e,e.name);return n&&await O(t,n,r),r},{savepoint:!0})}c(mt,"undeleteDocument");async function ie(t,n,e,a,i){await t.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(i??new Date().toISOString(),e.id);const r=await f(t,e.id),o=n?v(n):null;return o&&await S(t,o,r),await $(t,{event:"deleted",object:r,actor:o,attrs:{}},a),await t.prepare("DELETE FROM watches WHERE object = ?").run(e.id),await K(t,r,[]),r}c(ie,"markDeleted");async function re(t,n){return(await t.prepare("SELECT dst FROM edges WHERE type = 'links-to' AND src = ?").all(n)).map(({dst:e})=>e)}c(re,"linkTargets");async function oe(t,n,e){const a=t.prepare(`SELECT 1 FROM objects d JOIN objects w ON w.id = d.owner
|
|
16
16
|
WHERE d.id = ? AND d.type = 'document' AND d.deleted_at IS NULL AND w.deleted_at IS NOT NULL
|
|
17
17
|
AND NOT EXISTS (SELECT 1 FROM edges e JOIN objects s ON s.id = e.src
|
|
18
|
-
WHERE e.type = 'links-to' AND e.dst = d.id AND e.src != d.id AND s.deleted_at IS NULL)`),i=[...n];for(;i.length>0;){const r=i.pop();await a.get(r)!==void 0&&(await ie(t,null,await f(t,r),e),i.push(...await re(t,r)))}}c(oe,"collectUnlinked");async function
|
|
18
|
+
WHERE e.type = 'links-to' AND e.dst = d.id AND e.src != d.id AND s.deleted_at IS NULL)`),i=[...n];for(;i.length>0;){const r=i.pop();await a.get(r)!==void 0&&(await ie(t,null,await f(t,r),e),i.push(...await re(t,r)))}}c(oe,"collectUnlinked");async function dt(t,n,e){if(n.revisions.length===0)throw d(`import of ${n.name}: no revisions`);return await h(async()=>{const a=await ne(t,n,e);await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(n.revisions[0].created_at,a.id);let i=null;return await Te(n.revisions,async(r,o)=>{i=(await D(t,a,{...r,number:o+1,parents:i===null?[]:[i]})).rev_id}),await L(t,a),await f(t,a.id)},{savepoint:!0})}c(dt,"importDocument");async function ft(t,n,e){if(y(n),n.privacy!=="public"&&await X(t,n))throw d(`a repo owns only public documents; refusing revisions of ${n.name}`);return await h(async()=>{const a=t.prepare("SELECT rev_id, number, document, body_hash FROM revisions WHERE rev_id = ?"),i=t.prepare("SELECT parent FROM revision_parents WHERE child = ?");let r=await Oe(e,async u=>{const s=await a.get(u.rev_id);if(s===void 0)return!0;const p=(await i.all(u.rev_id)).map(m=>m.parent).sort().join(",");if(s.document!==n.id||s.body_hash!==u.body_hash||p!==[...u.parents].sort().join(","))throw d(`revision ${u.rev_id} already exists with different content (document, body hash or parents); refusing to overwrite it`);return!1});for(;r.length>0;){const u=[];for(const s of r){const p=await k(s.parents,async l=>await a.get(l));if(p.some(l=>l===void 0)){u.push(s);continue}const m=p;if(m.some(l=>l.document!==n.id))throw d(`revision ${s.rev_id} names a parent of another document`);await D(t,n,{...s,author:null,number:1+Math.max(0,...m.map(l=>l.number)),parents:m.map(l=>l.rev_id)})}if(u.length===r.length)throw d(`revisions of ${n.name} name unknown parents: ${u.map(s=>s.rev_id).join(", ")}`);r=u}const{heads_key:o,headCount:w}=await L(t,n);return{heads_key:o,headCount:w}},{savepoint:!0})}c(ft,"insertImportedRevisions");async function ht(t,n){const e=await f(t,n);if(!e||e.type!=="document")throw g(`no document ${n}`);return e}c(ht,"documentById");export{v as actorOf,J as applyDocumentFields,We as applyReplacements,oe as collectUnlinked,lt as deleteDocument,ht as documentById,T as documentRecord,st as editDocument,j as heads,$e as headsKeyOf,wt as history,dt as importDocument,ft as insertImportedRevisions,He as linksIn,pt as moveDocument,Me as readBase,ut as readDocument,Fe as restoreDocument,ct as setDocumentRecord,b as setRevisionLinks,mt as undeleteDocument,te as withCurrentNames,ot as writeDocument};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var l=Object.defineProperty;var
|
|
1
|
+
var l=Object.defineProperty;var a=(n,i)=>l(n,"name",{value:i,configurable:!0});import{header as p}from"./render.js";import{objectDTO as u}from"./dto.js";import{receiverForObject as m}from"../receivers.js";function _(n,i){const d=Object.fromEntries(Object.entries(i).map(([o,{ends_wait:c,...s}])=>[`${n}.${o}`,{...s,carriesBody:!0,...c===void 0?{}:{endsWait:c}}]));return{name:n,events:{created:{level:4},read:{level:1},watched:{level:1},deleted:{level:5},configured:{level:1},...d},addressable:"name",receiverFor:m,async read(o,c,s){const e=await o.prepare("SELECT description, summary, state_json, published_at, receiver_json, dropped FROM custom_objects WHERE object = ?").get(s.id),t=e?.receiver_json==null?null:JSON.parse(e.receiver_json),r={object:await u(o,s),description:e?.description??"",summary:e?.summary??null,state:e?.state_json==null?null:JSON.parse(e.state_json),published_at:e?.published_at??null,receiver:typeof t=="string"?t:t&&typeof t=="object"?Object.keys(t)[0]:null,dropped:e?.dropped??0};return{data:r,text:`${p("object",r.object)}
|
|
2
2
|
Description: ${r.description}
|
|
3
3
|
Summary: ${r.summary??""}
|
|
4
4
|
State: ${JSON.stringify(r.state)}
|
|
5
5
|
Published: ${r.published_at??"never"}
|
|
6
6
|
Receiver: ${r.receiver??"none"}
|
|
7
|
-
Dropped: ${r.dropped}`}}}}
|
|
7
|
+
Dropped: ${r.dropped}`}}}}a(_,"customKind");export{_ as customKind};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND substr(o.name, 1, ?) = ? AND strpos(substr(o.name, ? + 1), '/') = 0 AND ${
|
|
1
|
+
var _=Object.defineProperty;var m=(e,t)=>_(e,"name",{value:t,configurable:!0});import{deliveryDocOf as N,nodeSubject as D}from"../../substrate/delivery/corpus.js";import{renderExplicitRead as $}from"../../substrate/delivery/render-event.js";import{permits as x,resolveReader as O}from"../../permissions/evaluator.js";import{documentRecord as j,headsKeyOf as S,readDocument as b}from"../documents.js";import{loadLedger as A}from"../exposures.js";import{rulesOf as f}from"../rules.js";import{objectDTO as R,objectDTOs as p}from"./dto.js";import{withBase as E}from"./kind.js";import{attr as l,header as T,section as k}from"./render.js";async function I(e,t,n){const s=`${n.name}/`,i=await x(e,t,"read","o"),a=await e.prepareUncached(`SELECT o.* FROM objects o WHERE o.type = 'document' AND o.deleted_at IS NULL AND o.home_machine IS NULL AND o.owner IS NOT DISTINCT FROM ?
|
|
2
|
+
AND substr(o.name, 1, ?) = ? AND strpos(substr(o.name, ? + 1), '/') = 0 AND ${i.sql} ORDER BY o.name`).all(n.owner,s.length,s,s.length,...i.params);return await p(e,a)}m(I,"listingOf");async function L(e,t,n){const s=t.class==="node",i=s?await A(e,t.node.id):{node:"",preferenceSnapshot:null,objects:new Map,listed:new Map},a={db:e,reader:t,subject:s?await D(e,t):null,ledger:i,channel:"transcript"},o=await $(a,await N(e,t,n));return{attachments:o.attachments,linked:o.linked.map(u=>u.object),...s?{ledger:i}:{},delivered:o.delivered}}m(L,"explicitReadAttachments");function M(e,t){const n=[];if(t.attachments&&n.push(t.attachments,""),n.push(T("object",e,l("privacy",e.privacy)+l("revision",t.revision))),n.push(`Preview: ${e.preview}`),t.summary&&n.push(`Summary: ${t.summary}`),t.fields!==void 0&&n.push(`<fields>
|
|
3
3
|
${JSON.stringify(t.fields,null,2)}
|
|
4
|
-
</fields>`),t.needs_merge?(t.heads.forEach((i
|
|
5
|
-
`)}m(
|
|
4
|
+
</fields>`),t.needs_merge?(t.heads.forEach((s,i)=>{n.push(`<head${l("rev",s.rev_id)}${l("number",s.number)}${l("author",s.author_id)}>`,t.bodies[i]??"","</head>")}),n.push(`This document has ${t.heads.length} heads. Your next \`crtr doc edit\` writes the merged body and joins them into one revision.`)):n.push("",t.bodies[0]??""),t.listing&&t.listing.length>0){const s=t.listing.some(o=>o.owner?.id===e.owner?.id&&o.name.startsWith(`${e.name}/`)),i=t.listing.some(o=>o.owner?.id!==e.owner?.id||!o.name.startsWith(`${e.name}/`)),a=s&&i?`Names under ${e.name}/ and documents it links to`:s?`Names under ${e.name}/`:"Documents it links to";n.push("",...k(a,t.listing))}return n.join(`
|
|
5
|
+
`)}m(M,"render");function K(e){const t=e.attrs.revision,n=e.attrs.from_revision??(typeof t=="number"?t-1:null),s=e.attrs.rationale;return{...e.attrs,from_revision:n,revision:t,authors:e.actor?[e.actor.id]:[],rationales:typeof s=="string"?[s]:[]}}m(K,"editAttrs");const U=m((e,t)=>{const n=K(t);if(e===null)return n;const s=e.authors??[];return{...n,from_revision:e.from_revision??null,authors:[...s,...n.authors.filter(i=>!s.includes(i))],rationales:[...e.rationales??[],...n.rationales]}},"mergeEdits"),G={name:"document",addressable:"name",events:E({edited:{level:8,supersedes:!0,merge:U},deleted:{level:8}}),async listItem(e,t){return{summary:(await j(e,t)).summary??null,rules:(await f(e,t)).length}},async read(e,t,n,s){const i=await b(e,t,n),a=i.record,o=await I(e,await O(e,t),n),{attachments:u,linked:w,ledger:c,delivered:g}=await L(e,t,n),y=new Set(o.map(r=>r.id)),h=[...o,...await p(e,w.filter(r=>!y.has(r.id)))],d={summary:a.summary??null,revision:a.revision,heads:i.heads.map(r=>({rev_id:r.rev_id,number:r.number,author_id:r.author,created_at:r.created_at})),bodies:i.heads.map(r=>r.body),needs_merge:i.needsMerge,...h.length>0?{listing:h}:{},...u===""?{}:{attachments:u}};return s.fields&&(d.fields={why_it_exists:a.why_it_exists??null,unlisted:a.unlisted,lint_ignore:a.lint_ignore??[],extensions:a.extensions??{},rules:(await f(e,n)).map(({matchFrontmatter:r,...v})=>({...v,...r===void 0?{}:{match_frontmatter:r}}))}),{data:d,text:M(await R(e,n),d),record:{headsKey:S(i.heads),...c===void 0?{}:{ledger:c},delivered:g}}}};export{G as documentKind};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{objectDTO as
|
|
2
|
-
`);return{data:e,text:
|
|
1
|
+
import{objectDTO as r}from"./dto.js";import{withBase as d}from"./kind.js";import{attr as i,header as _}from"./render.js";const w={name:"environment",addressable:"id",events:d(),async read(a,c,t){const n=await a.prepare("SELECT kind, machine_id, last_seen_at FROM environments WHERE object = ?").get(t.id);if(!n)throw new Error(`environment object ${t.id} has no environments row`);const s=await r(a,t),e={kind:n.kind,machine_id:n.machine_id,last_seen_at:n.last_seen_at},o=[_("object",s,i("machine_id",e.machine_id)+i("last_seen_at",e.last_seen_at)),`Kind: ${e.kind}`,`Machine: ${e.machine_id}`,`Last seen: ${e.last_seen_at}`].join(`
|
|
2
|
+
`);return{data:e,text:o}}};export{w as environmentKind};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jobRow as
|
|
2
|
-
`);return{data:o,text:
|
|
1
|
+
import{jobRow as d}from"../jobs.js";import{objectDTO as i}from"./dto.js";import{withBase as c}from"./kind.js";import{attr as a,header as m}from"./render.js";const _={name:"job",addressable:"id",events:c({exited:{level:7},killed:{level:7},silent:{level:7}}),async read(r,l,t){const e=await d(r,t);if(!e)throw new Error(`job object ${t.id} has no jobs row`);const n=await i(r,t),o={command:e.command,status:e.status,exit_code:e.exit_code,output_key:e.output_key},s=[m("object",n,a("status",o.status)+a("exit_code",o.exit_code)),`Command: ${o.command}`,`Output: \`crtr node bash log ${t.id}${t.owner===null?"":` --node ${t.owner}`}\``].join(`
|
|
2
|
+
`);return{data:o,text:s}}};export{_ as jobKind};
|
|
@@ -4,6 +4,8 @@ import type { ReposFn } from '../reader.js';
|
|
|
4
4
|
import type { ReceiverName } from '../receivers.js';
|
|
5
5
|
import type { CanvasEvent, Level, ObjectRow, Reader } from '../types.js';
|
|
6
6
|
import type { CanvasDb } from '../../canvas/db.js';
|
|
7
|
+
import type { DeliveredDoc } from '../../substrate/delivery/render-event.js';
|
|
8
|
+
import type { Ledger } from '../exposures.js';
|
|
7
9
|
/** A superseding event's attrs: built from the superseded pending delivery's attrs (null when it
|
|
8
10
|
* supersedes nothing) and the new event. */
|
|
9
11
|
export type SupersedeMerge = (prior: Record<string, unknown> | null, ev: CanvasEvent) => Record<string, unknown>;
|
|
@@ -36,6 +38,12 @@ export type EventCatalog = Readonly<Record<string, EventSpec>>;
|
|
|
36
38
|
export interface KindRead {
|
|
37
39
|
data: Record<string, unknown>;
|
|
38
40
|
text: string;
|
|
41
|
+
/** What a document read rendered, for `recordRead`: the heads shown and, for a node reader, the ledger and deliveries the render filled. */
|
|
42
|
+
record?: {
|
|
43
|
+
headsKey: string;
|
|
44
|
+
ledger?: Ledger;
|
|
45
|
+
delivered: DeliveredDoc[];
|
|
46
|
+
};
|
|
39
47
|
}
|
|
40
48
|
export interface ReadOpts {
|
|
41
49
|
/** A document read also returns its optional fields. */
|
|
@@ -57,7 +65,7 @@ export interface ObjectKind {
|
|
|
57
65
|
/** A kind may fence claimed deliveries when a superseding event replaces them. Return true
|
|
58
66
|
* only if the claimed delivery was replaced; model handoffs are not retractable. */
|
|
59
67
|
supersedeClaimed?(db: CanvasDb, deliveryId: string): Promise<boolean>;
|
|
60
|
-
/**
|
|
68
|
+
/** Renders the object; records nothing (the caller records the read with `recordRead` afterwards). */
|
|
61
69
|
read(db: CanvasDb, reader: Reader, object: ObjectRow, opts: ReadOpts): Promise<KindRead>;
|
|
62
70
|
/** Extra fields a list or search row carries. */
|
|
63
71
|
listItem?(db: CanvasDb, object: ObjectRow): Promise<Record<string, unknown>>;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { ReposFn } from '../reader.js';
|
|
2
2
|
import type { ObjectRow, Reader } from '../types.js';
|
|
3
3
|
import type { CanvasDb } from '../../canvas/db.js';
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
import type { KindRead } from './kind.js';
|
|
5
|
+
/** Record a rendered read, after the render and in the caller's short write: the reader watches the object (a document at the
|
|
6
|
+
* heads it was shown, so a later edit still reaches it), its other watchers hear `read`, and a node saves what the render exposed to it. */
|
|
7
|
+
export declare function recordRead(db: CanvasDb, reader: Reader, object: ObjectRow, record: KindRead['record'], reposFn: ReposFn): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var d=(e,n)=>m(e,"name",{value:n,configurable:!0});import{recordMemoryReadsIn as f}from"../../canvas/memory-reads.js";import{ownerHandle as l}from"../../substrate/delivery/corpus.js";import{recordContentDelivery as p}from"../../substrate/delivery/deliver.js";import{actorOf as w}from"../documents.js";import{publish as s}from"../events.js";import{saveLedger as u}from"../exposures.js";import{getById as y}from"../objects.js";import{recordWatch as g}from"../watches.js";async function R(e,n,r,a,t){const i=w(n);if(i.id===r.id||(await g(e,i,r,"read",a===void 0?{}:{readHeadsKey:a.headsKey}),await s(e,{event:"read",object:r,actor:i,attrs:{}},t),a?.ledger===void 0||n.class!=="node"))return;await p(e,n,a.delivered,t),await u(e,a.ledger);const o=(r.kind==="knowledge"||r.kind==="preference")&&r.owner!==null?await y(e,r.owner):null;o!==null&&await f(e,n.node.id,[{name:r.name,scope:l(o),at:new Date().toISOString(),type:"read"}])}d(R,"recordRead");export{R as recordRead};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(r=>r.trim()).find(r=>r!=="")??""}
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`);for(const
|
|
4
|
-
WHERE n.parent = ? AND o.deleted_at IS NULL AND ${
|
|
5
|
-
`);return{data:
|
|
1
|
+
var f=Object.defineProperty;var l=(t,r)=>f(t,"name",{value:r,configurable:!0});import{settleMatchingControllerWait as _}from"../../canvas/waits.js";import{consumeDeadlineOnWake as T,effectiveTier as b,listenDeliveryTier as N,newId as R}from"../../feed/messages.js";import{readGoal as h}from"../../runtime/kickoff.js";import{permits as I,resolveReader as D}from"../../permissions/evaluator.js";import{objectDTO as y}from"./dto.js";import{withBase as S}from"./kind.js";import{attr as O,header as L,section as m}from"./render.js";import{mapAsync as j}from"../../async-array.js";const p=[3,5,7];function A(t){return t?.split(`
|
|
2
|
+
`).map(r=>r.trim()).find(r=>r!=="")??""}l(A,"firstLine");const F={bodyOwner:l(t=>t[0]?.id??null,"bodyOwner"),async enqueue(t,r,a){const d=Date.now(),i=r.senderNodeId,o=a.map(e=>e.id),c=`(${o.map(()=>"?").join(",")})`,u=i===null?new Set:new Set((await t.prepareUncached(`SELECT DISTINCT node_id FROM waits WHERE kind = 'controller' AND target_id = ? AND satisfied_at IS NULL AND node_id IN ${c}`).all(i,...o)).map(e=>e.node_id)),n=new Set((await t.prepareUncached(`SELECT DISTINCT anchor_node FROM crons WHERE cancel_on_wake = 1 AND anchor_node IN ${c}`).all(...o)).map(e=>e.anchor_node)),w=t.prepare(`INSERT INTO deliveries (delivery_id, message_id, destination_id, urgency, wake, state, created_at, updated_at, idempotency_key)
|
|
3
|
+
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`);for(const e of a){const s=N(e.delivery),v=e.reception===2?s.wake:0,E=r.elevatesTier?await b(e.id,s.urgency):s.urgency;await w.run(R(),r.messageId,e.id,E,v,d,d,r.idempotencyKey===void 0?null:`${r.idempotencyKey}:${e.id}`),u.has(e.id)&&await _(e.id,i,d,t),v===1&&E!=="deferred"&&n.has(e.id)&&await T(e.id)}}},H={name:"node",addressable:"id",receiver:"inbox",receiverFor:l(async(t,r,a)=>a??await t.prepare("SELECT 1 FROM peer_stubs WHERE object = ?").get(r.id)!==void 0?"peer":"inbox","receiverFor"),events:S({configured:{level:1,durable:!0},messaged:{level:2,durable:!0},sent:{level:1,durable:!0},"report.update":{level:5,levels:p,durable:!0,carriesBody:!0,elevatesTier:!0},"report.final":{level:7,durable:!0,carriesBody:!0,elevatesTier:!0,inboxKind:"final"},outcome:{level:1,durable:!0,supersedes:!0,carriesBody:!0},"report.result":{level:5,durable:!0,carriesBody:!0,elevatesTier:!0,inboxKind:"completed"},"notice.crash":{level:5,levels:p,durable:!0,carriesBody:!0,elevatesTier:!0},"notice.deadline":{level:5,levels:p,durable:!0,carriesBody:!0,elevatesTier:!0},"notice.close":{level:5,levels:p,durable:!0,carriesBody:!0,elevatesTier:!0}}),async read(t,r,a){const d=await t.prepare("SELECT status FROM nodes WHERE node_id = ?").get(a.id),i=await I(t,await D(t,r),"read","o"),o=l(async e=>await j(e,async s=>await y(t,s)),"visible"),c=await t.prepareUncached(`SELECT o.* FROM nodes n JOIN objects o ON o.id = n.node_id
|
|
4
|
+
WHERE n.parent = ? AND o.deleted_at IS NULL AND ${i.sql} ORDER BY o.seq`).all(a.id,...i.params),u=await t.prepareUncached(`SELECT o.* FROM objects o WHERE o.owner = ? AND o.deleted_at IS NULL AND ${i.sql} ORDER BY o.seq`).all(a.id,...i.params),n={status:d?.status??"deleted",mandate_first_line:A(await h(a.id)),children:await o(c),owned:await o(u.filter(e=>e.type!=="job")),jobs:await o(u.filter(e=>e.type==="job"))},w=[L("object",await y(t,a),O("status",n.status)),`Mandate: ${n.mandate_first_line}`,...m("Children",n.children),...m("Owns",n.owned),...m("Jobs",n.jobs)].join(`
|
|
5
|
+
`);return{data:n,text:w}}};export{F as nodeInbox,H as nodeKind};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);return{data:
|
|
1
|
+
var o=Object.defineProperty;var d=(n,i)=>o(n,"name",{value:i,configurable:!0});import{objectDTO as p}from"./dto.js";import{withBase as m}from"./kind.js";import{header as c}from"./render.js";function a(n){return{name:n,addressable:"handle",events:m(),async read(i,l,e){const r=await i.prepare("SELECT scheme, external_id FROM identities WHERE object = ?").get(e.id),t={handle:e.name,display_name:e.preview||e.name,identity:{scheme:r?.scheme??"",external_id:r?.external_id??""}},s=[c("object",await p(i,e)),`Handle: ${t.handle}`,`Display name: ${t.display_name}`,`Identity: ${t.identity.scheme}:${t.identity.external_id}`].join(`
|
|
2
|
+
`);return{data:t,text:s}}}}d(a,"ownerKind");const f=[a("person"),a("app"),a("repo"),a("profile"),a("group")];export{f as ownerKinds};
|
|
@@ -14,6 +14,9 @@ export declare function buildProjectContextBlock(cwd: string): string;
|
|
|
14
14
|
* every node, rendered as the `## Your documents and context directory`
|
|
15
15
|
* subsection of <crtr-bearings>. */
|
|
16
16
|
export declare function contextDirNote(nodeId: string, grantee?: string): string;
|
|
17
|
+
/** Where the node's engine and shell run, by the runner of its latest execution. A cloud sandbox is not the person's
|
|
18
|
+
* computer, so a path from their Mac (a pasted screenshot's temp file, a `/Users/...` path) does not exist there. */
|
|
19
|
+
export declare function whereYouRunNote(runner: 'process' | 'blaxel' | 'machine' | undefined): string;
|
|
17
20
|
/** The profile-purview note — rendered ONLY when the profile resolves to a
|
|
18
21
|
* manifest that names at least one project dir. Phrased as PURVIEW, not a cwd
|
|
19
22
|
* replacement: the node's cwd is still its one working dir (bash/edits run
|