@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.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/command-manifest/index.d.ts +1 -0
- package/dist/api/command-manifest/index.js +1 -1
- package/dist/api/command-manifest/memory-extensions.d.ts +34 -0
- package/dist/api/command-manifest/memory-extensions.js +1 -0
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/crouter-plugin/bundles-and-memory.md +16 -1
- package/dist/builtin-memory/internal/INDEX.md +1 -1
- package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
- package/dist/clients/attach/viewer.js +255 -255
- package/dist/commands/canvas-history/shared.js +1 -1
- package/dist/commands/node/create.js +2 -2
- package/dist/commands/person-settings.js +1 -1
- package/dist/commands/profile/daemon-profiles.js +4 -4
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/history.d.ts +2 -8
- package/dist/core/canvas/history.js +9 -9
- package/dist/core/canvas/node-tokens.js +3 -3
- package/dist/core/canvas/person-state.d.ts +5 -7
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +3 -30
- package/dist/core/canvas/person.js +1 -11
- package/dist/core/config.d.ts +4 -1
- package/dist/core/config.js +1 -1
- package/dist/core/directory/join.d.ts +4 -6
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/graph/documents.d.ts +1 -1
- package/dist/core/graph/kinds/document.js +1 -1
- package/dist/core/human/requests.d.ts +11 -1
- package/dist/core/human/requests.js +22 -22
- package/dist/core/plugin-extensions.d.ts +3 -6
- package/dist/core/plugin-extensions.js +1 -1
- package/dist/core/review/store.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/launch-config-worker.js +1 -1
- package/dist/core/runtime/launch-target.d.ts +6 -4
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/launch.d.ts +5 -1
- package/dist/core/runtime/launch.js +2 -2
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +1 -1
- package/dist/core/runtime/runner/delete-sandboxes.js +5 -5
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/spawn-env-rows.js +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/environment-owner.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/human/sweep.js +1 -1
- package/dist/daemon/peer/ingress.d.ts +2 -2
- package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
- package/dist/daemon/runs/observer.js +6 -5
- package/dist/types.d.ts +2 -28
- package/docs/plugin/bundles-and-memory.md +15 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/command-manifest/index.js +1 -0
- package/packages/crouter-api/dist/api/command-manifest/memory-extensions.js +91 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
- package/packages/crouter-api/dist/core/config.js +10 -0
- package/packages/crouter-api/dist/core/directory/join.js +11 -45
- package/packages/crouter-api/dist/core/plugin-extensions.js +2 -86
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/bundle.js +1 -0
- package/packages/crouter-plugin/dist/define.js +10 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/join.d.ts +0 -3
- package/dist/commands/sys/join.js +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
var
|
|
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],
|
|
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
|
-
|
|
5
|
-
AND
|
|
6
|
-
|
|
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
|
|
37
|
-
|
|
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.
|
|
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.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
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. */
|
|
@@ -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.
|
|
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 (
|
|
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
|
|
15
|
+
let clientPersonId;
|
|
16
16
|
let cloudRole = false;
|
|
17
17
|
const requestPersons = new AsyncLocalStorage();
|
|
18
|
-
/** crtrd
|
|
19
|
-
export function
|
|
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
|
|
31
|
-
* `PersonUnresolvedError` when
|
|
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 (
|
|
38
|
+
if (clientPersonId === undefined)
|
|
39
39
|
throw new PersonUnresolvedError();
|
|
40
|
-
return
|
|
40
|
+
return clientPersonId;
|
|
41
41
|
}
|
|
42
|
-
/** The
|
|
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
|
|
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: '
|
|
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
|
|
92
|
-
* without
|
|
93
|
-
* and
|
|
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
|
|
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
|
|
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
|
|
102
|
+
/** The issuer a successful registration recorded, or null. */
|
|
106
103
|
export function joinedIssuer() { return readJoined()?.issuer ?? null; }
|
|
107
|
-
/** The whole registration a successful
|
|
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: '
|
|
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 (
|
|
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
|
-
|
|
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.
|
|
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",
|
|
@@ -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. */
|