@north-light/cli 0.3.789 → 0.3.791

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.
Files changed (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/nodes.d.ts +0 -12
  6. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  7. package/dist/clients/attach/viewer.js +526 -526
  8. package/dist/commands/canvas-history/shared.js +1 -1
  9. package/dist/commands/node/bash.js +1 -1
  10. package/dist/commands/node/create.js +2 -2
  11. package/dist/commands/node/inspect.js +6 -6
  12. package/dist/commands/node/lifecycle.js +4 -4
  13. package/dist/commands/node-context.js +2 -2
  14. package/dist/commands/person-settings.js +1 -1
  15. package/dist/commands/profile/daemon-profiles.js +4 -4
  16. package/dist/commands/sys.js +1 -1
  17. package/dist/core/canvas/history.d.ts +2 -8
  18. package/dist/core/canvas/history.js +9 -9
  19. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  20. package/dist/core/canvas/node-agent-paths.js +1 -1
  21. package/dist/core/canvas/node-tokens.js +3 -3
  22. package/dist/core/canvas/paths.d.ts +3 -10
  23. package/dist/core/canvas/paths.js +1 -1
  24. package/dist/core/canvas/person-state.d.ts +5 -7
  25. package/dist/core/canvas/person-state.js +1 -1
  26. package/dist/core/canvas/person.d.ts +3 -30
  27. package/dist/core/canvas/person.js +1 -11
  28. package/dist/core/canvas/render-source.js +1 -1
  29. package/dist/core/config.d.ts +4 -1
  30. package/dist/core/config.js +1 -1
  31. package/dist/core/directory/join.d.ts +4 -6
  32. package/dist/core/directory/join.js +1 -1
  33. package/dist/core/grants/sync.js +1 -1
  34. package/dist/core/human/requests.d.ts +11 -1
  35. package/dist/core/human/requests.js +22 -22
  36. package/dist/core/providers/files.js +1 -1
  37. package/dist/core/review/store.js +1 -1
  38. package/dist/core/runtime/bearings-render.d.ts +2 -2
  39. package/dist/core/runtime/bearings-render.js +11 -11
  40. package/dist/core/runtime/bearings.js +1 -1
  41. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  42. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  43. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  44. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  45. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  46. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  47. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  48. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  49. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  50. package/dist/core/runtime/broker-extension-render.js +2 -2
  51. package/dist/core/runtime/broker.js +1 -1
  52. package/dist/core/runtime/host.js +3 -3
  53. package/dist/core/runtime/kickoff.d.ts +1 -1
  54. package/dist/core/runtime/kickoff.js +12 -12
  55. package/dist/core/runtime/launch-config-worker.js +1 -1
  56. package/dist/core/runtime/launch-target.d.ts +6 -4
  57. package/dist/core/runtime/launch-target.js +1 -1
  58. package/dist/core/runtime/launch.d.ts +5 -1
  59. package/dist/core/runtime/launch.js +2 -2
  60. package/dist/core/runtime/nodes.js +1 -1
  61. package/dist/core/runtime/revive.js +2 -2
  62. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  63. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  64. package/dist/core/runtime/runner/launch-env.js +1 -0
  65. package/dist/core/runtime/runner/machine/executor.js +2 -2
  66. package/dist/core/runtime/runner/machine/runner.js +1 -1
  67. package/dist/core/runtime/runner/types.d.ts +1 -0
  68. package/dist/core/runtime/spawn-env-rows.js +1 -1
  69. package/dist/core/runtime/spawn.js +2 -2
  70. package/dist/core/secrets/environment-owner.js +1 -1
  71. package/dist/core/storage/attachments.d.ts +1 -1
  72. package/dist/core/storage/attachments.js +1 -1
  73. package/dist/core/storage/tables.d.ts +6 -2
  74. package/dist/core/storage/tables.js +4 -4
  75. package/dist/core/substrate/delivery/deliver.js +1 -1
  76. package/dist/core/substrate/delivery/render-boot.js +1 -1
  77. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  78. package/dist/daemon/api/handlers/canvas.js +5 -5
  79. package/dist/daemon/api/handlers/nodes.js +1 -1
  80. package/dist/daemon/api/handlers/profiles.js +1 -1
  81. package/dist/daemon/api/map.d.ts +1 -4
  82. package/dist/daemon/api/map.js +2 -2
  83. package/dist/daemon/cron/lease-recovery.js +1 -1
  84. package/dist/daemon/cron/machine-fire.js +1 -1
  85. package/dist/daemon/human/sweep.js +1 -1
  86. package/dist/daemon/peer/ingress.d.ts +2 -2
  87. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  88. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  89. package/dist/daemon/runs/observer.js +6 -5
  90. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  91. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  92. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  93. package/package.json +3 -3
  94. package/packages/crouter-api/dist/api/client.js +2 -2
  95. package/packages/crouter-api/dist/api/contract.js +1 -1
  96. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  97. package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
  98. package/packages/crouter-api/dist/core/config.js +10 -0
  99. package/packages/crouter-api/dist/core/directory/join.js +11 -45
  100. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  101. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  102. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/sandbox-start.mjs +5 -3
  108. package/dist/commands/sys/join.d.ts +0 -3
  109. package/dist/commands/sys/join.js +0 -1
@@ -1 +1 @@
1
- var O=Object.defineProperty;var r=(e,n)=>O(e,"name",{value:n,configurable:!0});import{createPrivateKey as T,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as N}from"node:fs";import{join as R}from"node:path";import{crtrHome as D}from"../canvas/paths.js";import{withCanvasWrite as k}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as b}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as E,outboundJson as S,outboundRefusal as x}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as F,replaceGrants as M,teamsOf as W}from"./mirror.js";import{seedTerminalDefaults as q}from"../scoped-state/seed-terminal-defaults.js";import{loadPersonSettings as I}from"../scoped-state/person-rows.js";import{onGrantSync as L}from"./on-sync.js";import{hostedEndpointOf as H,paymentSetupUrlOf as z,storeHostedEndpoint as K}from"./hosted-endpoint.js";import{PersonOutsideRequestError as V,PersonUnresolvedError as Y,personId as Q,resolvePerson as X,retireLocalPerson as Z,setPersonId as ee}from"../canvas/person.js";const xe=300;function te(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:T({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(te,"assertion");function y(){const e=JSON.parse(N(R(D(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Pe(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Pe,"runtimeId");function ne(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ne,"machineRevokedMessage");class P extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ne(n)),this.name="MachineRevokedError"}}async function re(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:te(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await E("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&b()&&await oe(o)?new P(e):x("directory_token",c,`directory token request failed: ${o.status}`);const a=await S("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:ie(a.access_token,a.expires_in)}}r(re,"mintDirectoryToken");async function oe(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(oe,"isInvalidClient");function ie(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ie,"tokenExpiry");function se(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||b()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=F(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(se,"responseGrant");async function ae(){try{return{id:Q(),late:null}}catch(n){if(n instanceof V)return null;if(!(n instanceof Y))throw n}const e=await X();return e===null?null:{id:e.id,late:e}}r(ae,"pullPerson");async function ce(e){ee(e.id),await I(e.id);const n=await Z();await k(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(ce,"bindLatePerson");let _;function je(e){return _?_(e):Promise.resolve()}r(je,"requestGrantSync");function Oe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),l=await re(i),m=await E("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${l.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw x("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await S("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:H(s.hosted_endpoint??null),payment_setup_url:z(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(p=>se(p,d)),w=await k(async()=>{await M(h,j,i,W(s.teams));const p=await ae();return g&&p&&await K(g,p.id),p}),v=await q();v.length>0&&f({level:"info",event:"daemon.settings.terminal_defaults_seeded",fields:{people:v.length}}),f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await ce(w.late);try{await L(n)}catch(p){f({level:"error",event:"daemon.grants.on_sync_failed",error:p})}},"run");let u;const o=r(()=>{const d=c().catch(l=>{throw l instanceof P?f({level:"error",event:"daemon.grants.machine_revoked",error:l}):f({level:"error",event:"daemon.grants.sync_failed",error:l,fields:J(l)}),l}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(Oe,"createGrantSync");export{xe as GRANT_SYNC_INTERVAL_S,P as MachineRevokedError,te as assertion,Oe as createGrantSync,ne as machineRevokedMessage,re as mintDirectoryToken,je as requestGrantSync,y as runtimeClient,Pe as runtimeId};
1
+ var j=Object.defineProperty;var r=(t,n)=>j(t,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as T,sign as $}from"node:crypto";import{readFileSync as A}from"node:fs";import{join as N}from"node:path";import{crtrHome as P}from"../canvas/paths.js";import{withCanvasWrite as R}from"../canvas/db.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as l}from"../events/emit.js";import{describeOutboundFailure as D,outboundFetch as v,outboundJson as b,outboundRefusal as E}from"../events/outbound.js";import{dependenciesOf as G,endpointPays as J,inferenceEndpointOf as U,principalPayer as B,replaceGrants as C,teamsOf as F}from"./mirror.js";import{seedTerminalDefaults as M}from"../scoped-state/seed-terminal-defaults.js";import{onGrantSync as W}from"./on-sync.js";import{hostedEndpointOf as q,paymentSetupUrlOf as I,storeHostedEndpoint as H}from"./hosted-endpoint.js";import{PersonOutsideRequestError as L,PersonUnresolvedError as z,personId as K}from"../canvas/person.js";const _e=300;function V(t,n){const e=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:t.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:t.client_id,sub:t.client_id,aud:n,iat:e,exp:e+300,jti:T()})).toString("base64url"),u=`${i}.${c}`,o=$("sha256",Buffer.from(u),{key:O({key:t.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(V,"assertion");function y(){const t=JSON.parse(A(N(P(),"secrets","runtime-client.json"),"utf8"));if(!t.jwk||t.alg!=="ES256"||!t.kid||!t.client_id||!t.runtime||t.jwk.kid!==t.kid||t.jwk.kty!=="EC"||t.jwk.crv!=="P-256"||!t.jwk.d)throw new TypeError("invalid runtime client key");return t}r(y,"runtimeClient");function ge(t=y()){return t.runtime.startsWith("runtime:")?t.runtime.slice(8):t.runtime}r(ge,"runtimeId");function Y(t){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(Y,"machineRevokedMessage");class S extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(Y(n)),this.name="MachineRevokedError"}}async function Q(t,n,e){const i=y(),c=`${t.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:V(i,c),...n===void 0?{}:{audience:n},...e===void 0?{}:{sub:e}}),o=await v("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await X(o)?new S(t):E("directory_token",c,`directory token request failed: ${o.status}`);const a=await b("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:Z(a.access_token,a.expires_in)}}r(Q,"mintDirectoryToken");async function X(t){try{return(await t.json()).error==="invalid_client"}catch{return!1}}r(X,"isInvalidClient");function Z(t,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const e=JSON.parse(Buffer.from(t.split(".")[1]??"","base64url").toString("utf8"));if(typeof e.exp=="number")return e.exp*1e3}catch{}return Date.now()+3e5}r(Z,"tokenExpiry");function ee(t,n){if(!t||typeof t!="object")throw new TypeError("invalid grant sync response");const e=t,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(e.runtime===i||k()&&typeof e.runtime=="string"&&e.runtime.startsWith("runtime:")&&e.grantee!=="app:terminal")||typeof e.id!="string"||typeof e.sub!="string"||typeof e.grantee!="string"||!Number.isInteger(e.rev)||!Array.isArray(e.scopes)||!Array.isArray(e.resolved_scopes)||!["active","revoked","removed"].includes(e.status??"")||typeof e.synced_at!="string")throw new TypeError("invalid grant sync response");const o=t.revisions?.find(d=>d.rev===e.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=B(e.payer,e.sub,e.grantee);return{...e,spend_cap:e.spend_cap??null,expires_at:e.expires_at??null,grantee_prefix:typeof e.grantee_prefix=="string"?e.grantee_prefix:null,revoked_at:e.revoked_at??null,approved_at:o,payer:a,dependencies:G(e.dependencies),inference_endpoint:J({payer:a})?U(e.inference_endpoint):null,run_notice_url:typeof e.run_notice_url=="string"&&e.run_notice_url!==""?e.run_notice_url:null}}r(ee,"responseGrant");function te(){try{return K()}catch(t){if(t instanceof L||t instanceof z)return null;throw t}}r(te,"pullPerson");let _;function he(t){return _?_(t):Promise.resolve()}r(he,"requestGrantSync");function we(t,n=e=>{}){let e;const i=t.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await Q(i),m=await v("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw E("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await b("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:q(s.hosted_endpoint??null),payment_setup_url:I(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,x=s.synced_at,h=s.grants.map(f=>ee(f,d));await R(async()=>{await C(h,x,i,F(s.teams));const f=te();return g&&f&&await H(g,f),f});const w=await M();w.length>0&&l({level:"info",event:"daemon.settings.terminal_defaults_seeded",fields:{people:w.length}}),l({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}});try{await W(n)}catch(f){l({level:"error",event:"daemon.grants.on_sync_failed",error:f})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof S?l({level:"error",event:"daemon.grants.machine_revoked",error:p}):l({level:"error",event:"daemon.grants.sync_failed",error:p,fields:D(p)}),p}).finally(()=>{e===d&&(e=void 0)});return e=d,d},"start"),a=r((d={})=>e?d.fresh?(u??=e.catch(()=>{}).then(()=>(u=void 0,e??o())),u):e:o(),"sync");return _=a,a}r(we,"createGrantSync");export{_e as GRANT_SYNC_INTERVAL_S,S as MachineRevokedError,V as assertion,we as createGrantSync,Y as machineRevokedMessage,Q as mintDirectoryToken,he as requestGrantSync,y as runtimeClient,ge as runtimeId};
@@ -116,7 +116,17 @@ export declare function listPendingAsks(): Promise<HumanRequestRecord[]>;
116
116
  export declare function openRequestsByRequester(nodeId: string): Promise<HumanRequestRecord[]>;
117
117
  export declare function hasOpenReplyBearingRequestByRequester(nodeId: string): Promise<boolean>;
118
118
  /** Indexed attention projection: only open inbox-listed requests with a reply target keep a node wakeable. */
119
- export declare function listOpenReplyBearingRequests(): Promise<HumanRequestRecord[]>;
119
+ export declare function listOpenReplyBearingRequests(): Promise<Array<Pick<HumanRequestRecord, 'requester_node_id' | 'title'>>>;
120
+ export type ReviewRequestRow = Omit<HumanRequestRecord, 'action_json' | 'progress_json' | 'feedback_json' | 'anchor_base_bytes' | 'action_delivery_id' | 'submit_note_delivery_id'>;
121
+ /** Non-binding reviews, filtered in SQL. `state` is the review state: settled reviews are `approved` or `canceled` by outcome. */
122
+ export declare function listReviewRequests(filter: {
123
+ state?: 'open' | 'approved' | 'canceled';
124
+ requester_node_id?: string;
125
+ file?: string;
126
+ }): Promise<ReviewRequestRow[]>;
127
+ /** Ids of every review (binding included) asked by one of these nodes. */
128
+ export declare function reviewRequestIdsByRequesters(nodeIds: readonly string[]): Promise<string[]>;
129
+ export declare function listReviewRequestIds(): Promise<string[]>;
120
130
  export declare function listBindingRequests(): Promise<HumanRequestRecord[]>;
121
131
  export declare function listSubmitRequestedRequests(): Promise<HumanRequestRecord[]>;
122
132
  export declare function listUnprojectedReviews(): Promise<HumanRequestRecord[]>;
@@ -1,56 +1,56 @@
1
- var ge=Object.defineProperty;var r=(e,t)=>ge(e,"name",{value:t,configurable:!0});import{prepared as l}from"../sqlite-statements.js";import{createHash as Ne,randomBytes as x}from"node:crypto";import{existsSync as y,mkdirSync as R,readFileSync as G,readdirSync as be,realpathSync as I,statSync as he,writeFileSync as Te}from"node:fs";import{basename as C,join as _}from"node:path";import{z as c}from"zod";import{crtrHome as z,isSafeNodeId as qe,nodesRoot as q}from"../canvas/paths.js";import{withCanvasWrite as Z,openDb as d}from"../canvas/db.js";import{syncDirectory as Se,syncFile as we}from"../fs-utils.js";import{newNodeId as Ae}from"../runtime/nodes.js";import{pageManifestPath as ee,pageModulePath as te,pagePath as ne}from"./convention.js";import{preparePageSource as Re}from"./page-authoring.js";import{pageAwaitsResponse as De,pageDeliverySchema as ve,pageIsNoticeSql as U,validatePageManifest as ie}from"./page-schema.js";import{appendWaitingOnUser as Oe}from"../runs/questions.js";import{isCloudRole as xe}from"../canvas/person.js";import{REQUEST_BLOB_PREFIX as Ie,isBlobRequestPath as re,writeRequestFile as P}from"./request-files.js";function L(e){return e===1||e===!0}r(L,"bool");function se(e){return{request_id:e.request_id,kind:e.kind,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,presentation_dir:e.presentation_dir,requester_node_id:e.requester_node_id,companion_node_id:e.companion_node_id,idempotency_key:e.idempotency_key,state:e.state,outcome:e.outcome,inbox_listed:L(e.inbox_listed),settleable:L(e.settleable),title:e.title,subtitle:e.subtitle,file:e.file,specification_json:e.specification_json,action_json:e.action_json,progress_json:e.progress_json,feedback_json:e.feedback_json,result_json:e.result_json,anchor_base_sha256:e.anchor_base_sha256,anchor_base_bytes:e.anchor_base_bytes===null?null:Buffer.from(e.anchor_base_bytes),created_at:e.created_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,settled_at:e.settled_at,settlement_delivery_id:e.settlement_delivery_id,action_delivery_id:e.action_delivery_id,submit_note_delivery_id:e.submit_note_delivery_id,projected_at:e.projected_at,projection_error:e.projection_error,companion_retired_at:e.companion_retired_at,updated_at:e.updated_at}}r(se,"recordFromRow");async function h(e,t,...i){const s=await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t}`).get(...i);return s===void 0?null:se(s)}r(h,"one");async function g(e,t,i=[],s="created_at ASC, request_id ASC"){return(await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t} ORDER BY ${s}`).all(...i)).map(se)}r(g,"many");function oe(){return _(z(),"requests")}r(oe,"humanRequestsRoot");function $(e){if(!qe(e))throw new TypeError(`request_id must be a safe path segment: ${e}`);if(xe())return`${Ie}${e}`;const t=oe();return R(t,{recursive:!0,mode:448}),_(I(t),e)}r($,"requestDir");function H(){return x(32).toString("hex")}r(H,"randomTicketId");function M(e,t){return Ne("sha256").update(`${I(e)}\0${t}`,"utf8").digest("hex")}r(M,"legacyTicketId");const Le={writeFile(e,t){Te(e,t,{flag:"wx",mode:384})},syncFile:we,syncDirectory:Se};function je(e){return _(e,"revisions")}r(je,"revisionRoot");function ae(e,t,i=Le){R(e,{recursive:!0,mode:448});const s=je(e);R(s,{recursive:!0,mode:448});const n=_(s,x(16).toString("hex"));R(n,{mode:448});const o=ne(n,t.manifest.dialect);if(i.writeFile(o,t.document),i.syncFile(o),t.manifest.dialect==="jsx"){const a=te(n);i.writeFile(a,t.module),i.syncFile(a)}const u=ee(n);return i.writeFile(u,`${JSON.stringify(t.manifest,null,2)}
2
- `),i.syncFile(u),i.syncDirectory(n),i.syncDirectory(s),i.syncDirectory(e),i.syncDirectory(oe()),n}r(ae,"publishPageRevision");async function ke(e,t){if(!re(e))return ae(e,t);const i=`${e}/revisions/${x(16).toString("hex")}`;return await P(ee(i),`${JSON.stringify(t.manifest,null,2)}
3
- `),await P(ne(i,t.manifest.dialect),t.document),t.manifest.dialect==="jsx"&&await P(te(i),t.module),i}r(ke,"publishPageRevisionTo");function pt(e){if(e.kind!=="page"||e.presentation_dir===null)throw new Error(`page request has no selected presentation: ${e.request_id}`);return e.presentation_dir}r(pt,"presentationDir");async function mt(e){const t=e.request_id??await Ae(),i=$(t),s=await ke(i,e.prepared),n=new Date().toISOString(),o=e.prepared.manifest;return await Z(async u=>{await u.prepare(`
1
+ var ge=Object.defineProperty;var s=(e,t)=>ge(e,"name",{value:t,configurable:!0});import{prepared as _}from"../sqlite-statements.js";import{createHash as Ne,randomBytes as x}from"node:crypto";import{existsSync as g,mkdirSync as A,readFileSync as z,readdirSync as he,realpathSync as I,statSync as be,writeFileSync as qe}from"node:fs";import{basename as C,join as l}from"node:path";import{z as c}from"zod";import{crtrHome as Z,isSafeNodeId as Te,nodesRoot as T}from"../canvas/paths.js";import{withCanvasWrite as ee,openDb as a}from"../canvas/db.js";import{syncDirectory as we,syncFile as Se}from"../fs-utils.js";import{newNodeId as Re}from"../runtime/nodes.js";import{pageManifestPath as te,pageModulePath as ne,pagePath as ie}from"./convention.js";import{preparePageSource as Ae}from"./page-authoring.js";import{pageAwaitsResponse as ve,pageDeliverySchema as De,pageIsNoticeSql as U,validatePageManifest as se}from"./page-schema.js";import{appendWaitingOnUser as Oe}from"../runs/questions.js";import{isCloudRole as xe}from"../canvas/person.js";import{REQUEST_BLOB_PREFIX as Ie,isBlobRequestPath as re,writeRequestFile as P}from"./request-files.js";function L(e){return e===1||e===!0}s(L,"bool");function $(e){return{request_id:e.request_id,kind:e.kind,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,presentation_dir:e.presentation_dir,requester_node_id:e.requester_node_id,companion_node_id:e.companion_node_id,idempotency_key:e.idempotency_key,state:e.state,outcome:e.outcome,inbox_listed:L(e.inbox_listed),settleable:L(e.settleable),title:e.title,subtitle:e.subtitle,file:e.file,specification_json:e.specification_json,action_json:e.action_json,progress_json:e.progress_json,feedback_json:e.feedback_json,result_json:e.result_json,anchor_base_sha256:e.anchor_base_sha256,anchor_base_bytes:e.anchor_base_bytes===null?null:Buffer.from(e.anchor_base_bytes),created_at:e.created_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,settled_at:e.settled_at,settlement_delivery_id:e.settlement_delivery_id,action_delivery_id:e.action_delivery_id,submit_note_delivery_id:e.submit_note_delivery_id,projected_at:e.projected_at,projection_error:e.projection_error,companion_retired_at:e.companion_retired_at,updated_at:e.updated_at}}s($,"recordFromRow");async function h(e,t,...i){const r=await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t}`).get(...i);return r===void 0?null:$(r)}s(h,"one");async function b(e,t,i=[],r="created_at ASC, request_id ASC"){return(await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t} ORDER BY ${r}`).all(...i)).map($)}s(b,"many");function oe(){return l(Z(),"requests")}s(oe,"humanRequestsRoot");function H(e){if(!Te(e))throw new TypeError(`request_id must be a safe path segment: ${e}`);if(xe())return`${Ie}${e}`;const t=oe();return A(t,{recursive:!0,mode:448}),l(I(t),e)}s(H,"requestDir");function M(){return x(32).toString("hex")}s(M,"randomTicketId");function F(e,t){return Ne("sha256").update(`${I(e)}\0${t}`,"utf8").digest("hex")}s(F,"legacyTicketId");const Le={writeFile(e,t){qe(e,t,{flag:"wx",mode:384})},syncFile:Se,syncDirectory:we};function je(e){return l(e,"revisions")}s(je,"revisionRoot");function ae(e,t,i=Le){A(e,{recursive:!0,mode:448});const r=je(e);A(r,{recursive:!0,mode:448});const n=l(r,x(16).toString("hex"));A(n,{mode:448});const o=ie(n,t.manifest.dialect);if(i.writeFile(o,t.document),i.syncFile(o),t.manifest.dialect==="jsx"){const d=ne(n);i.writeFile(d,t.module),i.syncFile(d)}const u=te(n);return i.writeFile(u,`${JSON.stringify(t.manifest,null,2)}
2
+ `),i.syncFile(u),i.syncDirectory(n),i.syncDirectory(r),i.syncDirectory(e),i.syncDirectory(oe()),n}s(ae,"publishPageRevision");async function ke(e,t){if(!re(e))return ae(e,t);const i=`${e}/revisions/${x(16).toString("hex")}`;return await P(te(i),`${JSON.stringify(t.manifest,null,2)}
3
+ `),await P(ie(i,t.manifest.dialect),t.document),t.manifest.dialect==="jsx"&&await P(ne(i),t.module),i}s(ke,"publishPageRevisionTo");function mt(e){if(e.kind!=="page"||e.presentation_dir===null)throw new Error(`page request has no selected presentation: ${e.request_id}`);return e.presentation_dir}s(mt,"presentationDir");async function ft(e){const t=e.request_id??await Re(),i=H(t),r=await ke(i,e.prepared),n=new Date().toISOString(),o=e.prepared.manifest;return await ee(async u=>{await u.prepare(`
4
4
  INSERT INTO human_requests (
5
5
  request_id, kind, inbox_ticket_id, request_dir, presentation_dir, requester_node_id, state, inbox_listed,
6
6
  settleable, title, subtitle, specification_json, action_json, created_at, updated_at
7
7
  ) VALUES (?, 'page', ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ?, ?)
8
- `).run(t,e.inbox_ticket_id??H(),i,s,e.requester_node_id??null,o.delivery.inbox?1:0,o.delivery.inbox||o.delivery.reply?1:0,o.title,o.subtitle??null,JSON.stringify(o),e.action_json??null,n,n);const a=await h(u,"request_id = ?",t);if(a===null)throw new Error(`page request insert did not produce a row: ${t}`);return await Oe(u,a),a})}r(mt,"createPageRequest");async function ft(e){return await Z(async t=>{const i=await t.prepare(`
8
+ `).run(t,e.inbox_ticket_id??M(),i,r,e.requester_node_id??null,o.delivery.inbox?1:0,o.delivery.inbox||o.delivery.reply?1:0,o.title,o.subtitle??null,JSON.stringify(o),e.action_json??null,n,n);const d=await h(u,"request_id = ?",t);if(d===null)throw new Error(`page request insert did not produce a row: ${t}`);return await Oe(u,d),d})}s(ft,"createPageRequest");async function Et(e){return await ee(async t=>{const i=await t.prepare(`
9
9
  INSERT INTO human_requests (
10
10
  request_id, kind, inbox_ticket_id, request_dir, requester_node_id, companion_node_id,
11
11
  idempotency_key, state, inbox_listed, settleable, title, subtitle, file,
12
12
  specification_json, anchor_base_sha256, anchor_base_bytes, created_at, updated_at
13
13
  ) VALUES (?, 'review', ?, ?, ?, ?, ?, 'binding', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)
14
14
  ON CONFLICT(idempotency_key) DO NOTHING
15
- `).run(e.request_id,H(),e.request_dir,e.requester_node_id,e.companion_node_id,e.idempotency_key,e.inbox_listed?1:0,e.title??C(e.file),e.subtitle??null,e.file,JSON.stringify(e.specification),e.anchor_base_sha256,e.anchor_base_bytes,e.created_at,e.created_at),s=await h(t,"idempotency_key = ?",e.idempotency_key);if(s===null)throw new Error(`review binding insert did not produce a row: ${e.idempotency_key}`);return{request_id:s.request_id,won:i.changes>0}})}r(ft,"commitBindingRequest");async function Et(e){return await h(await d(),"request_id = ?",e)}r(Et,"getRequest");async function yt(e){return await h(await d(),"inbox_ticket_id = ?",e)}r(yt,"getRequestByInboxTicket");async function gt(e){return e.length===0?[]:await g(await d(),"inbox_ticket_id = ANY(?::text[])",[[...e]])}r(gt,"getRequestsByInboxTickets");async function Nt(e){let t=e;if(!re(e))try{t=I(e)}catch{}return await h(await d(),"request_dir = ?",t)}r(Nt,"getRequestByDirectory");async function bt(e){return await h(await d(),"companion_node_id = ? AND state <> 'binding'",e)}r(bt,"getRequestByCompanion");async function ht(e){return await h(await d(),"idempotency_key = ?",e)}r(ht,"getRequestByIdempotencyKey");const Ce=r(e=>`COALESCE(${e}.requester_node_id, CASE WHEN ${e}.kind = 'page' AND ${U(`${e}.specification_json`)} THEN ${e}.specification_json #>> '{source,nodeId}' END)`,"askingNodeSql"),de=`NOT (kind = 'page' AND EXISTS (SELECT 1 FROM node_rows n WHERE n.node_id = ${Ce("human_requests")}
16
- AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))`;async function Tt(){return await g(await d(),`state = 'open' AND inbox_listed = 1 AND ${de}`,[],"created_at DESC, request_id DESC")}r(Tt,"listOpenInboxRequests");async function qt(){return(await g(await d(),`state = 'open' AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${U("specification_json")}) AND ((inbox_listed = 1 AND ${de}) OR (kind = 'page' AND inbox_listed = 0 AND settleable = 1))`,[],"created_at ASC, request_id ASC")).filter(e=>e.inbox_listed||De(JSON.parse(e.specification_json)))}r(qt,"listPendingAsks");async function Ue(e){return await g(await d(),"state = 'open' AND requester_node_id = ?",[e],"created_at DESC, request_id DESC")}r(Ue,"openRequestsByRequester");async function St(e){return(await Ue(e)).some(t=>t.kind==="review"?!0:JSON.parse(t.specification_json).delivery?.reply===!0)}r(St,"hasOpenReplyBearingRequestByRequester");async function wt(){return await g(await d(),`state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${U("specification_json")})`,[],"created_at DESC, request_id DESC")}r(wt,"listOpenReplyBearingRequests");async function At(){return await g(await d(),"kind = 'review' AND state = 'binding'")}r(At,"listBindingRequests");async function Rt(){return await g(await d(),"kind = 'review' AND state = 'open' AND submit_requested_at IS NOT NULL")}r(Rt,"listSubmitRequestedRequests");async function Dt(){return await g(await d(),"kind = 'review' AND state = 'settled' AND projected_at IS NULL")}r(Dt,"listUnprojectedReviews");async function vt(e={}){const t=["true"],i=[];for(const[s,n]of Object.entries(e))n!==void 0&&(t.push(`${s} = ?`),i.push(n));return await g(await d(),t.join(" AND "),i)}r(vt,"listRequests");const ce=["canceled","dismissed"],ue=ce.map(e=>`'${e}'`).join(", ");function Ot(e){return e.state!=="settled"?e.settleable?"pending":"passive":e.outcome!==null&&ce.includes(e.outcome)?"canceled":"resolved"}r(Ot,"pageSummaryState");const Pe={pending:"state <> 'settled' AND settleable = 1",passive:"state <> 'settled' AND settleable <> 1",canceled:`state = 'settled' AND outcome IN (${ue})`,resolved:`state = 'settled' AND (outcome IS NULL OR outcome NOT IN (${ue}))`};async function xt(e={}){const t=["kind = 'page'"],i=[];return e.source_node_id!==void 0&&(t.push("specification_json #>> '{source,nodeId}' = ?"),i.push(e.source_node_id)),e.summary_state!==void 0&&t.push(Pe[e.summary_state]),(await(await d()).prepareUncached(`
15
+ `).run(e.request_id,M(),e.request_dir,e.requester_node_id,e.companion_node_id,e.idempotency_key,e.inbox_listed?1:0,e.title??C(e.file),e.subtitle??null,e.file,JSON.stringify(e.specification),e.anchor_base_sha256,e.anchor_base_bytes,e.created_at,e.created_at),r=await h(t,"idempotency_key = ?",e.idempotency_key);if(r===null)throw new Error(`review binding insert did not produce a row: ${e.idempotency_key}`);return{request_id:r.request_id,won:i.changes>0}})}s(Et,"commitBindingRequest");async function yt(e){return await h(await a(),"request_id = ?",e)}s(yt,"getRequest");async function gt(e){return await h(await a(),"inbox_ticket_id = ?",e)}s(gt,"getRequestByInboxTicket");async function Nt(e){return e.length===0?[]:await b(await a(),"inbox_ticket_id = ANY(?::text[])",[[...e]])}s(Nt,"getRequestsByInboxTickets");async function ht(e){let t=e;if(!re(e))try{t=I(e)}catch{}return await h(await a(),"request_dir = ?",t)}s(ht,"getRequestByDirectory");async function bt(e){return await h(await a(),"companion_node_id = ? AND state <> 'binding'",e)}s(bt,"getRequestByCompanion");async function qt(e){return await h(await a(),"idempotency_key = ?",e)}s(qt,"getRequestByIdempotencyKey");const Ce=s(e=>`COALESCE(${e}.requester_node_id, CASE WHEN ${e}.kind = 'page' AND ${U(`${e}.specification_json`)} THEN ${e}.specification_json #>> '{source,nodeId}' END)`,"askingNodeSql"),de=`NOT (kind = 'page' AND EXISTS (SELECT 1 FROM node_rows n WHERE n.node_id = ${Ce("human_requests")}
16
+ AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))`;async function Tt(){return await b(await a(),`state = 'open' AND inbox_listed = 1 AND ${de}`,[],"created_at DESC, request_id DESC")}s(Tt,"listOpenInboxRequests");async function wt(){return(await b(await a(),`state = 'open' AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${U("specification_json")}) AND ((inbox_listed = 1 AND ${de}) OR (kind = 'page' AND inbox_listed = 0 AND settleable = 1))`,[],"created_at ASC, request_id ASC")).filter(e=>e.inbox_listed||ve(JSON.parse(e.specification_json)))}s(wt,"listPendingAsks");async function Ue(e){return await b(await a(),"state = 'open' AND requester_node_id = ?",[e],"created_at DESC, request_id DESC")}s(Ue,"openRequestsByRequester");async function St(e){return(await Ue(e)).some(t=>t.kind==="review"?!0:JSON.parse(t.specification_json).delivery?.reply===!0)}s(St,"hasOpenReplyBearingRequestByRequester");async function Rt(){return await(await a()).prepareUncached(`SELECT requester_node_id, title FROM human_requests WHERE state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${U("specification_json")}) ORDER BY created_at DESC, request_id DESC`).all()}s(Rt,"listOpenReplyBearingRequests");const Pe="request_id, kind, inbox_ticket_id, request_dir, presentation_dir, requester_node_id, companion_node_id, idempotency_key, state, outcome, inbox_listed, settleable, title, subtitle, file, specification_json, result_json, anchor_base_sha256, created_at, opened_at, submit_requested_at, settled_at, settlement_delivery_id, projected_at, projection_error, companion_retired_at, updated_at";async function At(e){const t=["kind = 'review'","state != 'binding'"],i=[];return e.state==="open"?t.push("state = 'open'"):e.state==="approved"?t.push("state = 'settled' AND outcome = 'approved'"):e.state==="canceled"&&t.push("state = 'settled' AND outcome IS DISTINCT FROM 'approved'"),e.requester_node_id!==void 0&&(t.push("requester_node_id = ?"),i.push(e.requester_node_id)),e.file!==void 0&&(t.push("file = ?"),i.push(e.file)),(await(await a()).prepareUncached(`SELECT ${Pe} FROM human_requests WHERE ${t.join(" AND ")} ORDER BY created_at ASC, request_id ASC`).all(...i)).map(n=>{const{anchor_base_bytes:o,action_json:u,progress_json:d,feedback_json:p,action_delivery_id:m,submit_note_delivery_id:E,...y}=$({...n,anchor_base_bytes:null});return y})}s(At,"listReviewRequests");async function vt(e){return e.length===0?[]:(await(await a()).prepareUncached(`SELECT request_id FROM human_requests WHERE kind = 'review' AND requester_node_id IN (${e.map(()=>"?").join(",")})`).all(...e)).map(i=>i.request_id)}s(vt,"reviewRequestIdsByRequesters");async function Dt(){return(await(await a()).prepareUncached("SELECT request_id FROM human_requests WHERE kind = 'review'").all()).map(e=>e.request_id)}s(Dt,"listReviewRequestIds");async function Ot(){return await b(await a(),"kind = 'review' AND state = 'binding'")}s(Ot,"listBindingRequests");async function xt(){return await b(await a(),"kind = 'review' AND state = 'open' AND submit_requested_at IS NOT NULL")}s(xt,"listSubmitRequestedRequests");async function It(){return await b(await a(),"kind = 'review' AND state = 'settled' AND projected_at IS NULL")}s(It,"listUnprojectedReviews");async function Lt(e={}){const t=["true"],i=[];for(const[r,n]of Object.entries(e))n!==void 0&&(t.push(`${r} = ?`),i.push(n));return await b(await a(),t.join(" AND "),i)}s(Lt,"listRequests");const ce=["canceled","dismissed"],ue=ce.map(e=>`'${e}'`).join(", ");function jt(e){return e.state!=="settled"?e.settleable?"pending":"passive":e.outcome!==null&&ce.includes(e.outcome)?"canceled":"resolved"}s(jt,"pageSummaryState");const $e={pending:"state <> 'settled' AND settleable = 1",passive:"state <> 'settled' AND settleable <> 1",canceled:`state = 'settled' AND outcome IN (${ue})`,resolved:`state = 'settled' AND (outcome IS NULL OR outcome NOT IN (${ue}))`};async function kt(e={}){const t=["kind = 'page'"],i=[];return e.source_node_id!==void 0&&(t.push("specification_json #>> '{source,nodeId}' = ?"),i.push(e.source_node_id)),e.summary_state!==void 0&&t.push($e[e.summary_state]),(await(await a()).prepareUncached(`
17
17
  SELECT request_id, inbox_ticket_id, request_dir, state, outcome, inbox_listed, settleable, title, subtitle, specification_json, result_json, created_at
18
- FROM human_requests WHERE ${t.join(" AND ")} ORDER BY created_at ASC, request_id ASC`).all(...i)).map(n=>({...n,inbox_listed:L(n.inbox_listed),settleable:L(n.settleable)}))}r(xt,"listPageSummaryRows");async function It(){return await(await d()).prepare(`
18
+ FROM human_requests WHERE ${t.join(" AND ")} ORDER BY created_at ASC, request_id ASC`).all(...i)).map(n=>({...n,inbox_listed:L(n.inbox_listed),settleable:L(n.settleable)}))}s(kt,"listPageSummaryRows");async function Ct(){return await(await a()).prepare(`
19
19
  SELECT 1 FROM human_requests
20
20
  WHERE kind = 'page' AND result_json IS NOT NULL
21
21
  AND (result_json ->> 'kind') = 'page'
22
22
  AND jsonb_typeof(result_json -> 'summary') IS DISTINCT FROM 'string'
23
23
  LIMIT 1
24
- `).get()!==void 0}r(It,"hasPageResultException");async function Lt(){return await(await d()).prepare(`
24
+ `).get()!==void 0}s(Ct,"hasPageResultException");async function Ut(){return await(await a()).prepare(`
25
25
  SELECT request_id, specification_json FROM human_requests
26
26
  WHERE kind = 'page' AND jsonb_typeof(specification_json) <> 'object'
27
27
  ORDER BY created_at ASC, request_id ASC LIMIT 1
28
- `).get()??null}r(Lt,"firstInvalidPageSpecification");async function jt(e,t){return(await(await d()).prepare("UPDATE human_requests SET state = 'open', opened_at = ?, updated_at = ? WHERE request_id = ? AND state = 'binding'").run(t,t,e)).changes>0}r(jt,"openRequest");async function kt(e,t,i){return(await(await d()).prepare(`
28
+ `).get()??null}s(Ut,"firstInvalidPageSpecification");async function Pt(e,t){return(await(await a()).prepare("UPDATE human_requests SET state = 'open', opened_at = ?, updated_at = ? WHERE request_id = ? AND state = 'binding'").run(t,t,e)).changes>0}s(Pt,"openRequest");async function $t(e,t,i){return(await(await a()).prepare(`
29
29
  UPDATE human_requests SET state = 'settled', outcome = 'canceled', result_json = ?, settled_at = ?, updated_at = ?
30
30
  WHERE request_id = ? AND kind = 'review' AND state = 'binding'
31
- `).run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t,reason:i}),t,t,e)).changes>0}r(kt,"cancelBindingRequest");async function Ct(e,t){return(await(await d()).prepare("UPDATE human_requests SET submit_requested_at = ?, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open' AND submit_requested_at IS NULL").run(t,t,e)).changes>0}r(Ct,"requestSubmit");async function Ut(e,t){return(await e.prepare(`
31
+ `).run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t,reason:i}),t,t,e)).changes>0}s($t,"cancelBindingRequest");async function Ht(e,t){return(await(await a()).prepare("UPDATE human_requests SET submit_requested_at = ?, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open' AND submit_requested_at IS NULL").run(t,t,e)).changes>0}s(Ht,"requestSubmit");async function Mt(e,t){return(await e.prepare(`
32
32
  UPDATE human_requests SET state = 'settled', outcome = ?, result_json = ?, settled_at = ?,
33
33
  progress_json = NULL, updated_at = ?
34
34
  WHERE request_id = ? AND state = 'open'
35
- `).run(t.outcome,t.result_json,t.settled_at,t.settled_at,t.request_id)).changes===0?null:await h(e,"request_id = ?",t.request_id)}r(Ut,"settleRequestLocked");async function Pt(e,t,i){await e.prepare("UPDATE human_requests SET settlement_delivery_id = ?, action_delivery_id = ?, updated_at = ? WHERE request_id = ?").run(i.settlement_delivery_id??null,i.action_delivery_id??null,new Date().toISOString(),t)}r(Pt,"setSettlementDeliveryMarksLocked");async function $t(e,t,i){return(await e.prepare("UPDATE human_requests SET submit_note_delivery_id = ?, updated_at = ? WHERE request_id = ? AND state = 'open' AND submit_note_delivery_id IS NULL").run(i,new Date().toISOString(),t)).changes>0}r($t,"setSubmitNoteDeliveryLocked");async function Ht(e,t){return(await(await d()).prepare(`
35
+ `).run(t.outcome,t.result_json,t.settled_at,t.settled_at,t.request_id)).changes===0?null:await h(e,"request_id = ?",t.request_id)}s(Mt,"settleRequestLocked");async function Ft(e,t,i){await e.prepare("UPDATE human_requests SET settlement_delivery_id = ?, action_delivery_id = ?, updated_at = ? WHERE request_id = ?").run(i.settlement_delivery_id??null,i.action_delivery_id??null,new Date().toISOString(),t)}s(Ft,"setSettlementDeliveryMarksLocked");async function Wt(e,t,i){return(await e.prepare("UPDATE human_requests SET submit_note_delivery_id = ?, updated_at = ? WHERE request_id = ? AND state = 'open' AND submit_note_delivery_id IS NULL").run(i,new Date().toISOString(),t)).changes>0}s(Wt,"setSubmitNoteDeliveryLocked");async function Xt(e,t){return(await(await a()).prepare(`
36
36
  UPDATE human_requests SET presentation_dir = ?, specification_json = ?, title = ?, subtitle = ?, inbox_listed = ?, settleable = ?, updated_at = ?
37
37
  WHERE request_id = ? AND kind = 'page' AND state = 'open'
38
- `).run(t.presentation_dir,t.specification_json,t.title,t.subtitle,t.inbox_listed?1:0,t.settleable?1:0,new Date().toISOString(),e)).changes>0}r(Ht,"revisePageRequest");async function Mt(e,t){return(await(await d()).prepare(`
38
+ `).run(t.presentation_dir,t.specification_json,t.title,t.subtitle,t.inbox_listed?1:0,t.settleable?1:0,new Date().toISOString(),e)).changes>0}s(Xt,"revisePageRequest");async function Bt(e,t){return(await(await a()).prepare(`
39
39
  UPDATE human_requests SET progress_json = ?, updated_at = ?
40
40
  WHERE inbox_ticket_id = ? AND kind = 'page' AND state = 'open' AND settleable = 1
41
- `).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e)).changes>0}r(Mt,"writeProgress");async function Ft(e,t){await(await d()).prepare("UPDATE human_requests SET projected_at = ?, projection_error = NULL, updated_at = ? WHERE request_id = ?").run(t,t,e)}r(Ft,"markProjected");async function Xt(e,t){await(await d()).prepare("UPDATE human_requests SET projection_error = ?, updated_at = ? WHERE request_id = ? AND projected_at IS NULL").run(t,new Date().toISOString(),e)}r(Xt,"markProjectionError");async function Wt(e,t){await(await d()).prepare("UPDATE human_requests SET companion_retired_at = ?, updated_at = ? WHERE request_id = ? AND companion_retired_at IS NULL").run(t,t,e)}r(Wt,"markCompanionRetired");async function Jt(e){const t=await(await d()).prepare("SELECT anchor_base_bytes, anchor_base_sha256 FROM human_requests WHERE request_id = ?").get(e);return t===void 0||t.anchor_base_bytes===null||t.anchor_base_sha256===null?null:{bytes:Buffer.from(t.anchor_base_bytes),sha256:t.anchor_base_sha256}}r(Jt,"readAnchorBase");async function Bt(e,t,i,s){await e.prepare("UPDATE human_requests SET anchor_base_bytes = ?, anchor_base_sha256 = ?, updated_at = ? WHERE request_id = ?").run(i,s,new Date().toISOString(),t)}r(Bt,"replaceAnchorBaseLocked");function $e(e){if(typeof e!="object"||e===null)throw new Error("result is not an object");const t=e;return t.kind==="canceled"?{outcome:t.disposition==="dismissed"?"dismissed":"canceled",settledAt:String(t.canceledAt)}:{outcome:"answered",settledAt:String(t.completedAt)}}r($e,"legacyPageResult");function A(e){try{return JSON.parse(G(e,"utf8"))}catch(t){throw new Error(`corrupt required input: ${e}`,{cause:t})}}r(A,"readJson");function F(){return x(16).toString("hex")}r(F,"migrationId");function He(e){return Number(l(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}r(He,"nextMessageSeq");function Me(e,t,i,s){return(s==="page"?l(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
41
+ `).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e)).changes>0}s(Bt,"writeProgress");async function Jt(e,t){await(await a()).prepare("UPDATE human_requests SET projected_at = ?, projection_error = NULL, updated_at = ? WHERE request_id = ?").run(t,t,e)}s(Jt,"markProjected");async function Kt(e,t){await(await a()).prepare("UPDATE human_requests SET projection_error = ?, updated_at = ? WHERE request_id = ? AND projected_at IS NULL").run(t,new Date().toISOString(),e)}s(Kt,"markProjectionError");async function Yt(e,t){await(await a()).prepare("UPDATE human_requests SET companion_retired_at = ?, updated_at = ? WHERE request_id = ? AND companion_retired_at IS NULL").run(t,t,e)}s(Yt,"markCompanionRetired");async function Qt(e){const t=await(await a()).prepare("SELECT anchor_base_bytes, anchor_base_sha256 FROM human_requests WHERE request_id = ?").get(e);return t===void 0||t.anchor_base_bytes===null||t.anchor_base_sha256===null?null:{bytes:Buffer.from(t.anchor_base_bytes),sha256:t.anchor_base_sha256}}s(Qt,"readAnchorBase");async function Vt(e,t,i,r){await e.prepare("UPDATE human_requests SET anchor_base_bytes = ?, anchor_base_sha256 = ?, updated_at = ? WHERE request_id = ?").run(i,r,new Date().toISOString(),t)}s(Vt,"replaceAnchorBaseLocked");function He(e){if(typeof e!="object"||e===null)throw new Error("result is not an object");const t=e;return t.kind==="canceled"?{outcome:t.disposition==="dismissed"?"dismissed":"canceled",settledAt:String(t.canceledAt)}:{outcome:"answered",settledAt:String(t.completedAt)}}s(He,"legacyPageResult");function R(e){try{return JSON.parse(z(e,"utf8"))}catch(t){throw new Error(`corrupt required input: ${e}`,{cause:t})}}s(R,"readJson");function W(){return x(16).toString("hex")}s(W,"migrationId");function Me(e){return Number(_(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}s(Me,"nextMessageSeq");function Fe(e,t,i,r){return(r==="page"?_(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
42
42
  WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.sender_node_id = ?
43
- AND m.disposition IN ('human-answer', 'human-canceled') LIMIT 1`).get(i,t):l(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
44
- WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.body_json LIKE ? LIMIT 1`).get(i,`%"review_id":"${t}"%`))?.delivery_id??null}r(Me,"importedTerminalDelivery");function le(e,t,i){if(t===null||i===null)return!1;const s=l(e,"SELECT status, final_report FROM nodes WHERE node_id = ?").get(t);return s?.status==="canceled"||i==="approved"&&s?.status==="done"&&s.final_report!==null}r(le,"companionRetirementProven");function _e(e){if(typeof e!="object"||e===null)return"no reason was given";const t=e.reason;return typeof t=="string"&&t!==""?t:"no reason was given"}r(_e,"migratedCancellationReason");function Fe(e,t){const i=e.outcome==="canceled"||e.outcome==="dismissed";return[e.kind==="review"?i?`Review ${e.requestId} was canceled \u2014 ${_e(t)}.`:`Review ${e.requestId} was approved by the user.`:i?`Human request ${e.requestId} was canceled \u2014 ${_e(t)}.`:`Human request ${e.requestId} was answered.`,...e.kind==="review"?[`The review result is at ${e.requestDir}/result.json.`]:[],`Result:
43
+ AND m.disposition IN ('human-answer', 'human-canceled') LIMIT 1`).get(i,t):_(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
44
+ WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.body_json LIKE ? LIMIT 1`).get(i,`%"review_id":"${t}"%`))?.delivery_id??null}s(Fe,"importedTerminalDelivery");function _e(e,t,i){if(t===null||i===null)return!1;const r=_(e,"SELECT status, final_report FROM nodes WHERE node_id = ?").get(t);return r?.status==="canceled"||i==="approved"&&r?.status==="done"&&r.final_report!==null}s(_e,"companionRetirementProven");function le(e){if(typeof e!="object"||e===null)return"no reason was given";const t=e.reason;return typeof t=="string"&&t!==""?t:"no reason was given"}s(le,"migratedCancellationReason");function We(e,t){const i=e.outcome==="canceled"||e.outcome==="dismissed";return[e.kind==="review"?i?`Review ${e.requestId} was canceled \u2014 ${le(t)}.`:`Review ${e.requestId} was approved by the user.`:i?`Human request ${e.requestId} was canceled \u2014 ${le(t)}.`:`Human request ${e.requestId} was answered.`,...e.kind==="review"?[`The review result is at ${e.requestDir}/result.json.`]:[],`Result:
45
45
  ${JSON.stringify(t,null,2)}`].join(`
46
46
 
47
- `)}r(Fe,"migratedTerminalBody");function Xe(e,t){const i=F(),s=F(),n=Date.parse(t.settledAt),o=Number.isFinite(n)?n:0,u=t.outcome==="answered"||t.outcome==="approved"?"human-answer":"human-canceled",a=JSON.parse(t.resultJson),p=Fe(t,a);return l(e,`INSERT INTO messages
47
+ `)}s(We,"migratedTerminalBody");function Xe(e,t){const i=W(),r=W(),n=Date.parse(t.settledAt),o=Number.isFinite(n)?n:0,u=t.outcome==="answered"||t.outcome==="approved"?"human-answer":"human-canceled",d=JSON.parse(t.resultJson),p=We(t,d);return _(e,`INSERT INTO messages
48
48
  (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition)
49
- VALUES (?, ?, ?, ?, NULL, 'crtrd', 'completed', ?, NULL, ?, ?)`).run(i,He(e),F(),t.settledAt,p.split(`
50
- `,1)[0],JSON.stringify({body:p,result:a}),u),l(e,`INSERT INTO deliveries
49
+ VALUES (?, ?, ?, ?, NULL, 'crtrd', 'completed', ?, NULL, ?, ?)`).run(i,Me(e),W(),t.settledAt,p.split(`
50
+ `,1)[0],JSON.stringify({body:p,result:d}),u),_(e,`INSERT INTO deliveries
51
51
  (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, created_at, updated_at)
52
- VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(s,i,t.requesterNodeId,o,o),s}r(Xe,"createMigratedTerminalDelivery");function pe(e,t){if(t.requesterNodeId===null||t.outcome===null||t.resultJson===null||t.settledAt===null)return null;const i=Me(e,t.requestId,t.requesterNodeId,t.kind);return i!==null?i:t.deliveredAt!==null&&t.deliveredAt!==void 0?null:Xe(e,{requestId:t.requestId,requesterNodeId:t.requesterNodeId,kind:t.kind,outcome:t.outcome,resultJson:t.resultJson,settledAt:t.settledAt,requestDir:t.requestDir})}r(pe,"terminalDeliveryMark");const We=c.object({sessionName:c.string().optional(),askedBy:c.string().optional(),blockedSince:c.string().optional(),profileName:c.string().optional(),nodeId:c.string().optional()}).strict(),Je=c.object({id:c.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:c.string().min(1),step:c.number().int().nonnegative(),config:c.record(c.string(),c.unknown()),unvalidated:c.literal(!0).optional(),display:c.literal(!0).optional()}).strict(),Be=c.object({schema:c.literal("crtr.page/v1"),dialect:c.enum(["md","html","jsx"]),title:c.string().trim().min(1),subtitle:c.string().optional(),placement:c.enum(["inline","panel"]),document:c.enum(["page.md","page.html","page.tsx"]),steps:c.number().int().positive(),slots:c.array(Je),source:We.optional()}).strict().superRefine((e,t)=>{const i=e.dialect==="md"?"page.md":e.dialect==="html"?"page.html":"page.tsx";e.document!==i&&t.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),e.dialect==="md"&&e.steps!==1&&t.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})});function Ke(e){if(e.source===void 0)return;const{blockedSince:t,...i}=e.source,s={...i,...t!==void 0&&c.string().datetime({offset:!0}).safeParse(t).success?{emittedAt:t}:{}};return Object.keys(s).length===0?void 0:s}r(Ke,"legacyPresentationSource");function Qe(e,t,i){return`export default function LegacyPage() { return <Page title={${JSON.stringify(e)}}${t===void 0?"":` subtitle={${JSON.stringify(t)}}`}><pre>{${JSON.stringify(i)}}</pre></Page>; }
53
- `}r(Qe,"legacyReplayDocument");function me(e){return Array.isArray(e.slots)?{...e,slots:e.slots.map(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const i=t;if(i.kind!=="text"||typeof i.config!="object"||i.config===null||Array.isArray(i.config))return t;const{editable:s,...n}=i.config;return{...i,config:n}})}:e}r(me,"withoutLegacyTextEditable");function Ye(e,t){const i=_(e,"page.json"),s=Be.safeParse(t);if(!s.success)throw new Error(s.error.message);const n=s.data,o=Ke(n),u={placement:n.placement,inbox:!0,reply:n.source?.blockedSince!==void 0};ie(me({schema:"crtr.page/v2",dialect:"jsx",title:n.title,...n.subtitle===void 0?{}:{subtitle:n.subtitle},delivery:u,document:"page.tsx",steps:n.steps,slots:n.slots,...o===void 0?{}:{source:o}}));const a=_(e,n.document);if(!y(a))throw new Error(`corrupt required input: ${a}`);const p=G(a,"utf8"),f=Re({dialect:"jsx",document:Qe(n.title,n.subtitle,p),source:o,delivery:u});if(o!==void 0)return f;const{source:E,...N}=f.manifest;return{...f,manifest:N}}r(Ye,"migrateLegacyPage");function Kt(e){e.exec(`
52
+ VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(r,i,t.requesterNodeId,o,o),r}s(Xe,"createMigratedTerminalDelivery");function pe(e,t){if(t.requesterNodeId===null||t.outcome===null||t.resultJson===null||t.settledAt===null)return null;const i=Fe(e,t.requestId,t.requesterNodeId,t.kind);return i!==null?i:t.deliveredAt!==null&&t.deliveredAt!==void 0?null:Xe(e,{requestId:t.requestId,requesterNodeId:t.requesterNodeId,kind:t.kind,outcome:t.outcome,resultJson:t.resultJson,settledAt:t.settledAt,requestDir:t.requestDir})}s(pe,"terminalDeliveryMark");const Be=c.object({sessionName:c.string().optional(),askedBy:c.string().optional(),blockedSince:c.string().optional(),profileName:c.string().optional(),nodeId:c.string().optional()}).strict(),Je=c.object({id:c.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:c.string().min(1),step:c.number().int().nonnegative(),config:c.record(c.string(),c.unknown()),unvalidated:c.literal(!0).optional(),display:c.literal(!0).optional()}).strict(),Ke=c.object({schema:c.literal("crtr.page/v1"),dialect:c.enum(["md","html","jsx"]),title:c.string().trim().min(1),subtitle:c.string().optional(),placement:c.enum(["inline","panel"]),document:c.enum(["page.md","page.html","page.tsx"]),steps:c.number().int().positive(),slots:c.array(Je),source:Be.optional()}).strict().superRefine((e,t)=>{const i=e.dialect==="md"?"page.md":e.dialect==="html"?"page.html":"page.tsx";e.document!==i&&t.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),e.dialect==="md"&&e.steps!==1&&t.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})});function Ye(e){if(e.source===void 0)return;const{blockedSince:t,...i}=e.source,r={...i,...t!==void 0&&c.string().datetime({offset:!0}).safeParse(t).success?{emittedAt:t}:{}};return Object.keys(r).length===0?void 0:r}s(Ye,"legacyPresentationSource");function Qe(e,t,i){return`export default function LegacyPage() { return <Page title={${JSON.stringify(e)}}${t===void 0?"":` subtitle={${JSON.stringify(t)}}`}><pre>{${JSON.stringify(i)}}</pre></Page>; }
53
+ `}s(Qe,"legacyReplayDocument");function me(e){return Array.isArray(e.slots)?{...e,slots:e.slots.map(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const i=t;if(i.kind!=="text"||typeof i.config!="object"||i.config===null||Array.isArray(i.config))return t;const{editable:r,...n}=i.config;return{...i,config:n}})}:e}s(me,"withoutLegacyTextEditable");function Ve(e,t){const i=l(e,"page.json"),r=Ke.safeParse(t);if(!r.success)throw new Error(r.error.message);const n=r.data,o=Ye(n),u={placement:n.placement,inbox:!0,reply:n.source?.blockedSince!==void 0};se(me({schema:"crtr.page/v2",dialect:"jsx",title:n.title,...n.subtitle===void 0?{}:{subtitle:n.subtitle},delivery:u,document:"page.tsx",steps:n.steps,slots:n.slots,...o===void 0?{}:{source:o}}));const d=l(e,n.document);if(!g(d))throw new Error(`corrupt required input: ${d}`);const p=z(d,"utf8"),m=Ae({dialect:"jsx",document:Qe(n.title,n.subtitle,p),source:o,delivery:u});if(o!==void 0)return m;const{source:E,...y}=m.manifest;return{...m,manifest:y}}s(Ve,"migrateLegacyPage");function Gt(e){e.exec(`
54
54
  CREATE TABLE human_requests (
55
55
  request_id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('page','review')),
56
56
  inbox_ticket_id TEXT NOT NULL UNIQUE, request_dir TEXT NOT NULL, presentation_dir TEXT,
@@ -73,10 +73,10 @@ ${JSON.stringify(t,null,2)}`].join(`
73
73
  CREATE INDEX idx_human_requests_submit ON human_requests(state, submit_requested_at);
74
74
  CREATE INDEX idx_human_requests_file ON human_requests(file);
75
75
  CREATE INDEX idx_human_requests_requester ON human_requests(requester_node_id);
76
- `);const t=l(e,`INSERT INTO human_requests (
76
+ `);const t=_(e,`INSERT INTO human_requests (
77
77
  request_id, kind, inbox_ticket_id, request_dir, presentation_dir, requester_node_id, companion_node_id, idempotency_key,
78
78
  state, outcome, inbox_listed, settleable, title, subtitle, file, specification_json, action_json,
79
79
  progress_json, feedback_json, result_json, anchor_base_sha256, anchor_base_bytes, created_at, opened_at,
80
80
  submit_requested_at, settled_at, settlement_delivery_id, action_delivery_id, projected_at, projection_error,
81
81
  companion_retired_at, updated_at
82
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const s=l(e,"SELECT * FROM reviews").all();for(const n of s){const o=n.state,u=o==="approved"||o==="canceled",a=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&a===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const p=n.bridge_node_id===null?_(z(),"reviews",n.review_id):_(q(),n.bridge_node_id),f={origin_kind:n.origin_kind,bridge_node_id:n.bridge_node_id,origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,captured_at:n.captured_at,output_path:n.output_path},E=u?o==="approved"?"approved":"canceled":null,N=u?o==="approved"?n.approved_at:n.canceled_at:null,S=pe(e,{requestId:n.review_id,requesterNodeId:n.origin_node_id,kind:"review",outcome:E,resultJson:a,settledAt:N,requestDir:p,deliveredAt:n.delivered_at}),D=le(e,n.companion_node_id,E)?N:null;t.run(n.review_id,"review",n.origin_kind==="ticket"?M(q(),C(p)):H(),p,null,n.origin_node_id,n.companion_node_id,n.idempotency_key,u?"settled":o,E,n.origin_kind==="ticket"?1:0,1,C(n.file),n.subtitle,n.file,JSON.stringify(f),null,null,null,a,n.anchor_base_sha256,n.anchor_base_bytes,n.created,n.opened_at,n.submit_requested_at,N,S,null,n.projected_at,n.projection_error,D,n.created)}e.exec("DROP TABLE reviews")}for(const s of y(q())?be(q(),{withFileTypes:!0}):[]){if(!s.isDirectory())continue;const n=_(q(),s.name),o=_(n,"page.json"),u=_(n,"review.json");if(!y(o)){if(y(u))continue;continue}if(l(e,"SELECT 1 FROM human_requests WHERE request_id = ?").get(s.name)!==void 0)continue;let a,p,f,E;try{const m=A(o);if(typeof m!="object"||m===null||Array.isArray(m))throw new Error("page manifest must be an object");a=m,a.schema==="crtr.page/v1"?(p=Ye(n,m),a=p.manifest):a.schema==="crtr.page/v2"&&(a=me(a));const w=ve.safeParse(a.delivery);if(typeof a.title!="string"||!w.success)throw new Error(w.success?"page title must be a string":w.error.message);E=w.data,f=ie(a)}catch(m){const w=m instanceof Error&&m.cause instanceof Error?m.cause.message:m instanceof Error?m.message:String(m);console.warn(`skipping legacy page ${o}: ${w}`);continue}let N=I(n);p!==void 0&&(N=ae($(s.name),p));const S=f.source,D=_(n,"response.json"),v=y(D)?A(D):null,b=v===null?null:$e(v),fe=l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'deliveries'").get()===void 0?null:l(e,"SELECT delivery_id FROM deliveries WHERE idempotency_key = ?").get(`human-action:${M(q(),s.name)}`),X=_(n,"action.json"),W=_(n,"progress.json"),j=_(n,"feedback-comments.json"),k=_(n,"reply-route.json"),T=y(j)?A(j):null;if(T!==null&&(typeof T!="object"||typeof T.companionNodeId<"u"&&typeof T.companionNodeId!="string"))throw new Error(`corrupt required input: ${j}`);const O=y(k)?A(k):null;if(O!==null&&(typeof O!="object"||typeof O.bridge_node_id!="string"))throw new Error(`corrupt required input: ${k}`);const J=O?.bridge_node_id,B=(typeof J!="string"||l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'nodes'").get()===void 0?null:l(e,"SELECT parent FROM nodes WHERE node_id = ?").get(J))?.parent??(typeof S?.nodeId=="string"?S.nodeId:null),K=T?.companionNodeId,Q=typeof S?.emittedAt=="string"?S.emittedAt:he(o).mtime.toISOString(),Y=v===null?null:JSON.stringify(v),Ee=pe(e,{requestId:s.name,requesterNodeId:B,kind:"page",outcome:b?.outcome??null,resultJson:Y,settledAt:b?.settledAt??null,requestDir:n}),ye=le(e,K??null,b?.outcome??null)?b?.settledAt??null:null,V=$(s.name);R(V,{recursive:!0,mode:448}),t.run(s.name,"page",M(q(),s.name),V,N,B,K??null,null,b===null?"open":"settled",b?.outcome??null,E.inbox?1:0,E.inbox||E.reply?1:0,f.title,f.subtitle??null,null,JSON.stringify(f),y(X)?JSON.stringify(A(X)):null,y(W)&&b===null?JSON.stringify(A(W)):null,T===null?null:JSON.stringify(T),Y,null,null,Q,null,null,b?.settledAt??null,Ee,fe?.delivery_id??null,null,null,ye,Q)}const i=l(e,"SELECT request_id FROM human_requests WHERE state = 'settled' AND result_json IS NULL").get();if(i!==void 0)throw new Error(`human request migration produced terminal row without result: ${i.request_id}`);if(l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'review_comments'").get()!==void 0){const s=l(e,"SELECT review_id FROM review_comments WHERE review_id NOT IN (SELECT request_id FROM human_requests WHERE kind = 'review') LIMIT 1").get();if(s!==void 0)throw new Error(`review comment has no migrated review request: ${s.review_id}`)}}r(Kt,"migrateHumanRequestsState");export{de as NOT_OTHER_APP_QUESTION,Ce as askingNodeSql,kt as cancelBindingRequest,ft as commitBindingRequest,mt as createPageRequest,Lt as firstInvalidPageSpecification,Et as getRequest,bt as getRequestByCompanion,Nt as getRequestByDirectory,ht as getRequestByIdempotencyKey,yt as getRequestByInboxTicket,gt as getRequestsByInboxTickets,St as hasOpenReplyBearingRequestByRequester,It as hasPageResultException,oe as humanRequestsRoot,At as listBindingRequests,Tt as listOpenInboxRequests,wt as listOpenReplyBearingRequests,xt as listPageSummaryRows,qt as listPendingAsks,vt as listRequests,Rt as listSubmitRequestedRequests,Dt as listUnprojectedReviews,Wt as markCompanionRetired,Ft as markProjected,Xt as markProjectionError,Kt as migrateHumanRequestsState,jt as openRequest,Ue as openRequestsByRequester,Ot as pageSummaryState,pt as presentationDir,ae as publishPageRevision,ke as publishPageRevisionTo,Jt as readAnchorBase,Bt as replaceAnchorBaseLocked,$ as requestDir,Ct as requestSubmit,Ht as revisePageRequest,Pt as setSettlementDeliveryMarksLocked,$t as setSubmitNoteDeliveryLocked,Ut as settleRequestLocked,Mt as writeProgress};
82
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(_(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const r=_(e,"SELECT * FROM reviews").all();for(const n of r){const o=n.state,u=o==="approved"||o==="canceled",d=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&d===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const p=n.bridge_node_id===null?l(Z(),"reviews",n.review_id):l(T(),n.bridge_node_id),m={origin_kind:n.origin_kind,bridge_node_id:n.bridge_node_id,origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,captured_at:n.captured_at,output_path:n.output_path},E=u?o==="approved"?"approved":"canceled":null,y=u?o==="approved"?n.approved_at:n.canceled_at:null,w=pe(e,{requestId:n.review_id,requesterNodeId:n.origin_node_id,kind:"review",outcome:E,resultJson:d,settledAt:y,requestDir:p,deliveredAt:n.delivered_at}),v=_e(e,n.companion_node_id,E)?y:null;t.run(n.review_id,"review",n.origin_kind==="ticket"?F(T(),C(p)):M(),p,null,n.origin_node_id,n.companion_node_id,n.idempotency_key,u?"settled":o,E,n.origin_kind==="ticket"?1:0,1,C(n.file),n.subtitle,n.file,JSON.stringify(m),null,null,null,d,n.anchor_base_sha256,n.anchor_base_bytes,n.created,n.opened_at,n.submit_requested_at,y,w,null,n.projected_at,n.projection_error,v,n.created)}e.exec("DROP TABLE reviews")}for(const r of g(T())?he(T(),{withFileTypes:!0}):[]){if(!r.isDirectory())continue;const n=l(T(),r.name),o=l(n,"page.json"),u=l(n,"review.json");if(!g(o)){if(g(u))continue;continue}if(_(e,"SELECT 1 FROM human_requests WHERE request_id = ?").get(r.name)!==void 0)continue;let d,p,m,E;try{const f=R(o);if(typeof f!="object"||f===null||Array.isArray(f))throw new Error("page manifest must be an object");d=f,d.schema==="crtr.page/v1"?(p=Ve(n,f),d=p.manifest):d.schema==="crtr.page/v2"&&(d=me(d));const S=De.safeParse(d.delivery);if(typeof d.title!="string"||!S.success)throw new Error(S.success?"page title must be a string":S.error.message);E=S.data,m=se(d)}catch(f){const S=f instanceof Error&&f.cause instanceof Error?f.cause.message:f instanceof Error?f.message:String(f);console.warn(`skipping legacy page ${o}: ${S}`);continue}let y=I(n);p!==void 0&&(y=ae(H(r.name),p));const w=m.source,v=l(n,"response.json"),D=g(v)?R(v):null,N=D===null?null:He(D),fe=_(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'deliveries'").get()===void 0?null:_(e,"SELECT delivery_id FROM deliveries WHERE idempotency_key = ?").get(`human-action:${F(T(),r.name)}`),X=l(n,"action.json"),B=l(n,"progress.json"),j=l(n,"feedback-comments.json"),k=l(n,"reply-route.json"),q=g(j)?R(j):null;if(q!==null&&(typeof q!="object"||typeof q.companionNodeId<"u"&&typeof q.companionNodeId!="string"))throw new Error(`corrupt required input: ${j}`);const O=g(k)?R(k):null;if(O!==null&&(typeof O!="object"||typeof O.bridge_node_id!="string"))throw new Error(`corrupt required input: ${k}`);const J=O?.bridge_node_id,K=(typeof J!="string"||_(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'nodes'").get()===void 0?null:_(e,"SELECT parent FROM nodes WHERE node_id = ?").get(J))?.parent??(typeof w?.nodeId=="string"?w.nodeId:null),Y=q?.companionNodeId,Q=typeof w?.emittedAt=="string"?w.emittedAt:be(o).mtime.toISOString(),V=D===null?null:JSON.stringify(D),Ee=pe(e,{requestId:r.name,requesterNodeId:K,kind:"page",outcome:N?.outcome??null,resultJson:V,settledAt:N?.settledAt??null,requestDir:n}),ye=_e(e,Y??null,N?.outcome??null)?N?.settledAt??null:null,G=H(r.name);A(G,{recursive:!0,mode:448}),t.run(r.name,"page",F(T(),r.name),G,y,K,Y??null,null,N===null?"open":"settled",N?.outcome??null,E.inbox?1:0,E.inbox||E.reply?1:0,m.title,m.subtitle??null,null,JSON.stringify(m),g(X)?JSON.stringify(R(X)):null,g(B)&&N===null?JSON.stringify(R(B)):null,q===null?null:JSON.stringify(q),V,null,null,Q,null,null,N?.settledAt??null,Ee,fe?.delivery_id??null,null,null,ye,Q)}const i=_(e,"SELECT request_id FROM human_requests WHERE state = 'settled' AND result_json IS NULL").get();if(i!==void 0)throw new Error(`human request migration produced terminal row without result: ${i.request_id}`);if(_(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'review_comments'").get()!==void 0){const r=_(e,"SELECT review_id FROM review_comments WHERE review_id NOT IN (SELECT request_id FROM human_requests WHERE kind = 'review') LIMIT 1").get();if(r!==void 0)throw new Error(`review comment has no migrated review request: ${r.review_id}`)}}s(Gt,"migrateHumanRequestsState");export{de as NOT_OTHER_APP_QUESTION,Ce as askingNodeSql,$t as cancelBindingRequest,Et as commitBindingRequest,ft as createPageRequest,Ut as firstInvalidPageSpecification,yt as getRequest,bt as getRequestByCompanion,ht as getRequestByDirectory,qt as getRequestByIdempotencyKey,gt as getRequestByInboxTicket,Nt as getRequestsByInboxTickets,St as hasOpenReplyBearingRequestByRequester,Ct as hasPageResultException,oe as humanRequestsRoot,Ot as listBindingRequests,Tt as listOpenInboxRequests,Rt as listOpenReplyBearingRequests,kt as listPageSummaryRows,wt as listPendingAsks,Lt as listRequests,Dt as listReviewRequestIds,At as listReviewRequests,xt as listSubmitRequestedRequests,It as listUnprojectedReviews,Yt as markCompanionRetired,Jt as markProjected,Kt as markProjectionError,Gt as migrateHumanRequestsState,Pt as openRequest,Ue as openRequestsByRequester,jt as pageSummaryState,mt as presentationDir,ae as publishPageRevision,ke as publishPageRevisionTo,Qt as readAnchorBase,Vt as replaceAnchorBaseLocked,H as requestDir,Ht as requestSubmit,vt as reviewRequestIdsByRequesters,Xt as revisePageRequest,Ft as setSettlementDeliveryMarksLocked,Wt as setSubmitNoteDeliveryLocked,Mt as settleRequestLocked,Bt as writeProgress};
@@ -1 +1 @@
1
- var ue=Object.defineProperty;var u=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{closeSync as H,constants as le,createWriteStream as ce}from"node:fs";import{basename as fe,extname as pe,isAbsolute as he,join as F}from"node:path";import{Transform as we,Writable as _e}from"node:stream";import{pipeline as N}from"node:stream/promises";import{appSpace as W}from"../layout.js";import{RunError as T}from"../runs/operations.js";import{createFileBeneath as ge,existsBeneath as P,openBeneath as ye,removeTreeBeneath as I,setModeBeneath as me,unlinkBeneath as be,withDirBeneath as $e}from"../spaces/open-beneath.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{isCloudRole as O}from"../canvas/person-state.js";import{invalidStorageName as X,storageClient as B,StorageRefused as z,UPLOAD_MAX_BYTES as j}from"../storage/client.js";import{openCallerFile as Se}from"../storage/caller-file.js";import{contentTypeFor as Ee}from"../storage/media-types.js";import{withCanvasWrite as Y}from"../canvas/db.js";import{deleteUploadUse as G,getUpload as L,insertUpload as ze,insertUploadUses as J,setUploadSize as K,uploadUseAt as Ue}from"../storage/tables.js";import{ProviderError as s}from"./errors.js";const Ae=11e4,Ce="app:terminal";function Q(e){if(e.class==="person")return e.grantee??Ce;if(!e.grantee)throw new s("server_error","provider caller has no grantee");return e.grantee}u(Q,"grantee");function Re(e){if(e.class==="person"&&e.sub)throw new s("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:Q(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Re,"fileCaller");function m(e){return e instanceof s?e:e instanceof z?new s("storage_unavailable",`storage refused: ${e.message}`):e instanceof T&&e.code==="storage_unavailable"&&e.retryable?new s("storage_unavailable",e.message):e}u(m,"storageFailure");const S=u(e=>new s("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,o){if(typeof o!="string"||!o||!he(o)||o.includes("\0"))throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});let a;try{a=Se(Re(e),o)}catch(i){throw i instanceof T?i.code==="scope_missing"?new s("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new s("not_found",`no such file: ${o}`,{param:t}):i:i}try{if(a.size>j)throw new s("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=fe(a.path),n=X(i);if(n)throw new s("invalid_request",`${t}: file name cannot be sent: ${n}`,{param:t});return{param:t,file:a,name:i,mediaType:Ee(a.path)}}catch(i){throw H(a.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const o=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(o.upload_link,t.file.fd,t.file.size,t.mediaType);const a=await e.signOutbound(o.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:o.object_id,url:a.url}}catch(o){throw m(o)}}u(Te,"copyOutbound");function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Object.keys(e),o=e.upload_id;return t.length===1&&typeof o=="string"&&o!==""?o:null}u(Oe,"uploadRef");async function Be(e,t,o,a){if(!O())throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});const i=await L(o);if(!i||i.delete_pending_since||i.grantee!==e.grantee||i.sub!==null&&i.sub!==(e.sub??null))throw new s("not_found",`no such upload: ${o}`,{param:t});try{const n=await a().signDownload(o);return{param:t,path:"",name:i.name,object_id:o,upload_id:o,url:n.url}}catch(n){throw n instanceof z?new s("not_found",`upload ${o} holds no bytes`,{param:t}):m(n)}}u(Be,"uploadArgument");async function V(e,t,o,a){const i=[],n=[];try{for(const r of t){if(o[r]===void 0||o[r]===null)continue;const f=Oe(o[r]);if(f!==null){n.push(await Be(e,r,f,a));continue}i.push(Fe(e,r,o[r]))}if(!i.length)return n;let c;try{c=a()}catch(r){throw m(r)}const d=[...n];for(const r of i)d.push(await Te(c,r));return d}finally{for(const c of i)H(c.file.fd)}}u(V,"copyArguments");function Z(e){const t=X(e);if(t)throw new s("server_error",`file output ${e} cannot name an upload: ${t}`)}u(Z,"checkOutputField");async function ee(e,t,o){Z(t);const a=Q(e),i="application/octet-stream";let n;try{n=await o().createResultUpload({name:t,media_type:i,max_size:j})}catch(c){throw m(c)}return await ze({upload_id:n.upload_id,grantee:a,...O()&&e.sub?{sub:e.sub}:{},name:t,media_type:i,size:j,created_at:new Date().toISOString()}),{field:t,upload_id:n.upload_id,upload_link:n.upload_link,grantee:a}}u(ee,"createResultUpload");function te(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(te,"uploadHeaders");function oe(e,t){const o={...e};for(const a of t)o[a.param]=a.url;return o}u(oe,"withUrls");async function et(e,t,o,a={}){const i=a.storage??B;t.output&&Z(t.output);const n=await V(e,t.params,o,i),c=t.output?await ee(e,t.output,i):null;return{arguments:oe(o,n),copies:n,upload:c,headers:te(c)}}u(et,"prepareFileCall");async function tt(e,t,o,a,i={}){const n=i.storage??B,c=[];for(const r of a.copies)try{const f=r.upload_id?await n().signDownload(r.upload_id):await n().signOutbound(r.object_id);c.push({...r,url:f.url})}catch(f){if(!(f instanceof z))throw m(f);c.push(...await V(e,[r.param],o,n))}let d=a.upload;if(d)try{const r=await n().signUploadLink(d.upload_id);d={...d,upload_link:r.upload_link}}catch(r){if(!(r instanceof z))throw m(r);r.status===404&&(d=await ee(e,t.output??d.field,n))}return{arguments:oe(o,c),copies:c,upload:d,headers:te(d)}}u(tt,"resignForRetry");const je=/^[0-9a-f]{64}$/i;function Le(e,t){if(t===1)return e;const o=pe(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}u(Le,"candidate");async function ot(e,t,o,a={}){const i={result:o,file:null,cleanup:u(async()=>{},"cleanup")},n=t.upload;if(!n||!o||typeof o!="object"||Array.isArray(o))return i;const c=o,d=c[n.field];if(d==null)return i;if(typeof d!="object"||Array.isArray(d))throw S(`${n.field} must be {upload_id, size, sha256}`);const r=d;if(typeof r.upload_id!="string"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.sha256!="string"||!je.test(r.sha256))throw S(`${n.field} must be {upload_id, size, sha256}`);if(r.upload_id!==n.upload_id)throw S(`${n.field} names an upload other than Crtr-Upload-Id`);const f=r.size,U=r.sha256.toLowerCase(),_=AbortSignal.timeout(a.budgetMs??Ae),E=a.signal?AbortSignal.any([_,a.signal]):_;let l;try{l=await(a.storage??B)().fetchUpload(n.upload_id,E)}catch(y){throw y instanceof z?S(`${n.field} names an upload with nothing stored`):m(y)}if(l.size===null)throw l.body.destroy(),new s("storage_unavailable",`storage did not say how many bytes ${n.field} holds`);if(l.size!==f)throw l.body.destroy(),S(`${n.field} claims ${f} bytes; storage holds ${l.size}`);if(O())return await De(e,n,c,r,l,E,_);const b=n.grantee,w=e.node_id!==null,ne=await ve(b),h=w?W(b).nodes:W(b).files,R=w?F(h,e.node_id):h,A=w?F(R,"attachments"):h,ie={uid:process.getuid?.()??0,gid:ne.gid},D=w&&!P(h,R),re=w&&!D&&!P(h,A);let g=null,C=null,k=!1;const q=u(async()=>{if(!k){if(k=!0,C)try{await G(C)}catch{}if(g)try{be(h,g)}catch{}try{D?I(h,R):re&&I(h,A)}catch{}}},"cleanup");try{$e(h,A,()=>{},!0);for(let p=1;;p++){const $=F(A,Le(n.field,p));if(!await Ue($))try{ge(h,$,Buffer.alloc(0),432),g=$;break}catch(v){if(v.code!=="EEXIST")throw v}}let y=0;const M=x("sha256"),ae=new we({transform(p,$,v){y+=p.length,M.update(p),v(null,p)}}),se=ye(h,g,le.O_WRONLY);try{await N(l.body,ae,ce("",{fd:se,autoClose:!0}),{signal:E})}catch(p){throw _.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):p instanceof T?m(p):new s("storage_unavailable",`storage stopped sending ${n.field}: ${p instanceof Error?p.message:String(p)}`)}if(y!==f)throw new s("storage_unavailable",`storage sent ${y} of ${f} bytes of ${n.field}`);if(M.digest("hex")!==U)throw S(`${n.field}: the stored bytes do not match sha256`);me(h,g,432,ie);const de=g;await Y(async p=>{const $=await L(n.upload_id,p);if(!$||$.delete_pending_since)throw new s("not_found",`${n.field}: the upload was deleted while it was fetched`);if(await K(n.upload_id,f,p),!e.run_id)return;const v=await p.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!v||v.deleting_at)throw new s("not_found",`run ${e.run_id} was deleted while its file result was fetched`);C={upload_id:n.upload_id,run_id:e.run_id,path:de},await J([C],p)})}catch(y){throw l.body.destroy(),await q(),y}return{result:{...c,[n.field]:g},file:{path:g,upload_id:n.upload_id},cleanup:q}}u(ot,"resolveFileResult");async function De(e,t,o,a,i,n,c){const d=a.size,r=a.sha256.toLowerCase();if(!e.run_id)throw i.body.destroy(),new s("invalid_request","a file result needs a node to deliver it to");const f=e.run_id,U=x("sha256");let _=0;try{await N(i.body,new _e({write(l,b,w){U.update(l),_+=l.length,w()}}),{signal:n})}catch(l){throw i.body.destroy(),c.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):new s("storage_unavailable",`storage stopped sending ${t.field}: ${l instanceof Error?l.message:String(l)}`)}if(_!==d)throw new s("storage_unavailable",`storage sent ${_} of ${d} bytes of ${t.field}`);if(U.digest("hex")!==r)throw S(`${t.field}: the stored bytes do not match sha256`);const E={upload_id:t.upload_id,run_id:f,path:`upload:${t.upload_id}`};return await Y(async l=>{const b=await L(t.upload_id,l);if(!b||b.delete_pending_since)throw new s("not_found",`${t.field}: the upload was deleted while it was checked`);const w=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(f);if(!w||w.deleting_at)throw new s("not_found",`run ${f} was deleted while its file result was checked`);await K(t.upload_id,d,l),await J([E],l)}),{result:{...o,[t.field]:{upload_id:t.upload_id,size:d,sha256:r}},file:{path:"",upload_id:t.upload_id},cleanup:u(async()=>{try{await G(E)}catch{}},"cleanup")}}u(De,"keepCloudResult");export{Ae as FILE_RESULT_FETCH_BUDGET_MS,et as prepareFileCall,tt as resignForRetry,ot as resolveFileResult};
1
+ var ue=Object.defineProperty;var u=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{closeSync as H,constants as le,createWriteStream as ce}from"node:fs";import{basename as fe,extname as pe,isAbsolute as he,join as F}from"node:path";import{Transform as we,Writable as _e}from"node:stream";import{pipeline as N}from"node:stream/promises";import{appSpace as W}from"../layout.js";import{RunError as T}from"../runs/operations.js";import{createFileBeneath as ge,existsBeneath as P,openBeneath as ye,removeTreeBeneath as I,setModeBeneath as me,unlinkBeneath as be,withDirBeneath as $e}from"../spaces/open-beneath.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{isCloudRole as O}from"../canvas/person-state.js";import{invalidStorageName as X,storageClient as B,StorageRefused as z,UPLOAD_MAX_BYTES as j}from"../storage/client.js";import{openCallerFile as Se}from"../storage/caller-file.js";import{contentTypeFor as Ee}from"../storage/media-types.js";import{withCanvasWrite as Y}from"../canvas/db.js";import{deleteUploadUse as G,getUpload as L,insertUpload as ze,insertUploadUses as J,setUploadSize as K,uploadUseAt as Ue}from"../storage/tables.js";import{ProviderError as s}from"./errors.js";const Ae=11e4,Ce="app:terminal";function Q(e){if(e.class==="person")return e.grantee??Ce;if(!e.grantee)throw new s("server_error","provider caller has no grantee");return e.grantee}u(Q,"grantee");function Re(e){if(e.class==="person"&&e.sub)throw new s("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:Q(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Re,"fileCaller");function m(e){return e instanceof s?e:e instanceof z?new s("storage_unavailable",`storage refused: ${e.message}`):e instanceof T&&e.code==="storage_unavailable"&&e.retryable?new s("storage_unavailable",e.message):e}u(m,"storageFailure");const S=u(e=>new s("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!he(n)||n.includes("\0"))throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});let a;try{a=Se(Re(e),n)}catch(i){throw i instanceof T?i.code==="scope_missing"?new s("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new s("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(a.size>j)throw new s("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=fe(a.path),o=X(i);if(o)throw new s("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:a,name:i,mediaType:Ee(a.path)}}catch(i){throw H(a.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const a=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:a.url}}catch(n){throw m(n)}}u(Te,"copyOutbound");function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Object.keys(e),n=e.upload_id;return t.length===1&&typeof n=="string"&&n!==""?n:null}u(Oe,"uploadRef");async function Be(e,t,n,a){if(!O())throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});const i=await L(n);if(!i||i.delete_pending_since||i.grantee!==e.grantee||i.sub!==null&&i.sub!==(e.sub??null))throw new s("not_found",`no such upload: ${n}`,{param:t});try{const o=await a().signDownload(n);return{param:t,path:"",name:i.name,object_id:n,upload_id:n,url:o.url}}catch(o){throw o instanceof z?new s("not_found",`upload ${n} holds no bytes`,{param:t}):m(o)}}u(Be,"uploadArgument");async function V(e,t,n,a){const i=[],o=[];try{for(const r of t){if(n[r]===void 0||n[r]===null)continue;const f=Oe(n[r]);if(f!==null){o.push(await Be(e,r,f,a));continue}i.push(Fe(e,r,n[r]))}if(!i.length)return o;let c;try{c=a()}catch(r){throw m(r)}const d=[...o];for(const r of i)d.push(await Te(c,r));return d}finally{for(const c of i)H(c.file.fd)}}u(V,"copyArguments");function Z(e){const t=X(e);if(t)throw new s("server_error",`file output ${e} cannot name an upload: ${t}`)}u(Z,"checkOutputField");async function ee(e,t,n){Z(t);const a=Q(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:j})}catch(c){throw m(c)}return await ze({upload_id:o.upload_id,grantee:a,...O()&&e.sub?{sub:e.sub}:{},name:t,media_type:i,size:j,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:a}}u(ee,"createResultUpload");function te(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(te,"uploadHeaders");function ne(e,t){const n={...e};for(const a of t)n[a.param]=a.url;return n}u(ne,"withUrls");async function et(e,t,n,a={}){const i=a.storage??B;t.output&&Z(t.output);const o=await V(e,t.params,n,i),c=t.output?await ee(e,t.output,i):null;return{arguments:ne(n,o),copies:o,upload:c,headers:te(c)}}u(et,"prepareFileCall");async function tt(e,t,n,a,i={}){const o=i.storage??B,c=[];for(const r of a.copies)try{const f=r.upload_id?await o().signDownload(r.upload_id):await o().signOutbound(r.object_id);c.push({...r,url:f.url})}catch(f){if(!(f instanceof z))throw m(f);c.push(...await V(e,[r.param],n,o))}let d=a.upload;if(d)try{const r=await o().signUploadLink(d.upload_id);d={...d,upload_link:r.upload_link}}catch(r){if(!(r instanceof z))throw m(r);r.status===404&&(d=await ee(e,t.output??d.field,o))}return{arguments:ne(n,c),copies:c,upload:d,headers:te(d)}}u(tt,"resignForRetry");const je=/^[0-9a-f]{64}$/i;function Le(e,t){if(t===1)return e;const n=pe(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Le,"candidate");async function nt(e,t,n,a={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,d=c[o.field];if(d==null)return i;if(typeof d!="object"||Array.isArray(d))throw S(`${o.field} must be {upload_id, size, sha256}`);const r=d;if(typeof r.upload_id!="string"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.sha256!="string"||!je.test(r.sha256))throw S(`${o.field} must be {upload_id, size, sha256}`);if(r.upload_id!==o.upload_id)throw S(`${o.field} names an upload other than Crtr-Upload-Id`);const f=r.size,U=r.sha256.toLowerCase(),_=AbortSignal.timeout(a.budgetMs??Ae),E=a.signal?AbortSignal.any([_,a.signal]):_;let l;try{l=await(a.storage??B)().fetchUpload(o.upload_id,E)}catch(y){throw y instanceof z?S(`${o.field} names an upload with nothing stored`):m(y)}if(l.size===null)throw l.body.destroy(),new s("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(l.size!==f)throw l.body.destroy(),S(`${o.field} claims ${f} bytes; storage holds ${l.size}`);if(O())return await De(e,o,c,r,l,E,_);const b=o.grantee,w=e.node_id!==null,oe=await ve(b),h=w?W(b).nodes:W(b).files,A=w?F(h,e.node_id):h,C=w?F(A,"attachments"):h,ie={uid:process.getuid?.()??0,gid:oe.gid},D=w&&!P(h,A),re=w&&!D&&!P(h,C);let g=null,R=null,k=!1;const q=u(async()=>{if(!k){if(k=!0,R)try{await G(R)}catch{}if(g)try{be(h,g)}catch{}try{D?I(h,A):re&&I(h,C)}catch{}}},"cleanup");try{$e(h,C,()=>{},!0);for(let p=1;;p++){const $=F(C,Le(o.field,p));if(!await Ue($,void 0,w?{nodeId:e.node_id,nodeDir:A}:void 0))try{ge(h,$,Buffer.alloc(0),432),g=$;break}catch(v){if(v.code!=="EEXIST")throw v}}let y=0;const M=x("sha256"),ae=new we({transform(p,$,v){y+=p.length,M.update(p),v(null,p)}}),se=ye(h,g,le.O_WRONLY);try{await N(l.body,ae,ce("",{fd:se,autoClose:!0}),{signal:E})}catch(p){throw _.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):p instanceof T?m(p):new s("storage_unavailable",`storage stopped sending ${o.field}: ${p instanceof Error?p.message:String(p)}`)}if(y!==f)throw new s("storage_unavailable",`storage sent ${y} of ${f} bytes of ${o.field}`);if(M.digest("hex")!==U)throw S(`${o.field}: the stored bytes do not match sha256`);me(h,g,432,ie);const de=g;await Y(async p=>{const $=await L(o.upload_id,p);if(!$||$.delete_pending_since)throw new s("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await K(o.upload_id,f,p),!e.run_id)return;const v=await p.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!v||v.deleting_at)throw new s("not_found",`run ${e.run_id} was deleted while its file result was fetched`);R={upload_id:o.upload_id,run_id:e.run_id,path:de},await J([R],p)})}catch(y){throw l.body.destroy(),await q(),y}return{result:{...c,[o.field]:g},file:{path:g,upload_id:o.upload_id},cleanup:q}}u(nt,"resolveFileResult");async function De(e,t,n,a,i,o,c){const d=a.size,r=a.sha256.toLowerCase();if(!e.run_id)throw i.body.destroy(),new s("invalid_request","a file result needs a node to deliver it to");const f=e.run_id,U=x("sha256");let _=0;try{await N(i.body,new _e({write(l,b,w){U.update(l),_+=l.length,w()}}),{signal:o})}catch(l){throw i.body.destroy(),c.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):new s("storage_unavailable",`storage stopped sending ${t.field}: ${l instanceof Error?l.message:String(l)}`)}if(_!==d)throw new s("storage_unavailable",`storage sent ${_} of ${d} bytes of ${t.field}`);if(U.digest("hex")!==r)throw S(`${t.field}: the stored bytes do not match sha256`);const E={upload_id:t.upload_id,run_id:f,path:`upload:${t.upload_id}`};return await Y(async l=>{const b=await L(t.upload_id,l);if(!b||b.delete_pending_since)throw new s("not_found",`${t.field}: the upload was deleted while it was checked`);const w=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(f);if(!w||w.deleting_at)throw new s("not_found",`run ${f} was deleted while its file result was checked`);await K(t.upload_id,d,l),await J([E],l)}),{result:{...n,[t.field]:{upload_id:t.upload_id,size:d,sha256:r}},file:{path:"",upload_id:t.upload_id},cleanup:u(async()=>{try{await G(E)}catch{}},"cleanup")}}u(De,"keepCloudResult");export{Ae as FILE_RESULT_FETCH_BUDGET_MS,et as prepareFileCall,tt as resignForRetry,nt as resolveFileResult};
@@ -1 +1 @@
1
- var u=Object.defineProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});import{requestFileExists as l}from"../human/request-files.js";import{withCanvasWrite as d,openDb as s}from"../canvas/db.js";import{getRequest as _,getRequestByCompanion as p,getRequestByIdempotencyKey as w,listBindingRequests as m,listRequests as c,listSubmitRequestedRequests as v,listUnprojectedReviews as f,markProjected as y,markProjectionError as h,openRequest as R,readAnchorBase as E,replaceAnchorBaseLocked as j,requestSubmit as k}from"../human/requests.js";import{ReviewOperationError as b}from"./types.js";function g(e){try{const t=JSON.parse(e.specification_json);if(typeof t!="object"||t===null)throw new Error("not an object");return t}catch(t){throw new Error(`corrupt review specification: ${e.request_id}`,{cause:t})}}r(g,"specification");function x(e){return e.state!=="settled"?e.state:e.outcome==="approved"?"approved":"canceled"}r(x,"state");function N(e,t){if(e.kind!=="review")throw new Error(`human request is not a review: ${e.request_id}`);const n=g(e),i=x(e),o=e.settled_at;return{review_id:e.request_id,idempotency_key:e.idempotency_key??"",origin_kind:n.origin_kind??(e.inbox_listed?"ticket":"inline"),origin_node_id:e.requester_node_id??"",companion_node_id:e.companion_node_id??"",review_dir:e.request_dir,file:e.file??"",origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,anchor_base_sha256:e.anchor_base_sha256??"",state:i,created:e.created_at,captured_at:n.captured_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,output_path:n.output_path??null,document_id:n.document_id??null,document_name:n.document_name??null,document_base:n.document_base??null,subtitle:e.subtitle,approved_at:i==="approved"?o:null,approved_sha256:i==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").approved_sha256??null}catch{return null}})():null,changed:i==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").changed??null}catch{return null}})():null,comments_total:i==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").comments_total??null}catch{return null}})():null,comments_unresolved:i==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").comments_unresolved??null}catch{return null}})():null,result_json:e.result_json,canceled_at:i==="canceled"?o:null,cancel_reason:i==="canceled"?(()=>{try{return JSON.parse(e.result_json??"{}").reason??null}catch{return null}})():null,cancel_actor:i==="canceled"?(()=>{try{return JSON.parse(e.result_json??"{}").actor??null}catch{return null}})():null,delivery_entry_id:e.settlement_delivery_id,delivered_at:e.settlement_delivery_id===null?null:o,delivery_error:null,projected_at:e.projected_at,projection_error:e.projection_error,source_missing:t}}r(N,"record");async function a(e){return N(e,!await l(e.file??""))}r(a,"recordOf");async function S(e){const t=await _(e);return t?.kind==="review"?t:null}r(S,"requestForReview");async function A(e){const t=await S(e);return t===null?null:await a(t)}r(A,"getReview");async function U(e){const t=await A(e);if(t===null||t.state==="binding")throw new b("unknown_review","review was not found",{received:e});return t}r(U,"requireVisibleReview");async function T(e){const t=await w(e);return t?.kind==="review"?await a(t):null}r(T,"getReviewByIdempotencyKey");async function I(e){const t=await p(e);return t?.kind==="review"?await a(t):null}r(I,"getReviewByCompanion");async function J(e){const t=await c({kind:"review",...e.origin_node_id===void 0?{}:{requester_node_id:e.origin_node_id},...e.file===void 0?{}:{file:e.file}});return(await Promise.all(t.map(a))).filter(n=>n.state!=="binding"&&(e.state===void 0||n.state===e.state))}r(J,"listReviews");async function D(e){const t=new Set(e);return(await c({kind:"review"})).filter(n=>n.requester_node_id!==null&&t.has(n.requester_node_id)).map(n=>n.request_id)}r(D,"reviewIdsByOriginNodes");async function W(e){const t=await D(e);return t.length===0?[]:(await d(async n=>{const i=t.map(()=>"?").join(",");await n.prepareUncached(`DELETE FROM review_comment_events WHERE review_id IN (${i})`).run(...t),await n.prepareUncached(`DELETE FROM review_comments WHERE review_id IN (${i})`).run(...t),await n.prepareUncached(`DELETE FROM human_requests WHERE request_id IN (${i})`).run(...t)}),t)}r(W,"deleteReviewsByOriginNodes");async function H(){return await Promise.all((await m()).map(a))}r(H,"listBindingReviews");async function F(){return await Promise.all((await v()).map(a))}r(F,"listSubmitRequestedReviews");async function $(){return await Promise.all((await f()).map(a))}r($,"listUnprojectedTerminalReviews");async function C(e,t){return await R(e,t)}r(C,"openReviewRow");async function M(e){await(await s()).prepare("UPDATE human_requests SET submit_requested_at = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(new Date().toISOString(),e)}r(M,"clearReviewSubmit");async function K(e,t){return await k(e,t)}r(K,"requestReviewSubmit");async function V(e,t){return(await e.prepare("UPDATE human_requests SET state = 'settled', outcome = 'approved', result_json = ?, settled_at = ?, progress_json = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(t.result_json,t.approved_at,t.approved_at,t.review_id)).changes>0}r(V,"approveReviewLocked");async function z(e,t){return(await(await s()).prepare("UPDATE human_requests SET state = 'settled', outcome = 'canceled', result_json = ?, settled_at = ?, progress_json = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t.at,...t.reason===""?{}:{reason:t.reason},...t.actor===null?{}:{actor:t.actor}}),t.at,t.at,e)).changes>0}r(z,"cancelReviewRow");async function G(e,t){await y(e,t)}r(G,"markProjected");async function Q(e,t){await h(e,t)}r(Q,"markProjectionError");function X(e,t,n){}r(X,"markDelivered");function Y(e,t){}r(Y,"markDeliveryError");async function Z(e){return await E(e)}r(Z,"readAnchorBase");async function ee(e,t,n,i){await j(e,t,n,i)}r(ee,"replaceAnchorBaseLocked");export{V as approveReviewLocked,z as cancelReviewRow,M as clearReviewSubmit,W as deleteReviewsByOriginNodes,A as getReview,I as getReviewByCompanion,T as getReviewByIdempotencyKey,H as listBindingReviews,J as listReviews,F as listSubmitRequestedReviews,$ as listUnprojectedTerminalReviews,X as markDelivered,Y as markDeliveryError,G as markProjected,Q as markProjectionError,C as openReviewRow,Z as readAnchorBase,ee as replaceAnchorBaseLocked,K as requestReviewSubmit,U as requireVisibleReview,D as reviewIdsByOriginNodes};
1
+ var c=Object.defineProperty;var n=(e,t)=>c(e,"name",{value:t,configurable:!0});import{requestFileExists as u}from"../human/request-files.js";import{withCanvasWrite as l,openDb as s}from"../canvas/db.js";import{getRequest as d,getRequestByCompanion as _,getRequestByIdempotencyKey as p,listBindingRequests as w,listReviewRequests as m,reviewRequestIdsByRequesters as v,listSubmitRequestedRequests as y,listUnprojectedReviews as f,markProjected as h,markProjectionError as R,openRequest as E,readAnchorBase as j,replaceAnchorBaseLocked as b,requestSubmit as k}from"../human/requests.js";import{ReviewOperationError as g}from"./types.js";function x(e){try{const t=JSON.parse(e.specification_json);if(typeof t!="object"||t===null)throw new Error("not an object");return t}catch(t){throw new Error(`corrupt review specification: ${e.request_id}`,{cause:t})}}n(x,"specification");function N(e){return e.state!=="settled"?e.state:e.outcome==="approved"?"approved":"canceled"}n(N,"state");function S(e,t){if(e.kind!=="review")throw new Error(`human request is not a review: ${e.request_id}`);const r=x(e),a=N(e),o=e.settled_at;return{review_id:e.request_id,idempotency_key:e.idempotency_key??"",origin_kind:r.origin_kind??(e.inbox_listed?"ticket":"inline"),origin_node_id:e.requester_node_id??"",companion_node_id:e.companion_node_id??"",review_dir:e.request_dir,file:e.file??"",origin_session_file:r.origin_session_file,origin_session_id:r.origin_session_id,origin_leaf_id:r.origin_leaf_id,model_spec:r.model_spec,branch_file:r.branch_file,baseline_sha256:r.baseline_sha256,baseline_bytes:r.baseline_bytes,anchor_base_sha256:e.anchor_base_sha256??"",state:a,created:e.created_at,captured_at:r.captured_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,output_path:r.output_path??null,document_id:r.document_id??null,document_name:r.document_name??null,document_base:r.document_base??null,subtitle:e.subtitle,approved_at:a==="approved"?o:null,approved_sha256:a==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").approved_sha256??null}catch{return null}})():null,changed:a==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").changed??null}catch{return null}})():null,comments_total:a==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").comments_total??null}catch{return null}})():null,comments_unresolved:a==="approved"?(()=>{try{return JSON.parse(e.result_json??"{}").comments_unresolved??null}catch{return null}})():null,result_json:e.result_json,canceled_at:a==="canceled"?o:null,cancel_reason:a==="canceled"?(()=>{try{return JSON.parse(e.result_json??"{}").reason??null}catch{return null}})():null,cancel_actor:a==="canceled"?(()=>{try{return JSON.parse(e.result_json??"{}").actor??null}catch{return null}})():null,delivery_entry_id:e.settlement_delivery_id,delivered_at:e.settlement_delivery_id===null?null:o,delivery_error:null,projected_at:e.projected_at,projection_error:e.projection_error,source_missing:t}}n(S,"record");async function i(e){return S(e,!await u(e.file??""))}n(i,"recordOf");async function A(e){const t=await d(e);return t?.kind==="review"?t:null}n(A,"requestForReview");async function D(e){const t=await A(e);return t===null?null:await i(t)}n(D,"getReview");async function I(e){const t=await D(e);if(t===null||t.state==="binding")throw new g("unknown_review","review was not found",{received:e});return t}n(I,"requireVisibleReview");async function T(e){const t=await p(e);return t?.kind==="review"?await i(t):null}n(T,"getReviewByIdempotencyKey");async function J(e){const t=await _(e);return t?.kind==="review"?await i(t):null}n(J,"getReviewByCompanion");async function W(e){if(e.state==="binding")return[];const t=await m({...e.state===void 0?{}:{state:e.state},...e.origin_node_id===void 0?{}:{requester_node_id:e.origin_node_id},...e.file===void 0?{}:{file:e.file}});return await Promise.all(t.map(i))}n(W,"listReviews");async function O(e){return await v(e)}n(O,"reviewIdsByOriginNodes");async function H(e){const t=await O(e);return t.length===0?[]:(await l(async r=>{const a=t.map(()=>"?").join(",");await r.prepareUncached(`DELETE FROM review_comment_events WHERE review_id IN (${a})`).run(...t),await r.prepareUncached(`DELETE FROM review_comments WHERE review_id IN (${a})`).run(...t),await r.prepareUncached(`DELETE FROM human_requests WHERE request_id IN (${a})`).run(...t)}),t)}n(H,"deleteReviewsByOriginNodes");async function F(){return await Promise.all((await w()).map(i))}n(F,"listBindingReviews");async function $(){return await Promise.all((await y()).map(i))}n($,"listSubmitRequestedReviews");async function C(){return await Promise.all((await f()).map(i))}n(C,"listUnprojectedTerminalReviews");async function M(e,t){return await E(e,t)}n(M,"openReviewRow");async function K(e){await(await s()).prepare("UPDATE human_requests SET submit_requested_at = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(new Date().toISOString(),e)}n(K,"clearReviewSubmit");async function V(e,t){return await k(e,t)}n(V,"requestReviewSubmit");async function z(e,t){return(await e.prepare("UPDATE human_requests SET state = 'settled', outcome = 'approved', result_json = ?, settled_at = ?, progress_json = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(t.result_json,t.approved_at,t.approved_at,t.review_id)).changes>0}n(z,"approveReviewLocked");async function G(e,t){return(await(await s()).prepare("UPDATE human_requests SET state = 'settled', outcome = 'canceled', result_json = ?, settled_at = ?, progress_json = NULL, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open'").run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t.at,...t.reason===""?{}:{reason:t.reason},...t.actor===null?{}:{actor:t.actor}}),t.at,t.at,e)).changes>0}n(G,"cancelReviewRow");async function Q(e,t){await h(e,t)}n(Q,"markProjected");async function X(e,t){await R(e,t)}n(X,"markProjectionError");function Y(e,t,r){}n(Y,"markDelivered");function Z(e,t){}n(Z,"markDeliveryError");async function ee(e){return await j(e)}n(ee,"readAnchorBase");async function te(e,t,r,a){await b(e,t,r,a)}n(te,"replaceAnchorBaseLocked");export{z as approveReviewLocked,G as cancelReviewRow,K as clearReviewSubmit,H as deleteReviewsByOriginNodes,D as getReview,J as getReviewByCompanion,T as getReviewByIdempotencyKey,F as listBindingReviews,W as listReviews,$ as listSubmitRequestedReviews,C as listUnprojectedTerminalReviews,Y as markDelivered,Z as markDeliveryError,Q as markProjected,X as markProjectionError,M as openReviewRow,ee as readAnchorBase,te as replaceAnchorBaseLocked,V as requestReviewSubmit,I as requireVisibleReview,O as reviewIdsByOriginNodes};
@@ -13,7 +13,7 @@ export declare function buildProjectContextBlock(cwd: string): string;
13
13
  * a sibling block) as the place for files that are not documents. Present for
14
14
  * every node, rendered as the `## Your documents and context directory`
15
15
  * subsection of <crtr-bearings>. */
16
- export declare function contextDirNote(nodeId: string, grantee?: string): string;
16
+ export declare function contextDirNote(nodeId: string): string;
17
17
  /** Where the node's engine and shell run, by the runner of its latest execution. A cloud sandbox is not the person's
18
18
  * computer, so a path from their Mac (a pasted screenshot's temp file, a `/Users/...` path) does not exist there. */
19
19
  export declare function whereYouRunNote(runner: 'process' | 'blaxel' | 'machine' | undefined): string;
@@ -34,7 +34,7 @@ export declare function orchestratorContextNote(): string;
34
34
  /** The fork's context note: the fork's own context directory replaces the
35
35
  * source's for files, and the source's documents stay the source's — a bare
36
36
  * document name in the copied conversation now needs the source's prefix. */
37
- export declare function forkContextNote(nodeId: string, grantee: string | undefined, sourceId: string): string;
37
+ export declare function forkContextNote(sourceId: string): string;
38
38
  export interface RelativeLabelNode extends NamedNode {
39
39
  node_id: string;
40
40
  kind: string;
@@ -1,18 +1,18 @@
1
- var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function A(){const e=x();return`Host: ${[`${process.platform} ${process.arch}`,C(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function T(e){try{const n=_("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(T,"directoryListingLines");function f(e,t,n,r){const o=k(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(f,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function d(e,t){const n=f(e,"git",t,$());return n.ok?n.stdout:""}s(d,"runGit");function G(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(G,"parseWorktrees");function O(e){const t=f(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
1
+ var g=Object.defineProperty;var s=(e,t)=>g(e,"name",{value:t,configurable:!0});import{projectPaths as b}from"../../api/dto/profiles.js";import{fullName as w}from"../canvas/labels.js";import{tmuxSessionsReachable as v}from"./tmux-driver.js";import{spawnSync as x}from"node:child_process";import{readdirBeneath as k}from"../spaces/open-beneath.js";import{hostname as _}from"node:os";import{loadProfileManifest as C}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function A(){const e=v();return`Host: ${[`${process.platform} ${process.arch}`,_(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function D(e){try{const r=k("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),n=r.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=r.length-n.length;return o>0?[...n,`[+${o} more]`]:n}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(D,"directoryListingLines");function m(e,t,r,n){const o=x(t,r,{cwd:e,encoding:"utf8",...n===void 0?{}:{env:n}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(m,"runCommand");function f(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s(f,"gitEnv");function d(e,t){const r=m(e,"git",t,f());return r.ok?r.stdout:""}s(d,"runGit");function T(e){const t=[];let r={};for(const n of e)n.startsWith("worktree ")?(r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),r={path:n.slice(9)}):n.startsWith("branch ")&&(r.branch=n.slice(7).replace(/^refs\/heads\//,""));return r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),t}s(T,"parseWorktrees");function G(e){const t=m(e,"git",["rev-parse","--is-inside-work-tree"],f());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const r=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",n=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
2
2
  `).filter(c=>c!=="").length,i=d(e,["worktree","list","--porcelain"]).split(`
3
- `),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function P(e){const t=T(e),n=O(e);let r=`<project_context>
3
+ `),a=T(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${r} @ ${n}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(G,"gitSnapshotLines");function B(e){const t=D(e),r=G(e);let n=`<project_context>
4
4
 
5
- `;return r+=`<environment cwd="${N(e)}">
6
- `,r+=`${A()}
7
- `,r+=`Directory:
5
+ `;return n+=`<environment cwd="${N(e)}">
6
+ `,n+=`${A()}
7
+ `,n+=`Directory:
8
8
  ${t.map(o=>` ${o}`).join(`
9
9
  `)}
10
- `,r+=`${n.map(o=>`${o}`).join(`
10
+ `,n+=`${r.map(o=>`${o}`).join(`
11
11
  `)}
12
- `,r+=`</environment>
13
- </project_context>`,r}s(P,"buildProjectContextBlock");function W(e,t){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`${m(e,t)}\` (also \`$CRTR_CONTEXT_DIR\`) holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(W,"contextDirNote");function F(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(F,"whereYouRunNote");function X(e,t){if(t==null||t==="")return"";let n;try{n=D(t)}catch{return""}const r=w(n.manifest.projects);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(X,"profileNote");function z(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(z,"orchestratorContextNote");function K(e,t,n){return`Context directory: \`${m(e,t)}\` (\`$CRTR_CONTEXT_DIR\`), for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${n}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(K,"forkContextNote");function y(e){const t=v(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(y,"relativeLabel");const j=5;function U(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${y(c)}`)});const u=r.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const h=o.slice(0,j),l=o.length-h.length;return h.forEach((c,p)=>{const g=p===h.length-1&&l===0;a.push(`${i(u+1)}${g?"\u2514 ":"\u251C "}${y(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
- `)}s(U,"renderGraphMap");function q(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
- `)}s(q,"buildIdentityAssertion");function J(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
12
+ `,n+=`</environment>
13
+ </project_context>`,n}s(B,"buildProjectContextBlock");function M(e){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`$CRTR_CONTEXT_DIR\` holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(M,"contextDirNote");function P(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(P,"whereYouRunNote");function W(e,t){if(t==null||t==="")return"";let r;try{r=C(t)}catch{return""}const n=b(r.manifest.projects);return n.length===0?"":`Your working dir is \`${e}\`. Your profile **${r.manifest.name}** also has purview over: ${n.join(", ")}.`}s(W,"profileNote");function F(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(F,"orchestratorContextNote");function X(e){return`Context directory: \`$CRTR_CONTEXT_DIR\`, for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${e}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(X,"forkContextNote");function $(e){const t=w(e),r=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${r}`}s($,"relativeLabel");const O=5;function z(e,t,r,n,o){if(n.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];n.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${$(c)}`)});const u=n.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${r})`);const h=o.slice(0,O),l=o.length-h.length;return h.forEach((c,p)=>{const y=p===h.length-1&&l===0;a.push(`${i(u+1)}${y?"\u2514 ":"\u251C "}${$(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
+ `)}s(z,"renderGraphMap");function K(e,t,r,n,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${r}.`];return n!=null&&n!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
+ `)}s(K,"buildIdentityAssertion");function U(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
16
16
  Worktree: \`${e.path}\`
17
17
  Base: \`${e.base_ref}\` @ \`${e.base_sha}\`
18
- Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(J,"worktreeNote");export{q as buildIdentityAssertion,P as buildProjectContextBlock,W as contextDirNote,N as escapeAttribute,K as forkContextNote,z as orchestratorContextNote,X as profileNote,y as relativeLabel,U as renderGraphMap,F as whereYouRunNote,J as worktreeNote};
18
+ Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(U,"worktreeNote");export{K as buildIdentityAssertion,B as buildProjectContextBlock,M as contextDirNote,N as escapeAttribute,X as forkContextNote,F as orchestratorContextNote,W as profileNote,$ as relativeLabel,z as renderGraphMap,P as whereYouRunNote,U as worktreeNote};
@@ -2,6 +2,6 @@ var g=Object.defineProperty;var a=(e,n)=>g(e,"name",{value:n,configurable:!0});i
2
2
  ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
3
  </crtr-wake>`;const o=L(e);return`<crtr-wake>
4
4
  ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e,t?.grantee));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
5
+ </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
6
6
  `),n,r,k,o].filter(N=>N!=="").join(`
7
7
  `)}a(F,"bearingsShell");async function Z(e){const n=await s(e),r=await f(e);return n?.cwd!==void 0&&r?.runner==="process"?m(n.cwd):""}a(Z,"projectContextForNode");async function ee(e,n,r){const o=await Y(n),t=await $(n);return{content:await F(e,o.content,t.content,r),delivered:[...o.delivered,...t.delivered]}}a(ee,"buildContextBearings");export{te as CONTEXT_INTRO_CUSTOM_TYPE,ee as buildContextBearings,D as buildGraphMap,m as buildProjectContextBlock,V as buildWakeBearings,y as contextDirNote,Q as cronWakeOrigin,b as orchestratorContextNote,B as profileNote,Z as projectContextForNode};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var i=(a,e)=>s(a,"name",{value:e,configurable:!0});import{existsSync as m,mkdirSync as h,renameSync as p,writeFileSync as f}from"node:fs";import{dirname as l}from"node:path";import{daemonClient as y}from"./daemon-ops.js";async function A(a,e){const n=y(),o=e??(await n.listNodeAttachments(a)).attachments;for(const t of o){if(m(t.path))continue;const r=await n.readNodeAttachment(a,t.sha256);h(l(t.path),{recursive:!0});const c=`${t.path}.partial`;f(c,r),p(c,t.path)}}i(A,"fetchRunAttachments");export{A as fetchRunAttachments};
1
+ var p=Object.defineProperty;var r=(t,n)=>p(t,"name",{value:n,configurable:!0});import{existsSync as u,mkdirSync as d,renameSync as R,writeFileSync as y}from"node:fs";import{dirname as m,isAbsolute as C,join as h}from"node:path";import{daemonClient as T}from"./daemon-ops.js";import{hostContextDir as w}from"./host-path-tokens.js";async function S(t,n){const e=T(),i=n??(await e.listNodeAttachments(t)).attachments;if(i.length===0)return;const a=w();if(a===void 0)throw new Error(`cannot place attachments of node ${t}: this broker has no CRTR_CONTEXT_DIR and no CRTR_NODE_ID/CRTR_GRANTEE to derive it from`);const f=m(a);for(const s of i){const o={...s,path:x(f,s.path)};if(u(o.path))continue;const l=await e.readNodeAttachment(t,o.sha256);d(m(o.path),{recursive:!0});const c=`${o.path}.partial`;y(c,l),R(c,o.path)}}r(S,"fetchRunAttachments");function x(t,n){if(!C(n))return h(t,n);const e=/\/apps\/[^/]+\/nodes\/[^/]+\/(.+)$/.exec(n);return e===null?n:h(t,e[1])}r(x,"hostPath");export{S as fetchRunAttachments};
@@ -1,8 +1,4 @@
1
1
  import { type BashJobPaths } from '../../bash-jobs.js';
2
- /** True when the daemon's launcher starts jobs rather than this process: a Linux broker that shares the API host's
3
- * launcher. A sandbox broker (`CRTR_API_URL` set) runs on another machine, so it spawns its supervisor itself
4
- * and reports the job through `report`. */
5
- export declare function bashJobsUseLauncher(): boolean;
6
2
  /** The supervisor's optional notify arguments: the machine daemon's socket, the node and the job, only where a machine daemon runs beside the broker — an
7
3
  * install with `machine.json`, i.e. a Mac that is a machine environment. That Mac's brokers also have `CRTR_API_URL` set, so it says nothing about the
8
4
  * machine daemon. A sandbox has no `machine.json`, so it passes none and the supervisor skips the notice. */
@@ -1 +1 @@
1
- var p=Object.defineProperty;var n=(o,r)=>p(o,"name",{value:r,configurable:!0});import{spawn as h}from"node:child_process";import{writeFileSync as s}from"node:fs";import{BASH_JOB_SUPERVISOR_SCRIPT as l}from"../../bash-job-supervisor.js";import{readBashNiceness as j}from"../../bash-jobs.js";import{capturePidIdentities as g}from"../../canvas/pid.js";import{apiSocketPath as S}from"../../canvas/paths.js";import{readMachineConfig as y}from"../../../daemon/machine-link/config.js";import{freshChildNodeExecPath as P}from"../branded-host.js";import{resolveAdmittedHostCommand as I}from"../spawn-env.js";import{brokerApiUrl as w,startBrokerBashJob as x}from"./daemon-ops.js";function B(){return process.platform==="linux"&&w()===void 0}n(B,"bashJobsUseLauncher");function A(o,r){try{if(y()===void 0)return[]}catch{return[]}return[S(),o,r]}n(A,"exitNotifyArgs");async function $(o,r,a,d,c){const u=await P();if(B()){const{pid:e}=await x(o,{job_id:r.jobId,cwd:d,env:c});return{pgid:e,identity:`launcher:${e}`}}const m=I("bash",c,d),t=h(m,["-c",l,"--",r.cmdSh,r.jobLog,r.jobExit,r.jobRun,r.jobDone,m,String(j(a)),u,r.jobActivity,...A(o,r.jobId)],{cwd:d,detached:!0,stdio:"ignore",env:c}),i=await new Promise((e,b)=>{t.once("error",b),t.pid!==void 0&&e(t.pid)});t.unref();const f=g([i])?.get(i);if(f===void 0){try{process.kill(-i,"SIGKILL")}catch{}throw new Error(`bash job ${r.jobId} started without a process identity`)}return s(r.jobPgid,String(i)),s(r.jobPgidIdentity,f),{pgid:i,identity:f}}n($,"launchBashJobSupervisor");export{B as bashJobsUseLauncher,A as exitNotifyArgs,$ as launchBashJobSupervisor};
1
+ var p=Object.defineProperty;var n=(i,o)=>p(i,"name",{value:o,configurable:!0});import{spawn as S}from"node:child_process";import{writeFileSync as f}from"node:fs";import{BASH_JOB_SUPERVISOR_SCRIPT as g}from"../../bash-job-supervisor.js";import{readBashNiceness as h}from"../../bash-jobs.js";import{capturePidIdentities as j}from"../../canvas/pid.js";import{apiSocketPath as l}from"../../canvas/paths.js";import{readMachineConfig as y}from"../../../daemon/machine-link/config.js";import{freshChildNodeExecPath as P}from"../branded-host.js";import{resolveAdmittedHostCommand as I}from"../spawn-env.js";function w(i,o){try{if(y()===void 0)return[]}catch{return[]}return[l(),i,o]}n(w,"exitNotifyArgs");async function v(i,o,s,d,c){const a=await P(),m=I("bash",c,d),t=S(m,["-c",g,"--",o.cmdSh,o.jobLog,o.jobExit,o.jobRun,o.jobDone,m,String(h(s)),a,o.jobActivity,...w(i,o.jobId)],{cwd:d,detached:!0,stdio:"ignore",env:c}),r=await new Promise((u,b)=>{t.once("error",b),t.pid!==void 0&&u(t.pid)});t.unref();const e=j([r])?.get(r);if(e===void 0){try{process.kill(-r,"SIGKILL")}catch{}throw new Error(`bash job ${o.jobId} started without a process identity`)}return f(o.jobPgid,String(r)),f(o.jobPgidIdentity,e),{pgid:r,identity:e}}n(v,"launchBashJobSupervisor");export{w as exitNotifyArgs,v as launchBashJobSupervisor};
@@ -18,18 +18,10 @@ export declare function putBrokerRecap(nodeId: string, briefing: string): Promis
18
18
  export declare function readBrokerPassiveMessage(nodeId: string, ref: string): Promise<NodeMessageBodyDTO>;
19
19
  export declare function clearBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
20
20
  export declare function consumeBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
21
- export declare function startBrokerBashJob(nodeId: string, request: {
22
- job_id: string;
23
- cwd: string;
24
- env: NodeJS.ProcessEnv;
25
- }): Promise<{
26
- pid: number;
27
- }>;
28
21
  /** Record a command the valve just backgrounded as this node's job object. */
29
22
  export declare function recordBackgroundedJob(nodeId: string, jobId: string, request: BackgroundedJobRequest): Promise<BackgroundedJobDTO>;
30
23
  /** Report on a job this broker runs: process identity, activity, output, exit. */
31
24
  export declare function reportBrokerJob(nodeId: string, jobId: string, request: Omit<JobReportRequest, 'expected_execution_id'>): Promise<void>;
32
- export declare function stopBrokerBashJob(nodeId: string, jobId: string): Promise<void>;
33
25
  export declare function brokerExecutionId(): string;
34
26
  export declare function bindBrokerSession(nodeId: string, request: Omit<BrokerSessionBoundRequest, 'executionId'>): Promise<BrokerSessionBoundResultDTO>;
35
27
  type BrokerInput<T> = T extends unknown ? Omit<T, 'expected_execution_id'> : never;