@north-light/cli 0.3.788 → 0.3.790

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 (76) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/command-manifest/index.d.ts +1 -0
  4. package/dist/api/command-manifest/index.js +1 -1
  5. package/dist/api/command-manifest/memory-extensions.d.ts +34 -0
  6. package/dist/api/command-manifest/memory-extensions.js +1 -0
  7. package/dist/api/contract.d.ts +1 -1
  8. package/dist/api/contract.js +1 -1
  9. package/dist/builtin-memory/crouter-plugin/bundles-and-memory.md +16 -1
  10. package/dist/builtin-memory/internal/INDEX.md +1 -1
  11. package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
  12. package/dist/clients/attach/viewer.js +255 -255
  13. package/dist/commands/canvas-history/shared.js +1 -1
  14. package/dist/commands/node/create.js +2 -2
  15. package/dist/commands/person-settings.js +1 -1
  16. package/dist/commands/profile/daemon-profiles.js +4 -4
  17. package/dist/commands/sys.js +1 -1
  18. package/dist/core/canvas/history.d.ts +2 -8
  19. package/dist/core/canvas/history.js +9 -9
  20. package/dist/core/canvas/node-tokens.js +3 -3
  21. package/dist/core/canvas/person-state.d.ts +5 -7
  22. package/dist/core/canvas/person-state.js +1 -1
  23. package/dist/core/canvas/person.d.ts +3 -30
  24. package/dist/core/canvas/person.js +1 -11
  25. package/dist/core/config.d.ts +4 -1
  26. package/dist/core/config.js +1 -1
  27. package/dist/core/directory/join.d.ts +4 -6
  28. package/dist/core/directory/join.js +1 -1
  29. package/dist/core/grants/sync.js +1 -1
  30. package/dist/core/graph/documents.d.ts +1 -1
  31. package/dist/core/graph/kinds/document.js +1 -1
  32. package/dist/core/human/requests.d.ts +11 -1
  33. package/dist/core/human/requests.js +22 -22
  34. package/dist/core/plugin-extensions.d.ts +3 -6
  35. package/dist/core/plugin-extensions.js +1 -1
  36. package/dist/core/review/store.js +1 -1
  37. package/dist/core/runtime/broker.js +1 -1
  38. package/dist/core/runtime/host.js +3 -3
  39. package/dist/core/runtime/launch-config-worker.js +1 -1
  40. package/dist/core/runtime/launch-target.d.ts +6 -4
  41. package/dist/core/runtime/launch-target.js +1 -1
  42. package/dist/core/runtime/launch.d.ts +5 -1
  43. package/dist/core/runtime/launch.js +2 -2
  44. package/dist/core/runtime/runner/delete-sandboxes.d.ts +1 -1
  45. package/dist/core/runtime/runner/delete-sandboxes.js +5 -5
  46. package/dist/core/runtime/runner/machine/runner.js +1 -1
  47. package/dist/core/runtime/spawn-env-rows.js +1 -1
  48. package/dist/core/runtime/spawn.js +2 -2
  49. package/dist/core/secrets/environment-owner.js +1 -1
  50. package/dist/daemon/api/handlers/canvas.js +5 -5
  51. package/dist/daemon/api/handlers/nodes.js +1 -1
  52. package/dist/daemon/api/handlers/profiles.js +1 -1
  53. package/dist/daemon/cron/lease-recovery.js +1 -1
  54. package/dist/daemon/human/sweep.js +1 -1
  55. package/dist/daemon/peer/ingress.d.ts +2 -2
  56. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  57. package/dist/daemon/runs/observer.js +6 -5
  58. package/dist/types.d.ts +2 -28
  59. package/docs/plugin/bundles-and-memory.md +15 -1
  60. package/package.json +3 -3
  61. package/packages/crouter-api/dist/api/client.js +2 -2
  62. package/packages/crouter-api/dist/api/command-manifest/index.js +1 -0
  63. package/packages/crouter-api/dist/api/command-manifest/memory-extensions.js +91 -0
  64. package/packages/crouter-api/dist/api/contract.js +1 -1
  65. package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
  66. package/packages/crouter-api/dist/core/config.js +10 -0
  67. package/packages/crouter-api/dist/core/directory/join.js +11 -45
  68. package/packages/crouter-api/dist/core/plugin-extensions.js +2 -86
  69. package/packages/crouter-api/package.json +1 -1
  70. package/packages/crouter-identity/package.json +1 -1
  71. package/packages/crouter-plugin/dist/bundle.js +1 -0
  72. package/packages/crouter-plugin/dist/define.js +10 -1
  73. package/packages/crouter-plugin/package.json +3 -3
  74. package/runtime.lock.json +14 -14
  75. package/dist/commands/sys/join.d.ts +0 -3
  76. package/dist/commands/sys/join.js +0 -1
