@loomcycle/client 1.23.0 → 1.30.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.
@@ -292,6 +292,20 @@ class LoomcycleClient {
292
292
  body.reason = opts.reason;
293
293
  return (0, fetch_helpers_js_1.postJSON)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/compact`, body, opts);
294
294
  }
295
+ /**
296
+ * Replay a session's transcript into a NEW session bound to a (possibly
297
+ * different) target agent, so that agent continues from the same context
298
+ * (RFC BJ Phase 4). `sourceSessionId` is the source; the returned
299
+ * `new_session_id` is a fresh session you continue with the normal message
300
+ * path — the carried context replays automatically. Pass `compress` to
301
+ * collapse the carried history to a summary + recent tail.
302
+ */
303
+ async replaySession(sourceSessionId, opts) {
304
+ const body = { agent: opts.agent };
305
+ if (opts.compress !== undefined)
306
+ body.compress = opts.compress;
307
+ return (0, fetch_helpers_js_1.postJSON)(this.ctx, `/v1/sessions/${encodeURIComponent(sourceSessionId)}/replay`, body, opts);
308
+ }
295
309
  /**
296
310
  * Stop the CURRENT turn of a live interactive run (its in-flight generation +
297
311
  * the tool calls it started) and park it at awaiting_input — session +
@@ -1026,6 +1040,39 @@ class LoomcycleClient {
1026
1040
  query: browseQuery(opts),
1027
1041
  });
1028
1042
  }
1043
+ /** Build the URL of an image chunk's asset (RFC BO) — `GET
1044
+ * /v1/_document/asset/{chunkId}`. Attach the bytes to a chunk with the
1045
+ * `set_asset` op via {@link LoomcycleClient.document}, then read them here.
1046
+ * `scope` is "agent" | "user" (default "user"); `scopeId`/`tenant` are the
1047
+ * RFC AS browse overrides. NOTE: the URL needs the bearer to fetch — use
1048
+ * {@link LoomcycleClient.fetchDocumentAsset} for an authenticated GET (a bare
1049
+ * <img src> can't carry the Authorization header). */
1050
+ documentAssetUrl(chunkId, opts) {
1051
+ const q = new URLSearchParams({ scope: opts?.scope ?? "user" });
1052
+ if (opts?.scopeId)
1053
+ q.set("scope_id", opts.scopeId);
1054
+ if (opts?.tenant)
1055
+ q.set("tenant", opts.tenant);
1056
+ return `${this.ctx.baseUrl}/v1/_document/asset/${encodeURIComponent(chunkId)}?${q.toString()}`;
1057
+ }
1058
+ /** Fetch an image chunk's asset bytes (RFC BO) with authentication — returns
1059
+ * the raw {@link Response} so a caller can `.blob()` / `.arrayBuffer()` it.
1060
+ * Adds the bearer header (a bare <img src> can't). Throws on a non-2xx
1061
+ * (a cross-scope / missing asset is an opaque 404). */
1062
+ async fetchDocumentAsset(chunkId, opts) {
1063
+ const headers = {};
1064
+ if (this.ctx.authToken)
1065
+ headers.Authorization = `Bearer ${this.ctx.authToken}`;
1066
+ const resp = await this.ctx.fetchImpl(this.documentAssetUrl(chunkId, opts), {
1067
+ method: "GET",
1068
+ headers,
1069
+ signal: opts?.signal,
1070
+ });
1071
+ if (!resp.ok) {
1072
+ throw new Error(`fetchDocumentAsset: ${resp.status} ${resp.statusText}`);
1073
+ }
1074
+ return resp;
1075
+ }
1029
1076
  /** Invoke the RFC BE History tool over HTTP (`POST /v1/_history`). Browse,
1030
1077
  * search, and annotate PAST CHATS — a chat is a session (it may span
1031
1078
  * several runs). Op-discriminated (`list`/`get`/`search`/`rename`/
package/dist/client.d.ts CHANGED
@@ -25,7 +25,7 @@
25
25
  */
26
26
  import { InteractiveSession } from "./interactive.js";
27
27
  import { ClientToolHost, type ConnectClientToolsOptions } from "./client-tools.js";
28
- import type { Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, CreateSnapshotOptions, EnsureCodeAgentOptions, EnsureCodeAgentResult, EnsureMcpServerOptions, EnsureMcpServerResult, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAckResult, ChannelAwaitResult, ChannelBroadcastResult, ChannelDescriptor, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MCPServerDefVerifyResult, MemoryEntriesResponse, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopesResponse, PauseResult, PersistentVolumesResponse, EphemeralVolumesResponse, RegisterHookOptions, RegisterHookResponse, ResolveInterruptOptions, ResumeResult, ResolverMatrix, CompactRunResult, CancelTurnResult, RunBatchOptions, RunBatchResult, RunOptions, RunStateStreamItem, RuntimeStateResponse, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotRestoreResponse, StreamUserRunStatesOptions, SubstrateToolInput, SubstrateToolResponse, CreatedTeam, ListTeamsResponse, TeamDefDetail, TeamDiagram, TeamRunResult, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, TranscriptResponse, WhoamiResponse, UsageDimension, UsageReportResponse, TokenLimit, TokenLimitsResponse, SetTokenLimitRequest } from "./types.js";
28
+ import type { Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, CreateSnapshotOptions, EnsureCodeAgentOptions, EnsureCodeAgentResult, EnsureMcpServerOptions, EnsureMcpServerResult, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAckResult, ChannelAwaitResult, ChannelBroadcastResult, ChannelDescriptor, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MCPServerDefVerifyResult, MemoryEntriesResponse, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopesResponse, PauseResult, PersistentVolumesResponse, EphemeralVolumesResponse, RegisterHookOptions, RegisterHookResponse, ResolveInterruptOptions, ResumeResult, ResolverMatrix, CompactRunResult, ReplaySessionResult, CancelTurnResult, RunBatchOptions, RunBatchResult, RunOptions, RunStateStreamItem, RuntimeStateResponse, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotRestoreResponse, StreamUserRunStatesOptions, SubstrateToolInput, SubstrateToolResponse, CreatedTeam, ListTeamsResponse, TeamDefDetail, TeamDiagram, TeamRunResult, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, TranscriptResponse, WhoamiResponse, UsageDimension, UsageReportResponse, TokenLimit, TokenLimitsResponse, SetTokenLimitRequest } from "./types.js";
29
29
  export declare class LoomcycleClient {
30
30
  private ctx;
31
31
  constructor(opts?: ClientOptions);
@@ -143,6 +143,19 @@ export declare class LoomcycleClient {
143
143
  reason?: string;
144
144
  signal?: AbortSignal;
145
145
  }): Promise<CompactRunResult>;
146
+ /**
147
+ * Replay a session's transcript into a NEW session bound to a (possibly
148
+ * different) target agent, so that agent continues from the same context
149
+ * (RFC BJ Phase 4). `sourceSessionId` is the source; the returned
150
+ * `new_session_id` is a fresh session you continue with the normal message
151
+ * path — the carried context replays automatically. Pass `compress` to
152
+ * collapse the carried history to a summary + recent tail.
153
+ */
154
+ replaySession(sourceSessionId: string, opts: {
155
+ agent: string;
156
+ compress?: boolean;
157
+ signal?: AbortSignal;
158
+ }): Promise<ReplaySessionResult>;
146
159
  /**
147
160
  * Stop the CURRENT turn of a live interactive run (its in-flight generation +
148
161
  * the tool calls it started) and park it at awaiting_input — session +
@@ -726,6 +739,28 @@ export declare class LoomcycleClient {
726
739
  scopeId?: string;
727
740
  tenant?: string;
728
741
  }): Promise<DocumentToolResponse>;
742
+ /** Build the URL of an image chunk's asset (RFC BO) — `GET
743
+ * /v1/_document/asset/{chunkId}`. Attach the bytes to a chunk with the
744
+ * `set_asset` op via {@link LoomcycleClient.document}, then read them here.
745
+ * `scope` is "agent" | "user" (default "user"); `scopeId`/`tenant` are the
746
+ * RFC AS browse overrides. NOTE: the URL needs the bearer to fetch — use
747
+ * {@link LoomcycleClient.fetchDocumentAsset} for an authenticated GET (a bare
748
+ * <img src> can't carry the Authorization header). */
749
+ documentAssetUrl(chunkId: string, opts?: {
750
+ scope?: string;
751
+ scopeId?: string;
752
+ tenant?: string;
753
+ }): string;
754
+ /** Fetch an image chunk's asset bytes (RFC BO) with authentication — returns
755
+ * the raw {@link Response} so a caller can `.blob()` / `.arrayBuffer()` it.
756
+ * Adds the bearer header (a bare <img src> can't). Throws on a non-2xx
757
+ * (a cross-scope / missing asset is an opaque 404). */
758
+ fetchDocumentAsset(chunkId: string, opts?: {
759
+ scope?: string;
760
+ scopeId?: string;
761
+ tenant?: string;
762
+ signal?: AbortSignal;
763
+ }): Promise<Response>;
729
764
  /** Invoke the RFC BE History tool over HTTP (`POST /v1/_history`). Browse,
730
765
  * search, and annotate PAST CHATS — a chat is a session (it may span
731
766
  * several runs). Op-discriminated (`list`/`get`/`search`/`rename`/
package/dist/client.js CHANGED
@@ -289,6 +289,20 @@ export class LoomcycleClient {
289
289
  body.reason = opts.reason;
290
290
  return postJSON(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/compact`, body, opts);
