@loomcycle/client 0.11.3 → 0.11.5

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/README.md CHANGED
@@ -6,7 +6,7 @@ TypeScript client for the [loomcycle](https://github.com/denn-gubsky/loomcycle)
6
6
 
7
7
  ## Status
8
8
 
9
- **v0.11.3** — 41 methods covering run streaming, agent metadata, transcript, pause/resume/state, snapshot lifecycle, memory admin, interruption resolve, hook registration, **v0.8.22 substrate admin (agentDef + skillDef)**, **v0.9.x n8n Phase 0 (listChannels + streamUserRunStates)**, **v0.9.x content_sha256**, **v0.9.x dynamic MCP server registration (mcpServerDef)**, **v0.10.3 Library v2 enumeration (listLibraryAgents/Skills/McpServers)**, **v0.11.0 LLM Gateway (llmChat + llmStream)**, and health.
9
+ **v0.11.4** — 42 methods covering run streaming, agent metadata, transcript, pause/resume/state, snapshot lifecycle, memory admin, interruption resolve, hook registration, **v0.8.22 substrate admin (agentDef + skillDef)**, **v0.9.x n8n Phase 0 (listChannels + streamUserRunStates)**, **v0.9.x content_sha256**, **v0.9.x dynamic MCP server registration (mcpServerDef)**, **v0.10.3 Library v2 enumeration (listLibraryAgents/Skills/McpServers)**, **v0.11.0 LLM Gateway (llmChat + llmStream)**, **v0.11.4 OpenAI Embeddings (embeddings)**, and health.
10
10
 
11
11
  > Migrating from raw `fetch` against `/v1/*`? See **[docs/MIGRATING-FROM-HTTP.md](./docs/MIGRATING-FROM-HTTP.md)** for a side-by-side walkthrough.
12
12
 
@@ -25,6 +25,7 @@ TypeScript client for the [loomcycle](https://github.com/denn-gubsky/loomcycle)
25
25
  - **First-run UX on the binary** (v0.11.1) — paired CLI commands `loomcycle init` (bootstrap config) + `loomcycle doctor` (health check) + auto-discovery of `~/.config/loomcycle/loomcycle.yaml`. No adapter changes; lockstep version bump only.
26
26
  - **Docker image + brew formula polish** (v0.11.2) — multi-arch image at `docker.io/denngubsky/loomcycle`; brew formula caveats refreshed to reference `loomcycle init` / `loomcycle doctor`; new `installation` Context.help topic. No adapter changes; lockstep version bump only.
27
27
  - **OpenAI Chat Completions compatibility shim** (v0.11.3) — new `POST /v1/chat/completions` endpoint serves OpenAI's exact wire shape; consumers using the OpenAI SDK can point at loomcycle by changing only base URL + auth token. `@loomcycle/client` consumers should still prefer `llmChat()` / `llmStream()` over the shim for richer typing (per-frame discriminated unions vs OpenAI's flat chunks). No adapter changes; lockstep version bump only.
28
+ - **OpenAI Embeddings compatibility shim** (v0.11.4) — new `POST /v1/embeddings` endpoint serves OpenAI's Embeddings API shape. New `embeddings()` adapter method + four typed exports (`LLMEmbeddingsOptions`, `LLMEmbeddingsResponse`, `LLMEmbeddingItem`, `LLMEmbeddingsUsage`). Dispatches to the single configured `providers.Embedder` (the same instance Memory tool uses); RAG tools / vector DBs / LangChain `OpenAIEmbeddings` consumers point at loomcycle by changing only the base URL.
28
29
 
29
30
  ## Install
30
31
 
@@ -521,6 +521,29 @@ class LoomcycleClient {
521
521
  const reader = resp.body.getReader();
522
522
  yield* parseLLMStreamFrames(reader);
523
523
  }
524
+ // ---- v0.11.4 OpenAI Embeddings compatibility shim ----
525
+ /** Compute embedding vectors via the OpenAI-compatible
526
+ * `/v1/embeddings` endpoint. Dispatches to the single configured
527
+ * `providers.Embedder` (the same instance Memory tool uses for
528
+ * `embed:true` internally). No resolver path, no tier overlay,
529
+ * no streaming — embeddings are synchronous.
530
+ *
531
+ * Accepts `input` as a string OR string array. Tokenized inputs
532
+ * (number arrays) are refused at the server boundary — send text.
533
+ * `encoding_format: "base64"` packs each float32 little-endian
534
+ * then base64-encodes (saves ~25% wire bytes on 1536-dim
535
+ * vectors); "float" (default) emits each vector as a JSON array.
536
+ *
537
+ * Raises {@link AuthError} on 401; {@link UnavailableError} on
538
+ * 503 (no embedder configured — set memory.embedder.* in
539
+ * loomcycle.yaml); {@link InvalidArgumentError} on 400 (bad
540
+ * request shape). */
541
+ async embeddings(opts) {
542
+ const { signal: _signal, ...body } = opts;
543
+ return (0, fetch_helpers_js_1.postJSON)(this.ctx, "/v1/embeddings", body, {
544
+ signal: opts.signal,
545
+ });
546
+ }
524
547
  // ---- Internal helpers ----
525
548
  /** Shared SSE POST → stream-of-AgentEvent path. Used by
526
549
  * runStreaming + continueSession.
@@ -684,6 +707,78 @@ class LoomcycleClient {
684
707
  const path = channelOpPath(channel, opts.scope, opts.userId, "ack");
685
708
  return (0, fetch_helpers_js_1.postJSON)(this.ctx, path, { cursor: opts.cursor }, { signal: opts.signal });
686
709
  }
710
+ // ---- v0.11.5 Channel admin CRUD ----
711
+ //
712
+ // Three bearer-authed ops that mutate the runtime-substrate
713
+ // channel registry. yaml-declared channels are immutable from
714
+ // this surface — the server refuses with HTTP 409 + wire `code`
715
+ // `channel_yaml_immutable`. The TS adapter surfaces that as a
716
+ // {@link LoomcycleError} with status 409.
717
+ /** Create a new runtime-substrate channel. Refuses with HTTP 409
718
+ * when the name matches a yaml-declared channel (code
719
+ * `channel_yaml_immutable`) or an existing runtime channel
720
+ * (code `channel_name_in_use`). */
721
+ async createChannel(opts) {
722
+ const body = { name: opts.name };
723
+ if (opts.description !== undefined)
724
+ body.description = opts.description;
725
+ if (opts.scope !== undefined)
726
+ body.scope = opts.scope;
727
+ if (opts.semantic !== undefined)
728
+ body.semantic = opts.semantic;
729
+ if (opts.default_ttl !== undefined)
730
+ body.default_ttl = opts.default_ttl;
731
+ if (opts.max_messages !== undefined)
732
+ body.max_messages = opts.max_messages;
733
+ if (opts.publisher !== undefined)
734
+ body.publisher = opts.publisher;
735
+ if (opts.period !== undefined)
736
+ body.period = opts.period;
737
+ return (0, fetch_helpers_js_1.postJSON)(this.ctx, "/v1/_channels", body, {
738
+ signal: opts.signal,
739
+ });
740
+ }
741
+ /** Partially update a runtime-substrate channel. Nil-valued fields
742
+ * in `opts` leave the corresponding attribute unchanged. Refuses
743
+ * yaml-declared channels with HTTP 409. */
744
+ async updateChannel(name, opts) {
745
+ const body = {};
746
+ if (opts.description !== undefined)
747
+ body.description = opts.description;
748
+ if (opts.default_ttl !== undefined)
749
+ body.default_ttl = opts.default_ttl;
750
+ if (opts.max_messages !== undefined)
751
+ body.max_messages = opts.max_messages;
752
+ if (opts.semantic !== undefined)
753
+ body.semantic = opts.semantic;
754
+ return (0, fetch_helpers_js_1.patchJSON)(this.ctx, `/v1/_channels/${encodeURIComponent(name)}`, body, { signal: opts.signal });
755
+ }
756
+ /** Delete a runtime-substrate channel + cascade its persisted
757
+ * messages + cursors. yaml-declared channels refuse with HTTP 409.
758
+ * Idempotent: deleting a non-existent runtime channel returns a
759
+ * {@link NotFoundError} so the caller can distinguish that case. */
760
+ async deleteChannel(name, opts) {
761
+ return (0, fetch_helpers_js_1.deleteRequest)(this.ctx, `/v1/_channels/${encodeURIComponent(name)}`, opts);
762
+ }
763
+ // ---- v0.11.5 Memory entry admin CRUD ----
764
+ /** Idempotently upsert one memory entry by full (scope, scope_id,
765
+ * key) identifier. PUT semantics — re-writes overwrite the value.
766
+ * Optional embed flag triggers a synchronous embed via the
767
+ * operator-configured embedder. */
768
+ async setMemoryEntry(scope, scopeID, key, opts) {
769
+ const body = { value: opts.value };
770
+ if (opts.embed !== undefined)
771
+ body.embed = opts.embed;
772
+ if (opts.ttl_seconds !== undefined)
773
+ body.ttl_seconds = opts.ttl_seconds;
774
+ return (0, fetch_helpers_js_1.putJSON)(this.ctx, `/v1/_memory/scopes/${encodeURIComponent(scope)}/${encodeURIComponent(scopeID)}/keys/${encodeURIComponent(key)}`, body, { signal: opts.signal });
775
+ }
776
+ /** Delete one memory entry by (scope, scope_id, key). Idempotent:
777
+ * deleting a missing row is a non-error per the in-band Memory
778
+ * tool's semantics — both surfaces return 204. */
779
+ async deleteMemoryEntry(scope, scopeID, key, opts) {
780
+ return (0, fetch_helpers_js_1.deleteRequest)(this.ctx, `/v1/_memory/scopes/${encodeURIComponent(scope)}/${encodeURIComponent(scopeID)}/keys/${encodeURIComponent(key)}`, opts);
781
+ }
687
782
  /** Subscribe to run state transitions for one user_id via SSE.
688
783
  * Yields one `{ kind: "open", ... }` item first (confirms the
689
784
  * connection is live), then one `{ kind: "event", ... }` per
@@ -14,6 +14,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.authHeaders = authHeaders;
15
15
  exports.jsonFetch = jsonFetch;
16
16
  exports.postJSON = postJSON;
17
+ exports.putJSON = putJSON;
18
+ exports.patchJSON = patchJSON;
17
19
  exports.deleteRequest = deleteRequest;
18
20
  exports.raiseFromResponse = raiseFromResponse;
19
21
  const errors_js_1 = require("./errors.js");
@@ -65,6 +67,51 @@ async function postJSON(ctx, path, body, opts) {
65
67
  return null;
66
68
  return (await resp.json());
67
69
  }
70
+ /** putJSON sends a JSON-encoded body via PUT and unwraps the
71
+ * response. Idempotent — REST-canonical verb for "create or
72
+ * overwrite by full identifier." */
73
+ async function putJSON(ctx, path, body, opts) {
74
+ const headers = authHeaders(ctx);
75
+ let bodyStr;
76
+ if (body !== undefined) {
77
+ headers["Content-Type"] = "application/json";
78
+ bodyStr = JSON.stringify(body);
79
+ }
80
+ const resp = await ctx.fetchImpl(ctx.baseUrl + path, {
81
+ method: "PUT",
82
+ headers,
83
+ body: bodyStr,
84
+ signal: opts?.signal,
85
+ });
86
+ if (!resp.ok) {
87
+ await raiseFromResponse(resp);
88
+ }
89
+ if (resp.status === 204)
90
+ return null;
91
+ return (await resp.json());
92
+ }
93
+ /** patchJSON sends a JSON-encoded body via PATCH and unwraps the
94
+ * response. For partial-update endpoints. */
95
+ async function patchJSON(ctx, path, body, opts) {
96
+ const headers = authHeaders(ctx);
97
+ let bodyStr;
98
+ if (body !== undefined) {
99
+ headers["Content-Type"] = "application/json";
100
+ bodyStr = JSON.stringify(body);
101
+ }
102
+ const resp = await ctx.fetchImpl(ctx.baseUrl + path, {
103
+ method: "PATCH",
104
+ headers,
105
+ body: bodyStr,
106
+ signal: opts?.signal,
107
+ });
108
+ if (!resp.ok) {
109
+ await raiseFromResponse(resp);
110
+ }
111
+ if (resp.status === 204)
112
+ return null;
113
+ return (await resp.json());
114
+ }
68
115
  /** deleteRequest sends a DELETE and tolerates 204/200/404-with-
69
116
  * idempotent-semantics per the loomcycle wire contract. */
70
117
  async function deleteRequest(ctx, path, opts) {
package/dist/cjs/index.js CHANGED
@@ -56,6 +56,9 @@
56
56
  * llmChat(opts: LLMChatOptions): Promise<LLMChatResponse>
57
57
  * llmStream(opts: LLMChatOptions): AsyncIterable<LLMChatStreamItem>
58
58
  *
59
+ * // OpenAI Embeddings compatibility shim (v0.11.4)
60
+ * embeddings(opts: LLMEmbeddingsOptions): Promise<LLMEmbeddingsResponse>
61
+ *
59
62
  * Errors (typed subclasses of LoomcycleError; see README for the
60
63
  * full HTTP-status → typed-error mapping table):
61
64
  * LoomcycleError, AgentNotFoundError, SessionNotFoundError,
package/dist/client.d.ts CHANGED
@@ -23,7 +23,7 @@
23
23
  * via fetch-helpers.ts:raiseFromResponse — see README.md for the
24
24
  * full mapping table.
25
25
  */
26
- import type { Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, CreateSnapshotOptions, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, ChannelAckResult, ChannelPeekResult, ChannelPublishResult, ChannelSubscribeResult, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, MemoryEntriesResponse, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopesResponse, PauseResult, RegisterHookOptions, RegisterHookResponse, ResolveInterruptOptions, ResumeResult, RunOptions, RunStateStreamItem, RuntimeStateResponse, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotRestoreResponse, StreamUserRunStatesOptions, SubstrateToolInput, SubstrateToolResponse, TranscriptResponse } from "./types.js";
26
+ import type { Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, CreateSnapshotOptions, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, ChannelAckResult, ChannelDescriptor, ChannelPeekResult, ChannelPublishResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MemoryEntriesResponse, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopesResponse, PauseResult, RegisterHookOptions, RegisterHookResponse, ResolveInterruptOptions, ResumeResult, RunOptions, RunStateStreamItem, RuntimeStateResponse, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotRestoreResponse, StreamUserRunStatesOptions, SubstrateToolInput, SubstrateToolResponse, TranscriptResponse } from "./types.js";
27
27
  export declare class LoomcycleClient {
28
28
  private ctx;
29
29
  constructor(opts?: ClientOptions);
@@ -361,6 +361,23 @@ export declare class LoomcycleClient {
361
361
  * Use this for live token streaming into LangChain BaseChatModel
362
362
  * `_stream` callbacks. */
363
363
  llmStream(opts: LLMChatOptions): AsyncIterable<LLMChatStreamItem>;
364
+ /** Compute embedding vectors via the OpenAI-compatible
365
+ * `/v1/embeddings` endpoint. Dispatches to the single configured
366
+ * `providers.Embedder` (the same instance Memory tool uses for
367
+ * `embed:true` internally). No resolver path, no tier overlay,
368
+ * no streaming — embeddings are synchronous.
369
+ *
370
+ * Accepts `input` as a string OR string array. Tokenized inputs
371
+ * (number arrays) are refused at the server boundary — send text.
372
+ * `encoding_format: "base64"` packs each float32 little-endian
373
+ * then base64-encodes (saves ~25% wire bytes on 1536-dim
374
+ * vectors); "float" (default) emits each vector as a JSON array.
375
+ *
376
+ * Raises {@link AuthError} on 401; {@link UnavailableError} on
377
+ * 503 (no embedder configured — set memory.embedder.* in
378
+ * loomcycle.yaml); {@link InvalidArgumentError} on 400 (bad
379
+ * request shape). */
380
+ embeddings(opts: LLMEmbeddingsOptions): Promise<LLMEmbeddingsResponse>;
364
381
  /** Shared SSE POST → stream-of-AgentEvent path. Used by
365
382
  * runStreaming + continueSession.
366
383
  *
@@ -408,6 +425,33 @@ export declare class LoomcycleClient {
408
425
  * raise a {@link ConflictError} (HTTP 409, code
409
426
  * `channel_cursor_regression`). */
410
427
  ackChannel(channel: string, opts: AckChannelOptions): Promise<ChannelAckResult>;
428
+ /** Create a new runtime-substrate channel. Refuses with HTTP 409
429
+ * when the name matches a yaml-declared channel (code
430
+ * `channel_yaml_immutable`) or an existing runtime channel
431
+ * (code `channel_name_in_use`). */
432
+ createChannel(opts: CreateChannelOptions): Promise<ChannelDescriptor>;
433
+ /** Partially update a runtime-substrate channel. Nil-valued fields
434
+ * in `opts` leave the corresponding attribute unchanged. Refuses
435
+ * yaml-declared channels with HTTP 409. */
436
+ updateChannel(name: string, opts: UpdateChannelOptions): Promise<ChannelDescriptor>;
437
+ /** Delete a runtime-substrate channel + cascade its persisted
438
+ * messages + cursors. yaml-declared channels refuse with HTTP 409.
439
+ * Idempotent: deleting a non-existent runtime channel returns a
440
+ * {@link NotFoundError} so the caller can distinguish that case. */
441
+ deleteChannel(name: string, opts?: {
442
+ signal?: AbortSignal;
443
+ }): Promise<void>;
444
+ /** Idempotently upsert one memory entry by full (scope, scope_id,
445
+ * key) identifier. PUT semantics — re-writes overwrite the value.
446
+ * Optional embed flag triggers a synchronous embed via the
447
+ * operator-configured embedder. */
448
+ setMemoryEntry(scope: string, scopeID: string, key: string, opts: SetMemoryEntryOptions): Promise<SetMemoryEntryResponse>;
449
+ /** Delete one memory entry by (scope, scope_id, key). Idempotent:
450
+ * deleting a missing row is a non-error per the in-band Memory
451
+ * tool's semantics — both surfaces return 204. */
452
+ deleteMemoryEntry(scope: string, scopeID: string, key: string, opts?: {
453
+ signal?: AbortSignal;
454
+ }): Promise<void>;
411
455
  /** Subscribe to run state transitions for one user_id via SSE.
412
456
  * Yields one `{ kind: "open", ... }` item first (confirms the
413
457
  * connection is live), then one `{ kind: "event", ... }` per
package/dist/client.js CHANGED
@@ -23,7 +23,7 @@
23
23
  * via fetch-helpers.ts:raiseFromResponse — see README.md for the
24
24
  * full mapping table.
25
25
  */
26
- import { authHeaders, deleteRequest, jsonFetch, postJSON, raiseFromResponse, } from "./fetch-helpers.js";
26
+ import { authHeaders, deleteRequest, jsonFetch, patchJSON, postJSON, putJSON, raiseFromResponse, } from "./fetch-helpers.js";
27
27
  import { parseSSE } from "./stream.js";
28
28
  export class LoomcycleClient {
29
29
  ctx;
@@ -518,6 +518,29 @@ export class LoomcycleClient {
518
518
  const reader = resp.body.getReader();
519
519
  yield* parseLLMStreamFrames(reader);
520
520
  }
521
+ // ---- v0.11.4 OpenAI Embeddings compatibility shim ----
522
+ /** Compute embedding vectors via the OpenAI-compatible
523
+ * `/v1/embeddings` endpoint. Dispatches to the single configured
524
+ * `providers.Embedder` (the same instance Memory tool uses for
525
+ * `embed:true` internally). No resolver path, no tier overlay,
526
+ * no streaming — embeddings are synchronous.
527
+ *
528
+ * Accepts `input` as a string OR string array. Tokenized inputs
529
+ * (number arrays) are refused at the server boundary — send text.
530
+ * `encoding_format: "base64"` packs each float32 little-endian
531
+ * then base64-encodes (saves ~25% wire bytes on 1536-dim
532
+ * vectors); "float" (default) emits each vector as a JSON array.
533
+ *
534
+ * Raises {@link AuthError} on 401; {@link UnavailableError} on
535
+ * 503 (no embedder configured — set memory.embedder.* in
536
+ * loomcycle.yaml); {@link InvalidArgumentError} on 400 (bad
537
+ * request shape). */
538
+ async embeddings(opts) {
539
+ const { signal: _signal, ...body } = opts;
540
+ return postJSON(this.ctx, "/v1/embeddings", body, {
541
+ signal: opts.signal,
542
+ });
543
+ }
521
544
  // ---- Internal helpers ----
522
545
  /** Shared SSE POST → stream-of-AgentEvent path. Used by
523
546
  * runStreaming + continueSession.
@@ -681,6 +704,78 @@ export class LoomcycleClient {
681
704
  const path = channelOpPath(channel, opts.scope, opts.userId, "ack");
682
705
  return postJSON(this.ctx, path, { cursor: opts.cursor }, { signal: opts.signal });
683
706
  }
707
+ // ---- v0.11.5 Channel admin CRUD ----
708
+ //
709
+ // Three bearer-authed ops that mutate the runtime-substrate
710
+ // channel registry. yaml-declared channels are immutable from
711
+ // this surface — the server refuses with HTTP 409 + wire `code`
712
+ // `channel_yaml_immutable`. The TS adapter surfaces that as a
713
+ // {@link LoomcycleError} with status 409.
714
+ /** Create a new runtime-substrate channel. Refuses with HTTP 409
715
+ * when the name matches a yaml-declared channel (code
716
+ * `channel_yaml_immutable`) or an existing runtime channel
717
+ * (code `channel_name_in_use`). */
718
+ async createChannel(opts) {
719
+ const body = { name: opts.name };
720
+ if (opts.description !== undefined)
721
+ body.description = opts.description;
722
+ if (opts.scope !== undefined)
723
+ body.scope = opts.scope;
724
+ if (opts.semantic !== undefined)
725
+ body.semantic = opts.semantic;
726
+ if (opts.default_ttl !== undefined)
727
+ body.default_ttl = opts.default_ttl;
728
+ if (opts.max_messages !== undefined)
729
+ body.max_messages = opts.max_messages;
730
+ if (opts.publisher !== undefined)
731
+ body.publisher = opts.publisher;
732
+ if (opts.period !== undefined)
733
+ body.period = opts.period;
734
+ return postJSON(this.ctx, "/v1/_channels", body, {
735
+ signal: opts.signal,
736
+ });
737
+ }
738
+ /** Partially update a runtime-substrate channel. Nil-valued fields
739
+ * in `opts` leave the corresponding attribute unchanged. Refuses
740
+ * yaml-declared channels with HTTP 409. */
741
+ async updateChannel(name, opts) {
742
+ const body = {};
743
+ if (opts.description !== undefined)
744
+ body.description = opts.description;
745
+ if (opts.default_ttl !== undefined)
746
+ body.default_ttl = opts.default_ttl;
747
+ if (opts.max_messages !== undefined)
748
+ body.max_messages = opts.max_messages;
749
+ if (opts.semantic !== undefined)
750
+ body.semantic = opts.semantic;
751
+ return patchJSON(this.ctx, `/v1/_channels/${encodeURIComponent(name)}`, body, { signal: opts.signal });
752
+ }
753
+ /** Delete a runtime-substrate channel + cascade its persisted
754
+ * messages + cursors. yaml-declared channels refuse with HTTP 409.
755
+ * Idempotent: deleting a non-existent runtime channel returns a
756
+ * {@link NotFoundError} so the caller can distinguish that case. */
757
+ async deleteChannel(name, opts) {
758
+ return deleteRequest(this.ctx, `/v1/_channels/${encodeURIComponent(name)}`, opts);
759
+ }
760
+ // ---- v0.11.5 Memory entry admin CRUD ----
761
+ /** Idempotently upsert one memory entry by full (scope, scope_id,
762
+ * key) identifier. PUT semantics — re-writes overwrite the value.
763
+ * Optional embed flag triggers a synchronous embed via the
764
+ * operator-configured embedder. */
765
+ async setMemoryEntry(scope, scopeID, key, opts) {
766
+ const body = { value: opts.value };
767
+ if (opts.embed !== undefined)
768
+ body.embed = opts.embed;
769
+ if (opts.ttl_seconds !== undefined)
770
+ body.ttl_seconds = opts.ttl_seconds;
771
+ return putJSON(this.ctx, `/v1/_memory/scopes/${encodeURIComponent(scope)}/${encodeURIComponent(scopeID)}/keys/${encodeURIComponent(key)}`, body, { signal: opts.signal });
772
+ }
773
+ /** Delete one memory entry by (scope, scope_id, key). Idempotent:
774
+ * deleting a missing row is a non-error per the in-band Memory
775
+ * tool's semantics — both surfaces return 204. */
776
+ async deleteMemoryEntry(scope, scopeID, key, opts) {
777
+ return deleteRequest(this.ctx, `/v1/_memory/scopes/${encodeURIComponent(scope)}/${encodeURIComponent(scopeID)}/keys/${encodeURIComponent(key)}`, opts);
778
+ }
684
779
  /** Subscribe to run state transitions for one user_id via SSE.
685
780
  * Yields one `{ kind: "open", ... }` item first (confirms the
686
781
  * connection is live), then one `{ kind: "event", ... }` per
@@ -43,6 +43,17 @@ export declare function jsonFetch<T>(ctx: _FetchContext, path: string, opts?: {
43
43
  export declare function postJSON<T>(ctx: _FetchContext, path: string, body?: unknown, opts?: {
44
44
  signal?: AbortSignal;
45
45
  }): Promise<T>;
46
+ /** putJSON sends a JSON-encoded body via PUT and unwraps the
47
+ * response. Idempotent — REST-canonical verb for "create or
48
+ * overwrite by full identifier." */
49
+ export declare function putJSON<T>(ctx: _FetchContext, path: string, body?: unknown, opts?: {
50
+ signal?: AbortSignal;
51
+ }): Promise<T>;
52
+ /** patchJSON sends a JSON-encoded body via PATCH and unwraps the
53
+ * response. For partial-update endpoints. */
54
+ export declare function patchJSON<T>(ctx: _FetchContext, path: string, body?: unknown, opts?: {
55
+ signal?: AbortSignal;
56
+ }): Promise<T>;
46
57
  /** deleteRequest sends a DELETE and tolerates 204/200/404-with-
47
58
  * idempotent-semantics per the loomcycle wire contract. */
48
59
  export declare function deleteRequest(ctx: _FetchContext, path: string, opts?: {
@@ -58,6 +58,51 @@ export async function postJSON(ctx, path, body, opts) {
58
58
  return null;
59
59
  return (await resp.json());
60
60
  }
61
+ /** putJSON sends a JSON-encoded body via PUT and unwraps the
62
+ * response. Idempotent — REST-canonical verb for "create or
63
+ * overwrite by full identifier." */
64
+ export async function putJSON(ctx, path, body, opts) {
65
+ const headers = authHeaders(ctx);
66
+ let bodyStr;
67
+ if (body !== undefined) {
68
+ headers["Content-Type"] = "application/json";
69
+ bodyStr = JSON.stringify(body);
70
+ }
71
+ const resp = await ctx.fetchImpl(ctx.baseUrl + path, {
72
+ method: "PUT",
73
+ headers,
74
+ body: bodyStr,
75
+ signal: opts?.signal,
76
+ });
77
+ if (!resp.ok) {
78
+ await raiseFromResponse(resp);
79
+ }
80
+ if (resp.status === 204)
81
+ return null;
82
+ return (await resp.json());
83
+ }
84
+ /** patchJSON sends a JSON-encoded body via PATCH and unwraps the
85
+ * response. For partial-update endpoints. */
86
+ export async function patchJSON(ctx, path, body, opts) {
87
+ const headers = authHeaders(ctx);
88
+ let bodyStr;
89
+ if (body !== undefined) {
90
+ headers["Content-Type"] = "application/json";
91
+ bodyStr = JSON.stringify(body);
92
+ }
93
+ const resp = await ctx.fetchImpl(ctx.baseUrl + path, {
94
+ method: "PATCH",
95
+ headers,
96
+ body: bodyStr,
97
+ signal: opts?.signal,
98
+ });
99
+ if (!resp.ok) {
100
+ await raiseFromResponse(resp);
101
+ }
102
+ if (resp.status === 204)
103
+ return null;
104
+ return (await resp.json());
105
+ }
61
106
  /** deleteRequest sends a DELETE and tolerates 204/200/404-with-
62
107
  * idempotent-semantics per the loomcycle wire contract. */
63
108
  export async function deleteRequest(ctx, path, opts) {
package/dist/index.d.ts CHANGED
@@ -55,6 +55,9 @@
55
55
  * llmChat(opts: LLMChatOptions): Promise<LLMChatResponse>
56
56
  * llmStream(opts: LLMChatOptions): AsyncIterable<LLMChatStreamItem>
57
57
  *
58
+ * // OpenAI Embeddings compatibility shim (v0.11.4)
59
+ * embeddings(opts: LLMEmbeddingsOptions): Promise<LLMEmbeddingsResponse>
60
+ *
58
61
  * Errors (typed subclasses of LoomcycleError; see README for the
59
62
  * full HTTP-status → typed-error mapping table):
60
63
  * LoomcycleError, AgentNotFoundError, SessionNotFoundError,
@@ -73,5 +76,5 @@
73
76
  * See `adapters/ts/README.md` for usage examples.
74
77
  */
75
78
  export { LoomcycleClient } from "./client.js";
76
- export type { AgentEvent, ClientOptions, ContinueOptions, EventType, HostWidening, PromptContent, PromptSegment, RetryInfo, RunOptions, ToolUse, Usage, Agent, AgentStatus, AgentUsage, CancelAgentResult, ListAgentsResponse, TranscriptEvent, TranscriptResponse, HealthResponse, ListUsersResponse, UserSummary, PauseResult, ResumeResult, RuntimeStateResponse, RuntimeStateStatus, CreateSnapshotOptions, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotListResponse, SnapshotRestoreResponse, MemoryEntriesResponse, MemoryEntry, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopeIDSummary, MemoryScopeKind, MemoryScopesResponse, InterruptListResponse, InterruptRow, InterruptStatus, ResolveInterruptOptions, Hook, HookFailMode, HookPhase, HookToolCall, HookToolResult, ListHooksResponse, PostHookCall, PostHookResult, PreHookCall, PreHookResult, RegisterHookOptions, RegisterHookResponse, SubstrateToolInput, SubstrateToolResponse, SystemPromptPayload, UserInputPayload, ChannelDescriptor, ListChannelsResponse, RunStateEvent, RunStateStreamClose, RunStateStreamItem, RunStateStreamOpen, StreamUserRunStatesOptions, AckChannelOptions, ChannelAckResult, ChannelMessageItem, ChannelPeekResult, ChannelPublishResult, ChannelScope, ChannelSubscribeResult, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, AgentDefRowResponse, AgentDefVerifyResult, SkillDefVerifyResult, MCPServerDefRowResponse, MCPServerDefVerifyResult, LibraryAgentDefinition, LibraryEntry, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, LLMChatContent, LLMChatMessage, LLMChatOptions, LLMChatResponse, LLMChatStreamDelta, LLMChatStreamItem, LLMChatToolCall, LLMChatUsage, LLMTool, } from "./types.js";
79
+ export type { AgentEvent, ClientOptions, ContinueOptions, EventType, HostWidening, PromptContent, PromptSegment, RetryInfo, RunOptions, ToolUse, Usage, Agent, AgentStatus, AgentUsage, CancelAgentResult, ListAgentsResponse, TranscriptEvent, TranscriptResponse, HealthResponse, ListUsersResponse, UserSummary, PauseResult, ResumeResult, RuntimeStateResponse, RuntimeStateStatus, CreateSnapshotOptions, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotListResponse, SnapshotRestoreResponse, MemoryEntriesResponse, MemoryEntry, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopeIDSummary, MemoryScopeKind, MemoryScopesResponse, InterruptListResponse, InterruptRow, InterruptStatus, ResolveInterruptOptions, Hook, HookFailMode, HookPhase, HookToolCall, HookToolResult, ListHooksResponse, PostHookCall, PostHookResult, PreHookCall, PreHookResult, RegisterHookOptions, RegisterHookResponse, SubstrateToolInput, SubstrateToolResponse, SystemPromptPayload, UserInputPayload, ChannelDescriptor, ListChannelsResponse, RunStateEvent, RunStateStreamClose, RunStateStreamItem, RunStateStreamOpen, StreamUserRunStatesOptions, AckChannelOptions, ChannelAckResult, ChannelMessageItem, ChannelPeekResult, ChannelPublishResult, ChannelScope, ChannelSubscribeResult, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, CreateChannelOptions, UpdateChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, AgentDefRowResponse, AgentDefVerifyResult, SkillDefVerifyResult, MCPServerDefRowResponse, MCPServerDefVerifyResult, LibraryAgentDefinition, LibraryEntry, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, LLMChatContent, LLMChatMessage, LLMChatOptions, LLMChatResponse, LLMChatStreamDelta, LLMChatStreamItem, LLMChatToolCall, LLMChatUsage, LLMTool, LLMEmbeddingItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, LLMEmbeddingsUsage, } from "./types.js";
77
80
  export { AgentIDInUseError, AgentNotFoundError, AlreadyPausingError, AuthError, BackpressureError, HookNotFoundError, NotFoundError, InvalidArgumentError, ChannelCursorRegressionError, LoomcycleError, NotPausedError, PauseNotConfiguredError, PerUserQuotaExhaustedError, SessionBusyError, SessionNotFoundError, SnapshotNotFoundError, SnapshotTooLargeError, SnapshotVersionError, SubstrateToolRefusedError, UnavailableError, } from "./errors.js";
package/dist/index.js CHANGED
@@ -55,6 +55,9 @@
55
55
  * llmChat(opts: LLMChatOptions): Promise<LLMChatResponse>
56
56
  * llmStream(opts: LLMChatOptions): AsyncIterable<LLMChatStreamItem>
57
57
  *
58
+ * // OpenAI Embeddings compatibility shim (v0.11.4)
59
+ * embeddings(opts: LLMEmbeddingsOptions): Promise<LLMEmbeddingsResponse>
60
+ *
58
61
  * Errors (typed subclasses of LoomcycleError; see README for the
59
62
  * full HTTP-status → typed-error mapping table):
60
63
  * LoomcycleError, AgentNotFoundError, SessionNotFoundError,
package/dist/types.d.ts CHANGED
@@ -555,6 +555,7 @@ export interface PostHookResult {
555
555
  * {@link LoomcycleClient.listChannels}. */
556
556
  export interface ChannelDescriptor {
557
557
  name: string;
558
+ description?: string;
558
559
  scope?: string;
559
560
  semantic?: string;
560
561
  publisher?: string;
@@ -565,6 +566,10 @@ export interface ChannelDescriptor {
565
566
  /** RFC3339 — empty when count == 0. */
566
567
  oldest_visible_at?: string;
567
568
  newest_visible_at?: string;
569
+ /** v0.11.5: "yaml" (operator yaml — immutable from this surface),
570
+ * "runtime" (substrate — CRUD-mutable), "orphan" (no declaration,
571
+ * only orphan messages). */
572
+ source?: "yaml" | "runtime" | "orphan" | string;
568
573
  }
569
574
  /** Response shape for {@link LoomcycleClient.listChannels}. */
570
575
  export interface ListChannelsResponse {
@@ -656,6 +661,63 @@ export interface AckChannelOptions {
656
661
  export interface ChannelAckResult {
657
662
  ok: boolean;
658
663
  }
664
+ /** Options for {@link LoomcycleClient.createChannel}. Operator-yaml
665
+ * channels are immutable from this surface; the server returns
666
+ * HTTP 409 `channel_yaml_immutable` when `name` matches a yaml-
667
+ * declared channel. */
668
+ export interface CreateChannelOptions {
669
+ name: string;
670
+ description?: string;
671
+ /** "global" | "agent" | "user". Defaults to "global" if omitted. */
672
+ scope?: string;
673
+ /** "queue" | "topic". Defaults to "queue" if omitted. */
674
+ semantic?: string;
675
+ /** Seconds; 0 = no TTL. */
676
+ default_ttl?: number;
677
+ /** 0 = unbounded. */
678
+ max_messages?: number;
679
+ /** Free-form attribution; not enforced by the substrate. */
680
+ publisher?: string;
681
+ /** Free-form retention hint; not enforced by the substrate. */
682
+ period?: string;
683
+ signal?: AbortSignal;
684
+ }
685
+ /** Options for {@link LoomcycleClient.updateChannel}. Nil fields
686
+ * leave the corresponding channel attribute unchanged. */
687
+ export interface UpdateChannelOptions {
688
+ description?: string;
689
+ default_ttl?: number;
690
+ max_messages?: number;
691
+ /** "queue" | "topic" */
692
+ semantic?: string;
693
+ signal?: AbortSignal;
694
+ }
695
+ /** Options for {@link LoomcycleClient.setMemoryEntry}. `value` is
696
+ * opaque JSON. Setting `embed: true` triggers a synchronous embed
697
+ * via the operator-configured embedder; the returned `embedded`
698
+ * flag + optional `embed_warning` report whether the embedding
699
+ * landed. */
700
+ export interface SetMemoryEntryOptions {
701
+ value: unknown;
702
+ /** When true, also compute + store the embedding (requires
703
+ * memory.embedder yaml + a vector-capable store backend). */
704
+ embed?: boolean;
705
+ /** Optional TTL in seconds; <= 0 means "no expiry". */
706
+ ttl_seconds?: number;
707
+ signal?: AbortSignal;
708
+ }
709
+ /** Response shape for {@link LoomcycleClient.setMemoryEntry}. */
710
+ export interface SetMemoryEntryResponse {
711
+ scope: string;
712
+ scope_id: string;
713
+ key: string;
714
+ /** true when the embedding was computed AND stored. */
715
+ embedded: boolean;
716
+ /** Non-empty when embed was requested but failed (transient
717
+ * error, embedder unconfigured, vector backend not available).
718
+ * The k/v row still landed. */
719
+ embed_warning?: string;
720
+ }
659
721
  /** One run state transition emitted by
660
722
  * {@link LoomcycleClient.streamUserRunStates}. The TS field is RFC3339. */
661
723
  export interface RunStateEvent {
@@ -1027,3 +1089,49 @@ export interface LLMChatStreamDelta {
1027
1089
  text?: string;
1028
1090
  partial_json?: string;
1029
1091
  }
1092
+ /** Request body for `embeddings()`. */
1093
+ export interface LLMEmbeddingsOptions {
1094
+ /** Consumer's requested model id (echoed in the response).
1095
+ * Loomcycle uses the single configured embedder regardless;
1096
+ * the field is informational for drop-in compatibility. */
1097
+ model: string;
1098
+ /** Text(s) to embed. v1 accepts string or string[]; tokenized
1099
+ * inputs (number arrays) are refused — send text. */
1100
+ input: string | string[];
1101
+ /** "float" (default) emits each vector as a JSON array of
1102
+ * numbers; "base64" packs each float32 little-endian then
1103
+ * base64-encodes (saves ~25% wire bytes on 1536-dim vectors). */
1104
+ encoding_format?: "float" | "base64";
1105
+ /** OpenAI's post-hoc dimension reduction parameter. Accepted-
1106
+ * but-ignored in v0.11.4 (the providers.Embedder interface
1107
+ * doesn't take a dimension parameter today). */
1108
+ dimensions?: number;
1109
+ /** OpenAI-standard opaque end-user identifier. Maps to
1110
+ * loomcycle's per-user quota tracking + audit log. */
1111
+ user?: string;
1112
+ /** Optional AbortSignal for caller-driven cancellation. */
1113
+ signal?: AbortSignal;
1114
+ }
1115
+ /** Per-embedding entry in the response data array. */
1116
+ export interface LLMEmbeddingItem {
1117
+ object: "embedding";
1118
+ /** float[] when the request used encoding_format:"float"
1119
+ * (default); base64 string when encoding_format:"base64". */
1120
+ embedding: number[] | string;
1121
+ index: number;
1122
+ }
1123
+ /** Token-accounting payload. v0.11.4 leaves both fields at 0 — the
1124
+ * substrate's Embedder interface doesn't return per-call token
1125
+ * counts today. When that lands, the shim's translator populates
1126
+ * these automatically. */
1127
+ export interface LLMEmbeddingsUsage {
1128
+ prompt_tokens: number;
1129
+ total_tokens: number;
1130
+ }
1131
+ /** Response shape mirrors OpenAI's /v1/embeddings exactly. */
1132
+ export interface LLMEmbeddingsResponse {
1133
+ object: "list";
1134
+ data: LLMEmbeddingItem[];
1135
+ model: string;
1136
+ usage: LLMEmbeddingsUsage;
1137
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@loomcycle/client",
3
- "version": "0.11.3",
4
- "description": "TypeScript client for the loomcycle sidecar (HTTP+SSE). 41 methods covering run streaming, agent metadata, pause/resume/state, snapshot lifecycle, memory admin (incl. v0.9.0 Vector Memory embed_stats + reembed), interruption resolve, hook management, v0.8.22 substrate admin (agentDef + skillDef), v0.9.x n8n Phase 0 (listChannels + streamUserRunStates), v0.9.x Channel CRUD (publishChannel + subscribeChannel + peekChannel + ackChannel), v0.9.x content_sha256 verify, v0.9.1 transcript first-cycle, v0.9.x dynamic MCP server registration (mcpServerDef + MCPServerDefVerifyResult), v0.10.3 Library v2 enumeration (listLibraryAgents + listLibrarySkills + listLibraryMcpServers), and v0.11.0 LLM Gateway (llmChat + llmStream — direct provider routing without agent overhead; primary target is n8n's LoomCycleChatModel AI Agent sub-node and any LangChain-compatible consumer). v0.10.1 — dual ESM + CommonJS distribution (additive — ESM consumers unchanged; CJS consumers like n8n's community-node loader now work).",
3
+ "version": "0.11.5",
4
+ "description": "TypeScript client for the loomcycle sidecar (HTTP+SSE). 46 methods covering run streaming, agent metadata, pause/resume/state, snapshot lifecycle, memory admin (incl. v0.9.0 Vector Memory embed_stats + reembed AND v0.11.5 setMemoryEntry + deleteMemoryEntry), interruption resolve, hook management, v0.8.22 substrate admin (agentDef + skillDef), v0.9.x n8n Phase 0 (listChannels + streamUserRunStates), v0.9.x Channel CRUD (publishChannel + subscribeChannel + peekChannel + ackChannel), v0.11.5 Channel admin CRUD (createChannel + updateChannel + deleteChannel — runtime substrate; yaml channels refuse mutation with HTTP 409), v0.9.x content_sha256 verify, v0.9.1 transcript first-cycle, v0.9.x dynamic MCP server registration (mcpServerDef + MCPServerDefVerifyResult), v0.10.3 Library v2 enumeration (listLibraryAgents + listLibrarySkills + listLibraryMcpServers), and v0.11.0 LLM Gateway (llmChat + llmStream — direct provider routing without agent overhead; primary target is n8n's LoomCycleChatModel AI Agent sub-node and any LangChain-compatible consumer). v0.10.1 — dual ESM + CommonJS distribution (additive — ESM consumers unchanged; CJS consumers like n8n's community-node loader now work).",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "repository": {