yaml-flow 7.0.0 → 7.1.0
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/browser/asset-integrity.json +1 -1
- package/browser/board-livecards-client.js +1 -1
- package/browser/board-livecards-client.js.map +1 -1
- package/browser/board-livecards-localstorage.js +5 -5
- package/browser/board-livecards-localstorage.js.map +1 -1
- package/browser/live-cards.js +3 -1
- package/dist/{board-live-cards-public-CW5074xr.d.cts → board-live-cards-public-5n1-syA3.d.cts} +1 -2
- package/dist/{board-live-cards-public-hnZo0mAf.d.ts → board-live-cards-public-CK_J8uv0.d.ts} +1 -2
- package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs +2 -2
- package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs.map +1 -1
- package/dist/cli/browser-api/board-live-cards-browser-adapter.d.cts +2 -2
- package/dist/cli/browser-api/board-live-cards-browser-adapter.d.ts +2 -2
- package/dist/cli/browser-api/board-live-cards-browser-adapter.js +2 -2
- package/dist/cli/browser-api/board-live-cards-browser-adapter.js.map +1 -1
- package/dist/cli/browser-api/card-store-browser-api.cjs.map +1 -1
- package/dist/cli/browser-api/card-store-browser-api.js.map +1 -1
- package/dist/cli/node/artifacts-store-cli.cjs +5 -5
- package/dist/cli/node/artifacts-store-cli.cjs.map +1 -1
- package/dist/cli/node/artifacts-store-cli.js +5 -5
- package/dist/cli/node/artifacts-store-cli.js.map +1 -1
- package/dist/cli/node/board-live-cards-cli.cjs +7 -7
- package/dist/cli/node/board-live-cards-cli.cjs.map +1 -1
- package/dist/cli/node/board-live-cards-cli.js +7 -7
- package/dist/cli/node/board-live-cards-cli.js.map +1 -1
- package/dist/cli/node/card-store-cli.cjs +4 -4
- package/dist/cli/node/card-store-cli.cjs.map +1 -1
- package/dist/cli/node/card-store-cli.js +4 -4
- package/dist/cli/node/card-store-cli.js.map +1 -1
- package/dist/cli/node/execution-adapter.cjs +1 -1
- package/dist/cli/node/execution-adapter.cjs.map +1 -1
- package/dist/cli/node/execution-adapter.js +1 -1
- package/dist/cli/node/execution-adapter.js.map +1 -1
- package/dist/cli/node/fs-board-adapter.cjs +7 -7
- package/dist/cli/node/fs-board-adapter.cjs.map +1 -1
- package/dist/cli/node/fs-board-adapter.d.cts +2 -2
- package/dist/cli/node/fs-board-adapter.d.ts +2 -2
- package/dist/cli/node/fs-board-adapter.js +7 -7
- package/dist/cli/node/fs-board-adapter.js.map +1 -1
- package/dist/cli/node/source-cli-task-executor.cjs +2 -2
- package/dist/cli/node/source-cli-task-executor.cjs.map +1 -1
- package/dist/cli/node/source-cli-task-executor.js +2 -2
- package/dist/cli/node/source-cli-task-executor.js.map +1 -1
- package/dist/execution-refs.cjs +2 -2
- package/dist/execution-refs.cjs.map +1 -1
- package/dist/execution-refs.d.cts +9 -4
- package/dist/execution-refs.d.ts +9 -4
- package/dist/execution-refs.js +2 -2
- package/dist/execution-refs.js.map +1 -1
- package/dist/server-runtime/index.cjs +4 -4
- package/dist/server-runtime/index.cjs.map +1 -1
- package/dist/server-runtime/index.d.cts +3 -3
- package/dist/server-runtime/index.d.ts +3 -3
- package/dist/server-runtime/index.js +4 -4
- package/dist/server-runtime/index.js.map +1 -1
- package/dist/step-machine-public/index.cjs +2 -1
- package/dist/step-machine-public/index.cjs.map +1 -1
- package/dist/step-machine-public/index.d.cts +7 -0
- package/dist/step-machine-public/index.d.ts +7 -0
- package/dist/step-machine-public/index.js +2 -1
- package/dist/step-machine-public/index.js.map +1 -1
- package/dist/storage-refs.cjs +2 -2
- package/dist/storage-refs.cjs.map +1 -1
- package/dist/storage-refs.d.cts +1 -2
- package/dist/storage-refs.d.ts +1 -2
- package/dist/storage-refs.js +2 -2
- package/dist/storage-refs.js.map +1 -1
- package/dist/{types-BxEFcVK9.d.cts → types-CU3DjTKL.d.cts} +1 -1
- package/dist/{types-B1ZRa4aI.d.ts → types-HGDTWIun.d.ts} +1 -1
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.js +13 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.py +398 -0
- package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +4 -4
- package/examples/cli/step-machine-demo/jsonata-init-board.flow.yaml +1 -1
- package/examples/cli/step-machine-demo/one-step-cli-only.flow.yaml +1 -1
- package/examples/cli/step-machine-demo/two-step-mixed.flow.yaml +1 -1
- package/examples/example-board/agent-instructions.md +1 -1
- package/examples/example-board/cards/{card-market-prices.json → cardT-market-prices.json} +2 -2
- package/examples/example-board/cards/{card-portfolio.json → cardT-portfolio.json} +3 -13
- package/examples/example-board/demo-server-config.json +1 -1
- package/examples/example-board/demo-server.js +48 -25
- package/examples/example-board/demo-shell-localstorage.html +3 -3
- package/examples/example-board/demo-shell-with-server.html +2 -2
- package/examples/example-board/demo-task-executor.js +4 -8
- package/package.json +2 -2
- package/step-machine-cli.js +1 -1
- package/examples/example-board/cards/_index.json +0 -47
- /package/examples/example-board/cards/{card-portfolio-value.json → cardT-portfolio-value.json} +0 -0
|
@@ -180,12 +180,17 @@ interface ExecutionRef {
|
|
|
180
180
|
*/
|
|
181
181
|
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';
|
|
182
182
|
/**
|
|
183
|
-
* Address of the artifact to run
|
|
183
|
+
* Address of the artifact to run. Two valid forms:
|
|
184
|
+
* - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)
|
|
185
|
+
* - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)
|
|
184
186
|
* @example 'b64:<base64url({"kind":"fs-path","value":"/dist/cli/source-cli-task-executor.js"})>'
|
|
185
|
-
* @example
|
|
186
|
-
* @example
|
|
187
|
+
* @example { kind: 'http-url', value: '/api/workiq/ask' }
|
|
188
|
+
* @example { kind: 'fs-path', value: './my-handler.js' }
|
|
187
189
|
*/
|
|
188
|
-
whatToRun: string
|
|
190
|
+
whatToRun: string | {
|
|
191
|
+
kind: string;
|
|
192
|
+
value: string;
|
|
193
|
+
};
|
|
189
194
|
/**
|
|
190
195
|
* Optional JSONata-based mapping from logical args → physical call shape.
|
|
191
196
|
* When omitted, the adapter applies its default protocol for the howToRun kind.
|
package/dist/execution-refs.d.ts
CHANGED
|
@@ -180,12 +180,17 @@ interface ExecutionRef {
|
|
|
180
180
|
*/
|
|
181
181
|
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';
|
|
182
182
|
/**
|
|
183
|
-
* Address of the artifact to run
|
|
183
|
+
* Address of the artifact to run. Two valid forms:
|
|
184
|
+
* - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)
|
|
185
|
+
* - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)
|
|
184
186
|
* @example 'b64:<base64url({"kind":"fs-path","value":"/dist/cli/source-cli-task-executor.js"})>'
|
|
185
|
-
* @example
|
|
186
|
-
* @example
|
|
187
|
+
* @example { kind: 'http-url', value: '/api/workiq/ask' }
|
|
188
|
+
* @example { kind: 'fs-path', value: './my-handler.js' }
|
|
187
189
|
*/
|
|
188
|
-
whatToRun: string
|
|
190
|
+
whatToRun: string | {
|
|
191
|
+
kind: string;
|
|
192
|
+
value: string;
|
|
193
|
+
};
|
|
189
194
|
/**
|
|
190
195
|
* Optional JSONata-based mapping from logical args → physical call shape.
|
|
191
196
|
* When omitted, the adapter applies its default protocol for the howToRun kind.
|
package/dist/execution-refs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var s="b64:";function l(e){let
|
|
2
|
-
export{
|
|
1
|
+
var s="b64:";function l(e){let r=new TextEncoder().encode(e),t=globalThis.Buffer,n;if(t)n=t.from(r).toString("base64");else if(typeof btoa=="function"){let o="";for(let a of r)o+=String.fromCharCode(a);n=btoa(o);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function i(e){return `${s}${l(JSON.stringify(e))}`}function c(e,r){let t;return /\.m?js$/i.test(e)?t="local-node":/\.py$/i.test(e)?t="local-python":t="local-process",{meta:"task-executor",howToRun:t,whatToRun:i({kind:"fs-path",value:e}),...r?{extra:r}:{}}}function f(e){return JSON.stringify(e)}function d(e){let r;try{r=JSON.parse(e);}catch{throw new Error(`parseExecutionRef: invalid JSON \u2014 ${e}`)}if(typeof r!="object"||r===null||typeof r.howToRun!="string"||typeof r.whatToRun!="string")throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun \u2014 ${e}`);return r}
|
|
2
|
+
export{c as executionRefFromScriptPath,d as parseExecutionRef,f as serializeExecutionRef};//# sourceMappingURL=execution-refs.js.map
|
|
3
3
|
//# sourceMappingURL=execution-refs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/common/storage-interface.ts","../src/cli/common/execution-interface.ts"],"names":["REF_PREFIX","toBase64Url","raw","utf8","buf","base64","binary","byte","serializeRef","ref","executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","parseExecutionRef","s","parsed"],"mappings":"AAqFA,IAAMA,EAAa,MAAA,CAEnB,SAASC,EAAYC,CAAAA,CAAqB,CACxC,IAAMC,CAAAA,CAAO,IAAI,aAAY,CAAE,MAAA,CAAOD,CAAG,CAAA,CACnCE,CAAAA,CAAO,WAA0F,MAAA,CACnGC,CAAAA,CACJ,GAAID,CAAAA,CACFC,CAAAA,CAASD,EAAI,IAAA,CAAKD,CAAI,EAAE,QAAA,CAAS,QAAQ,UAChC,OAAO,IAAA,EAAS,WAAY,CACrC,IAAIG,EAAS,EAAA,CACb,IAAA,IAAWC,KAAQJ,CAAAA,CAAMG,CAAAA,EAAU,OAAO,YAAA,CAAaC,CAAI,EAC3DF,CAAAA,CAAS,IAAA,CAAKC,CAAM,EACtB,MACE,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAE/D,OAAOD,CAAAA,CAAO,OAAA,CAAQ,MAAO,GAAG,CAAA,CAAE,QAAQ,KAAA,CAAO,GAAG,EAAE,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAC1E,CAiBO,SAASG,CAAAA,CAAaC,CAAAA,CAA2B,CACtD,OAAO,CAAA,EAAGT,CAAU,CAAA,EAAGC,CAAAA,CAAY,KAAK,SAAA,CAAUQ,CAAG,CAAC,CAAC,CAAA,CACzD,CCqKO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,UAAA,CAAW,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,aACnC,QAAA,CAAS,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,eAC1CA,CAAAA,CAAW,eAAA,CACT,CACL,IAAA,CAAM,eAAA,CACN,SAAAA,CAAAA,CACA,SAAA,CAAWL,EAAa,CAAE,IAAA,CAAM,UAAW,KAAA,CAAOG,CAAW,CAAC,CAAA,CAC9D,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBL,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,UAAUA,CAAG,CAC3B,CAMO,SAASM,CAAAA,CAAkBC,EAAyB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAA,CAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,MAAM,CAAA,uCAAA,EAAqCA,CAAC,EAAE,CAC1D,CACA,GACE,OAAOC,CAAAA,EAAW,UAClBA,CAAAA,GAAW,IAAA,EACX,OAAQA,CAAAA,CAAmC,QAAA,EAAa,UACxD,OAAQA,CAAAA,CAAmC,WAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,CAAA,qEAAA,EAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.js","sourcesContent":["/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef.\n * Also accepts the legacy ::fs-path::<path> format for backward compatibility. */\nexport function parseRef(s: string): KindValueRef {\n // Legacy format: ::fs-path::<path>\n if (s.startsWith('::fs-path::')) {\n return { kind: 'fs-path', value: s.slice('::fs-path::'.length) };\n }\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: 'b64:<base64url({\"kind\":\"built-in\",\"value\":\"source-cli-task-executor\"})>',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/path/to/my-executor.js\"})>',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/task-executor\"})>',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/chat\"})>',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// OutputTransforms\n// ============================================================================\n\nimport { serializeRef } from './storage-interface.js';\n\n/**\n * Optional JSONata-based transforms applied to the raw invoke result.\n * Context for all expressions: `{ output: { result, data, error? } }`.\n * All fields are optional.\n */\nexport interface OutputTransforms {\n /**\n * JSONata expression that produces the transition name string.\n * @example \"output.code = 200 ? 'success' : 'failure'\"\n */\n resultExpr?: string;\n\n /**\n * JSONata expression that produces the data object.\n * @example \"{ 'value': output.body.value }\"\n */\n dataTemplate?: string;\n\n /**\n * JSONata expression that produces the error string, or $undefined() to clear it.\n * @example \"output.code != 200 ? output.error_message : $undefined()\"\n */\n errorExpr?: string;\n}\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';\n\n /**\n * Address of the artifact to run, in KindValueRef wire form (b64:<base64url(json)>).\n * @example 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/dist/cli/source-cli-task-executor.js\"})>'\n * @example 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://fn.example.com/api/executor\"})>'\n * @example 'b64:<base64url({\"kind\":\"built-in\",\"value\":\"source-cli-task-executor\"})>'\n */\n whatToRun: string;\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Optional JSONata-based transforms applied to the raw invoke result\n * before it reaches the step-machine engine.\n *\n * Context for all expressions: `{ output: { result, data, error? } }`\n * where `output` is the raw { result, data, error? } returned by invokeRefSync.\n *\n * All fields are optional — only defined ones override the raw value.\n *\n * @example\n * outputTransforms:\n * resultExpr: \"output.code = 200 ? 'success' : 'failure'\"\n * dataTemplate: \"{ 'value': output.body.value }\"\n * errorExpr: \"output.code != 200 ? output.error_message : $undefined()\"\n */\n outputTransforms?: OutputTransforms;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: serializeRef({ kind: 'fs-path', value: scriptPath }),\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/common/storage-interface.ts","../src/cli/common/execution-interface.ts"],"names":["REF_PREFIX","toBase64Url","raw","utf8","buf","base64","binary","byte","serializeRef","ref","executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","parseExecutionRef","s","parsed"],"mappings":"AAqFA,IAAMA,EAAa,MAAA,CAEnB,SAASC,EAAYC,CAAAA,CAAqB,CACxC,IAAMC,CAAAA,CAAO,IAAI,aAAY,CAAE,MAAA,CAAOD,CAAG,CAAA,CACnCE,CAAAA,CAAO,WAA0F,MAAA,CACnGC,CAAAA,CACJ,GAAID,CAAAA,CACFC,CAAAA,CAASD,EAAI,IAAA,CAAKD,CAAI,EAAE,QAAA,CAAS,QAAQ,UAChC,OAAO,IAAA,EAAS,WAAY,CACrC,IAAIG,EAAS,EAAA,CACb,IAAA,IAAWC,KAAQJ,CAAAA,CAAMG,CAAAA,EAAU,OAAO,YAAA,CAAaC,CAAI,EAC3DF,CAAAA,CAAS,IAAA,CAAKC,CAAM,EACtB,MACE,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAE/D,OAAOD,CAAAA,CAAO,OAAA,CAAQ,MAAO,GAAG,CAAA,CAAE,QAAQ,KAAA,CAAO,GAAG,EAAE,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAC1E,CAiBO,SAASG,CAAAA,CAAaC,CAAAA,CAA2B,CACtD,OAAO,CAAA,EAAGT,CAAU,CAAA,EAAGC,CAAAA,CAAY,KAAK,SAAA,CAAUQ,CAAG,CAAC,CAAC,CAAA,CACzD,CCuKO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,UAAA,CAAW,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,aACnC,QAAA,CAAS,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,eAC1CA,CAAAA,CAAW,eAAA,CACT,CACL,IAAA,CAAM,eAAA,CACN,SAAAA,CAAAA,CACA,SAAA,CAAWL,EAAa,CAAE,IAAA,CAAM,UAAW,KAAA,CAAOG,CAAW,CAAC,CAAA,CAC9D,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBL,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,UAAUA,CAAG,CAC3B,CAMO,SAASM,CAAAA,CAAkBC,EAAyB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAA,CAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,MAAM,CAAA,uCAAA,EAAqCA,CAAC,EAAE,CAC1D,CACA,GACE,OAAOC,CAAAA,EAAW,UAClBA,CAAAA,GAAW,IAAA,EACX,OAAQA,CAAAA,CAAmC,QAAA,EAAa,UACxD,OAAQA,CAAAA,CAAmC,WAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,CAAA,qEAAA,EAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.js","sourcesContent":["/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: 'b64:<base64url({\"kind\":\"built-in\",\"value\":\"source-cli-task-executor\"})>',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/path/to/my-executor.js\"})>',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/task-executor\"})>',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/chat\"})>',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// OutputTransforms\n// ============================================================================\n\nimport { serializeRef } from './storage-interface.js';\n\n/**\n * Optional JSONata-based transforms applied to the raw invoke result.\n * Context for all expressions: `{ output: { result, data, error? } }`.\n * All fields are optional.\n */\nexport interface OutputTransforms {\n /**\n * JSONata expression that produces the transition name string.\n * @example \"output.code = 200 ? 'success' : 'failure'\"\n */\n resultExpr?: string;\n\n /**\n * JSONata expression that produces the data object.\n * @example \"{ 'value': output.body.value }\"\n */\n dataTemplate?: string;\n\n /**\n * JSONata expression that produces the error string, or $undefined() to clear it.\n * @example \"output.code != 200 ? output.error_message : $undefined()\"\n */\n errorExpr?: string;\n}\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';\n\n /**\n * Address of the artifact to run. Two valid forms:\n * - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)\n * - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)\n * @example 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/dist/cli/source-cli-task-executor.js\"})>'\n * @example { kind: 'http-url', value: '/api/workiq/ask' }\n * @example { kind: 'fs-path', value: './my-handler.js' }\n */\n whatToRun: string | { kind: string; value: string };\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Optional JSONata-based transforms applied to the raw invoke result\n * before it reaches the step-machine engine.\n *\n * Context for all expressions: `{ output: { result, data, error? } }`\n * where `output` is the raw { result, data, error? } returned by invokeRefSync.\n *\n * All fields are optional — only defined ones override the raw value.\n *\n * @example\n * outputTransforms:\n * resultExpr: \"output.code = 200 ? 'success' : 'failure'\"\n * dataTemplate: \"{ 'value': output.body.value }\"\n * errorExpr: \"output.code != 200 ? output.error_message : $undefined()\"\n */\n outputTransforms?: OutputTransforms;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: serializeRef({ kind: 'fs-path', value: scriptPath }),\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|