@loomcycle/client 1.82.0 → 1.84.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.
@@ -68,6 +68,37 @@ function compactionToWire(c) {
68
68
  w.model = c.model;
69
69
  return w;
70
70
  }
71
+ /** contextToWire maps the camelCase ContextOptions to the snake_case `context`
72
+ * block the server decodes.
73
+ *
74
+ * Note `autorecapAtPct` -> `autorecap_at_pct`: the wire key has no underscore
75
+ * after "auto", unlike compaction's `autocompact_at_pct`. The two blocks are
76
+ * spelled differently on the wire and a shared helper would have to special-
77
+ * case one of them, so they stay separate functions. */
78
+ function contextToWire(c) {
79
+ const w = {};
80
+ if (c.mode !== undefined)
81
+ w.mode = c.mode;
82
+ if (c.keepLastN !== undefined)
83
+ w.keep_last_n = c.keepLastN;
84
+ if (c.reasoning !== undefined)
85
+ w.reasoning = c.reasoning;
86
+ if (c.recapMaxChars !== undefined)
87
+ w.recap_max_chars = c.recapMaxChars;
88
+ if (c.autorecapAtPct !== undefined)
89
+ w.autorecap_at_pct = c.autorecapAtPct;
90
+ if (c.stateSchema !== undefined)
91
+ w.state_schema = c.stateSchema;
92
+ if (c.onInvalidPatch !== undefined)
93
+ w.on_invalid_patch = c.onInvalidPatch;
94
+ if (c.maxPatchRetries !== undefined)
95
+ w.max_patch_retries = c.maxPatchRetries;
96
+ if (c.recall !== undefined)
97
+ w.recall = c.recall;
98
+ if (c.harvestToMemory !== undefined)
99
+ w.harvest_to_memory = c.harvestToMemory;
100
+ return w;
101
+ }
71
102
  /** runBody builds the snake_case /v1/runs request body from RunOptions,
72
103
  * omitting unset fields (preserves the server's nil semantics — notably
73
104
  * `allowedHosts: null` is treated as "omit", not deny-all). Shared by
@@ -109,6 +140,8 @@ function runBody(opts) {
109
140
  body.sampling = samplingToWire(opts.sampling);
110
141
  if (opts.compaction !== undefined)
111
142
  body.compaction = compactionToWire(opts.compaction);
143
+ if (opts.context !== undefined)
144
+ body.context = contextToWire(opts.context);
112
145
  if (opts.maxContextTokens !== undefined)
113
146
  body.max_context_tokens = opts.maxContextTokens;
114
147
  if (opts.interactive !== undefined)
@@ -123,6 +156,12 @@ function runBody(opts) {
123
156
  * to the TYPE but to only one of those lists is invisible on the wire from one
124
157
  * of them, silently. That is the shape of the bug RFC DA shipped.
125
158
  */
