@north-light/cli 0.3.711 → 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/graph/reader.js +3 -3
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/permissions/evaluator.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/machine-daemon.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/graph/reader.js +7 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +12 -6
- 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,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
content unavailable: ${o.unavailable}`,data:{...f,content:"markdown"in o?"live":"unavailable"}}})}u(ct,"read");function te(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}}u(te,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await ze(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await Ve(e)).join(", ")}`,received:t});return}return t}}u(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}u(je,"limitOf");function _e(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!q(n)||Object.values(n).some(a=>!q(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}u(_e,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}u(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await N(),t.get("type"),n),i=te(t.get("privacy"),"privacy",Ae,n),r=je(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const s=t.get("deleted");s!==null&&!["0","1","true","false"].includes(s)&&n.push({field:"deleted",problem:"must be true or false",received:s});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const l=_e(t.get("extensions"),n),f=ke(t.get("schema_type"),n);return n.length>0&&U("object list request",n),await R(e.principal),await v(async w=>{const b=await T(w,e),_={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...l?{extensions:l}:{},...f?{schemaType:f}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},g=t.get("owner");if(g!==null){const m=await he(w,b,g);if(m===null)return{items:[],next_cursor:null};_.owner=m}const p=await Je(w,b,_,{limit:r,after_seq:o===null?0:Number(o)}),d=p.at(-1);return{items:await pe(w,p),next_cursor:p.length===r&&d?String(d.seq):null}})}u(ve,"listLocal");const ut={ms:3e4},lt="self",ne=u((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=P.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(at(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:ne(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}u(Oe,"remotePage");async function ft(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([P.current.machines().catch(()=>null),t])}u(ft,"machinesWithin");async function dt(e){const t=e.query.get("machine");if(!we(e.principal)||!P.current.joined()||t===lt)return await ve(Ee(e));const a=P.current.self(),i=t!==null&&F(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,s=setTimeout(()=>o.abort(),ut.ms);s.unref?.();try{const c=await ft(o.signal);if(c===null){if(i)throw new h(503,"runtime_unreachable",`The directory did not answer, so ${F(t)} cannot be listed.`,{machine:F(t)});return r}const l=u(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=l(a),w=c.filter(d=>d.machine_id!==a&&d.kind!=="device"),b=H(e);if(t!==null){if(!i)return{items:ne(r.items,f),next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null}]};const d=F(t);if(!w.some(L=>L.machine_id===d))throw new h(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await Oe(e,l(d),b,o.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:l(d).name,state:m.state,more:m.next!==null}]}}const{cursor:_,...g}=b,p=await Promise.all(w.map(d=>Oe(e,l(d.machine_id),g,o.signal)));return{items:[...ne(r.items,f),...p.flatMap(d=>d.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null},...w.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:p[m].state,more:p[m].next!==null}))]}}finally{clearTimeout(s)}}u(dt,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}u(Ee,"withoutMachine");async function wt(e){const t=[],n=q(e.body)?e.body:{};q(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(y){t.push({field:"grep",problem:`is not a valid regular expression: ${y.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await N(),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 o=je(n.limit,"limit",t,50),s=_e(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&U("object search request",t),await R(e.principal);const l=await v(async y=>{const k=await T(y,e),$e=typeof n.owner=="string"?await he(y,k,n.owner):null;return{reader:k,owner:$e}}),{reader:f,owner:w}=l;if(typeof n.owner=="string"&&w===null)return{items:[]};const b={...s?{extensions:s}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...w?{owner:w}:{}},_=await N(),g=await ue(_,f,{text:a,body:n.body===!0||typeof i=="string",...b}),p=new Set(g.map(y=>y.object.id)),m=(typeof i=="string"?(await ue(_,f,{text:i,grep:!0,...b})).filter(y=>p.has(y.object.id)):g).slice(0,o),L=await pe(_,m.map(y=>y.object));return{items:m.map((y,k)=>({object:L[k],...y.line!==void 0?{matches:[{line:y.line,text:y.text??""}]}:{}}))}}u(wt,"search");const Te=["interrupt","steer","after-turn","next-turn"],mt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function pt(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!mt.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}}u(pt,"patternsOf");function ht(e,t){if(e===void 0)return;if(!q(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 r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Te.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Te.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}u(ht,"configOf");async function Re(e){const t=await x(e);if(t!==null)throw new h(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}u(Re,"refuseStubWatch");async function ae(e,t){const n=await I(e,t)??await(async()=>{const a=await Le(e,await We(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}u(ae,"findWatcher");const E=u(()=>{throw new h(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new h(400,"invalid_request","invalid watcher_machine");if(await ae(e,t)!==null)return null;const a=P.current;let i;try{i=await a.machines()}catch{throw new h(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=F(n);return(r===a.self()||!i.some(o=>F(o.machine_id)===r))&&E(),r}u(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return E();const i=await T(e,t);if(i.class==="person")return E();let r;try{r=await S(e,i,a)}catch{return E()}const o=r.owner===null?null:await I(e,r.owner);return o===null||!await oe(e,i,o)||!await De(e,i,"link",n)||(await Me(e,n)).id===i.app.id&&!(await D(e,i,n)&&await D(e,await C(e,n),r))?E():(await J(e,t,n),{actor:i.app,object:r})}u(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await T(e,t),i=n.owner===null?null:await I(e,n.owner);return i!==null&&await oe(e,a,i)&&await Ge(e,a,n)}u(Ie,"ownsWatcher");async function yt(e){const t=O(e),n=q(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Re(t),typeof n.watcher!="string"){const i=await ee(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw me(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw z(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Y(i.body,i.machine)}}const a=await qe(await N(),n.watcher,n.watcher_machine);return await bt(e,a)}u(yt,"watch");async function bt(e,t=null){const n=[],a=e.body===void 0?{}:q(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=pt(a.patterns,n),r=ht(a.config,n);return a.filter!==void 0&&!q(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&&U("watch request",n),await R(e.principal),await v(async o=>{const s=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new h(404,"not_found","watcher not found");const c=i??[">"],l={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(s){const _=a.watcher,g=t===null?null:await gt(o,e,_,t),p=g??(e.publishToken?await se(o,_):await ae(o,_));if(p===null)return E();if(g===null&&await Ie(o,e,p)){const L=await ce(o,e,p);await J(o,e,p);const y=await C(o,p),k=await S(o,y,O(e));if(!await D(o,y,k))throw new h(404,"not_found","object not found");return await M(o,p,k,"act",l),await G(o,p,k),await B(o,{event:"watched",object:k,actor:L,attrs:{}},await A(o)),{object:await $(o,k,await j(o,k)),patterns:c}}const{actor:d,object:m}=await Ne(o,e,p,O(e));return await M(o,p,m,"act",{...l,linkApp:d}),await G(o,p,m),await B(o,{event:"watched",object:m,actor:d,attrs:{}},await A(o)),{object:await $(o,m,await j(o,m)),patterns:c}}const f=await T(o,e),w=await Q(o,e)??ie(f),b=await S(o,f,O(e));return await M(o,w,b,"ask",l),await G(o,w,b),await B(o,{event:"watched",object:b,actor:w,attrs:{}},await A(o)),{object:await $(o,b,await j(o,b)),patterns:c}})}u(bt,"watchLocal");async function gt(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?E():await tt(e,n,a)}u(gt,"ensureNodeStubFor");async function Se(e,t,n,a){const i=u(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"),r=await i();await
|
|
1
|
+
var Ae=Object.defineProperty;var s=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{ApiError as j}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Fe}from"../../../api/dto/objects.js";import{openDb as T,withCanvasWrite as v}from"../../../core/canvas/db.js";import{actorOf as ae}from"../../../core/graph/documents.js";import{readerForObject as P,readerFor as We}from"../../../core/graph/reader.js";import{resolveName as Le,stubsNamed as Pe,unwrapRef as ie}from"../../../core/graph/names.js";import{shareReads as Ce}from"../../../core/permissions/evaluator.js";import{canRead as C,holdsObjectsScope as De,spaceOf as Me}from"../../../core/graph/access.js";import{customReachable as Ge,mayActAs as re}from"../../../core/graph/custom.js";import{customObjectRef as oe,authorizeCustom as se,fenceArgv as J}from"./custom-objects.js";import{edgesOf as Ue}from"../../../core/graph/edges.js";import{publish as B}from"../../../core/graph/events.js";import{objectDTO as He}from"../../../core/graph/kinds/dto.js";import{isKind as ze,kindNames as Ve,kindOf as ce}from"../../../core/graph/kinds/registry.js";import{recordRead as Je}from"../../../core/graph/kinds/live-read.js";import{listObjects as Be,searchObjects as ue}from"../../../core/graph/objects.js";import{checkoutsForCwd as Ke}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as D,unwatch as Ze,watchersOf as Qe,watchesOf as Ye}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as M,settleObjectWaitForUnwatch as Xe}from"../../../core/graph/object-waits.js";import{readerFor as q,resolveRef as K,warmReaderRepos as N}from"../reader.js";import{readDelegationFor as le,runReadLeaf as xe}from"../../plugin-objects/read-leaf.js";import{invalidRequest as G,isRecord as I}from"./validate.js";import{callerNode as de,callerStub as Z,forwardNamed as et,forwardVerb as fe,originates as we,queryWithoutMachine as U,relayError as H,remoteStub as tt,unknownError as me,forwarding as L,withMachine as Q}from"../../peer/forward.js";import{getById as S}from"../../../core/graph/objects.js";import{ensureNodeStub as nt,isStub as Y,stubOf as at,withKindDecl as z}from"../../../core/peer/stubs.js";import{isUnreachable as it}from"../../../core/peer/client.js";import{normalizeMachineId as A}from"../../../core/peer/directory.js";import{mapAsync as rt}from"../../../core/async-array.js";const F=s(async e=>async(t,n)=>await Ke(e,t,n),"reposFnFor");async function k(e,t){return{...await He(e,t),...t.type==="document"?{schema_type:t.schema_type??null}:{}}}s(k,"objectDTO");async function ot(e,t){const n=t.filter(r=>r.type==="document").map(r=>r.id),a=new Map;if(n.length===0)return a;const i=await e.prepareUncached(`SELECT object, extensions_json FROM documents WHERE object IN (${n.map(()=>"?").join(", ")})`).all(...n);for(const r of i)r.extensions_json!==null&&a.set(r.object,JSON.parse(r.extensions_json));return a}s(ot,"extensionsOf");async function pe(e,t){const n=await ot(e,t);return await rt(t,async a=>({...await k(e,a),...await(await ce(e,a.type)).listItem?.(e,a),...a.type==="document"?{extensions:n.get(a.id)??{}}:{}}))}s(pe,"listItems");function st(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}s(st,"remoteMessage");async function he(e,t,n){try{return await $(e,t,n)}catch(a){if(a instanceof j&&a.code==="not_found"&&!a.details?.deleted)return null;throw a}}s(he,"ownerFilter");async function $(e,t,n){const a=await K(e,t,n);if("remote"in a)throw new j(404,"not_found",st(a.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in a)throw new j(404,"not_found",`${a.deleted.name} is deleted`,{id:a.deleted.id,deleted:!0});return a}s($,"liveRef");const E=s(e=>decodeURIComponent(e.params.ref),"refParam"),ye=s(e=>{const t=ie(e),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");async function X(e){const t=await S(await T(),ye(e));return t!==null&&await Y(await T(),t)?t.id:null}s(X,"stubIdOf");async function ct(e,t){const n=await X(e);return n!==null?{stub:n,hit:!0}:(await N(t.principal),await v(async a=>{try{const i=await q(a,t),r=s(async()=>{const u=await Pe(a,i,e);if(u.length>1)throw new j(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:u.map(c=>c.id),next:"Read one by its object id."});return{stub:u[0]?.id??null,hit:!1}},"named");let o;try{o=await K(a,i,e)}catch(u){if(u instanceof j&&u.code==="not_found")return await r();throw u}if("remote"in o)return await r();if("deleted"in o){const u=await r();return u.stub===null?{stub:null,hit:!0}:u}return{stub:await Y(a,o)?o.id:null,hit:!0}}catch(i){if(i instanceof j&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}}))}s(ct,"resolvedLocally");async function x(e,t,n){const a=await ct(t,e);if(a.stub!==null)return fe(e,a.stub,n);if(a.hit||!we(e.principal))return{kind:"local"};const i=await fe(e,ye(t),n);return i.kind==="local"&&ie(t).includes("/")?et(e,n,{method:"GET",path:V(t),query:U(e)}):i}s(x,"forwardRef");const V=s(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,n,a,i){const r=t?.object;!r?.id||!r.type||await v(async o=>{const u=await de(o,e);if(u===null)return;const c=await tt(o,r.id,r.type,n,{kind:r.kind??null,name:r.name??r.id,...r.preview===void 0?{}:{preview:r.preview},owner:r.owner??null,...r.kind_decl===void 0?{}:{kind_decl:r.kind_decl},...r.privacy===void 0?{}:{privacy:r.privacy}});await D(o,u,c,a,i===void 0?{}:{patterns:i}),a==="ask"&&await M(o,u,c)})}s(be,"watchRemote");async function ut(e){const t=E(e),n=["1","true"].includes(e.query.get("fields")??""),a=s(async d=>{const m=await Z(d,e);return Ce(m===null?await q(d,e):await P(d,m,await F(d)))},"readerOf"),i=s(async(d,m,f)=>{const l=await S(d,f);if(l===null||l.deleted_at===null&&!await C(d,m,l))throw new j(404,"not_found","object not found");return l.deleted_at===null?l:{state:"deleted",deleted:await k(d,l)}},"stillReadable"),r=s(async(d,m,f)=>await(await ce(d,f.type)).read(d,m,f,{fields:n,reposFn:await F(d)}),"render"),o=s(async(d,m,{data:f,text:l,record:O})=>await v(async p=>{const g=await i(p,d,m);return"state"in g?g:(await Je(p,d,g,O,await F(p)),{state:"object",type:g.type,object:await z(p,g,await k(p,g)),text:l,data:f})}),"recorded"),u=s(async d=>{await N(e.principal);const m=await T(),f=await v(a),l=await K(m,f,t).catch(p=>{if(d||p instanceof j&&p.code==="ambiguous_name")throw p;return null});if(l===null||!d&&!("id"in l))return null;if("remote"in l)return{state:"remote",remote:l.remote};if("deleted"in l)return{state:"deleted",deleted:await k(m,l.deleted)};const O=await le(m,l);return O!==null?{delegate:O,hitId:l.id}:await o(f,l.id,await r(m,f,l))},"local"),c=(await X(t)===null?await u(!1):null)??await x(e,t,{method:"GET",path:V(t),query:U(e)}).then(async d=>{if(d.kind==="local")return await u(!0);if(d.kind==="unknown")return{state:"unknown",ref:t,unreachable:d.unreachable};if(d.status>=400)throw H(d.status,d.body);return await be(e,d.body,d.machine.id,"read").then(()=>Q(d.body,d.machine))});if(!("delegate"in c))return c;const w=await xe(c.delegate,e.principal);await N(e.principal);const h=await T(),y=await v(a),b=await i(h,y,c.hitId);if("state"in b)return b;const _=await o(y,b.id,await r(h,y,b));return _.state!=="object"||await le(h,b)===null?_:{..._,text:"markdown"in w?w.markdown:`${_.text}
|
|
2
|
+
content unavailable: ${w.unavailable}`,data:{..._.data,content:"markdown"in w?"live":"unavailable"}}}s(ut,"read");function ee(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}}s(ee,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await ze(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await Ve(e)).join(", ")}`,received:t});return}return t}}s(ge,"kindName");function _e(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}s(_e,"limitOf");function je(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!I(n)||Object.values(n).some(a=>!I(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}s(je,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}s(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await T(),t.get("type"),n),i=ee(t.get("privacy"),"privacy",Fe,n),r=_e(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const u=t.get("deleted");u!==null&&!["0","1","true","false"].includes(u)&&n.push({field:"deleted",problem:"must be true or false",received:u});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const w=je(t.get("extensions"),n),h=ke(t.get("schema_type"),n);return n.length>0&&G("object list request",n),await N(e.principal),await v(async y=>{const b=await q(y,e),_={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...u==="1"||u==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...w?{extensions:w}:{},...h?{schemaType:h}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},d=t.get("owner");if(d!==null){const l=await he(y,b,d);if(l===null)return{items:[],next_cursor:null};_.owner=l}const m=await Be(y,b,_,{limit:r,after_seq:o===null?0:Number(o)}),f=m.at(-1);return{items:await pe(y,m),next_cursor:m.length===r&&f?String(f.seq):null}})}s(ve,"listLocal");const lt={ms:3e4},dt="self",te=s((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=L.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(it(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:te(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}s(Oe,"remotePage");async function ft(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([L.current.machines().catch(()=>null),t])}s(ft,"machinesWithin");async function wt(e){const t=e.query.get("machine");if(!we(e.principal)||!L.current.joined()||t===dt)return await ve(Ee(e));const a=L.current.self(),i=t!==null&&A(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,u=setTimeout(()=>o.abort(),lt.ms);u.unref?.();try{const c=await ft(o.signal);if(c===null){if(i)throw new j(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return r}const w=s(f=>({id:f,name:c.find(l=>l.machine_id===f)?.name??f}),"labelOf"),h=w(a),y=c.filter(f=>f.machine_id!==a&&f.kind!=="device"),b=U(e);if(t!==null){if(!i)return{items:te(r.items,h),next_cursor:r.next_cursor,machines:[{machine_id:a,name:h.name,state:"ok",more:r.next_cursor!==null}]};const f=A(t);if(!y.some(O=>O.machine_id===f))throw new j(404,"not_found",`no machine ${f} on your account`,{machine:f});const l=await Oe(e,w(f),b,o.signal);return{items:l.items,next_cursor:l.next,machines:[{machine_id:f,name:w(f).name,state:l.state,more:l.next!==null}]}}const{cursor:_,...d}=b,m=await Promise.all(y.map(f=>Oe(e,w(f.machine_id),d,o.signal)));return{items:[...te(r.items,h),...m.flatMap(f=>f.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:h.name,state:"ok",more:r.next_cursor!==null},...y.map((f,l)=>({machine_id:f.machine_id,name:f.name,state:m[l].state,more:m[l].next!==null}))]}}finally{clearTimeout(u)}}s(wt,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}s(Ee,"withoutMachine");async function mt(e){const t=[],n=I(e.body)?e.body:{};I(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(p){t.push({field:"grep",problem:`is not a valid regular expression: ${p.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await T(),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 o=_e(n.limit,"limit",t,50),u=je(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&G("object search request",t),await N(e.principal);const w=await v(async p=>{const g=await q(p,e),$e=typeof n.owner=="string"?await he(p,g,n.owner):null;return{reader:g,owner:$e}}),{reader:h,owner:y}=w;if(typeof n.owner=="string"&&y===null)return{items:[]};const b={...u?{extensions:u}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...y?{owner:y}:{}},_=await T(),d=await ue(_,h,{text:a,body:n.body===!0||typeof i=="string",...b}),m=new Set(d.map(p=>p.object.id)),l=(typeof i=="string"?(await ue(_,h,{text:i,grep:!0,...b})).filter(p=>m.has(p.object.id)):d).slice(0,o),O=await pe(_,l.map(p=>p.object));return{items:l.map((p,g)=>({object:O[g],...p.line!==void 0?{matches:[{line:p.line,text:p.text??""}]}:{}}))}}s(mt,"search");const Re=["interrupt","steer","after-turn","next-turn"],pt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function ht(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!pt.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}}s(ht,"patternsOf");function yt(e,t){if(e===void 0)return;if(!I(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 r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Re.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Re.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}s(yt,"configOf");async function Te(e){const t=await X(e);if(t!==null)throw new j(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}s(Te,"refuseStubWatch");async function ne(e,t){const n=await S(e,t)??await(async()=>{const a=await Le(e,await We(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}s(ne,"findWatcher");const R=s(()=>{throw new j(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new j(400,"invalid_request","invalid watcher_machine");if(await ne(e,t)!==null)return null;const a=L.current;let i;try{i=await a.machines()}catch{throw new j(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=A(n);return(r===a.self()||!i.some(o=>A(o.machine_id)===r))&&R(),r}s(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return R();const i=await q(e,t);if(i.class==="person")return R();let r;try{r=await $(e,i,a)}catch{return R()}const o=r.owner===null?null:await S(e,r.owner);return o===null||!await re(e,i,o)||!await De(e,i,"link",n)||(await Me(e,n)).id===i.app.id&&!(await C(e,i,n)&&await C(e,await P(e,n),r))?R():(await J(e,t,n),{actor:i.app,object:r})}s(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await q(e,t),i=n.owner===null?null:await S(e,n.owner);return i!==null&&await re(e,a,i)&&await Ge(e,a,n)}s(Ie,"ownsWatcher");async function bt(e){const t=E(e),n=I(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Te(t),typeof n.watcher!="string"){const i=await x(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw me(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw H(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Q(i.body,i.machine)}}const a=await qe(await T(),n.watcher,n.watcher_machine);return await gt(e,a)}s(bt,"watch");async function gt(e,t=null){const n=[],a=e.body===void 0?{}:I(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=ht(a.patterns,n),r=yt(a.config,n);return a.filter!==void 0&&!I(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&&G("watch request",n),await N(e.principal),await v(async o=>{const u=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!u)throw new j(404,"not_found","watcher not found");const c=i??[">"],w={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(u){const _=a.watcher,d=t===null?null:await _t(o,e,_,t),m=d??(e.publishToken?await oe(o,_):await ne(o,_));if(m===null)return R();if(d===null&&await Ie(o,e,m)){const O=await se(o,e,m);await J(o,e,m);const p=await P(o,m),g=await $(o,p,E(e));if(!await C(o,p,g))throw new j(404,"not_found","object not found");return await D(o,m,g,"act",w),await M(o,m,g),await B(o,{event:"watched",object:g,actor:O,attrs:{}},await F(o)),{object:await z(o,g,await k(o,g)),patterns:c}}const{actor:f,object:l}=await Ne(o,e,m,E(e));return await D(o,m,l,"act",{...w,linkApp:f}),await M(o,m,l),await B(o,{event:"watched",object:l,actor:f,attrs:{}},await F(o)),{object:await z(o,l,await k(o,l)),patterns:c}}const h=await q(o,e),y=await Z(o,e)??ae(h),b=await $(o,h,E(e));return await D(o,y,b,"ask",w),await M(o,y,b),await B(o,{event:"watched",object:b,actor:y,attrs:{}},await F(o)),{object:await z(o,b,await k(o,b)),patterns:c}})}s(gt,"watchLocal");async function _t(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?R():await nt(e,n,a)}s(_t,"ensureNodeStubFor");async function Se(e,t,n,a){const i=s(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"),r=await i();await Ze(e,t,n,a??void 0);const o=await i();return o===0&&await Xe(e,t,n),{object:await k(e,n),removed:r-o}}s(Se,"dropWatch");async function jt(e){const t=E(e);if(e.query.get("watcher")&&await Te(t),!e.query.get("watcher")){const a=await x(e,t,{method:"DELETE",path:`${V(t)}/watch`,query:U(e)});if(a.kind==="unknown")throw me(t,a.unreachable);if(a.kind==="remote"){const i=a.status===404?a.body.error?.details:void 0,r=i?.deleted===!0?i.id:void 0;if(a.status>=400&&r===void 0)throw H(a.status,a.body);const o=r??a.body.object?.id,u=await v(async c=>{const w=await de(c,e),h=o===void 0?null:await S(c,o);return w===null||h===null||!await Y(c,h)?null:await Se(c,w,h,e.query.get("pattern"))});if(r!==void 0){if(u===null)throw H(a.status,a.body);return{...u,machine:a.machine}}return Q(a.body,a.machine)}}const n=await qe(await T(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await kt(e,n)}s(jt,"unwatchRoute");async function kt(e,t=null){const n=e.query.get("pattern"),a=e.query.get("watcher");return await N(e.principal),await v(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!a)throw new j(404,"not_found","watcher not found");const r=s(async(c,w)=>await Se(i,c,w,n),"drop");if(a){const c=t===null?null:await(async()=>{const h=await S(i,a);return h!==null&&await at(i,h)!==null?h:null})();if(t!==null&&c===null)return R();const w=c??(e.publishToken?await oe(i,a):await ne(i,a));return w===null?R():c===null&&await Ie(i,e,w)?(await se(i,e,w),await J(i,e,w),await r(w,await $(i,await P(i,w),E(e)))):await r(w,(await Ne(i,e,w,E(e))).object)}const o=await q(i,e),u=await Z(i,e)??ae(o);return await r(u,await $(i,o,E(e)))})}s(kt,"unwatchLocal");async function vt(e){const t=[],n=ee(e.query.get("type"),"type",["acted-on","links-to","watches"],t),a=ee(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&G("edges request",t),await N(e.principal),await v(async i=>{const r=await q(i,e),o=await $(i,r,E(e)),u=[];if(n!=="watches")for(const c of await Ue(i,r,o,{...n?{type:n}:{},direction:a??"both"}))u.push({type:c.type,src:await k(i,c.src),dst:await k(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...a!=="in"?await Ye(i,r,o):[],...a!=="out"?await Qe(i,r,o):[]];for(const w of c)u.push({type:"watches",src:await k(i,w.watcher),dst:await k(i,w.object)})}return{items:u}})}s(vt,"edges");const W=s(e=>async t=>({status:200,body:await e(t)}),"ok"),xt=[{method:"POST",pattern:"/v1/objects/search",handler:W(mt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:W(vt)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:W(bt)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:W(jt)},{method:"GET",pattern:"/v1/objects/:ref",handler:W(ut)},{method:"GET",pattern:"/v1/objects",handler:W(wt)}];export{lt as listBudget,xt as objectRoutes,ct as resolvedLocally};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var s=(n,e)=>g(n,"name",{value:e,configurable:!0});import{ApiError as p}from"../../../api/index.js";import{isCloudRole as R}from"../../../core/canvas/person.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{readDocument as q}from"../../../core/graph/documents.js";import{
|
|
1
|
+
var g=Object.defineProperty;var s=(n,e)=>g(n,"name",{value:e,configurable:!0});import{ApiError as p}from"../../../api/index.js";import{isCloudRole as R}from"../../../core/canvas/person.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{readDocument as q}from"../../../core/graph/documents.js";import{recordRead as S}from"../../../core/graph/kinds/live-read.js";import{getById as E}from"../../../core/graph/objects.js";import{checkoutsForCwd as T}from"../../../core/graph/repo-sync/repos.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{assertScope as C}from"../../../core/scopes.js";import{createReview as A}from"../../../core/review/birth.js";import{readAnchorBase as $,listReviews as I,requireVisibleReview as b}from"../../../core/review/store.js";import{canvasOrigin as D}from"../canvas-host.js";import{cancelReview as O,submitReviewApproval as L}from"../../review/finish.js";import{toFeedbackResultDTO as F,toReviewDTO as N}from"../map.js";import{readerFor as P,resolveRef as j,warmReaderRepos as B}from"../reader.js";import{actsAsPerson as G,canReadNode as V}from"../router.js";import{invalidRequest as K,objectBody as v,optionalString as c,requireParam as W,requiredString as y}from"./validate.js";import{filterAsync as M}from"../../../core/async-array.js";const U=new Set(["open","approved","canceled"]),z=["origin_kind","origin_node_id","document","idempotency_key","subtitle","output_path"],H=["reason","actor","disposition"];function l(n){K("review request",n)}s(l,"invalidRequest");function w(n,e){return W(n,"review_id","must be a safe review id",h,e)}s(w,"requireReviewId");function m(n){return{...N(n,n.state==="approved"?{result_path:`${n.review_dir}/result.json`}:{}),review_dir:n.review_dir}}s(m,"toReviewResponseDTO");function J(n){const e=[],i=v(n.body,z,e),o=i.origin_kind,t=o==="ticket"||o==="inline"?o:void 0;t===void 0&&e.push({field:"origin_kind",problem:"must be ticket or inline",...o===void 0?{}:{received:o}});const r=y(i,"origin_node_id",e);r!==void 0&&!h(r)&&e.push({field:"origin_node_id",problem:"must be a safe node id",received:r});const d=c(i,"document",e);d===void 0&&e.push({field:"document",problem:"is required"});const a=y(i,"idempotency_key",e);a!==void 0&&a.length>128&&e.push({field:"idempotency_key",problem:"must be at most 128 characters",received:a});const f=c(i,"subtitle",e),u=c(i,"output_path",e);return t==="ticket"&&f===void 0&&i.subtitle===void 0&&e.push({field:"subtitle",problem:"is required for ticket reviews"}),t==="inline"&&i.subtitle!==void 0&&e.push({field:"subtitle",problem:"is only allowed for ticket reviews",received:i.subtitle}),t==="inline"&&i.output_path!==void 0&&e.push({field:"output_path",problem:"is only allowed for ticket reviews",received:i.output_path}),u!==void 0&&R()&&e.push({field:"output_path",problem:"is not supported on the cloud: a review result is projected only to its own request files",received:u}),(e.length>0||t===void 0||r===void 0||d===void 0||!h(r)||a===void 0||a.length>128)&&l(e),{origin_kind:t,origin_node_id:r,document:d,idempotency_key:a,...f===void 0?{}:{subtitle:f},...u===void 0?{}:{output_path:u}}}s(J,"parseCreate");function Q(n){const e=[],i={},o=new Set(["state","origin_node_id","file"]);for(const[t,r]of n.query.entries())o.has(t)||e.push({field:t,problem:"is not allowed",received:r});for(const t of o){const r=n.query.getAll(t);if(r.length>1){e.push({field:t,problem:"must appear at most once",received:r});continue}const d=r[0];d!==void 0&&(t==="state"?U.has(d)?i.state=d:e.push({field:t,problem:"must be open, approved, or canceled",received:d}):t==="origin_node_id"?h(d)?i.origin_node_id=d:e.push({field:t,problem:"must be a safe node id",received:d}):d===""?e.push({field:t,problem:"must be a non-empty string",received:d}):i.file=d)}return e.length>0&&l(e),i}s(Q,"parseList");function X(n,e){const i=n.body===void 0?{}:v(n.body,H,e),o=c(i,"reason",e),t=c(i,"actor",e),r=c(i,"disposition",e);return r!==void 0&&r!=="canceled"&&r!=="dismissed"&&e.push({field:"disposition",problem:'must be "canceled" or "dismissed"',received:r}),{...o===void 0?{}:{reason:o},...t===void 0?{}:{actor:t},...r==="canceled"||r==="dismissed"?{disposition:r}:{}}}s(X,"parseCancel");function Y(n,e){v(n.body,[],e)}s(Y,"requireEmptyBody");async function Z(n){const e=J(n);if(D()===void 0)throw new p(409,"no_canvas_host","this runtime has no canvas host to serve the review page",{next:"Reviews open in the browser at the canvas host (`CRTR_CANVAS_URL`); file this review from a cloud runtime."});const i=await _(e.origin_node_id);i!==null&&C(i,"crtr:act");const{document:o,...t}=e,r=await A({...t,document:await x(n,o)});return{status:200,body:m(r)}}s(Z,"handleCreate");async function x(n,e){return await B(n.principal),await k(async i=>{const o=await P(i,n),t=await j(i,o,e);if("remote"in t)throw new p(404,"not_found",`no document named ${t.remote} on this runtime`,{next:"Check the name with `crtr canvas search`."});if("deleted"in t)throw new p(404,"not_found",`${t.deleted.name} is deleted`,{id:t.deleted.id,deleted:!0});if(t.type!=="document")throw new p(400,"invalid_request",`${e} is a ${t.type}, not a document`);const r=await q(i,o,t);if(await S(i,o,t,{headsKey:r.record.heads_key,delivered:[]},async(f,u)=>await T(i,f,u)),r.needsMerge)throw new p(409,"needs_merge",`${t.name} has ${r.heads.length} heads; merge them before a review`,{id:t.id,next:`Read it with \`crtr canvas read ${t.id}\` and write the merged body with \`crtr doc edit\`.`});const d=t.owner===null?null:await E(i,t.owner),a=d===null?"":d.type==="node"?d.id:d.name;return{id:t.id,name:a===""?t.name:`${a}/${t.name}`,base:r.record.heads_key,body:r.heads[0].body}})}s(x,"reviewedDocument");async function ee(n){const e=Q(n);return{status:200,body:{reviews:(await M(await I(e),async o=>{if(G(n.principal))return!0;const t=await _(o.origin_node_id);return t!==null&&await V(n.principal,t.grantee??"app:terminal",t.node_id)})).map(m)}}}s(ee,"handleList");async function te(n){const e=[],i=w(n,e);return(e.length>0||i===void 0)&&l(e),{status:200,body:m(await b(i))}}s(te,"handleRead");async function ie(n){const e=[],i=w(n,e);Y(n,e),(e.length>0||i===void 0)&&l(e);const o=await L(i);return{status:200,body:o.outcome==="awaiting_companion"?{review:m(o.record),outcome:o.outcome}:{review:m(o.record),result:F(o.result),outcome:o.outcome}}}s(ie,"handleSubmit");async function ne(n){const e=[],i=w(n,e),o=X(n,e);(e.length>0||i===void 0)&&l(e);const t=await O(i,o);return{status:200,body:{review:m(t.record),outcome:t.outcome}}}s(ne,"handleCancel");async function oe(n){const e=[],i=w(n,e);(e.length>0||i===void 0)&&l(e);const o=await b(i),t=await $(o.review_id);if(t===null)throw new Error(`review anchor base is missing: ${o.review_id}`);return{status:200,body:{review_id:o.review_id,anchor_base_sha256:t.sha256,anchor_base_text:new TextDecoder("utf-8",{fatal:!0}).decode(t.bytes),file:o.file}}}s(oe,"handleDocument");const Se=[{method:"POST",pattern:"/v1/human/reviews",scope:"crtr:act",handler:Z},{method:"GET",pattern:"/v1/human/reviews",handler:ee},{method:"GET",pattern:"/v1/human/reviews/:review_id",handler:te},{method:"POST",pattern:"/v1/human/reviews/:review_id/submit",handler:ie},{method:"POST",pattern:"/v1/human/reviews/:review_id/cancel",handler:ne},{method:"GET",pattern:"/v1/human/reviews/:review_id/document",handler:oe}];export{J as parseCreate,Se as reviewRoutes};
|
package/dist/daemon/api/map.d.ts
CHANGED
|
@@ -155,6 +155,12 @@ export declare function errorToStatus(thrown: unknown): {
|
|
|
155
155
|
status: number;
|
|
156
156
|
code: string;
|
|
157
157
|
};
|
|
158
|
+
/** The single-line, length-bounded cause a 500 body may safely carry. A curated
|
|
159
|
+
* `Error.message` is a diagnostic, not a raw stack trace: surfacing its first
|
|
160
|
+
* line (capped) turns an opaque `internal error` into an actionable one while
|
|
161
|
+
* still refusing to leak multi-line traces. The router logs the FULL error
|
|
162
|
+
* (with stack) server-side alongside this. */
|
|
163
|
+
export declare function boundedCause(err: unknown): string;
|
|
158
164
|
/** Build the uniform JSON error body (spec §8) for a thrown value, using
|
|
159
165
|
* `errorToStatus` for the status/code. Structured `details` are surfaced for a
|
|
160
166
|
* CrtrError or ApiError (they let the client reconstruct the error verbatim). A 500 still
|
package/dist/daemon/api/map.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var k=Object.defineProperty;var d=(e,t)=>k(e,"name",{value:t,configurable:!0});import{join as g}from"node:path";import{liveExecutionForNode as b}from"../../core/canvas/executions.js";import{readOutputResult as h}from"../../core/runtime/output-result.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as y}from"../../core/canvas/crons.js";import{isProfilePaused as x,profileDir as O,sanitizeProfileMetadata as D}from"../../core/profiles/manifest.js";import{nodeMetaPath as T,transcriptPath as E,viewSocketPath as S}from"../../core/canvas/paths.js";import{appForNode as c,contextDir as A,nodeAgentDir as R}from"../../core/canvas/node-agent-paths.js";import{readControllerWaits as N}from"../../core/canvas/waits.js";import{FinalizationError as z}from"../../core/feed/feed.js";import{NodeIdConflictError as C}from"../../core/runtime/nodes.js";import{ScopeDeniedError as j}from"../../core/scopes.js";import{isBeneathRefusal as q}from"../../core/spaces/open-beneath.js";import{CrtrError as a}from"../../core/errors.js";import{WorktreeError as F}from"../../core/worktree.js";import{ApiError as I}from"../../api/errors.js";import{RunError as s}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ve(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}d(ve,"toMigrateStateDTO");async function P(e){try{return await h(e)??null}catch{return null}}d(P,"readStructuredResult");function U(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}d(U,"toNodeOutcomeSummaryDTO");async function f(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?await P(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}d(f,"toNodeOutcomeDTO");async function ke(e){const t=await f(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}d(ke,"toRunOutcomeDTO");function ge(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}d(ge,"toOutcomeDeliveryDTO");function be(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}d(be,"toGraphNodeDTO");async function he(e,t,n){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??await c(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:n,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??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,last_settled_at:e.last_settled_at??null,outcome:U(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}d(he,"toNodeSummaryDTO");function G(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}d(G,"toNodeEdgesDTO");async function M(e,t){return{node_dir:await R(e,t),context_dir:await A(e,t),meta_path:T(e),transcript_path:E(e),view_socket:S(e)}}d(M,"toNodePathsDTO");function W(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}d(W,"toNodeWorktreeDTO");async function ye(e,t){const n=await c(e.node_id),i={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,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:x(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:(await N([e.node_id])).get(e.node_id)?.controllerId??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,runner:(await b(e.node_id))?.runner??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??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,last_settled_at:e.last_settled_at??null,outcome:await f(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:G(e,t),paths:await M(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=W(e.managed_worktree)),i}d(ye,"toNodeDetailDTO");function xe(e,t,n,i){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome,ready:i}}d(xe,"toReviveResultDTO");function Oe(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}d(Oe,"toCloseResultDTO");function De(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}d(De,"toReportResultDTO");function Te(e){return{node_id:e.node_id,active:e.active,created:e.created}}d(Te,"toSubscriptionDTO");function B(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}d(B,"envKeys");function Ee(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:B(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:y(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}d(Ee,"toCronDTO");function Se(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}d(Se,"toCronRunDTO");function Ae(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:D(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,repositories:[],profile_path:O(e.profileId)}}d(Ae,"toProfileDTO");function p(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}d(p,"toReviewDTO");function Re(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}d(Re,"toReviewCommentDTO");function L(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}d(L,"toPageFeedbackCommentDTO");function Ne(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(L)}}d(Ne,"toPageFeedbackDTO");function ze(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}d(ze,"toReviewCommentEventDTO");function Ce(e){return{document:e.document,file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}d(Ce,"toFeedbackResultDTO");const $=!0,w=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},quote_not_found:{status:409,code:"quote_not_found"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"}});function K(e){const t=m(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof z)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof C)return{status:409,code:"node_id_exists"};if(t instanceof j)return{status:403,code:"scope_denied"};if(q(t))return{status:400,code:"invalid_request"};if(t instanceof _)return w[t.code];if(t instanceof a)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:J(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}d(K,"errorToStatus");function m(e){if(!(e instanceof F))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new a(e.code,e.message,t,n)}d(m,"normalizeThrow");function V(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:H(t)}}d(V,"reviewErrorDetails");function H(e){return e.state!=="approved"?p(e):p(e,{result_path:g(e.review_dir,"result.json")})}d(H,"terminalConflictReviewDTO");function J(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}d(J,"statusForExitCode");function Q(e){const n=(e instanceof Error?e.message:String(e)).split(`
|
|
2
|
-
`,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}d(Q,"boundedCause");function je(e){const t=m(e),{status:n,code:i}=K(t);if(n>=500){const u={error:{code:i,message:Q(t),origin:"runtime"}};return t instanceof s&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),l=t instanceof _?V(t):(t instanceof a||t instanceof I||t instanceof s)&&t.details!==void 0?t.details:void 0,r={error:{code:i,message:v,origin:"runtime"}};return l!==void 0&&(r.error.details=l),t instanceof s&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}d(je,"toErrorBody");export{w as REVIEW_ERROR_MAP,K as errorToStatus,Oe as toCloseResultDTO,Ee as toCronDTO,Se as toCronRunDTO,je as toErrorBody,Ce as toFeedbackResultDTO,be as toGraphNodeDTO,ve as toMigrateStateDTO,ye as toNodeDetailDTO,G as toNodeEdgesDTO,f as toNodeOutcomeDTO,U as toNodeOutcomeSummaryDTO,M as toNodePathsDTO,he as toNodeSummaryDTO,W as toNodeWorktreeDTO,ge as toOutcomeDeliveryDTO,L as toPageFeedbackCommentDTO,Ne as toPageFeedbackDTO,Ae as toProfileDTO,De as toReportResultDTO,Re as toReviewCommentDTO,ze as toReviewCommentEventDTO,p as toReviewDTO,xe as toReviveResultDTO,ke as toRunOutcomeDTO,Te as toSubscriptionDTO};
|
|
2
|
+
`,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}d(Q,"boundedCause");function je(e){const t=m(e),{status:n,code:i}=K(t);if(n>=500){const u={error:{code:i,message:Q(t),origin:"runtime"}};return t instanceof s&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),l=t instanceof _?V(t):(t instanceof a||t instanceof I||t instanceof s)&&t.details!==void 0?t.details:void 0,r={error:{code:i,message:v,origin:"runtime"}};return l!==void 0&&(r.error.details=l),t instanceof s&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}d(je,"toErrorBody");export{w as REVIEW_ERROR_MAP,Q as boundedCause,K as errorToStatus,Oe as toCloseResultDTO,Ee as toCronDTO,Se as toCronRunDTO,je as toErrorBody,Ce as toFeedbackResultDTO,be as toGraphNodeDTO,ve as toMigrateStateDTO,ye as toNodeDetailDTO,G as toNodeEdgesDTO,f as toNodeOutcomeDTO,U as toNodeOutcomeSummaryDTO,M as toNodePathsDTO,he as toNodeSummaryDTO,W as toNodeWorktreeDTO,ge as toOutcomeDeliveryDTO,L as toPageFeedbackCommentDTO,Ne as toPageFeedbackDTO,Ae as toProfileDTO,De as toReportResultDTO,Re as toReviewCommentDTO,ze as toReviewCommentEventDTO,p as toReviewDTO,xe as toReviveResultDTO,ke as toRunOutcomeDTO,Te as toSubscriptionDTO};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=Object.defineProperty;var i=(t,r)=>F(t,"name",{value:r,configurable:!0});import{chmodSync as Y,closeSync as A,existsSync as G,mkdirSync as k,openSync as $,unlinkSync as J,writeFileSync as X,rmSync as E}from"node:fs";import{createServer as z}from"node:http";import{dirname as x,join as R}from"node:path";import{spawn as L}from"node:child_process";import{SELF_UPDATE_SCRIPT as P}from"../core/self-update.js";import{apiSocketPath as K,crtrHome as C}from"../core/canvas/paths.js";import{bindDaemonEventSource as V}from"../core/events/source.js";import{emitEvent as p}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as W}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as Q,findBrokers as Z,stopAllBrokers as q}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as ee}from"../core/checkout-identities.js";import{machineWorktreeHandlers as ne}from"../core/worktree-machine.js";import{readPersonCredential as te}from"../core/directory/person-credential.js";import{socketDir as oe}from"../core/layout.js";import{isDaemonRunning as re,pidfilePath as _,readPidfile as ie}from"./pidfile.js";import{cancelMachineCron as ae,runMachineCron as se,stopOrphanedMachineCrons as ce}from"./cron/machine-exec.js";import{startMachineLink as de}from"./machine-link/client.js";import{deleteMoveRecord as O,readMachineConfig as me,readMachineCredential as j,readMoveRecord as fe,writeMoveRecord as le}from"./machine-link/config.js";import{jobExitReporting as pe,stopMachineJob as ue}from"./machine-link/job-sweep.js";import{notifyMoveFinished as he}from"./machine-link/move-notify.js";import{machineSupervision as ve,SUPERVISION_TICK_MS as ye}from"./machine-supervision.js";import{startBrokerMemoryCap as we}from"./broker-memory-cap.js";const Se=10*6e4;let D=0;function _e(t){if(Date.now()-D<Se||!/^\d+\.\d+\.\d+$/.test(t))return;D=Date.now(),p({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const r=R(x(P),"..","bin","crtr"),a=$(R(C(),"crtrd.err"),"a");L("/bin/sh",["-c",'"$0" "$1" --version "$2" && "$0" "$3" sys daemon restart',process.execPath,P,t,r],{detached:!0,stdio:["ignore",a,a]}).unref(),A(a)}i(_e,"updateToRelease");const B=1024;function Ie(t,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:r,startup_phase:t?"ready":"recovering"}}i(Ie,"machineHealth");async function Ve(){const t=me();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=te()!==void 0;if(r&&j(),re())throw new Error("a crtrd is already running for this home");V(),r||(await q(),await ce(),p({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),k(oe(),{recursive:!0,mode:493});const a=K();G(a)&&J(a);let n;const f=pe(()=>n),s=z((e,o)=>{const c=(e.url??"").split("?")[0];if(e.method==="POST"&&(c==="/job-exit"||c==="/job-activity")){const b=[];let S=0;e.on("data",d=>{S+=d.length,S<=B&&b.push(d)}),e.on("end",()=>{if(S>B){o.writeHead(413),o.end();return}let d={};try{d=JSON.parse(Buffer.concat(b).toString("utf8"))}catch{}const T=typeof d.node=="string"&&typeof d.job=="string";o.writeHead(T?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),T&&(c==="/job-exit"?f.notice:f.activity)(d.node,d.job)});return}const M=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(M?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(M?Ie(n?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{s.once("error",o),s.listen(a,()=>{s.off("error",o),Y(a,384),e()})}),k(x(_()),{recursive:!0}),X(_(),String(process.pid),"utf8");let l;await be(t.runId,r,()=>l!==void 0);const u=new Set,v=new Set;let y=!1;const m=Q({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:i(e=>n?.reportExit(e),"onExit")}),H=i(async(e,o)=>{u.add(e.executionId);for(const c of v)c.add(e.executionId);try{return await m.start(e,o)}finally{u.delete(e.executionId)}},"start");n=r?de({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:j,onOpen:i(()=>{f.onOpen(),y=!0},"onOpen"),onBehind:_e,handlers:{start:H,wake:m.wake,stop:m.stop,status:m.status,delete:m.delete,viewer:m.viewer,"cron.run":se,"cron.cancel":ae,"job.stop":i(e=>ue(e),"job.stop"),...ne,...ee}}):void 0;const I=n===void 0?void 0:ve({link:n,brokers:i(async()=>{const e=new Set(u);v.add(e);const o=await Z().finally(()=>v.delete(e));return y&&(y=!1,n?.reportRunning([...new Set([...e,...o.filter(c=>W(c.command,C())).map(c=>c.execution)])])),o},"brokers"),stop:i((e,o)=>m.stop({execution:{executionId:e,nodeId:o,attempt:0,sandboxName:null},options:{reason:"yield_stall"}}),"stop")});let w=!1;const N=I===void 0?void 0:setInterval(()=>{w||(w=!0,I(Date.now()).catch(e=>p({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},ye),U=we();p({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}});const g=i(()=>l??=(async()=>{n?.stop(),clearInterval(N),U(),await new Promise(e=>{s.close(()=>e()),s.closeAllConnections()}),ie()===process.pid&&(E(a,{force:!0}),E(_(),{force:!0})),process.off("SIGINT",h),process.off("SIGTERM",h)})(),"teardown"),h=i(()=>{g().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",h),process.on("SIGTERM",h),g}i(Ve,"runMachineDaemon");const ge=5e3,Me=3e5;async function be(t,r,a){let n;try{n=fe()}catch(s){p({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:s.message}});return}if(n===void 0||n.state==="running"||n.runId!==t)return;if(n.notified||n.notify===null){O();return}if(n.state==="committed"&&(n={...n,state:"activated"},le(n)),!r)return;const f=n;(async()=>{let s=ge;for(;;){try{await he(f),O();return}catch(l){p({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:f.notify??"",error:l.message}})}if(await new Promise(l=>{setTimeout(l,s).unref()}),a())return;s=Math.min(s*2,Me)}})()}i(be,"settleFinishedMove");export{Ie as machineHealth,Ve as runMachineDaemon};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t
|
|
1
|
+
var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t?.runner==="process"&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,i){await this.pass(t,{rows:[e],fleet:i})}async pass(t,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,i))}catch(a){const o=n.node_id;E({level:a instanceof R?"warn":"error",event:a instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(o)?{node_id:o}:{fields:{affected_node_id:o}},error:a})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:i})}async classifyRow(t,e,i,n){const a=e.node_id;if(X(e)){if(H(e,await i.fleet.has(a)))return;if(S(e)&&!await i.fleet.has(a)&&!f(e.profile_id)&&!await I(a)&&!k(e,t)&&await m(a)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(a);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(a):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(a)){const r=await p(a);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(a))try{if(await Q(r)==="lost")return}catch(l){if(l instanceof x)return;throw l}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(a)){f(e.profile_id)?await i.fleet.interruptForProfilePause(a):await this.thawMark(e);return}}if(await K(a,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(a);return}if(await I(a))return;const o=e.pi_pid==null?await v(a):null,u=o!==null&&D(o),h=o!==null&&!u&&M(o),_=e.pi_pid!=null?await b(a):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(a)){const r=_??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const l=await p(a);if(l!==null&&l.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await m(a)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(a)||Z(e,t,await v(a)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:a}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await z(a),(await A(a))?.interrupted===!0,await U(a));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(a),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|
|
1
|
+
var W=Object.defineProperty;var h=(r,t)=>W(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as J,envNodeId as $,envProfileId as G,envWatcherDebounceMs as X,envWatcherTickMs as j,envWatcherBackstopMs as z}from"../shared/env.js";import{coalesceBrokerInbox as L,entryCards as V}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as Q,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as k}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as C}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as D,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as w,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const _=64,O=16;let b,ce=0;class H extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:j(),debounceMs:X()}}h(me,"resolveCadence");function x(){const r=$();return r===void 0||r.trim()===""?void 0:r}h(x,"currentNodeId");function U(){const r=G();return r!==void 0&&r!==""&&fe(r)}h(U,"profilePaused");function T(r){try{return oe(r)}catch{return{class:"unknown"}}}h(T,"safeErrorClass");function v(r){try{P(r)}catch{}}h(v,"emitBestEffort");function E(r){try{y.fresh(t=>{v({...r,operation_id:t})})}catch{}}h(E,"emitFreshBestEffort");function S(r,t){try{y.run(r,()=>{v({...t,operation_id:r})})}catch{}}h(S,"emitStoredBestEffort");function pe(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}h(pe,"deliveryOrigin");function I(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-O;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,O),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(I,"deliveryFacts");function g(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}h(g,"deliveryFields");function ye(r){S(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:g(r)})}h(ye,"emitDeliveryCompleted");function F(r,t,e,i){S(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:e,...g(t)}})}h(F,"emitDeliveryFailure");function M(r,t){S(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...g(r)}})}h(M,"emitDeliveryAbandoned");function ge(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
+
`):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=k(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=x();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=B(i)?be(i):"reload";B(i)||E({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=x();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),z()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof H)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&w()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=w()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&w()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await Q(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:C,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>_)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||U())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>_)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&M(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(l=>l.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)F(d.operationId,d,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),D()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
|
package/docs/ci-runner.md
CHANGED
|
@@ -36,7 +36,7 @@ gh variable set CRTR_CI_RUNNER --body self-hosted -R Northlight-Systems/crouter
|
|
|
36
36
|
gh variable delete CRTR_CI_RUNNER -R Northlight-Systems/crouter # fall back to macos-latest
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
-
It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job
|
|
39
|
+
It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job per lane that has a selected laptop-only file (`macos unit`, `macos integration`, `macos seam`), plus `macos build-output` (the macOS concurrent-build test) only when the diff reaches the build (`scripts/build*`, `atomic-swap.c`, `pack-minify.mjs`, `runtime-lock.mjs`, `ensure-native-linux.mjs`, the patch and `check-*` scripts the build runs, `package.json`, the lockfile, `runtime.lock.json`, package manifests, tsconfigs, `test.yml`; the selector's `macos_build_output` output) or when there is no release tag to diff against; they run in parallel. Each macOS lane runs only the tests tagged `laptopOnly`, not whole files (a preload, `scripts/laptop-only-filter.mjs`, skips the rest), and fails if it ran none.
|
|
40
40
|
|
|
41
41
|
### Routing: minis first, hosted when none is free
|
|
42
42
|
|
|
@@ -83,7 +83,7 @@ Installing and upgrading: get a registration token (`gh api -X POST repos/Northl
|
|
|
83
83
|
|
|
84
84
|
## No double run on `main`
|
|
85
85
|
|
|
86
|
-
`publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `checks` and every `linux` shard pass and every `macos` job passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
|
|
86
|
+
`publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `build`, `checks` and every `linux` shard pass and every `macos` job (including `macos build-output`) passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
|
|
87
87
|
|
|
88
88
|
- Rebase-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
|
|
89
89
|
- A direct push to `main`, or a merge after `main` moved (a different tree from the one the PR run tested) → no artifact → the full suite runs exactly as before. A release commit (`chore: release …`, pushed by Publish itself) changes the tree, so a PR not updated since before the latest release runs the suite once on merge; update the branch to avoid it.
|
|
@@ -116,8 +116,8 @@ The hourly `17 * * * *` schedule and the `promote`, `api_ref`, `env_docker_ref`
|
|
|
116
116
|
- Selected tests run on every push with no label. Add `full-ci` to force the whole suite (`gh pr edit <n> --add-label full-ci`). Labels other than `full-ci` start nothing and cancel nothing.
|
|
117
117
|
- On a pull request each matrix (`linux`; `macos` never runs there) is `fail-fast`: the first failing job cancels that matrix's other jobs, the matrix result is `failure`, and `full suite` still runs and is red. On main, merge queue and dispatch runs every job finishes. A Linux failure does not cancel the macOS matrix.
|
|
118
118
|
- `record tested tree` runs only in mode `full`, so a partial run never lets Publish skip the suite.
|
|
119
|
-
- The `full suite` job is the single result to require. It fails if `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
|
|
120
|
-
- `
|
|
119
|
+
- The `full suite` job is the single result to require. It fails if `build`, `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
|
|
120
|
+
- `build` builds once on ubuntu and uploads the JS output; `checks` (typecheck of examples, contract check, script tests, the concurrent-build test) runs beside the lanes on that build, and the lanes wait only for `build`. The `linux` jobs unpack it and compile the Linux native addon in the container (the build is glibc, the image musl), and the `macos` jobs unpack it as is.
|
|
121
121
|
|
|
122
122
|
## The selector: `scripts/ci-select.mjs`
|
|
123
123
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.713",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.713",
|
|
162
|
+
"@north-light/plugin": "0.3.713",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|