@@ -1,6 +1,7 @@
1
- var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as R,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as D}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as N}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as g,emitRunSettlement as T,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",E=1e4,Y=250;async function w(t,e,i){return await C(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,t,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await i()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,i,n,s,r){this.nodeId=e,this.runId=i,this.owner=n,this.status=s,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,i,n){const s=await d(),r=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===i?"node.settled":"child.settled"),a=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),o=new v(e,i,n,a?JSON.parse(a.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await o.writeStream(null,null),await o.poll(),o}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<E/3?!0:await x(c,this.nodeId,this.owner,E)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,i,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
- WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await D(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const i=e.pi_pid===null?"dormant":e.status;if(this.status!==i){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,i,e.intent??null))).held){this.close();return}this.status=i}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const a=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const o of a)await L(o.node_id,this.runId),await p.get(o.node_id)?.poll()}this.outcomeRevision=n.revision;const s=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?T(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...s===void 0?{}:{result:s}}):T(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const a=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(a,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(o=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:o}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await N(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await $(this.nodeId),i=await this.viewAdmitted();if(this.client||this.closed||!i){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:y(),attends:!1}));const s=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const a=r.message.content;if(!Array.isArray(a))return;const o=a.at(-1);if(o&&typeof o=="object"&&"type"in o&&(o.type==="toolCall"?this.block={kind:"tool_call",name:"name"in o&&typeof o.name=="string"?o.name:""}:(o.type==="text"||o.type==="thinking")&&(this.block={kind:o.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const f=a.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),m=a.filter(u=>u?.type==="text").map(u=>u.text).join(""),k=f.startsWith(this.thinking)?f.slice(this.thinking.length):f,b=m.startsWith(this.output)?m.slice(this.output.length):m;this.thinking=f,this.output=m,this.pendingThinking+=k,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>s(r)).catch(a=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:a})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,i=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!i)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await g(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),i&&await g(this.runId,this.nodeId,"node.output_text.delta",{delta:i})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await R(c,this.nodeId,this.owner)}).then(()=>{}).catch(i=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:i})});const e=this.client;this.client=void 0,e?.close()}}async function $(t){const e=await N(t);if(e===null)return new O(t,{recordsViewerFaults:!1});const i=await W(e.runner).viewerAddress(e);return i.kind==="machine"?new A(t,()=>U(i.environmentId,t)):i.kind==="unix"?new O(t,{recordsViewerFaults:!1}):new A(t,()=>q(i.url,i.headers))}l($,"viewTransport");async function pe(t){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function fe(t){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(fe,"openAssistantBlock");async function me(){const t=[...p.values()];for(const e of t)e.close();await Promise.all(t.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(me,"closeRunObserversForTests");async function I(t){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(t,t)!==void 0}l(I,"runRootExists");const _=new Map;async function L(t,e){const i=_.get(t);if(i)return i;if(p.has(t))return;const n=Q(t,e).finally(()=>_.delete(t));return _.set(t,n),n}l(L,"ensureRunObserver");async function Q(t,e){if(!await I(e))return;const i=y();if(await F(c,t,i,E)!==void 0)try{if(t!==e){const n=await D(t);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,t)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(t,i,()=>g(e,t,"child.started",{child_node_id:t,kind:n.kind}))).held)return}await v.start(t,e,i)}catch(n){throw await R(c,t,i).catch(()=>{}),n}}l(Q,"startRunObserver");async function we(){const t=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id, n.pi_pid, COALESCE(n.outcome_revision, 1) AS revision, e.body_json
1
+ var C=Object.defineProperty;var l=(i,e)=>C(i,"name",{value:e,configurable:!0});import{randomUUID as R}from"node:crypto";import{openDb as d,withCanvasWrite as M}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as D,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as y}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as T}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as E,emitRunSettlement as N,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",g=1e4,Y=250;async function w(i,e,t){return await M(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,i,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await t()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,t,n,a,r){this.nodeId=e,this.runId=t,this.owner=n,this.status=a,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,t,n){const a=await d(),r=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===t?"node.settled":"child.settled"),o=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),s=new v(e,t,n,o?JSON.parse(o.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await s.writeStream(null,null),await s.poll(),s}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<g/3?!0:await x(c,this.nodeId,this.owner,g)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,t,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
+ WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],t===null?null:JSON.stringify(t),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await y(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const t=e.pi_pid===null?"dormant":e.status;if(this.status!==t){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,t,e.intent??null))).held){this.close();return}this.status=t}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const o=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const s of o)await k(s.node_id,this.runId),await p.get(s.node_id)?.poll()}this.outcomeRevision=n.revision;const a=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?N(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...a===void 0?{}:{result:a}}):N(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const o=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(o,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(s=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:s}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await T(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await X(this.nodeId),t=await this.viewAdmitted();if(this.client||this.closed||!t){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:R(),attends:!1}));const a=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const o=r.message.content;if(!Array.isArray(o))return;const s=o.at(-1);if(s&&typeof s=="object"&&"type"in s&&(s.type==="toolCall"?this.block={kind:"tool_call",name:"name"in s&&typeof s.name=="string"?s.name:""}:(s.type==="text"||s.type==="thinking")&&(this.block={kind:s.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const m=o.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),f=o.filter(u=>u?.type==="text").map(u=>u.text).join(""),L=m.startsWith(this.thinking)?m.slice(this.thinking.length):m,b=f.startsWith(this.output)?f.slice(this.output.length):f;this.thinking=m,this.output=f,this.pendingThinking+=L,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>a(r)).catch(o=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:o})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,t=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!t)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await E(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),t&&await E(this.runId,this.nodeId,"node.output_text.delta",{delta:t})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await D(c,this.nodeId,this.owner)}).then(()=>{}).catch(t=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:t})});const e=this.client;this.client=void 0,e?.close()}}async function X(i){const e=await T(i);if(e===null)return new O(i,{recordsViewerFaults:!1});const t=await W(e.runner).viewerAddress(e);return t.kind==="machine"?new A(i,()=>U(t.environmentId,i)):t.kind==="unix"?new O(i,{recordsViewerFaults:!1}):new A(i,()=>q(t.url,t.headers))}l(X,"viewTransport");async function pe(i){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function me(i){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(me,"openAssistantBlock");async function fe(){const i=[...p.values()];for(const e of i)e.close();await Promise.all(i.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(fe,"closeRunObserversForTests");async function I(i){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(i,i)!==void 0}l(I,"runRootExists");const _=new Map;async function k(i,e){const t=_.get(i);if(t)return t;if(p.has(i))return;const n=$(i,e).finally(()=>_.delete(i));return _.set(i,n),n}l(k,"ensureRunObserver");async function $(i,e){if(!await I(e))return;const t=R();if(await F(c,i,t,g)!==void 0)try{if(i!==e){const n=await y(i);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,i)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(i,t,()=>E(e,i,"child.started",{child_node_id:i,kind:n.kind}))).held)return}await v.start(i,e,t)}catch(n){throw await D(c,i,t).catch(()=>{}),n}}l($,"startRunObserver");async function we(){const i=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id
3
3
  FROM node_rows n
4
- LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
5
- AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
6
- WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,$ as viewTransport};
4
+ WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'
5
+ AND NOT EXISTS (SELECT 1 FROM run_events e WHERE e.run_id = n.run_id AND e.node_id = n.node_id
6
+ AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
7
+ AND (e.body_json::json #>> '{outcome,revision}') = COALESCE(n.outcome_revision, 1)::text)))`).all(i);for(const t of e)try{await k(t.node_id,t.run_id),S.delete(t.node_id)}catch(n){Q(t.node_id,n)}}l(we,"pollRunObservers");const S=new Map;function Q(i,e){const t=e instanceof Error?e.message:String(e);S.get(i)!==t&&(S.set(i,t),h({level:"error",event:"daemon.runs.observer_failed",node_id:i,error:e}))}l(Q,"reportObserverFailure");export{fe as closeRunObserversForTests,k as ensureRunObserver,me as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,X as viewTransport};
package/dist/types.d.ts CHANGED
@@ -33,33 +33,8 @@ export interface PluginBundle {
33
33
  endpoint: string;
34
34
  authEnv?: string;
35
35
  }
36
- export type MemoryExtensionScalar = string | boolean | number;
37
- export type MemoryExtensionFieldType = 'boolean' | 'string' | 'number' | 'enum';
38
- interface MemoryExtensionDeclarationBase {
39
- write_help: string;
40
- edit_help: string;
41
- }
42
- export interface BooleanMemoryExtensionDeclaration extends MemoryExtensionDeclarationBase {
43
- type: 'boolean';
44
- default?: boolean;
45
- }
46
- export interface StringMemoryExtensionDeclaration extends MemoryExtensionDeclarationBase {
47
- type: 'string';
48
- default?: string;
49
- }
50
- export interface NumberMemoryExtensionDeclaration extends MemoryExtensionDeclarationBase {
51
- type: 'number';
52
- default?: number;
53
- }
54
- export interface EnumMemoryExtensionDeclaration extends MemoryExtensionDeclarationBase {
55
- type: 'enum';
56
- values: string[];
57
- default?: string;
58
- }
59
- export type MemoryExtensionDeclaration = BooleanMemoryExtensionDeclaration | StringMemoryExtensionDeclaration | NumberMemoryExtensionDeclaration | EnumMemoryExtensionDeclaration;
60
- /** Field declarations owned by one plugin manifest. The plugin's `name` is
61
- * the namespace; keys here are its lowercase kebab-case local field names. */
62
- export type MemoryExtensionDeclarations = Record<string, MemoryExtensionDeclaration>;
36
+ export type { MemoryExtensionScalar, MemoryExtensionFieldType, BooleanMemoryExtensionDeclaration, StringMemoryExtensionDeclaration, NumberMemoryExtensionDeclaration, EnumMemoryExtensionDeclaration, MemoryExtensionDeclaration, MemoryExtensionDeclarations, } from './api/command-manifest/memory-extensions.js';
37
+ import type { MemoryExtensionDeclarations } from './api/command-manifest/memory-extensions.js';
63
38
  /** One canvas object kind a plugin declares in `object_kinds`. */
64
39
  export interface ObjectKindDeclaration {
65
40
  description: string;
@@ -567,4 +542,3 @@ export declare function defaultRemoteCanvasConfig(): RemoteCanvasConfig;
567
542
  export declare function defaultKindsConfig(): Record<string, KindConfig>;
568
543
  export declare function defaultModelLaddersConfig(): ModelLaddersConfig;
569
544
  export declare function defaultScopeState(): ScopeState;
570
- export {};
@@ -19,7 +19,7 @@ await writeFile('acme.tar', bundle.tar);
19
19
 
20
20
  `buildBundle` returns `commandsJson`, `bundleJson`, generated `memory/` members, uncompressed tar bytes, and an ETag. It runs the manifest validator and throws `ManifestInvalidError` when the generated command manifest is invalid. `buildCommandManifest(plugin, { mountPath })` returns the manifest object when archive bytes are not needed.
21
21
 
22
- The tar has exactly `bundle.json`, `commands.json`, and `memory/<name>.md` members for the documents declared in the `memory` array of `definePlugin`. `bundle.json` carries `bundleVersion`, plus `version` when the plugin declares one, `object_kinds` when it declares object kinds, and `groups` when a provider declares its tool groups (the directory refuses a provider archive without them). `groups` is keyed by group id, each value `{"consent_line": string, "who"?: "own" | "user" | "allowlist" | "any" | "team:<id>", "allowlist"?: string[]}`, with `who` and `allowlist` written only when declared:
22
+ The tar has exactly `bundle.json`, `commands.json`, and `memory/<name>.md` members for the documents declared in the `memory` array of `definePlugin`. `bundle.json` carries `bundleVersion`, plus `version` when the plugin declares one, `object_kinds` when it declares object kinds, `memory_extensions` when it declares `memoryExtensions`, and `groups` when a provider declares its tool groups (the directory refuses a provider archive without them). `groups` is keyed by group id, each value `{"consent_line": string, "who"?: "own" | "user" | "allowlist" | "any" | "team:<id>", "allowlist"?: string[]}`, with `who` and `allowlist` written only when declared:
23
23
 
24
24
  ```json
25
25
  {"bundleVersion":1,"version":1,"groups":{"read":{"consent_line":"Read your Acme apps and deployments."},"deploy":{"consent_line":"Start deployments on your Acme apps.","who":"allowlist","allowlist":["app:k3x9"]}}}
@@ -54,3 +54,17 @@ memory: [{
54
54
 
55
55
  `definePlugin` rejects a rule the installer would drop. Every rule costs context in every node it reaches, so prefer the narrowest trigger, and keep a `boot` rule at `content` for short, always-relevant guidance. An installation's profile can lower what a plugin's documents deliver at `boot`.
56
56
 
57
+
58
+ ## Typed document fields
59
+
60
+ `definePlugin({memoryExtensions})` declares typed frontmatter fields for documents; `buildBundle` writes them as `memory_extensions`, and crtr's installer validates them with the same function (`validateMemoryExtensionDeclarations`). Field names are lowercase kebab-case; values live at `extensions.<plugin name>.<field>`.
61
+
62
+ ```ts
63
+ definePlugin({
64
+ // ...
65
+ memoryExtensions: {
66
+ status: { type: 'enum', values: ['open', 'done'], default: 'open', write_help: 'Set the home status.', edit_help: 'Change the home status.' },
67
+ pinned: { type: 'boolean', write_help: 'Pin to the top.', edit_help: 'Pin or unpin.' },
68
+ },
69
+ });
70
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.788",
3
+ "version": "0.3.790",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.788",
161
- "@north-light/plugin": "0.3.788",
160
+ "@north-light/identity": "0.3.790",
161
+ "@north-light/plugin": "0.3.790",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -450,8 +450,8 @@ export class CrtrClient {
450
450
  waitNode(id, req) {
451
451
  return this.request('POST', routes.nodeWait(this.nodePath(id)), req);
452
452
  }
453
- listKinds() {
454
- return this.request('GET', routes.kinds());
453
+ listKinds(opts = {}) {
454
+ return this.request('GET', withQuery(routes.kinds(), { profile: opts.profile }));
455
455
  }
456
456
  /** A model change may first wait up to 30 s for a starting broker's view
457
457
  * socket and then 15 s for its ack, so it gets that budget on top. */
@@ -2,3 +2,4 @@ export * from './schema.js';
2
2
  export * from './manifest.js';
3
3
  export * from './result.js';
4
4
  export * from './object-kinds.js';
5
+ export * from './memory-extensions.js';
@@ -0,0 +1,91 @@
1
+ // The shape rules for a plugin's `memory_extensions` block, shared by crouter's install paths and the plugin kit
2
+ // (`definePlugin({memoryExtensions})`) so both refuse exactly the same declarations. Zero dependencies.
3
+ const LOCAL_FIELD_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
4
+ const DECLARATION_KEYS = new Set(['type', 'values', 'default', 'write_help', 'edit_help']);
5
+ function isRecord(value) {
6
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ }
8
+ export function isMemoryExtensionScalar(value) {
9
+ return typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
10
+ }
11
+ function declarationError(path, message) {
12
+ return new Error(`invalid memory_extensions declaration at ${path}: ${message}`);
13
+ }
14
+ function validHelp(value) {
15
+ return typeof value === 'string' && value.trim() !== '' && !/[\r\n]/.test(value);
16
+ }
17
+ export function validDefault(declaration, value) {
18
+ if (!isMemoryExtensionScalar(value))
19
+ return false;
20
+ if (declaration.type === 'enum')
21
+ return typeof value === 'string' && declaration.values.includes(value);
22
+ return typeof value === declaration.type;
23
+ }
24
+ /** Parse the closed declaration addendum. Callers that accept a plugin manifest
25
+ * invoke this at their install/preflight boundary; normal runtime catalogs only
26
+ * admit declarations which have already cleared that boundary. */
27
+ export function validateMemoryExtensionDeclarations(raw) {
28
+ if (!isRecord(raw))
29
+ throw declarationError('memory_extensions', 'expected a non-empty object');
30
+ const declarations = {};
31
+ const fields = Object.entries(raw);
32
+ if (fields.length === 0)
33
+ throw declarationError('memory_extensions', 'must not be empty');
34
+ for (const [field, value] of fields) {
35
+ const path = `memory_extensions.${field}`;
36
+ if (!LOCAL_FIELD_NAME.test(field)) {
37
+ throw declarationError(path, 'field names must be lowercase kebab-case');
38
+ }
39
+ if (!isRecord(value))
40
+ throw declarationError(path, 'expected a declaration object');
41
+ for (const key of Object.keys(value)) {
42
+ if (!DECLARATION_KEYS.has(key))
43
+ throw declarationError(path, `unknown key \`${key}\``);
44
+ }
45
+ const type = value['type'];
46
+ if (type !== 'boolean' && type !== 'string' && type !== 'number' && type !== 'enum') {
47
+ throw declarationError(`${path}.type`, 'expected boolean, string, number, or enum');
48
+ }
49
+ if (!validHelp(value['write_help']))
50
+ throw declarationError(`${path}.write_help`, 'expected a nonblank single-line string');
51
+ if (!validHelp(value['edit_help']))
52
+ throw declarationError(`${path}.edit_help`, 'expected a nonblank single-line string');
53
+ if (type === 'enum') {
54
+ const values = value['values'];
55
+ if (!Array.isArray(values) || values.length === 0 || !values.every((entry) => typeof entry === 'string' && entry !== '')) {
56
+ throw declarationError(`${path}.values`, 'expected a non-empty string list');
57
+ }
58
+ if (new Set(values).size !== values.length)
59
+ throw declarationError(`${path}.values`, 'values must be unique');
60
+ const declaration = {
61
+ type,
62
+ values: [...values],
63
+ write_help: value['write_help'],
64
+ edit_help: value['edit_help'],
65
+ };
66
+ if ('default' in value) {
67
+ if (!validDefault(declaration, value['default'])) {
68
+ throw declarationError(`${path}.default`, 'must be one of the declared enum values');
69
+ }
70
+ declaration.default = value['default'];
71
+ }
72
+ declarations[field] = declaration;
73
+ continue;
74
+ }
75
+ if ('values' in value)
76
+ throw declarationError(`${path}.values`, 'is allowed only for enum declarations');
77
+ const declaration = {
78
+ type,
79
+ write_help: value['write_help'],
80
+ edit_help: value['edit_help'],
81
+ };
82
+ if ('default' in value) {
83
+ if (!validDefault(declaration, value['default'])) {
84
+ throw declarationError(`${path}.default`, `must be a ${type}`);
85
+ }
86
+ declaration.default = value['default'];
87
+ }
88
+ declarations[field] = declaration;
89
+ }
90
+ return declarations;
91
+ }
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.88';
15
+ export const CONTRACT_LEVEL = '1.89';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1,4 +1,4 @@
1
- // person-state.ts — the process's person binding (boot-set person, cloud-role flag, per-request person). Pure: no database, so the
1
+ // person-state.ts — the process's person binding (client-bound person, cloud-role flag, per-request person). Pure: no database, so the
2
2
  // CLI-reachable settings cache can read the current person without reaching canvas state.
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
4
  /** Thrown by `personId()` before the person is known (a hosted first boot, before its first grant snapshot). */
@@ -12,11 +12,11 @@ export class PersonOutsideRequestError extends Error {
12
12
  code = 'person_outside_request';
13
13
  constructor() { super('no person: a cloud role reads the person only inside a request, from its token'); this.name = 'PersonOutsideRequestError'; }
14
14
  }
15
- let daemonPersonId;
15
+ let clientPersonId;
16
16
  let cloudRole = false;
17
17
  const requestPersons = new AsyncLocalStorage();
18
- /** crtrd sets this once at boot; it wins unconditionally. */
19
- export function setPersonId(id) { daemonPersonId = id; }
18
+ /** A CLI, viewer or launch-config subprocess binds the one person it acts for (the person its settings answer named). A crtrd process never calls this: it reads the person from the request or the row it serves. */
19
+ export function bindClientPerson(id) { clientPersonId = id; }
20
20
  /** crtrd calls this at boot on a cloud role, instead of resolving a person: from then on a person read outside a request throws. */
21
21
  export function markCloudRole() { cloudRole = true; }
22
22
  /** Whether this process is a cloud role (`markCloudRole` ran at boot). */
@@ -27,19 +27,17 @@ export function markEnginesInProcess() { enginesInProcess = true; }
27
27
  export function areEnginesInProcess() { return enginesInProcess; }
28
28
  /** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
29
29
  export function runAsPerson(person, fn) { return requestPersons.run(person, fn); }
30
- /** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
31
- * `PersonUnresolvedError` when a Mac's person is not bound. Tests and non-daemon processes use `personIdAsync()`. */
30
+ /** The request's person; else the person a CLI-side process bound. Throws `PersonOutsideRequestError` on a cloud role outside a request and
31
+ * `PersonUnresolvedError` when no client-bound person exists. Tests and non-daemon processes use `personIdAsync()`. */
32
32
  export function personId() {
33
33
  const request = requestPersons.getStore();
34
34
  if (request !== undefined)
35
35
  return request;
36
36
  if (cloudRole)
37
37
  throw new PersonOutsideRequestError();
38
- if (daemonPersonId === undefined)
38
+ if (clientPersonId === undefined)
39
39
  throw new PersonUnresolvedError();
40
- return daemonPersonId;
40
+ return clientPersonId;
41
41
  }
42
- /** The boot-set person, if any (for `personIdAsync`). */
43
- export function bootPersonId() { return daemonPersonId; }
44
- /** The request's person, if any (for `personIdAsync`). */
42
+ /** The request's person, if any. */
45
43
  export function requestPersonId() { return requestPersons.getStore(); }
@@ -934,6 +934,8 @@ function readRawProfileConfig(profileId) {
934
934
  * — the SCOPE THE CONFIG IS FOR, not necessarily the calling process's own
935
935
  * ambient cwd/profile (see `readMergedLaunchConfig`). */
936
936
  function readRawProjectScopeConfigs(targetCwd, targetProfileId) {
937
+ if (targetCwd === null)
938
+ return [];
937
939
  const nearestFirst = findProjectScopeRoots(targetCwd, targetProfileId);
938
940
  const farthestFirst = [...nearestFirst].reverse();
939
941
  // A root with no config.json still contributes: its installed plugins may
@@ -1020,6 +1022,14 @@ export function readMergedLaunchConfig(targetCwd = process.cwd(), targetProfileI
1020
1022
  spawnEnv,
1021
1023
  };
1022
1024
  }
1025
+ /** The launch config a process holding the project's files adds on top of a recipe's config, which a cloud control plane built without them:
1026
+ * the project stack's kinds (and the kinds its enabled plugins declare) in `cwd`, over the recipe's kinds. */
1027
+ export function overlayProjectLaunchConfig(base, cwd, profileId) {
1028
+ let kinds = base.kinds;
1029
+ for (const { root, raw } of readRawProjectScopeConfigs(cwd, profileId))
1030
+ kinds = mergeKinds(raw?.kinds, layerPluginKinds('project', root, kinds));
1031
+ return { ...base, kinds };
1032
+ }
1023
1033
  /** The effective `KindConfig` for one full kind string (top-level, e.g.
1024
1034
  * `developer`, or sub-kind, e.g. `audit/security`), across
1025
1035
  * project > user > builtin precedence. Returns `undefined` for a kind no
@@ -1,15 +1,12 @@
1
- // Runtime registration: send the directory a new public ES256 key under a credential (a hosted runtime's single-use enrollment token at first
2
- // boot, or a signed-in person's bearer from `crtr sys signin`), then record the returned identity and the private key in the runtime-client file.
1
+ // Runtime registration: send the directory a new public ES256 key under a credential (a signed-in person's bearer from `crtr sys signin`), then record the returned identity and the private key in the runtime-client file.
3
2
  // It writes no settings (the daemon applies them at its start); the private key never leaves this computer.
4
3
  import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
5
4
  import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
6
- import { request } from 'node:http';
7
5
  import { hostname } from 'node:os';
8
6
  import { join } from 'node:path';
9
7
  import { InputError } from '../io.js';
10
8
  import { network } from '../errors.js';
11
9
  import { secretsDir } from '../layout.js';
12
- import { apiSocketPath } from '../canvas/paths.js';
13
10
  import { atomicWriteJson, readJsonIfExists } from '../fs-utils.js';
14
11
  import { launcherPresent } from '../grants/sandboxes.js';
15
12
  import { crtrVersion } from '../../shared/crtr-version.js';
@@ -74,7 +71,7 @@ async function register(directory, token, publicJwk, name, retry) {
74
71
  if (response.status < 500)
75
72
  rmSync(pendingPath(), { force: true });
76
73
  throw new InputError({
77
- error: 'join_refused',
74
+ error: 'registration_refused',
78
75
  message: `directory refused the registration: ${response.status} ${text.slice(0, 500)}`,
79
76
  next: retry,
80
77
  });
@@ -88,34 +85,27 @@ async function register(directory, token, publicJwk, name, retry) {
88
85
  throw error;
89
86
  }
90
87
  }
91
- /** What a successful `crtr sys join` recorded in the client file, or null when join never wrote it (no file, or one provisioned
92
- * without join, which has no `token_sha256`). Join writes no settings: the daemon applies this at its start (`applyBootSettings`),
93
- * and its `retireLocalPerson` makes `owner` the install's person. */
88
+ /** What a successful registration recorded in the client file, or null when none did (no file, or one provisioned
89
+ * without registration, which has no `token_sha256`). Registration writes no settings: the daemon applies this at its start (`applyBootSettings`),
90
+ * and takes `owner` as the install's person. */
94
91
  function readJoined() {
95
92
  const stored = readJsonIfExists(clientPath());
96
93
  if (stored?.token_sha256 === undefined)
97
94
  return null;
98
95
  const { owner } = stored;
99
96
  if (typeof owner !== 'string' || !/^user:.+/.test(owner))
100
- throw new Error(`${clientPath()} was written by join but has a missing or invalid owner`);
97
+ throw new Error(`${clientPath()} was written by registration but has a missing or invalid owner`);
101
98
  return stored;
102
99
  }
103
- /** The owner a successful join recorded, or null when `crtr sys join` never wrote the client file. */
100
+ /** The owner a successful registration recorded, or null when no registration wrote the client file. */
104
101
  export function joinedOwner() { return readJoined()?.owner ?? null; }
105
- /** The issuer a successful join recorded, or null. */
102
+ /** The issuer a successful registration recorded, or null. */
106
103
  export function joinedIssuer() { return readJoined()?.issuer ?? null; }
107
- /** The whole registration a successful join recorded, or null; a damaged file throws. */
104
+ /** The whole registration a successful registration recorded, or null; a damaged file throws. */
108
105
  export function joinedClient() {
109
106
  const stored = readJoined();
110
107
  return stored === null ? null : registration(stored);
111
108
  }
112
- function daemonRunningError(socket) {
113
- return new InputError({
114
- error: 'daemon_running',
115
- message: `cannot register while a daemon answers on ${socket}`,
116
- next: 'Stop the daemon that owns this volume, then run `crtr sys join` again.',
117
- });
118
- }
119
109
  /** Register (or reuse the stored registration) without touching local state beyond the pending key. */
120
110
  async function obtainRegistration(directory, token, name, tokenHash, retry) {
121
111
  const stored = readJsonIfExists(clientPath());
@@ -143,7 +133,7 @@ function requireDirectory(directory) {
143
133
  async function registerAndStore(directory, credential, name, retry) {
144
134
  requireDirectory(directory);
145
135
  if (credential === '')
146
- throw new InputError({ error: 'invalid_token', message: 'credential is empty', field: 'token', next: 'Pass the enrollment token provisioning supplied.' });
136
+ throw new InputError({ error: 'invalid_token', message: 'credential is empty', field: 'token', next: 'Sign in again with `crtr sys signin`.' });
147
137
  const { joined, registered, client } = await obtainRegistration(directory, credential, name, createHash('sha256').update(credential).digest('hex'), retry);
148
138
  if (client) {
149
139
  atomicWriteJson(clientPath(), client, { mode: 0o600 });
@@ -151,32 +141,8 @@ async function registerAndStore(directory, credential, name, retry) {
151
141
  }
152
142
  return { ...joined, registered };
153
143
  }
154
- /** True when a daemon answers /healthz on the socket (a blocked daemon still answers and owns its files). */
155
- function daemonAnswers(socketPath) {
156
- return new Promise(resolve => {
157
- const req = request({ socketPath, path: '/healthz', method: 'GET', timeout: 1000 }, res => {
158
- res.resume();
159
- resolve(true);
160
- });
161
- req.on('timeout', () => req.destroy(new Error('daemon probe timed out')));
162
- req.on('error', error => {
163
- if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
164
- resolve(false);
165
- else
166
- resolve(true); // Uncertain probe: do not touch an owned volume.
167
- });
168
- req.end();
169
- });
170
- }
171
- /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
172
- export async function joinDirectory(directory, token, name = hostname()) {
173
- const socket = apiSocketPath();
174
- if (await daemonAnswers(socket))
175
- throw daemonRunningError(socket);
176
- return registerAndStore(directory, token, name, 'Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.');
177
- }
178
144
  /** `crtr sys signin`'s registration: the signed-in person's bearer registers this computer as one of the person's runtimes, once. A computer that
179
- * already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
145
+ * already holds a registration for this directory's owner (an earlier signin) is left as it is. */
180
146
  export async function registerSignedInMac(directory, bearer) {
181
147
  if (readJoined() !== null)
182
148
  return null;
@@ -1,95 +1,11 @@
1
1
  // plugin-extensions.ts — a plugin manifest's `memory_extensions` declarations and
2
2
  // the `extensions` frontmatter values its package documents carry.
3
+ import { isMemoryExtensionScalar, validateMemoryExtensionDeclarations, validDefault, } from '../api/command-manifest/memory-extensions.js';
3
4
  import { listInstalledPlugins, listInstalledPluginsInRoot } from './resolver.js';
4
- const LOCAL_FIELD_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
5
- const DECLARATION_KEYS = new Set(['type', 'values', 'default', 'write_help', 'edit_help']);
5
+ export { isMemoryExtensionScalar, validateMemoryExtensionDeclarations };
6
6
  function isRecord(value) {
7
7
  return value !== null && typeof value === 'object' && !Array.isArray(value);
8
8
  }
9
- export function isMemoryExtensionScalar(value) {
10
- return typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
11
- }
12
- function declarationError(path, message) {
13
- return new Error(`invalid memory_extensions declaration at ${path}: ${message}`);
14
- }
15
- function validHelp(value) {
16
- return typeof value === 'string' && value.trim() !== '' && !/[\r\n]/.test(value);
17
- }
18
- function validDefault(declaration, value) {
19
- if (!isMemoryExtensionScalar(value))
20
- return false;
21
- if (declaration.type === 'enum')
22
- return typeof value === 'string' && declaration.values.includes(value);
23
- return typeof value === declaration.type;
24
- }
25
- /** Parse the closed declaration addendum. Callers that accept a plugin manifest
26
- * invoke this at their install/preflight boundary; normal runtime catalogs only
27
- * admit declarations which have already cleared that boundary. */
28
- export function validateMemoryExtensionDeclarations(raw) {
29
- if (!isRecord(raw))
30
- throw declarationError('memory_extensions', 'expected a non-empty object');
31
- const declarations = {};
32
- const fields = Object.entries(raw);
33
- if (fields.length === 0)
34
- throw declarationError('memory_extensions', 'must not be empty');
35
- for (const [field, value] of fields) {
36
- const path = `memory_extensions.${field}`;
37
- if (!LOCAL_FIELD_NAME.test(field)) {
38
- throw declarationError(path, 'field names must be lowercase kebab-case');
39
- }
40
- if (!isRecord(value))
41
- throw declarationError(path, 'expected a declaration object');
42
- for (const key of Object.keys(value)) {
43
- if (!DECLARATION_KEYS.has(key))
44
- throw declarationError(path, `unknown key \`${key}\``);
45
- }
46
- const type = value['type'];
47
- if (type !== 'boolean' && type !== 'string' && type !== 'number' && type !== 'enum') {
48
- throw declarationError(`${path}.type`, 'expected boolean, string, number, or enum');
49
- }
50
- if (!validHelp(value['write_help']))
51
- throw declarationError(`${path}.write_help`, 'expected a nonblank single-line string');
52
- if (!validHelp(value['edit_help']))
53
- throw declarationError(`${path}.edit_help`, 'expected a nonblank single-line string');
54
- if (type === 'enum') {
55
- const values = value['values'];
56
- if (!Array.isArray(values) || values.length === 0 || !values.every((entry) => typeof entry === 'string' && entry !== '')) {
57
- throw declarationError(`${path}.values`, 'expected a non-empty string list');
58
- }
59
- if (new Set(values).size !== values.length)
60
- throw declarationError(`${path}.values`, 'values must be unique');
61
- const declaration = {
62
- type,
63
- values: [...values],
64
- write_help: value['write_help'],
65
- edit_help: value['edit_help'],
66
- };
67
- if ('default' in value) {
68
- if (!validDefault(declaration, value['default'])) {
69
- throw declarationError(`${path}.default`, 'must be one of the declared enum values');
70
- }
71
- declaration.default = value['default'];
72
- }
73
- declarations[field] = declaration;
74
- continue;
75
- }
76
- if ('values' in value)
77
- throw declarationError(`${path}.values`, 'is allowed only for enum declarations');
78
- const declaration = {
79
- type,
80
- write_help: value['write_help'],
81
- edit_help: value['edit_help'],
82
- };
83
- if ('default' in value) {
84
- if (!validDefault(declaration, value['default'])) {
85
- throw declarationError(`${path}.default`, `must be a ${type}`);
86
- }
87
- declaration.default = value['default'];
88
- }
89
- declarations[field] = declaration;
90
- }
91
- return declarations;
92
- }
93
9
  /** Throw when a manifest carries an invalid addendum; absent is valid. */
94
10
  export function validatePluginMemoryExtensions(manifest) {
95
11
  if (manifest.memory_extensions !== undefined)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.788",
3
+ "version": "0.3.790",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.788",
3
+ "version": "0.3.790",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,6 +24,7 @@ export async function buildBundle(plugin, options) {
24
24
  ...(plugin.version !== undefined ? { version: plugin.version } : {}),
25
25
  ...(plugin.groups !== undefined ? { groups: groupsBlock(plugin.groups) } : {}),
26
26
  ...(objectKinds !== undefined ? { object_kinds: objectKinds } : {}),
27
+ ...(plugin.memoryExtensions !== undefined ? { memory_extensions: plugin.memoryExtensions } : {}),
27
28
  })}\n`;
28
29
  const memory = buildMemoryMembers(plugin.memory);
29
30
  const members = [
@@ -1,4 +1,4 @@
1
- import { LOCAL, mentionsFile, objectBlocksShapeReasons, objectKindReadReasons, outputBaseType } from '@north-light/api/command-manifest';
1
+ import { LOCAL, mentionsFile, objectBlocksShapeReasons, validateMemoryExtensionDeclarations, objectKindReadReasons, outputBaseType } from '@north-light/api/command-manifest';
2
2
  /** Thrown by `definePlugin` when a declaration is malformed, before anything is served. */
3
3
  export class PluginDefinitionError extends Error {
4
4
  constructor(message) {
@@ -87,6 +87,14 @@ export function definePlugin(spec) {
87
87
  validateMemoryDoc(doc);
88
88
  if (spec.objectKinds !== undefined)
89
89
  validateObjectKinds(spec.objectKinds, spec.name, spec.commands);
90
+ if (spec.memoryExtensions !== undefined) {
91
+ try {
92
+ validateMemoryExtensionDeclarations(spec.memoryExtensions);
93
+ }
94
+ catch (error) {
95
+ throw new PluginDefinitionError(error instanceof Error ? error.message : String(error));
96
+ }
97
+ }
90
98
  return Object.freeze({
91
99
  name: spec.name,
92
100
  description: spec.description,
@@ -100,6 +108,7 @@ export function definePlugin(spec) {
100
108
  ...(spec.provider !== undefined ? { provider: spec.provider } : {}),
101
109
  ...(spec.objectKinds !== undefined ? { objectKinds: snapshotObjectKinds(spec.objectKinds) } : {}),
102
110
  ...(spec.groups !== undefined ? { groups: snapshotGroups(spec.groups) } : {}),
111
+ ...(spec.memoryExtensions !== undefined ? { memoryExtensions: structuredClone(spec.memoryExtensions) } : {}),
103
112
  });
104
113
  }
105
114
  /** Each declared group is well formed and every leaf names a declared group. A declared group no leaf uses is allowed: a provider that ships documents only declares one so a grant naming it installs the bundle. */