159
+ // The parameter is RunOverrideOptions itself, not a structural copy of its
160
+ // fields. It WAS such a copy — a second enumeration of the same list sitting in
161
+ // the signature of the function whose whole job is to be the single one — and
162
+ // adding a field to the shared interface then failed to compile here, which is
163
+ // the good outcome only because someone was looking. Typing it as the interface
164
+ // makes the list unduplicated rather than merely checked.
126
165
  function applyOverridesToWire(body, opts) {
127
166
  if (opts.model !== undefined)
128
167
  body.model = opts.model;
@@ -148,6 +187,10 @@ function applyOverridesToWire(body, opts) {
148
187
  body.memory_index_max_bytes = opts.memoryIndexMaxBytes;
149
188
  if (opts.injectToolGuide !== undefined)
150
189
  body.inject_tool_guide = opts.injectToolGuide;
190
+ if (opts.interactive !== undefined)
191
+ body.interactive = opts.interactive;
192
+ if (opts.interruption !== undefined)
193
+ body.interruption = opts.interruption;
151
194
  }
152
195
  class LoomcycleClient {
153
196
  ctx;
@@ -229,6 +272,8 @@ class LoomcycleClient {
229
272
  body.sampling = samplingToWire(opts.sampling);
230
273
  if (opts.compaction !== undefined)
231
274
  body.compaction = compactionToWire(opts.compaction);
275
+ if (opts.context !== undefined)
276
+ body.context = contextToWire(opts.context);
232
277
  if (opts.maxContextTokens !== undefined)
233
278
  body.max_context_tokens = opts.maxContextTokens;
234
279
  if (opts.interactive !== undefined)
@@ -247,7 +292,69 @@ class LoomcycleClient {
247
292
  * Raises {@link UnavailableError} (503, steering off / no run),
248
293
  * {@link AuthError} (401). A full steer queue surfaces as a 429. */
249
294
  async sendRunInput(runId, text, opts) {
250
- return (0, fetch_helpers_js_1.postJSON)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/input`, { text }, opts);
295
+ const body = { text };
296
+ if (opts?.overrides) {
297
+ // The wire nests these under `overrides` on THIS endpoint (unlike the flat
298
+ // fields on /v1/runs), because the request's other job is sending a turn
299
+ // and the group needs a name.
300
+ const o = {};
301
+ applyOverridesToWire(o, opts.overrides);
302
+ if (Object.keys(o).length > 0)
303
+ body.overrides = o;
304
+ }
305
+ return (0, fetch_helpers_js_1.postJSON)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/input`, body, opts);
306
+ }
307
+ /** Change a run's settings WITHOUT sending it a turn. Mirrors
308
+ * `POST /v1/runs/{run_id}/retune`.
309
+ *
310
+ * Use this to retune a PARKED chat — switch it to a different model, raise
311
+ * its iteration bound — when you do not also want a message in the
312
+ * transcript. `sendRunInput(runId, text, { overrides })` is the other half:
313
+ * retune and speak in one atomic call.
314
+ *
315
+ * The overrides select WITHIN what the agent's definition already allows and
316
+ * cannot widen it; an override the definition forbids is REFUSED here rather
317
+ * than silently dropped, so a rejected retune is visible at the call.
318
+ *
319
+ * Raises {@link NotFoundError} (404, no in-flight run — which is also what a
320
+ * run belonging to another tenant returns, deliberately), and 422 when no
321
+ * override is supplied at all. */
322
+ async retuneRun(runId, overrides, opts) {
323
+ const body = {};
324
+ applyOverridesToWire(body, overrides);
325
+ return (0, fetch_helpers_js_1.postJSON)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/retune`, body, opts);
326
+ }
327
+ /** Read a run's own stored overrides. Mirrors `GET /v1/runs/{run_id}/config`.
328
+ *
329
+ * This is what the RUN overrides, not what it will effectively use: a field
330
+ * absent from `config` means "this run does not override it", and the
331
+ * definition, the tier or a driver still decides. {@link getEffectiveConfig}
332
+ * is the resolved view.
333
+ *
334
+ * A run that was never retuned answers with an empty `config` — "this run
335
+ * overrides nothing" is an answer, not a 404.
336
+ *
337
+ * Raises {@link NotFoundError} (404), which is also what a run belonging to
338
+ * another tenant returns — deliberately, so the gate is not an existence
339
+ * oracle for run ids that are not secrets. */
340
+ async getRunConfig(runId, opts) {
341
+ return (0, fetch_helpers_js_1.jsonFetch)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/config`, opts);
342
+ }
343
+ /** Read what a run will ACTUALLY use, field by field, with the layer that
344
+ * decided each. Mirrors `GET /v1/runs/{run_id}/effective-config`.
345
+ *
346
+ * Nothing else assembles this: a definition is a sparse overlay, the tier and
347
+ * driver defaults are published nowhere else, and a field no layer set
348
+ * resolves later somewhere the caller cannot see. The `source` on each field
349
+ * is the point — `max_iterations: 16` cannot tell a deliberate setting from a
350
+ * default nobody chose, and those call for opposite actions.
351
+ *
352
+ * Keys are wire names (`max_tokens`, not `maxTokens`), so the result joins
353
+ * directly against a definition from the library endpoints.
354
+ *
355
+ * Raises {@link NotFoundError} (404) for an unknown or cross-tenant run. */
356
+ async getEffectiveConfig(runId, opts) {
357
+ return (0, fetch_helpers_js_1.jsonFetch)(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/effective-config`, opts);
251
358
  }
252
359
  /** Re-attach to a run's event stream by `run_id` (RFC AI), replaying from
253
360
  * `fromSeq` (default 0) then live-tailing — the gRPC-free twin of the Web
@@ -274,7 +381,8 @@ class LoomcycleClient {
274
381
  interactiveSession(opts) {
275
382
  const source = this.runStreaming({ ...opts, interactive: true });
276
383
  return new interactive_js_1.InteractiveSession(source, {
277
- sendRunInput: (rid, t) => this.sendRunInput(rid, t),
384
+ sendRunInput: (rid, t, o) => this.sendRunInput(rid, t, o),
385
+ retuneRun: (rid, ov) => this.retuneRun(rid, ov),
278
386
  cancelAgent: (aid) => this.cancelAgent(aid),
279
387
  });
280
388
  }
@@ -285,7 +393,8 @@ class LoomcycleClient {
285
393
  attachInteractiveSession(runId, opts) {
286
394
  const source = this.streamRunByID(runId, opts);
287
395
  const session = new interactive_js_1.InteractiveSession(source, {
288
- sendRunInput: (rid, t) => this.sendRunInput(rid, t),
396
+ sendRunInput: (rid, t, o) => this.sendRunInput(rid, t, o),
397
+ retuneRun: (rid, ov) => this.retuneRun(rid, ov),
289
398
  cancelAgent: (aid) => this.cancelAgent(aid),
290
399
  });
291
400
  session.runId = runId;
@@ -58,14 +58,30 @@ class InteractiveSession {
58
58
  * flag. Throws if the run_id isn't known yet — for a fresh session, consume
59
59
  * `events()` until the `agent` frame (or the first `awaiting_input`) first;
60
60
  * a re-attached session has the run_id up front. */
61
- async send(text) {
61
+ async send(text, opts) {
62
62
  if (!this.runId) {
63
63
  throw new Error("loomcycle: run_id not known yet — consume events() until the `agent` frame before send()");
64
64
  }
65
- const { delivered } = await this.ops.sendRunInput(this.runId, text);
65
+ const { delivered } = await this.ops.sendRunInput(this.runId, text, opts);
66
66
  this.awaitingInput = false;
67
67
  return delivered;
68
68
  }
69
+ /** Change this run's settings WITHOUT sending it a turn — switch a parked
70
+ * chat to another model, raise its iteration bound.
71
+ *
72
+ * `send(text, { overrides })` is the other half: retune and speak in one
73
+ * atomic call. Use THIS one when a message in the transcript would be an
74
+ * artefact of changing a setting rather than something the operator said.
75
+ *
76
+ * Does not clear `awaitingInput`: a parked run is still parked after a
77
+ * retune, because nothing was delivered for it to answer. */
78
+ async retune(overrides) {
79
+ if (!this.runId) {
80
+ throw new Error("loomcycle: run_id not known yet — consume events() until the `agent` frame before retune()");
81
+ }
82
+ const { retuned } = await this.ops.retuneRun(this.runId, overrides);
83
+ return retuned;
84
+ }
69
85
  /** Cancel the run (and its sub-agents). No-op if the agent_id isn't known
70
86
  * yet (nothing to cancel). */
71
87
  async cancel() {
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 { CredentialListResponse, CredentialMeta, CredentialScope, DirectoryInspection, DirectoryTenant, DirectoryUser, ErasureReport, ErasureResult, 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, ChannelReleaseResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, ReleaseChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, UserRecord, CreateUserBody, UpdateUserBody, MintedUserToken, ListUserTokensResponse, RunnableAgentsResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MCPServerDefVerifyResult, MemoryEmbedStatsResponse, MemoryEntriesResponse, MemoryEntryResponse, MemoryBackfillResponse, MemoryPurgeResponse, MemoryReembedResponse, MemoryScopeIDsResponse, MemoryScopesResponse, MemorySearchInput, MemorySearchResponse, 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, PromotedTeam, RetiredTeam, TeamBreakpoints, TeamDefDetail, TeamRunDetached, TeamRunTarget, TeamVerification, TeamVersionList, TeamDiagram, TeamRunResult, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, TranscriptResponse, WhoamiResponse, UsageDimension, UsageReportResponse, TokenLimit, TokenLimitsResponse, ConfigResponse, SetTokenLimitRequest } from "./types.js";
28
+ import type { CredentialListResponse, CredentialMeta, CredentialScope, DirectoryInspection, DirectoryTenant, DirectoryUser, ErasureReport, ErasureResult, Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, RunOverrideOptions, EffectiveConfigResponse, RetuneRunResponse, RunConfigResponse, CreateSnapshotOptions, EnsureCodeAgentOptions, EnsureCodeAgentResult, EnsureMcpServerOptions, EnsureMcpServerResult, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAckResult, ChannelAwaitResult, ChannelBroadcastResult, ChannelDescriptor, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelReleaseResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, ReleaseChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, UserRecord, CreateUserBody, UpdateUserBody, MintedUserToken, ListUserTokensResponse, RunnableAgentsResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MCPServerDefVerifyResult, MemoryEmbedStatsResponse, MemoryEntriesResponse, MemoryEntryResponse, MemoryBackfillResponse, MemoryPurgeResponse, MemoryReembedResponse, MemoryScopeIDsResponse, MemoryScopesResponse, MemorySearchInput, MemorySearchResponse, 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, PromotedTeam, RetiredTeam, TeamBreakpoints, TeamDefDetail, TeamRunDetached, TeamRunTarget, TeamVerification, TeamVersionList, TeamDiagram, TeamRunResult, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, TranscriptResponse, WhoamiResponse, UsageDimension, UsageReportResponse, TokenLimit, TokenLimitsResponse, ConfigResponse, SetTokenLimitRequest } from "./types.js";
29
29
  export declare class LoomcycleClient {
30
30
  private ctx;
31
31
  constructor(opts?: ClientOptions);
@@ -81,10 +81,61 @@ export declare class LoomcycleClient {
81
81
  * {@link AuthError} (401). A full steer queue surfaces as a 429. */
82
82
  sendRunInput(runId: string, text: string, opts?: {
83
83
  signal?: AbortSignal;
84
+ overrides?: RunOverrideOptions;
84
85
  }): Promise<{
85
86
  run_id: string;
86
87
  delivered: boolean;
87
88
  }>;
89
+ /** Change a run's settings WITHOUT sending it a turn. Mirrors
90
+ * `POST /v1/runs/{run_id}/retune`.
91
+ *
92
+ * Use this to retune a PARKED chat — switch it to a different model, raise
93
+ * its iteration bound — when you do not also want a message in the
94
+ * transcript. `sendRunInput(runId, text, { overrides })` is the other half:
95
+ * retune and speak in one atomic call.
96
+ *
97
+ * The overrides select WITHIN what the agent's definition already allows and
98
+ * cannot widen it; an override the definition forbids is REFUSED here rather
99
+ * than silently dropped, so a rejected retune is visible at the call.
100
+ *
101
+ * Raises {@link NotFoundError} (404, no in-flight run — which is also what a
102
+ * run belonging to another tenant returns, deliberately), and 422 when no
103
+ * override is supplied at all. */
104
+ retuneRun(runId: string, overrides: RunOverrideOptions, opts?: {
105
+ signal?: AbortSignal;
106
+ }): Promise<RetuneRunResponse>;
107
+ /** Read a run's own stored overrides. Mirrors `GET /v1/runs/{run_id}/config`.
108
+ *
109
+ * This is what the RUN overrides, not what it will effectively use: a field
110
+ * absent from `config` means "this run does not override it", and the
111
+ * definition, the tier or a driver still decides. {@link getEffectiveConfig}
112
+ * is the resolved view.
113
+ *
114
+ * A run that was never retuned answers with an empty `config` — "this run
115
+ * overrides nothing" is an answer, not a 404.
116
+ *
117
+ * Raises {@link NotFoundError} (404), which is also what a run belonging to
118
+ * another tenant returns — deliberately, so the gate is not an existence
119
+ * oracle for run ids that are not secrets. */
120
+ getRunConfig(runId: string, opts?: {
121
+ signal?: AbortSignal;
122
+ }): Promise<RunConfigResponse>;
123
+ /** Read what a run will ACTUALLY use, field by field, with the layer that
124
+ * decided each. Mirrors `GET /v1/runs/{run_id}/effective-config`.
125
+ *
126
+ * Nothing else assembles this: a definition is a sparse overlay, the tier and
127
+ * driver defaults are published nowhere else, and a field no layer set
128
+ * resolves later somewhere the caller cannot see. The `source` on each field
129
+ * is the point — `max_iterations: 16` cannot tell a deliberate setting from a
130
+ * default nobody chose, and those call for opposite actions.
131
+ *
132
+ * Keys are wire names (`max_tokens`, not `maxTokens`), so the result joins
133
+ * directly against a definition from the library endpoints.
134
+ *
135
+ * Raises {@link NotFoundError} (404) for an unknown or cross-tenant run. */
136
+ getEffectiveConfig(runId: string, opts?: {
137
+ signal?: AbortSignal;
138
+ }): Promise<EffectiveConfigResponse>;
88
139
  /** Re-attach to a run's event stream by `run_id` (RFC AI), replaying from
89
140
  * `fromSeq` (default 0) then live-tailing — the gRPC-free twin of the Web
90
141
  * UI's resume-in-terminal. Mirrors `GET /v1/runs/{run_id}/stream`. The
package/dist/client.js CHANGED
@@ -65,6 +65,37 @@ function compactionToWire(c) {
65
65
  w.model = c.model;
66
66
  return w;
67
67
  }
68
+ /** contextToWire maps the camelCase ContextOptions to the snake_case `context`
69
+ * block the server decodes.
70
+ *
71
+ * Note `autorecapAtPct` -> `autorecap_at_pct`: the wire key has no underscore
72
+ * after "auto", unlike compaction's `autocompact_at_pct`. The two blocks are
73
+ * spelled differently on the wire and a shared helper would have to special-
74
+ * case one of them, so they stay separate functions. */
75
+ function contextToWire(c) {
76
+ const w = {};
77
+ if (c.mode !== undefined)
78
+ w.mode = c.mode;
79
+ if (c.keepLastN !== undefined)
80
+ w.keep_last_n = c.keepLastN;
81
+ if (c.reasoning !== undefined)
82
+ w.reasoning = c.reasoning;
83
+ if (c.recapMaxChars !== undefined)
84
+ w.recap_max_chars = c.recapMaxChars;
85
+ if (c.autorecapAtPct !== undefined)
86
+ w.autorecap_at_pct = c.autorecapAtPct;
87
+ if (c.stateSchema !== undefined)
88
+ w.state_schema = c.stateSchema;
89
+ if (c.onInvalidPatch !== undefined)
90
+ w.on_invalid_patch = c.onInvalidPatch;
91
+ if (c.maxPatchRetries !== undefined)
92
+ w.max_patch_retries = c.maxPatchRetries;
93
+ if (c.recall !== undefined)
94
+ w.recall = c.recall;
95
+ if (c.harvestToMemory !== undefined)
96
+ w.harvest_to_memory = c.harvestToMemory;
97
+ return w;
98
+ }
68
99
  /** runBody builds the snake_case /v1/runs request body from RunOptions,
69
100
  * omitting unset fields (preserves the server's nil semantics — notably
70
101
  * `allowedHosts: null` is treated as "omit", not deny-all). Shared by
@@ -106,6 +137,8 @@ function runBody(opts) {
106
137
  body.sampling = samplingToWire(opts.sampling);
107
138
  if (opts.compaction !== undefined)
108
139
  body.compaction = compactionToWire(opts.compaction);
140
+ if (opts.context !== undefined)
141
+ body.context = contextToWire(opts.context);
109
142
  if (opts.maxContextTokens !== undefined)
110
143
  body.max_context_tokens = opts.maxContextTokens;
111
144
  if (opts.interactive !== undefined)
@@ -120,6 +153,12 @@ function runBody(opts) {
120
153
  * to the TYPE but to only one of those lists is invisible on the wire from one
121
154
  * of them, silently. That is the shape of the bug RFC DA shipped.
122
155
  */
156
+ // The parameter is RunOverrideOptions itself, not a structural copy of its
157
+ // fields. It WAS such a copy — a second enumeration of the same list sitting in
158
+ // the signature of the function whose whole job is to be the single one — and
159
+ // adding a field to the shared interface then failed to compile here, which is
160
+ // the good outcome only because someone was looking. Typing it as the interface
161
+ // makes the list unduplicated rather than merely checked.
123
162
  function applyOverridesToWire(body, opts) {
124
163
  if (opts.model !== undefined)
125
164
  body.model = opts.model;
@@ -145,6 +184,10 @@ function applyOverridesToWire(body, opts) {
145
184
  body.memory_index_max_bytes = opts.memoryIndexMaxBytes;
146
185
  if (opts.injectToolGuide !== undefined)
147
186
  body.inject_tool_guide = opts.injectToolGuide;
187
+ if (opts.interactive !== undefined)
188
+ body.interactive = opts.interactive;
189
+ if (opts.interruption !== undefined)
190
+ body.interruption = opts.interruption;
148
191
  }
149
192
  export class LoomcycleClient {
150
193
  ctx;
@@ -226,6 +269,8 @@ export class LoomcycleClient {
226
269
  body.sampling = samplingToWire(opts.sampling);
227
270
  if (opts.compaction !== undefined)
228
271
  body.compaction = compactionToWire(opts.compaction);
272
+ if (opts.context !== undefined)
273
+ body.context = contextToWire(opts.context);
229
274
  if (opts.maxContextTokens !== undefined)
230
275
  body.max_context_tokens = opts.maxContextTokens;
231
276
  if (opts.interactive !== undefined)
@@ -244,7 +289,69 @@ export class LoomcycleClient {
244
289
  * Raises {@link UnavailableError} (503, steering off / no run),
245
290
  * {@link AuthError} (401). A full steer queue surfaces as a 429. */
246
291
  async sendRunInput(runId, text, opts) {
247
- return postJSON(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/input`, { text }, opts);
292
+ const body = { text };
293
+ if (opts?.overrides) {
294
+ // The wire nests these under `overrides` on THIS endpoint (unlike the flat
295
+ // fields on /v1/runs), because the request's other job is sending a turn
296
+ // and the group needs a name.
297
+ const o = {};
298
+ applyOverridesToWire(o, opts.overrides);
299
+ if (Object.keys(o).length > 0)
300
+ body.overrides = o;
301
+ }
302
+ return postJSON(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/input`, body, opts);
303
+ }
304
+ /** Change a run's settings WITHOUT sending it a turn. Mirrors
305
+ * `POST /v1/runs/{run_id}/retune`.
306
+ *
307
+ * Use this to retune a PARKED chat — switch it to a different model, raise
308
+ * its iteration bound — when you do not also want a message in the
309
+ * transcript. `sendRunInput(runId, text, { overrides })` is the other half:
310
+ * retune and speak in one atomic call.
311
+ *
312
+ * The overrides select WITHIN what the agent's definition already allows and
313
+ * cannot widen it; an override the definition forbids is REFUSED here rather
314
+ * than silently dropped, so a rejected retune is visible at the call.
315
+ *
316
+ * Raises {@link NotFoundError} (404, no in-flight run — which is also what a
317
+ * run belonging to another tenant returns, deliberately), and 422 when no
318
+ * override is supplied at all. */
319
+ async retuneRun(runId, overrides, opts) {
320
+ const body = {};
321
+ applyOverridesToWire(body, overrides);
322
+ return postJSON(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/retune`, body, opts);
323
+ }
324
+ /** Read a run's own stored overrides. Mirrors `GET /v1/runs/{run_id}/config`.
325
+ *
326
+ * This is what the RUN overrides, not what it will effectively use: a field
327
+ * absent from `config` means "this run does not override it", and the
328
+ * definition, the tier or a driver still decides. {@link getEffectiveConfig}
329
+ * is the resolved view.
330
+ *
331
+ * A run that was never retuned answers with an empty `config` — "this run
332
+ * overrides nothing" is an answer, not a 404.
333
+ *
334
+ * Raises {@link NotFoundError} (404), which is also what a run belonging to
335
+ * another tenant returns — deliberately, so the gate is not an existence
336
+ * oracle for run ids that are not secrets. */
337
+ async getRunConfig(runId, opts) {
338
+ return jsonFetch(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/config`, opts);
339
+ }
340
+ /** Read what a run will ACTUALLY use, field by field, with the layer that
341
+ * decided each. Mirrors `GET /v1/runs/{run_id}/effective-config`.
342
+ *
343
+ * Nothing else assembles this: a definition is a sparse overlay, the tier and
344
+ * driver defaults are published nowhere else, and a field no layer set
345
+ * resolves later somewhere the caller cannot see. The `source` on each field
346
+ * is the point — `max_iterations: 16` cannot tell a deliberate setting from a
347
+ * default nobody chose, and those call for opposite actions.
348
+ *
349
+ * Keys are wire names (`max_tokens`, not `maxTokens`), so the result joins
350
+ * directly against a definition from the library endpoints.
351
+ *
352
+ * Raises {@link NotFoundError} (404) for an unknown or cross-tenant run. */
353
+ async getEffectiveConfig(runId, opts) {
354
+ return jsonFetch(this.ctx, `/v1/runs/${encodeURIComponent(runId)}/effective-config`, opts);
248
355
  }
249
356
  /** Re-attach to a run's event stream by `run_id` (RFC AI), replaying from
250
357
  * `fromSeq` (default 0) then live-tailing — the gRPC-free twin of the Web
@@ -271,7 +378,8 @@ export class LoomcycleClient {
271
378
  interactiveSession(opts) {
272
379
  const source = this.runStreaming({ ...opts, interactive: true });
273
380
  return new InteractiveSession(source, {
274
- sendRunInput: (rid, t) => this.sendRunInput(rid, t),
381
+ sendRunInput: (rid, t, o) => this.sendRunInput(rid, t, o),
382
+ retuneRun: (rid, ov) => this.retuneRun(rid, ov),
275
383
  cancelAgent: (aid) => this.cancelAgent(aid),
276
384
  });
277
385
  }
@@ -282,7 +390,8 @@ export class LoomcycleClient {
282
390
  attachInteractiveSession(runId, opts) {
283
391
  const source = this.streamRunByID(runId, opts);
284
392
  const session = new InteractiveSession(source, {
285
- sendRunInput: (rid, t) => this.sendRunInput(rid, t),
393
+ sendRunInput: (rid, t, o) => this.sendRunInput(rid, t, o),
394
+ retuneRun: (rid, ov) => this.retuneRun(rid, ov),
286
395
  cancelAgent: (aid) => this.cancelAgent(aid),
287
396
  });
288
397
  session.runId = runId;
package/dist/index.d.ts CHANGED
@@ -128,5 +128,5 @@ export { InteractiveSession } from "./interactive.js";
128
128
  export type { InteractiveSessionOps } from "./interactive.js";
129
129
  export { ClientToolHost, clientToolsURL, CLIENT_TOOL_SUBPROTOCOL } from "./client-tools.js";
130
130
  export type { ClientToolSchema, ClientToolInvocation, ConnectClientToolsOptions, WebSocketLike, WebSocketCtor, } from "./client-tools.js";
131
- export type { AgentEvent, ClientOptions, ContinueOptions, EventType, HostWidening, ImageMediaType, ParentContext, PromptContent, PromptSegment, RetryInfo, RunOptions, SamplingOptions, CompactionOptions, ToolUse, Usage, Agent, AgentStatus, AgentUsage, CancelAgentResult, ListAgentsResponse, RunBatchOptions, RunBatchResult, SpawnRunResult, CompactRunResult, DirectoryBudget, DirectoryInspection, DirectoryTenant, DirectoryUser, ErasureReport, ErasureResidue, ErasureResult, ErasureTier, CancelTurnResult, TranscriptEvent, TranscriptResponse, HealthResponse, ListUsersResponse, UserSummary, UserRecord, CreateUserBody, UpdateUserBody, MintedUserToken, UserTokenMeta, ListUserTokensResponse, RunnableAgent, RunnableAgentsResponse, WhoamiResponse, PauseResult, ResumeResult, RuntimeStateResponse, RuntimeStateStatus, ResolverMatrix, ResolverModelStatus, ResolverProviderAvailability, CreateSnapshotOptions, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotListResponse, SnapshotRestoreResponse, MemoryEntriesResponse, MemoryEntry, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopeIDSummary, MemoryScopeKind, MemoryScopesResponse, MemorySearchInput, MemorySource, MemoryWhen, MemoryTimeFilter, MemorySearchEntry, MemorySearchResponse, MemoryEmbedModelStats, MemoryEmbedStatsResponse, MemoryReembedConfigured, MemoryReembedResponse, MemoryBackfillResponse, MemoryPurgeResponse, InterruptListResponse, InterruptRow, InterruptStatus, ResolveInterruptOptions, Hook, HookFailMode, HookPhase, HookToolCall, HookToolResult, ListHooksResponse, PostHookCall, PostHookResult, PreHookCall, PreHookResult, RegisterHookOptions, RegisterHookResponse, SubstrateToolInput, SubstrateToolResponse, TeamNameSummary, ListTeamsResponse, TeamDiagram, CreatedTeam, PromotedTeam, RetiredTeam, TeamDefDetail, TeamVerification, TeamVersion, TeamVersionList, TeamBreakpoints, TeamRunDetached, TeamRunResult, TeamRunTarget, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, VolumeMode, PersistentVolumeEntry, PersistentVolumesResponse, EphemeralVolumeEntry, EphemeralVolumesResponse, SystemPromptPayload, UserInputPayload, ChannelDescriptor, ListChannelsResponse, RunStateEvent, RunStateStreamClose, RunStateStreamItem, RunStateStreamOpen, StreamUserRunStatesOptions, AckChannelOptions, ChannelAckResult, ChannelMessageItem, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelReleaseResult, ChannelScope, ChannelSubscribeResult, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAwaitEntry, ChannelAwaitMode, ChannelAwaitResult, ChannelBroadcastEntry, ChannelBroadcastResult, CreateChannelOptions, ReleaseChannelOptions, UpdateChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, AgentDefRowResponse, AgentDefVerifyResult, SkillDefVerifyResult, EnsureMcpServerOptions, EnsureMcpServerResult, MCPServerDefRowResponse, MCPServerDefVerifyResult, AgentDefOverlay, EnsureCodeAgentOptions, EnsureCodeAgentResult, LibraryAgentDefinition, LibraryEntry, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, LLMChatContent, LLMChatMessage, LLMChatOptions, LLMChatResponse, LLMChatStreamDelta, LLMChatStreamItem, LLMChatToolCall, LLMChatUsage, LLMTool, LLMEmbeddingItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, LLMEmbeddingsUsage, UsageDimension, UsageAggregate, UsageReportResponse, LimitInfo, TokenLimit, TokenLimitsResponse, ConfigResponse, ConfigProvider, ConfigModel, ConfigSearch, ConfigInstance, SetTokenLimitRequest, CredentialScope, CredentialMeta, CredentialListResponse, } from "./types.js";
131
+ export type { AgentEvent, ClientOptions, ContinueOptions, EventType, HostWidening, ImageMediaType, ParentContext, PromptContent, PromptSegment, RetryInfo, RunOptions, SamplingOptions, CompactionOptions, ContextOptions, ToolUse, Usage, Agent, AgentStatus, AgentUsage, CancelAgentResult, ListAgentsResponse, RunBatchOptions, RunBatchResult, SpawnRunResult, CompactRunResult, DirectoryBudget, DirectoryInspection, DirectoryTenant, DirectoryUser, ErasureReport, ErasureResidue, ErasureResult, ErasureTier, CancelTurnResult, TranscriptEvent, TranscriptResponse, HealthResponse, ListUsersResponse, UserSummary, UserRecord, CreateUserBody, UpdateUserBody, MintedUserToken, UserTokenMeta, ListUserTokensResponse, RunnableAgent, RunnableAgentsResponse, WhoamiResponse, PauseResult, ResumeResult, RuntimeStateResponse, RuntimeStateStatus, ResolverMatrix, ResolverModelStatus, ResolverProviderAvailability, CreateSnapshotOptions, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotListResponse, SnapshotRestoreResponse, MemoryEntriesResponse, MemoryEntry, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopeIDSummary, MemoryScopeKind, MemoryScopesResponse, MemorySearchInput, MemorySource, MemoryWhen, MemoryTimeFilter, MemorySearchEntry, MemorySearchResponse, MemoryEmbedModelStats, MemoryEmbedStatsResponse, MemoryReembedConfigured, MemoryReembedResponse, MemoryBackfillResponse, MemoryPurgeResponse, InterruptListResponse, InterruptRow, InterruptStatus, ResolveInterruptOptions, Hook, HookFailMode, HookPhase, HookToolCall, HookToolResult, ListHooksResponse, PostHookCall, PostHookResult, PreHookCall, PreHookResult, RegisterHookOptions, RegisterHookResponse, SubstrateToolInput, SubstrateToolResponse, TeamNameSummary, ListTeamsResponse, TeamDiagram, CreatedTeam, PromotedTeam, RetiredTeam, TeamDefDetail, TeamVerification, TeamVersion, TeamVersionList, TeamBreakpoints, TeamRunDetached, TeamRunResult, TeamRunTarget, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, HistoryToolInput, HistoryToolResponse, VolumeMode, PersistentVolumeEntry, PersistentVolumesResponse, EphemeralVolumeEntry, EphemeralVolumesResponse, SystemPromptPayload, UserInputPayload, ChannelDescriptor, ListChannelsResponse, RunStateEvent, RunStateStreamClose, RunStateStreamItem, RunStateStreamOpen, StreamUserRunStatesOptions, AckChannelOptions, ChannelAckResult, ChannelMessageItem, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelReleaseResult, ChannelScope, ChannelSubscribeResult, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAwaitEntry, ChannelAwaitMode, ChannelAwaitResult, ChannelBroadcastEntry, ChannelBroadcastResult, CreateChannelOptions, ReleaseChannelOptions, UpdateChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, AgentDefRowResponse, AgentDefVerifyResult, SkillDefVerifyResult, EnsureMcpServerOptions, EnsureMcpServerResult, MCPServerDefRowResponse, MCPServerDefVerifyResult, AgentDefOverlay, EnsureCodeAgentOptions, EnsureCodeAgentResult, LibraryAgentDefinition, LibraryEntry, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, LLMChatContent, LLMChatMessage, LLMChatOptions, LLMChatResponse, LLMChatStreamDelta, LLMChatStreamItem, LLMChatToolCall, LLMChatUsage, LLMTool, LLMEmbeddingItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, LLMEmbeddingsUsage, UsageDimension, UsageAggregate, UsageReportResponse, CapabilityInertInfo, LimitInfo, EffectiveConfigResponse, EffectiveConfigSource, EffectiveValue, RetuneRunResponse, RunConfigRecord, RunConfigResponse, TokenLimit, TokenLimitsResponse, ConfigResponse, ConfigProvider, ConfigModel, ConfigSearch, ConfigInstance, SetTokenLimitRequest, CredentialScope, CredentialMeta, CredentialListResponse, } from "./types.js";
132
132
  export { AgentIDInUseError, AgentNotFoundError, AlreadyPausingError, AuthError, BackpressureError, HookNotFoundError, NotFoundError, InvalidArgumentError, ChannelCursorRegressionError, LoomcycleError, NotPausedError, PauseNotConfiguredError, PerUserQuotaExhaustedError, SessionBusyError, SessionNotFoundError, SnapshotNotFoundError, SnapshotTooLargeError, SnapshotVersionError, SubstrateToolRefusedError, UnavailableError, } from "./errors.js";
@@ -1,11 +1,16 @@
1
- import type { AgentEvent } from "./types.js";
1
+ import type { AgentEvent, RunOverrideOptions } from "./types.js";
2
2
  /** The client-side operations an {@link InteractiveSession} routes through.
3
3
  * Supplied by LoomcycleClient.interactiveSession / attachInteractiveSession —
4
4
  * the session itself holds no transport logic. */
5
5
  export interface InteractiveSessionOps {
6
- sendRunInput: (runId: string, text: string) => Promise<{
6
+ sendRunInput: (runId: string, text: string, opts?: {
7
+ overrides?: RunOverrideOptions;
8
+ }) => Promise<{
7
9
  delivered: boolean;
8
10
  }>;
11
+ retuneRun: (runId: string, overrides: RunOverrideOptions) => Promise<{
12
+ retuned: boolean;
13
+ }>;
9
14
  cancelAgent: (agentId: string) => Promise<unknown>;
10
15
  }
11
16
  /** A high-level driver for an interactive agentic session (RFC AI) — the
@@ -46,7 +51,19 @@ export declare class InteractiveSession {
46
51
  * flag. Throws if the run_id isn't known yet — for a fresh session, consume
47
52
  * `events()` until the `agent` frame (or the first `awaiting_input`) first;
48
53
  * a re-attached session has the run_id up front. */
49
- send(text: string): Promise<boolean>;
54
+ send(text: string, opts?: {
55
+ overrides?: RunOverrideOptions;
56
+ }): Promise<boolean>;
57
+ /** Change this run's settings WITHOUT sending it a turn — switch a parked
58
+ * chat to another model, raise its iteration bound.
59
+ *
60
+ * `send(text, { overrides })` is the other half: retune and speak in one
61
+ * atomic call. Use THIS one when a message in the transcript would be an
62
+ * artefact of changing a setting rather than something the operator said.
63
+ *
64
+ * Does not clear `awaitingInput`: a parked run is still parked after a
65
+ * retune, because nothing was delivered for it to answer. */
66
+ retune(overrides: RunOverrideOptions): Promise<boolean>;
50
67
  /** Cancel the run (and its sub-agents). No-op if the agent_id isn't known
51
68
  * yet (nothing to cancel). */
52
69
  cancel(): Promise<void>;
@@ -55,14 +55,30 @@ export class InteractiveSession {
55
55
  * flag. Throws if the run_id isn't known yet — for a fresh session, consume
56
56
  * `events()` until the `agent` frame (or the first `awaiting_input`) first;
57
57
  * a re-attached session has the run_id up front. */
58
- async send(text) {
58
+ async send(text, opts) {
59
59
  if (!this.runId) {
60
60
  throw new Error("loomcycle: run_id not known yet — consume events() until the `agent` frame before send()");
61
61
  }
62
- const { delivered } = await this.ops.sendRunInput(this.runId, text);
62
+ const { delivered } = await this.ops.sendRunInput(this.runId, text, opts);
63
63
  this.awaitingInput = false;
64
64
  return delivered;
65
65
  }
66
+ /** Change this run's settings WITHOUT sending it a turn — switch a parked
67
+ * chat to another model, raise its iteration bound.
68
+ *
69
+ * `send(text, { overrides })` is the other half: retune and speak in one
70
+ * atomic call. Use THIS one when a message in the transcript would be an
71
+ * artefact of changing a setting rather than something the operator said.
72
+ *
73
+ * Does not clear `awaitingInput`: a parked run is still parked after a
74
+ * retune, because nothing was delivered for it to answer. */
75
+ async retune(overrides) {
76
+ if (!this.runId) {
77
+ throw new Error("loomcycle: run_id not known yet — consume events() until the `agent` frame before retune()");
78
+ }
79
+ const { retuned } = await this.ops.retuneRun(this.runId, overrides);
80
+ return retuned;
81
+ }
66
82
  /** Cancel the run (and its sub-agents). No-op if the agent_id isn't known
67
83
  * yet (nothing to cancel). */
68
84
  async cancel() {
package/dist/types.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * `client.ts` for the input shapes (RunOptions, CreateSnapshotOptions,
8
8
  * etc.) — those are translated to snake_case in the request body.
9
9
  */
10
- export type EventType = "started" | "text" | "tool_call" | "tool_result" | "usage" | "done" | "error" | "retry" | "host_widened" | "session" | "agent" | "awaiting_input" | "steer" | "context_compaction" | "limit" | "override" | "_meta";
10
+ export type EventType = "started" | "text" | "tool_call" | "tool_result" | "usage" | "done" | "error" | "retry" | "host_widened" | "session" | "agent" | "awaiting_input" | "steer" | "context_compaction" | "capability_inert" | "limit" | "override" | "_meta";
11
11
  export interface ToolUse {
12
12
  id: string;
13
13
  name: string;
@@ -60,13 +60,116 @@ export interface HostWidening {
60
60
  * scope stands against its ceiling — so a UI can render "tenant acme at 1.2M /
61
61
  * 1M tokens this month" without a follow-up fetch. Wire-stable; mirrors
62
62
  * providers.LimitInfo. */
63
+ /** A run's own stored overrides — what the RUN set, not what it will
64
+ * effectively use. Mirrors the `config` object on `GET /v1/runs/{id}/config`
65
+ * and on the `retuneRun` reply.
66
+ *
67
+ * A field absent here means "this run does not override it", which is a
68
+ * different and more useful answer at this layer than a resolved value would
69
+ * be: it says the definition, the tier or a driver still decides. Use
70
+ * {@link LoomcycleClient.getEffectiveConfig} for the resolved view. */
71
+ export interface RunConfigRecord {
72
+ sampling?: Record<string, unknown>;
73
+ compaction?: Record<string, unknown>;
74
+ context?: Record<string, unknown>;
75
+ max_context_tokens?: number;
76
+ run_timeout_seconds?: number;
77
+ routing?: {
78
+ provider?: string;
79
+ model?: string;
80
+ tier?: string;
81
+ effort?: string;
82
+ };
83
+ resources?: {
84
+ max_tokens?: number;
85
+ max_iterations?: number;
86
+ unbounded_iterations?: boolean;
87
+ max_concurrent_children?: number;
88
+ };
89
+ tuning?: {
90
+ retry_attempts?: number;
91
+ memory_inject_max_tokens?: number;
92
+ memory_index_max_bytes?: number;
93
+ inject_tool_guide?: boolean;
94
+ };
95
+ interactive?: boolean;
96
+ interruption?: {
97
+ enabled?: boolean;
98
+ kinds?: string[];
99
+ max_pending?: number;
100
+ };
101
+ hosts?: Record<string, unknown>;
102
+ }
103
+ /** Which layer decided an effective value.
104
+ *
105
+ * This is the half that makes the report worth fetching. `max_iterations: 16`
106
+ * cannot distinguish a deliberate setting from a default nobody chose, and
107
+ * those call for opposite actions — so every field carries where it came from.
108
+ *
109
+ * - `run` — a per-run override set it
110
+ * - `definition` — the agent definition set it
111
+ * - `user_tier` — operator tier policy (e.g. retry_attempts)
112
+ * - `operator` — operator env / global configuration
113
+ * - `resolved` — decided at runtime: the tier cascade, the driver, the model.
114
+ * A `resolved` field with a null value means the runtime
115
+ * settles it somewhere this report cannot see, which is a
116
+ * more honest answer than omitting the field.
117
+ * - `default` — a fixed constant in the runtime */
118
+ export type EffectiveConfigSource = "run" | "definition" | "user_tier" | "operator" | "resolved" | "default";
119
+ /** One field's effective value plus the layer that decided it. */
120
+ export interface EffectiveValue {
121
+ value: unknown;
122
+ source: EffectiveConfigSource;
123
+ }
124
+ /** The reply from `GET /v1/runs/{run_id}/config` — what the RUN overrides. */
125
+ export interface RunConfigResponse {
126
+ run_id: string;
127
+ agent: string;
128
+ /** The model the run last resolved to, as recorded on the run row. */
129
+ model: string;
130
+ config: RunConfigRecord;
131
+ }
132
+ /** The reply from `GET /v1/runs/{run_id}/effective-config` — for every
133
+ * overridable field, the value this run will actually use and which layer
134
+ * decided it.
135
+ *
136
+ * Keyed by the wire name the rest of the API uses (`max_tokens`, not
137
+ * `maxTokens`), so it joins directly against a definition from
138
+ * `/v1/_library/agents`. */
139
+ export interface EffectiveConfigResponse {
140
+ run_id: string;
141
+ agent: string;
142
+ fields: Record<string, EffectiveValue>;
143
+ }
144
+ /** The reply from `retuneRun` — the run's MERGED configuration, not an echo of
145
+ * the request.
146
+ *
147
+ * A caller cannot recompute it: the merge is not a field-wise union. Naming a
148
+ * `model` clears the `provider` so a previous choice cannot contradict the new
149
+ * pin, and naming a `tier` clears the `model`. */
150
+ export interface RetuneRunResponse {
151
+ run_id: string;
152
+ retuned: boolean;
153
+ config: RunConfigRecord;
154
+ }
63
155
  /** OverrideInfo accompanies an `event: override` frame (RFC DC per-run
64
156
  * overrides): a run's own configuration changed mid-run because an operator
65
157
  * retuned it.
66
158
  *
67
- * It names what MOVED rather than what the settings now are, because "the
68
- * configuration changed" answers nothing for someone trying to explain why the
69
- * answers got different after turn 12.
159
+ * TWO EVENTS CARRY THIS TYPE, and a consumer needs to tell them apart because
160
+ * one retune can produce both. The server emits one when the operator acts,
161
+ * listing in `fields` the keys the REQUEST set and carrying NO from/to pair —
162
+ * nothing has been re-resolved yet, so there is no honest "to" to report. The
163
+ * runtime emits one when the run ADOPTS a routing change, and that one always
164
+ * carries both halves of the pair.
165
+ *
166
+ * So: a pair present means "the run is now using this"; a pair absent means
167
+ * "an operator asked for these fields". Filter on `from_model === undefined`
168
+ * for the second kind.
169
+ *
170
+ * `fields` used to be documented as the request's keys unconditionally while
171
+ * the only site filling it in was the runtime's, which cannot see a request —
172
+ * so a branch written for "max_tokens changed" could never run.
70
173
  *
71
174
  * Carries only operator-chosen configuration whose effects are already visible
72
175
  * — a model name, a budget. No credential, no operator host. */
@@ -102,6 +205,21 @@ export interface ErrorInfo {
102
205
  * instructions. */
103
206
  retry_after_ms?: number;
104
207
  }
208
+ /** The payload on a `capability_inert` event: one tool the agent holds and
209
+ * cannot use, because the capability gate that tool reads grants nothing.
210
+ *
211
+ * Server-generated, emitted ONCE at run start — the condition is a property of
212
+ * the definition, not of any one call. It carries the FIX as well as the fact:
213
+ * the governing yaml key is not guessable from the tool name, which is most of
214
+ * why this failure was hard to act on. */
215
+ export interface CapabilityInertInfo {
216
+ /** The granted tool, as named in the agent's `tools` list. */
217
+ tool: string;
218
+ /** The yaml key that governs it, e.g. `agent_def_scopes`. */
219
+ gate: string;
220
+ /** A line naming the tool, the gate, and what to set. */
221
+ message?: string;
222
+ }
105
223
  export interface LimitInfo {
106
224
  /** Which axis tripped: "operator" | "tenant" | "user". */
107
225
  scope: string;
@@ -150,6 +268,8 @@ export interface AgentEvent {
150
268
  /** Payload on `event: limit` (RFC AW) — a per-scope token-budget crossing.
151
269
  * Nil on all other event types. */
152
270
  limit?: LimitInfo;
271
+ /** Set on `capability_inert` events: a tool the agent holds and cannot use. */
272
+ capability_inert?: CapabilityInertInfo;
153
273
  /** Set on `event: override` frames — what the operator changed, and from
154
274
  * what to what. */
155
275
  override?: OverrideInfo;
@@ -188,7 +308,14 @@ export interface PromptSegment {
188
308
  }
189
309
  /** The per-run overrides (RFC DC) — a run's own answer to how it should run,
190
310
  * instead of its agent definition's. Persisted with the run, so they survive a
191
- * pause; a parked run can also be retuned via `sendRunInput`.
311
+ * pause. A parked run is retuned with `retuneRun()` or with
312
+ * `sendRunInput(id, text, { overrides })` when you also want to say something.
313
+ *
314
+ * This line used to say "can also be retuned via `sendRunInput`", which was
315
+ * true of the WIRE and not of the method: the adapter sent a bare `{text}`, so
316
+ * the sentence described a capability no caller could reach through it. A
317
+ * comment that names the transport instead of the API is how a gap reads as
318
+ * closed.
192
319
  *
193
320
  * Declared ONCE and extended by both {@link RunOptions} and
194
321
  * {@link ContinueOptions}, because the serializer that writes them is shared
@@ -233,6 +360,24 @@ export interface RunOverrideOptions {
233
360
  memoryIndexMaxBytes?: number;
234
361
  /** Whether to inject the generated tool guide into the prompt. */
235
362
  injectToolGuide?: boolean;
363
+ /** Park this run at its turn boundaries instead of finishing, so an operator
364
+ * can steer it — settable while the run is ALREADY GOING, which is the point:
365
+ * nobody knows at start that they will need to correct it.
366
+ *
367
+ * `false` releases a run that was started interactive. Omit to keep whatever
368
+ * the run has; a retune of anything else must not disturb this. */
369
+ interactive?: boolean;
370
+ /** Let this run's agent ASK a human a question, overriding what its
371
+ * definition allows.
372
+ *
373
+ * Overridable because an interruption touches no data and no host — it blocks
374
+ * and waits for a person — so the exposure is liveness, bounded by the run's
375
+ * timeout and the interruption's own. */
376
+ interruption?: {
377
+ enabled?: boolean;
378
+ kinds?: string[];
379
+ max_pending?: number;
380
+ };
236
381
  }
237
382
  export interface RunOptions extends RunOverrideOptions {
238
383
  agent: string;
@@ -320,6 +465,14 @@ export interface RunOptions extends RunOverrideOptions {
320
465
  * Omitted = inherit entirely. Trigger compaction mid-run with
321
466
  * {@link LoomcycleClient.compactRun}. */
322
467
  compaction?: CompactionOptions;
468
+ /** Per-run context-DISTILLATION override, merged PER FIELD over the agent's
469
+ * own `context` block (this wins; unset fields inherit).
470
+ *
471
+ * Start-only — see {@link ContextOptions}. This is what varies the
472
+ * distillation strategy for a run without forking the agent, and outside
473
+ * `mode: "append"` it, not {@link RunOptions.compaction}, is the block the
474
+ * runtime reads. */
475
+ context?: ContextOptions;
323
476
  /** Per-run context-WINDOW override in tokens (RFC CJ). Wins over the agent's
324
477
  * own `max_context_tokens` when > 0; omitted = inherit it (which itself
325
478
  * defers to the provider/driver default). Distinct from a model's output
@@ -374,6 +527,76 @@ export interface CompactionOptions {
374
527
  * provider. Omitted = the run's model. */
375
528
  model?: string;
376
529
  }
530
+ /** Per-run context-distillation override. Mirrors the server's `context`
531
+ * block — every field optional; an unset field inherits the agent's value,
532
+ * merged per field.
533
+ *
534
+ * DISTINCT from {@link CompactionOptions}, and the two are not
535
+ * interchangeable: `compaction` is the append-mode summariser, while this
536
+ * chooses HOW history is distilled at all. Outside `mode: "append"` the
537
+ * compaction knobs are never consulted — so setting `autocompactAtPct` on a
538
+ * recap or stateful run does nothing. The server reports settings in that
539
+ * state under `inert` on GET /v1/runs/{id}/effective-config.
540
+ *
541
+ * START-ONLY. These are accepted when a run BEGINS, not by retune: `mode` is
542
+ * latched before the loop starts (the stateful branch is taken or not, and
543
+ * the tool catalogue is already resolved), so a retune could apply the
544
+ * thresholds and silently ignore the mode. */
545
+ export interface ContextOptions {
546
+ /** How history is distilled.
547
+ * - `append` — keep everything; the compaction knobs apply here and
548
+ * ONLY here.
549
+ * - `recap` — fold the evicted span into a running progress note.
550
+ * - `stateful` — a different loop: the model emits a patch + action each
551
+ * step and carries state rather than transcript.
552
+ * - `auto` — resolved at run start from the provider: a local backend
553
+ * or an interactive run takes `recap`, a frontier API takes
554
+ * `stateful`. */
555
+ mode?: "append" | "recap" | "stateful" | "auto";
556
+ /** Keep the last N messages verbatim (default 6; 0 = distil all).
557
+ *
558
+ * ⚠️ This is a FLOOR on what can be distilled: a conversation of N+1
559
+ * messages or fewer has nothing left after the pinned first turn, so it
560
+ * never distils however full the window is. A chat of few enormous turns
561
+ * is exactly that shape. The run reports it as a `context_distill_declined`
562
+ * event with reason `split_declined`, carrying both numbers. */
563
+ keepLastN?: number;
564
+ /** What happens to the evicted span in recap mode.
565
+ * - `recap` (default) — summarise it into a running note.
566
+ * - `drop` — discard it with no note.
567
+ * - `keep` — distil nothing (reported as a decline, so the
568
+ * run says why the window is not being reclaimed). */
569
+ reasoning?: "recap" | "drop" | "keep";
570
+ /** Character budget for the running recap note (default 512).
571
+ *
572
+ * ⚠️ The summariser's token budget is derived from this
573
+ * (`recapMaxChars/4 + 64`), so the default allows ~192 tokens. A model that
574
+ * spends its budget on reasoning can return nothing at all, which the run
575
+ * reports as a `context_distill_declined` event with reason
576
+ * `empty_summary`. Raise this, or pick an effort that stops the model
577
+ * thinking. */
578
+ recapMaxChars?: number;
579
+ /** Auto-distil when used/window ≥ N% (50..95; default 80). This is the live
580
+ * threshold in recap mode — NOT `compaction.autocompactAtPct`. */
581
+ autorecapAtPct?: number;
582
+ /** JSON Schema the stateful mode validates every state patch against.
583
+ * Stateful mode only. */
584
+ stateSchema?: Record<string, unknown>;
585
+ /** What a stateful run does with a patch that fails the schema
586
+ * (`retry` default, or `fail`). */
587
+ onInvalidPatch?: "retry" | "fail";
588
+ /** How many times a rejected patch may be retried (default 2). */
589
+ maxPatchRetries?: number;
590
+ /** Grant the Recall tool so the agent can fetch back detail the
591
+ * distillation dropped. */
592
+ recall?: boolean;
593
+ /** Bank each evicted span for the memory consolidator.
594
+ *
595
+ * This is the flag the recap and stateful paths actually read —
596
+ * `compaction.memoryFlush` installs the banking callback but nothing
597
+ * outside append mode calls it. */
598
+ harvestToMemory?: boolean;
599
+ }
377
600
  /** Opaque caller-tracking lineage (v0.12.x) attached to a run and
378
601
  * propagated to all its sub-agents. The runtime stores and echoes
379
602
  * these fields verbatim and never interprets them. All fields
@@ -457,6 +680,9 @@ export interface ContinueOptions extends RunOverrideOptions {
457
680
  sampling?: SamplingOptions;
458
681
  /** Per-continuation context-compaction override — see {@link RunOptions.compaction}. */
459
682
  compaction?: CompactionOptions;
683
+ /** Per-continuation context-distillation override — see
684
+ * {@link RunOptions.context}. */
685
+ context?: ContextOptions;
460
686
  /** Per-continuation context-WINDOW override in tokens — see
461
687
  * {@link RunOptions.maxContextTokens}. */
462
688
  maxContextTokens?: number;
@@ -2244,6 +2470,25 @@ export interface AgentDefOverlay {
2244
2470
  tools?: string[];
2245
2471
  skills?: string[];
2246
2472
  memory_scopes?: string[];
2473
+ /** RFC DF: recall attaches the conversation TURN each fact was distilled from,
2474
+ * for this agent, WITHOUT the model asking for it. Operator-set on purpose — a
2475
+ * tool parameter is a decision the model makes, and measured across three local
2476
+ * models they do not make it. Also gated by `history_scope`: this decides whether
2477
+ * turns are OFFERED, history_scope whether they may be READ. */
2478
+ recall_include_turns?: boolean;
2479
+ /** Also run the QUESTION-anchored trace search on every `recall` and return those
2480
+ * turns as their own block, beside the facts.
2481
+ *
2482
+ * Distinct from `recall_include_turns`, which attaches the turn each recalled FACT
2483
+ * was distilled from: fact-anchored retrieval can only reach turns some fact was
2484
+ * already extracted from, and the turns that answer the rest are the ones the
2485
+ * extractor passed over. Measured on one corpus the two routes differ by 24 points.
2486
+ *
2487
+ * Operator-set, with deliberately NO tool parameter: told to pass the sibling's
2488
+ * parameter on every call, one model passed it on 51 of 128. Also gated by
2489
+ * `history_scope`, and needs the trace index enabled AND backfilled — an empty
2490
+ * index yields zero turns silently. */
2491
+ recall_attach_traces?: boolean;
2247
2492
  memory_quota_bytes?: number;
2248
2493
  memory_backend?: string;
2249
2494
  retry_attempts?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loomcycle/client",
3
- "version": "1.82.0",
3
+ "version": "1.84.0",
4
4
  "description": "TypeScript client for the loomcycle sidecar (HTTP+SSE). 71 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. v1.45.0 — RFC BL P5 subject erasure: erasureReport(subject, {tenant}) (GET /v1/_erasure — what this deployment holds about one subject, in three tiers: deletable with existing primitives, subject-keyed but not deletable, and facts ABOUT the subject in scopes they do not own) + erasureExecute(subject, {dryRun, confirm, tenant}) (POST /v1/_erasure — removes tiers 1 and 2). DEFAULTS TO A DRY RUN: dryRun defaults true and a live run also requires confirm === subject. The tier-3 residue is traceable only through the subject's chats, which a live run deletes, so a report afterwards shows rows: 0 while those facts remain — the returned object is the only durable record of what was not reached; persist it. New ErasureReport / ErasureResult / ErasureTier / ErasureResidue types. v1.47.0 — RFC BV memory-view SDK: memorySearch() (POST /v1/_memory/search — off-run unified semantic search spanning k/v entries AND document-chunk bodies in one ranked list, each hit tagged kind memory|document with chunk_id on document hits) + memoryEmbedStats(scope) + reembedMemory(scope, scopeId, {dryRun,limit}) (the Vector Memory embed-admin reads the memory-view console needs; dry_run defaults true). Fact reads (list_facts + get_chunk's entity block) ride the existing document() passthrough. Additive — existing callers unchanged. v1.61.0 — RFC CJ per-run context-window override: runStreaming / continueSession accept an optional maxContextTokens (integer tokens) that wins over the agent's own max_context_tokens; omitted inherits it (which defers to the provider/driver default). Distinct from a model's output cap; primarily for local inference (Ollama num_ctx). Serialized as the snake_case max_context_tokens field on POST /v1/runs + the continuation body; additive, existing callers unchanged. v1.72.1 — the TeamDef version lifecycle: listTeamVersions(name) (op=list — every version of one team, newest first), promoteTeam(defId) (op=promote — point the active pointer, which is what a run BY NAME executes; forkTeam defaults to promote:false, so authoring and putting in force stay two steps), retireTeam(defId, retired) (op=retire — reversible and version-scoped, unlike deleteTeam) and verifyTeam(name, contentSha256) (op=verify — the drift check for a workflow kept in source control and pushed to several deployments; an absent team answers deployed:false rather than raising). The ops existed on the substrate and over HTTP; a client that could author a team could not put one in force.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",