291
291
  }
292
+ /**
293
+ * Replay a session's transcript into a NEW session bound to a (possibly
294
+ * different) target agent, so that agent continues from the same context
295
+ * (RFC BJ Phase 4). `sourceSessionId` is the source; the returned
296
+ * `new_session_id` is a fresh session you continue with the normal message
297
+ * path — the carried context replays automatically. Pass `compress` to
298
+ * collapse the carried history to a summary + recent tail.
299
+ */
300
+ async replaySession(sourceSessionId, opts) {
301
+ const body = { agent: opts.agent };
302
+ if (opts.compress !== undefined)
303
+ body.compress = opts.compress;
304
+ return postJSON(this.ctx, `/v1/sessions/${encodeURIComponent(sourceSessionId)}/replay`, body, opts);
305
+ }
292
306
  /**
293
307
  * Stop the CURRENT turn of a live interactive run (its in-flight generation +
294
308
  * the tool calls it started) and park it at awaiting_input — session +
@@ -1023,6 +1037,39 @@ export class LoomcycleClient {
1023
1037
  query: browseQuery(opts),
1024
1038
  });
1025
1039
  }
1040
+ /** Build the URL of an image chunk's asset (RFC BO) — `GET
1041
+ * /v1/_document/asset/{chunkId}`. Attach the bytes to a chunk with the
1042
+ * `set_asset` op via {@link LoomcycleClient.document}, then read them here.
1043
+ * `scope` is "agent" | "user" (default "user"); `scopeId`/`tenant` are the
1044
+ * RFC AS browse overrides. NOTE: the URL needs the bearer to fetch — use
1045
+ * {@link LoomcycleClient.fetchDocumentAsset} for an authenticated GET (a bare
1046
+ * <img src> can't carry the Authorization header). */
1047
+ documentAssetUrl(chunkId, opts) {
1048
+ const q = new URLSearchParams({ scope: opts?.scope ?? "user" });
1049
+ if (opts?.scopeId)
1050
+ q.set("scope_id", opts.scopeId);
1051
+ if (opts?.tenant)
1052
+ q.set("tenant", opts.tenant);
1053
+ return `${this.ctx.baseUrl}/v1/_document/asset/${encodeURIComponent(chunkId)}?${q.toString()}`;
1054
+ }
1055
+ /** Fetch an image chunk's asset bytes (RFC BO) with authentication — returns
1056
+ * the raw {@link Response} so a caller can `.blob()` / `.arrayBuffer()` it.
1057
+ * Adds the bearer header (a bare <img src> can't). Throws on a non-2xx
1058
+ * (a cross-scope / missing asset is an opaque 404). */
1059
+ async fetchDocumentAsset(chunkId, opts) {
1060
+ const headers = {};
1061
+ if (this.ctx.authToken)
1062
+ headers.Authorization = `Bearer ${this.ctx.authToken}`;
1063
+ const resp = await this.ctx.fetchImpl(this.documentAssetUrl(chunkId, opts), {
1064
+ method: "GET",
1065
+ headers,
1066
+ signal: opts?.signal,
1067
+ });
1068
+ if (!resp.ok) {
1069
+ throw new Error(`fetchDocumentAsset: ${resp.status} ${resp.statusText}`);
1070
+ }
1071
+ return resp;
1072
+ }
1026
1073
  /** Invoke the RFC BE History tool over HTTP (`POST /v1/_history`). Browse,
1027
1074
  * search, and annotate PAST CHATS — a chat is a session (it may span
1028
1075
  * several runs). Op-discriminated (`list`/`get`/`search`/`rename`/
package/dist/types.d.ts CHANGED
@@ -436,6 +436,16 @@ export interface CompactRunResult {
436
436
  after_tokens: number;
437
437
  applied: "live" | "marker" | "noop";
438
438
  }
439
+ /** Result of {@link LoomcycleClient.replaySession} (RFC BJ Phase 4) — a NEW
440
+ * session bound to the target agent, seeded with the source conversation.
441
+ * Continue `new_session_id` with the normal message/run path; the carried
442
+ * context replays automatically. */
443
+ export interface ReplaySessionResult {
444
+ new_session_id: string;
445
+ seed_run_id: string;
446
+ events_copied: number;
447
+ compacted: boolean;
448
+ }
439
449
  /** Result of {@link LoomcycleClient.cancelTurn} (RFC BH) — the current turn was
440
450
  * stopped and the interactive run parked at awaiting_input (session +
441
451
  * transcript intact). This is NOT whole-run cancel ({@link
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loomcycle/client",
3
- "version": "1.23.0",
3
+ "version": "1.30.0",
4
4
  "description": "TypeScript client for the loomcycle sidecar (HTTP+SSE). 64 methods covering run streaming, agent metadata, pause/resume/state, resolver re-probe (resolveProbe — issue #88 operator escape hatch), operator-token admin (operatorTokenDef — RFC L OSS multi-tenant auth) + whoami (RFC L authoritative principal, v0.17.0) + tenant-scoped listUsers / listUserAgents, dynamic MCP registration (mcpServerDef + v0.18.0 typed mcpServerDefVerify + ensureMcpServer idempotent register-if-changed), 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). v0.19.0 — typed inline code-js agent ingestion (AgentDefOverlay.code_body + ensureCodeAgent — register a deterministic code agent through the substrate with no host filesystem bind; RFC J). v0.20.0 — ensureMcpServer surfaces discoveredToolCount straight from create (loomcycle now auto-discovers MCP tools at ingestion); rediscover is now an explicit force-refresh. v0.21.0 — run/continue accept optional non-secret `metadata` (repo name, review policy, …) passed to the agent, symmetric with the WebHook/Schedule trigger paths. v0.22.0 — version-aligned lockstep release; no client-surface change (RFC N tenant isolation of the agent/skill/MCP/Schedule/Webhook definition plane + real op-schemas on the builtin MCP meta-tools are both server-side). v0.23.0 — version-aligned lockstep release; no client-surface change (RFCs O/P/R MCP-server hardening + thin client and the RFC Q DeepSeek tool-content fix are all server-side / MCP-transport-side). v0.24.0 — purgeChannel clears a channel's buffered messages without deleting its definition (allowed on yaml-declared channels too, unlike deleteChannel — F20); AgentDefOverlay gains channels / evaluation_scopes / interruption so a COMPLETE interactive/multi-agent agent round-trips over the substrate (F14). (Consolidates the interim 0.24/0.25 package bumps, which were never tag-published, back into lockstep with the loomcycle v0.24.0 tag.) v0.25.0 — adds the RFC S channel fan-in/fan-out client twins: awaitChannels() (wait for any/all/at_least N messages across channels, or a timeout — non-committing) + broadcastChannels() (publish one payload to N channels in one atomic-pre-flight call), the client-facing counterparts of the in-band Channel.await / Channel.broadcast tool ops (the rest of v0.25.0 — the manual-management Web UI console + Context op=time + max_fires self-retiring schedules — is server-side / in-band, no client-surface change). v0.29.1 — Usage gains optional `max_context_tokens` (the serving model's context-window ceiling, stamped by the loop from Provider.Capabilities() on each usage event) so a consumer can render a 'context used / max' gauge without a hard-coded per-model table; additive + optional, no behavior change. (Lockstep catch-up: the field landed in loomcycle v0.29.0 but the adapter publish skipped on a version mismatch; v0.29.1 realigns the package version with the release tag so it publishes.) v0.33.0 — gRPC + TS client parity for the RFC Y external fan-out and the compaction surface: spawnRunBatch() (POST /v1/runs:batch — spawn up to 32 fresh runs concurrently in one call, combined index-aligned envelope, per-child failures in-envelope) + compactRun(runId) (POST /v1/runs/{run_id}/compact — summarize a parked run's context); plus per-run sampling + compaction overrides now accepted on runStreaming / continueSession (an explicit temperature 0 is preserved as deterministic, not dropped as falsy). (The gRPC half adds the matching SpawnRunBatch / CompactRun RPCs + the sampling/compaction fields on RunRequest/ContinueRequest — server-side.) v0.34.0 — version-aligned lockstep release; no client-surface change (context-transform plugins / RFC Z Phase 1a are server-side config; the exp7 hardening pass is server-side; the R2 cross-provider thinking-model downgrade surfaces a new `model_downgraded` SSE event the generic stream passes through unchanged). v0.35.0 — RFC AH dynamic filesystem volumes: volumeDef() (POST /v1/_volumedef — op-discriminated create/get/list/delete/purge; a Volume is flat, so delete unmaps + purge RemoveAll's, no retire/promote/fork) + listVolumes() / listEphemeralVolumes() (GET /v1/_volumes[/ephemeral] — tenant-scoped; host paths redacted for non-operator callers). Tenant-confined; the runtime derives the path inside an operator-blessed dynamic_root, so callers pass name + mode, never a host path. v1.1.1 — RFC AI interactive agentic sessions: an `interactive: true` flag on runStreaming/continueSession (a run that parks at end_turn for steering) + sendRunInput(runId, text) (POST /v1/runs/{id}/input — steer a live run) + streamRunByID(runId, {fromSeq}) (GET /v1/runs/{id}/stream — re-attach by run_id; the operator's prior turns replay as `steer` events so a cold client reconstructs the whole conversation) + a high-level InteractiveSession driver (client.interactiveSession / attachInteractiveSession — events()/send()/cancel(), the adapter port of the Web UI run terminal). The AgentEvent union gains awaiting_input/steer/context_compaction frames. Version-aligned with the loomcycle v1.1.x line so the v1.1.1 tag publishes it (also carrying the previously-unpublished v0.35.0 volume surface). v1.4.0 — RFC AL Path VFS + RFC AK Document on the wire: path(input) (POST /v1/_path — a Unix-like filesystem over Memory/Volumes/Documents; resolve/ls/stat/mkdir/mv/rm) + document(input) (POST /v1/_document — chunked-graph documents; 13 ops, needs SQL Memory on the sidecar). Scope (agent/user/tenant) + tenant are resolved server-side from the authenticated principal, never the wire; an off-run scope:'user' op keys on the principal subject so it interoperates with that user's agent runs. New PathToolInput / DocumentToolInput types; responses are op-varying (unknown — narrow as needed). v1.7.0 — RFC AT image/vision input: the PromptContent union gains an `image` variant ({ type:'image'; media_type: ImageMediaType; data: base64-no-prefix }) accepted in a user segment by runStreaming / continueSession (segments pass through unchanged — no method change). The model must be vision-capable or the run errors before the call. New ImageMediaType type (image/png|jpeg|gif|webp). v1.12.1 — Path/Document browse-by-subject + the full Document op set (RFC AS/AK): path(input, opts) / document(input, opts) accept optional scopeId / tenant browse overrides sent as ?scope_id= / ?tenant= query params (server reads them from the URL, re-checks authorization; omit both to browse your own subject — byte-identical to the pre-RFC-AS request), and DocumentToolInput.op now covers all 16 backend ops (adds set_path, export_md, import_md) with the matching include_metadata / markdown fields. Additive — existing path() / document() callers are unchanged. v1.16.0 — RFC BC client-executed tools (local tool host): connectClientTools({tools,onInvoke}) opens a persistent WebSocket to /v1/client-tools, registers tools this client runs on the user's machine (browser DOM / files / shell), and answers the invoke frames loomcycle routes when an agent of your principal calls a client:<tool> — returning your reply as an ordinary tool result. Returns a ClientToolHost driver (.close() to stop; auto-reconnect); dependency-free (global WebSocket in browsers / Node 22+, or an injected WebSocketImpl like the ws package on older Node); the bearer rides the Sec-WebSocket-Protocol subprotocol (browsers can't set an Authorization header on a WebSocket). The runtime's first WebSocket surface.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",