ruicode 0.75.0 → 0.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -241,3 +241,12 @@ A later Message to an archived Session restores it transactionally before admitt
241
241
  `unarchive()` restores only organization and never resumes stopped work.
242
242
  Replaying an archive request with its original key does not archive again after a later restore.
243
243
  Both methods notify local activity followers without submitting a Message or starting work.
244
+
245
+ ## Stop one Action
246
+
247
+ `session.stopAction(action, { idempotencyKey })` selects one Action in that Session for stop.
248
+ It returns the existing Resolution position when the Action has already ended, or `null` when stop selection precedes completion.
249
+ Use `session.readAction(action)` to read completion and saved output.
250
+ Retain the key and exact inputs before sending. Retry them unchanged to recover a lost reply.
251
+ A stop selection suppresses that Action's final Session input and preserves its sole Resolution.
252
+ Other Actions continue.
package/dist/binary.d.ts CHANGED
@@ -1,10 +1,7 @@
1
- /** The platform packages, by `process.platform` and `process.arch` (D127, D186). */
2
1
  export declare const PLATFORM_PACKAGES: Record<string, Record<string, string>>;
3
2
  export interface BinaryLookup {
4
3
  platform?: string;
5
4
  arch?: string;
6
- /** A file URL or path that module resolution starts from. Default: this module. */
7
5
  from?: string;
8
6
  }
9
- /** The executable to start: `binary` if given, else the installed platform package's, else `rui` on PATH. */
10
7
  export declare function resolveBinary(binary: string | undefined, lookup?: BinaryLookup): string;
package/dist/binary.js CHANGED
@@ -1,13 +1,9 @@
1
- // Where the `rui` executable comes from when the caller names none: the
2
- // platform package installed beside this one (D125, D127), else PATH.
3
1
  import { createRequire } from "node:module";
4
2
  import { dirname, join } from "node:path";
5
- /** The platform packages, by `process.platform` and `process.arch` (D127, D186). */
6
3
  export const PLATFORM_PACKAGES = {
7
4
  linux: { x64: "ruicode-linux-x64", arm64: "ruicode-linux-arm64" },
8
5
  darwin: { arm64: "ruicode-darwin-arm64" },
9
6
  };
10
- /** The executable to start: `binary` if given, else the installed platform package's, else `rui` on PATH. */
11
7
  export function resolveBinary(binary, lookup = {}) {
12
8
  if (binary !== undefined)
13
9
  return binary;
package/dist/client.d.ts CHANGED
@@ -34,7 +34,6 @@ export declare class Rui extends EventEmitter<{
34
34
  exit: [ExitEvent];
35
35
  }> {
36
36
  #private;
37
- /** Local Session write notifications, shared by every handle. Internal. */
38
37
  readonly activity: SessionNotifications;
39
38
  /** Create and list Sessions. */
40
39
  readonly sessions: Sessions;
@@ -53,27 +52,12 @@ export declare class Rui extends EventEmitter<{
53
52
  * Host's 10 s shutdown (D129). Later calls fail with RuiUnavailableError.
54
53
  */
55
54
  close(): Promise<void>;
56
- /**
57
- * Sends one request to the ready Host. A call that finds the child gone
58
- * waits for the restarted Host and is sent once more. Internal: the
59
- * package's calls are built on it.
60
- */
61
55
  call(path: string, body: string, environment?: Buffer, limits?: ReplyLimits): Promise<Buffer>;
62
- /**
63
- * Sends one request built for the Host's Store. `build` receives the
64
- * canonical Store name the Host reported at readiness. Internal: the
65
- * package's calls are built on it.
66
- */
67
56
  exchange(path: string, build: (store: string) => string, environment?: Buffer, limits?: ReplyLimits): Promise<Buffer>;
68
- /** The running child's process id. Internal. */
69
57
  get pid(): number | undefined;
70
- /** The latest host-info reply. Internal. */
71
58
  get hostInfo(): HostInfo | undefined;
72
59
  }
73
60
  export declare function launchFor(settings: HostSettings, runtimeDir: string, options?: ClientOptions): Launch;
74
- /** One length-prefixed JSON frame: a 4-byte big-endian length, then UTF-8 JSON (D130). */
75
61
  export declare function encodeSettings(document: Schemas["HostSettings"]): Buffer;
76
- /** Only the fixed leading child receipt is authoritative; later path bytes are not records. */
77
62
  export declare function readinessInstance(prefix: Buffer): string | undefined;
78
- /** The refusal a child wrote as its one stdout line, `{"rui_start_error":{code,message}}` (D211). */
79
63
  export declare function startError(output: string): RuiStartError | undefined;
package/dist/client.js CHANGED
@@ -1,10 +1,3 @@
1
- // Rui.connect starts the Host as a child of this process, hands it the settings
2
- // document on stdin and waits until it answers host-info on the socket in its
3
- // private interface (D107, D112, D130, D131). By default the child lives as
4
- // long as stdin stays open (D5, D118); settings may select detached lifetime.
5
- // A child that exits on its own is restarted with
6
- // capped backoff, and calls in flight are retried once the new Host is ready;
7
- // every write carries a request key, so a retry is safe (D118, D129).
8
1
  import { spawn } from "node:child_process";
9
2
  import { EventEmitter } from "node:events";
10
3
  import { mkdtemp, rm, stat, symlink } from "node:fs/promises";
@@ -22,15 +15,11 @@ const DEFAULT_LOCK_WAIT_MS = 120_000;
22
15
  const LOCK_RETRY_MS = 500;
23
16
  const FIRST_RESTART_MS = 500;
24
17
  const MAX_RESTART_MS = 30_000;
25
- /** The Host bounds its own shutdown at 10 s (D118); this leaves room for the exit to arrive. */
26
18
  const CLOSE_GRACE_MS = 15_000;
27
19
  const READY_POLL_MS = 25;
28
20
  const READINESS_RECEIPT_BYTES = Buffer.byteLength("ready instance=") + 32 + 1;
29
- /** How long a refused connection waits for the child's exit before it counts as unanswered. */
30
21
  const EXIT_NOTICE_MS = 2_000;
31
- /** Transient refusals during automatic restart, not initial connect. */
32
22
  const RETRYABLE_START_CODES = new Set(["store_locked", "mysql_unreachable"]);
33
- /** A failed start, with the child's exit when there was a child. */
34
23
  class AttemptFailed extends Error {
35
24
  error;
36
25
  exit;
@@ -44,14 +33,12 @@ export class Rui extends EventEmitter {
44
33
  #launch;
45
34
  #runtimeDir;
46
35
  #host;
47
- /** The child of the latest start, ready or not. */
48
36
  #child;
49
37
  #waiters = [];
50
38
  #backoff = FIRST_RESTART_MS;
51
39
  #restart;
52
40
  #closing;
53
41
  #dead;
54
- /** Local Session write notifications, shared by every handle. Internal. */
55
42
  activity = new SessionNotifications();
56
43
  /** Create and list Sessions. */
57
44
  sessions = new Sessions(this);
@@ -133,11 +120,6 @@ export class Rui extends EventEmitter {
133
120
  await rm(this.#runtimeDir, { recursive: true, force: true });
134
121
  }
135
122
  }
136
- /**
137
- * Sends one request to the ready Host. A call that finds the child gone
138
- * waits for the restarted Host and is sent once more. Internal: the
139
- * package's calls are built on it.
140
- */
141
123
  async call(path, body, environment, limits) {
142
124
  let retried = false;
143
125
  for (;;) {
@@ -162,20 +144,13 @@ export class Rui extends EventEmitter {
162
144
  }
163
145
  }
164
146
  }
165
- /**
166
- * Sends one request built for the Host's Store. `build` receives the
167
- * canonical Store name the Host reported at readiness. Internal: the
168
- * package's calls are built on it.
169
- */
170
147
  async exchange(path, build, environment, limits) {
171
148
  const host = await this.#ready();
172
149
  return this.call(path, build(host.info.store), environment, limits);
173
150
  }
174
- /** The running child's process id. Internal. */
175
151
  get pid() {
176
152
  return this.#host?.child.pid;
177
153
  }
178
- /** The latest host-info reply. Internal. */
179
154
  get hostInfo() {
180
155
  return this.#host?.info;
181
156
  }
@@ -208,13 +183,11 @@ export class Rui extends EventEmitter {
208
183
  waiter.reject(error);
209
184
  }
210
185
  #scheduleRestart() {
211
- // Once close has begun nothing may start again, whoever asked (an exit listener may close).
212
186
  if (this.#closing)
213
187
  return;
214
188
  const delay = this.#backoff;
215
189
  this.#backoff = Math.min(this.#backoff * 2, MAX_RESTART_MS);
216
190
  this.#restart = setTimeout(() => void this.#restartNow(), delay);
217
- // An idle client does not keep the process alive; a call waiting for the restart does (see #ready).
218
191
  if (this.#waiters.length === 0)
219
192
  this.#restart.unref();
220
193
  }
@@ -246,7 +219,6 @@ export class Rui extends EventEmitter {
246
219
  }
247
220
  }
248
221
  export function launchFor(settings, runtimeDir, options = {}) {
249
- // Inherit program/home lookup plus only the secret sources this document names.
250
222
  const env = Object.create(null);
251
223
  for (const name of ["PATH", "HOME", "TMPDIR"]) {
252
224
  const value = process.env[name];
@@ -259,13 +231,11 @@ export function launchFor(settings, runtimeDir, options = {}) {
259
231
  socketPath: join(runtimeDir, "interface", SOCKET_NAME), env, detached,
260
232
  };
261
233
  }
262
- /** Release all restart-owned secret bytes/references on every terminal transition. */
263
234
  function disposeLaunch(launch) {
264
235
  launch.document.fill(0);
265
236
  for (const name of Object.keys(launch.env))
266
237
  delete launch.env[name];
267
238
  }
268
- /** Starts one child and resolves once it answers host-info, or throws AttemptFailed. */
269
239
  async function start(launch, spawned) {
270
240
  let child;
271
241
  try {
@@ -279,7 +249,6 @@ async function start(launch, spawned) {
279
249
  }
280
250
  spawned(child);
281
251
  const stdout = [];
282
- // This fixed prefix precedes every caller-controlled path in the child's record.
283
252
  const receipt = Buffer.alloc(READINESS_RECEIPT_BYTES);
284
253
  let receiptBytes = 0;
285
254
  let readyInstance;
@@ -301,12 +270,10 @@ async function start(launch, spawned) {
301
270
  const outputEnded = new Promise((done) => child.stdout?.once("close", done));
302
271
  const launchError = new Promise((done) => child.once("error", done));
303
272
  const exited = exitOf(child);
304
- // The child must not keep this process alive; its stdin closing is how it learns this process ended.
305
273
  child.unref();
306
274
  child.stdout?.unref();
307
275
  child.stdin?.unref();
308
276
  child.stdin?.on("error", () => { });
309
- // write owns this copy until its callback; retain the restart document separately.
310
277
  const bytes = Buffer.from(launch.document);
311
278
  const wipeWrite = () => bytes.fill(0);
312
279
  child.stdin?.once("close", wipeWrite);
@@ -332,7 +299,6 @@ async function start(launch, spawned) {
332
299
  if (ended instanceof Error) {
333
300
  throw new AttemptFailed(new RuiUnavailableError(`could not start ${launch.binary}: ${ended.message}`, { cause: ended }), undefined);
334
301
  }
335
- // The refusal line is written before the exit; give the pipe a moment to deliver it.
336
302
  await Promise.race([outputEnded, sleep(1_000)]);
337
303
  const output = Buffer.concat(stdout);
338
304
  let refusal;
@@ -353,7 +319,6 @@ async function start(launch, spawned) {
353
319
  stdout.length = 0;
354
320
  }
355
321
  }
356
- /** Readiness proves the Host admitted the path; decoding and alias effects belong after it. */
357
322
  async function createInterfaceAlias(launch) {
358
323
  const dir = launch.interfaceDir;
359
324
  const target = typeof dir === "string" ? dir : Buffer.from(dir.hex, "hex");
@@ -379,7 +344,6 @@ async function probe(launch, instance) {
379
344
  throw new RuiUnavailableError("the Host socket did not match the started child's readiness instance");
380
345
  return info;
381
346
  }
382
- /** One length-prefixed JSON frame: a 4-byte big-endian length, then UTF-8 JSON (D130). */
383
347
  export function encodeSettings(document) {
384
348
  const json = Buffer.from(JSON.stringify(document));
385
349
  try {
@@ -392,13 +356,11 @@ export function encodeSettings(document) {
392
356
  json.fill(0);
393
357
  }
394
358
  }
395
- /** Only the fixed leading child receipt is authoritative; later path bytes are not records. */
396
359
  export function readinessInstance(prefix) {
397
360
  if (prefix.length !== READINESS_RECEIPT_BYTES)
398
361
  return undefined;
399
362
  return /^ready instance=([0-9a-f]{32}) $/.exec(prefix.toString("latin1"))?.[1];
400
363
  }
401
- /** The refusal a child wrote as its one stdout line, `{"rui_start_error":{code,message}}` (D211). */
402
364
  export function startError(output) {
403
365
  for (const line of output.split("\n").reverse()) {
404
366
  if (!line.trim())
@@ -411,7 +373,6 @@ export function startError(output) {
411
373
  }
412
374
  }
413
375
  catch {
414
- // Not the refusal line.
415
376
  }
416
377
  }
417
378
  return undefined;
package/dist/errors.d.ts CHANGED
@@ -12,7 +12,6 @@ type Status<T> = T extends {
12
12
  } ? S : never;
13
13
  export type RequestAnswer = Answer<Reply>;
14
14
  export type RequestRejectionCode = Code<RequestAnswer>;
15
- /** HTTP ErrorReply deliberately accepts codes beyond the command rejection enums. */
16
15
  export type RequestErrorCode = RequestRejectionCode | Schemas["ErrorReply"]["code"];
17
16
  type RequestErrorType = Schemas["ErrorReply"]["type"] | Status<Extract<RequestAnswer, {
18
17
  code: string;
package/dist/errors.js CHANGED
@@ -1,6 +1,3 @@
1
- // The three error types a caller sees (D116). Request failures are
2
- // RuiRequestError, a refusal at open is RuiStartError, and a call that finds
3
- // no running Host is RuiUnavailableError.
4
1
  /** Rui rejected one request. `code` is the Host's rejection code; `message` preserves advisory detail when provided. */
5
2
  export class RuiRequestError extends Error {
6
3
  name = "RuiRequestError";
package/dist/feed.d.ts CHANGED
@@ -23,7 +23,6 @@ export interface ListActivityOptions {
23
23
  /** Ends the iterator, even while it waits for new entries: a pending `next()` then resolves as done. */
24
24
  signal?: AbortSignal;
25
25
  }
26
- /** Maps only the row's own keys; nested values retain their wire spelling (D128). */
27
26
  type CamelKey<Key extends string> = Key extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<CamelKey<Tail>>}` : Key;
28
27
  type CamelRow<Payload> = {
29
28
  [Key in keyof Payload as Key extends "session" ? "sessionId" : Key extends string ? CamelKey<Key> : Key]: Payload[Key];
@@ -48,18 +47,15 @@ type EntryFromRow<R extends Row> = R extends Row ? {
48
47
  * `session_changed` uses `reasoning_effort_refused` and inline `providerText` for a refused effort change.
49
48
  */
50
49
  export type FeedEntry = EntryFromRow<Row>;
51
- /** An opaque cursor: after the row at this position and ordinal. */
52
50
  export declare function encodeCursor(position: string, ordinal: string): string;
53
51
  export declare function decodeCursor(cursor: string): {
54
52
  position: string;
55
53
  ordinal: string;
56
54
  };
57
- /** The whole text of an entry that has some, as UTF-8 bytes, however long (D134). */
58
55
  export declare function readContentBytes(link: Link, session: string, entry: {
59
56
  position: string;
60
57
  ordinal: string;
61
58
  }): Promise<Buffer>;
62
- /** The whole text of an entry as a string. A text past the JavaScript string limit (about 512 MiB) throws; use `readContentBytes`. */
63
59
  export declare function readContent(link: Link, session: string, entry: {
64
60
  position: string;
65
61
  ordinal: string;
@@ -75,6 +71,5 @@ export interface SearchActivityOptions {
75
71
  export type ActivitySearchEntry = Schemas["ActivitySearchReply"]["items"][number] & {
76
72
  cursor: string;
77
73
  };
78
- /** Search public feed text newest first. Empty budget-limited pages still advance. */
79
74
  export declare function searchActivity(link: Link, session: string, query: string, options?: SearchActivityOptions): AsyncGenerator<ActivitySearchEntry, void, undefined>;
80
75
  export {};
package/dist/feed.js CHANGED
@@ -1,8 +1,3 @@
1
- // The Session feed: `listActivity` is an async iterator over /v1/activity-page
2
- // (D9, D10, D117, A-D117, D134, D168). The Host sends rows with content
3
- // references only, and no cursor type. The client encodes the cursor from a
4
- // row's position and ordinal, and fills `text` from /v1/activity-content, so
5
- // the Host holds no reply buffer for either (D168).
6
1
  import { WIRE_VERSION } from "./transport.js";
7
2
  /** Every kind the Host's feed has, in its own order. */
8
3
  export const FEED_KINDS = [
@@ -22,7 +17,6 @@ export const FEED_KINDS = [
22
17
  "compacted",
23
18
  "model_call",
24
19
  ];
25
- // A kind the wire gains fails to compile here until the list has it.
26
20
  const complete = true;
27
21
  void complete;
28
22
  /** Entry text is inline up to this many bytes (D168). */
@@ -30,9 +24,7 @@ export const INLINE_TEXT_BYTES = 16 * 1024;
30
24
  const PAGE_ROWS = 16;
31
25
  const FIRST_POLL_MS = 250;
32
26
  const MAX_POLL_MS = 2_000;
33
- /** The only endings whose `turn_ended` entry carries text (D168). */
34
27
  const ENDINGS_WITH_TEXT = new Set(["provider_refused", "failed"]);
35
- /** An opaque cursor: after the row at this position and ordinal. */
36
28
  export function encodeCursor(position, ordinal) {
37
29
  return Buffer.from(`1:${position}:${ordinal}`).toString("base64url");
38
30
  }
@@ -53,7 +45,6 @@ function camelCase(row) {
53
45
  function isReference(value) {
54
46
  return typeof value === "object" && value !== null && "bytes" in value && "sha256" in value;
55
47
  }
56
- /** Builds an entry from a row, without its text. Returns the content reference when text is to be read. */
57
48
  function entryOf(row) {
58
49
  const [kind, payload] = Object.entries(row.value)[0];
59
50
  const reference = isReference(payload.content) ? payload.content : undefined;
@@ -66,7 +57,7 @@ function entryOf(row) {
66
57
  at: row.at,
67
58
  ...camelCase(payload),
68
59
  ...(reference && wanted ? { contentBytes: reference.bytes } : {}),
69
- }; // Object.entries erases the generated kind/payload correlation at this boundary.
60
+ };
70
61
  return { entry, reference: reference && wanted ? reference : undefined };
71
62
  }
72
63
  function activityBody(store, session, request) {
@@ -94,17 +85,13 @@ function contentBody(store, session, entry) {
94
85
  ordinal: entry.ordinal,
95
86
  });
96
87
  }
97
- /** The Host stores up to a little under 1 GiB of text in one entry. */
98
88
  const MAX_CONTENT_BYTES = 1024 * 1024 * 1024;
99
- /** The whole text of an entry that has some, as UTF-8 bytes, however long (D134). */
100
89
  export function readContentBytes(link, session, entry) {
101
90
  return link.exchange("/v1/activity-content", (store) => contentBody(store, session, entry), undefined, { max: MAX_CONTENT_BYTES });
102
91
  }
103
- /** The whole text of an entry as a string. A text past the JavaScript string limit (about 512 MiB) throws; use `readContentBytes`. */
104
92
  export async function readContent(link, session, entry) {
105
93
  return (await readContentBytes(link, session, entry)).toString("utf8");
106
94
  }
107
- /** Waits `ms`, or less when `signal` aborts; with no `ms`, waits only for the abort. */
108
95
  function pause(ms, signal) {
109
96
  return new Promise((resolve) => {
110
97
  if (signal?.aborted)
@@ -119,7 +106,6 @@ function pause(ms, signal) {
119
106
  });
120
107
  }
121
108
  export async function* listActivity(link, session, options = {}) {
122
- // The Host wants kinds in its own order, each once.
123
109
  const kinds = options.kinds === undefined ? FEED_KINDS : FEED_KINDS.filter((kind) => options.kinds?.includes(kind));
124
110
  let position = "0";
125
111
  let ordinal = null;
@@ -136,7 +122,6 @@ export async function* listActivity(link, session, options = {}) {
136
122
  const watcher = options.follow ? link.activity?.watch(session) : undefined;
137
123
  try {
138
124
  while (!signal?.aborted) {
139
- // Capture before I/O so a write racing an idle reply cannot be lost.
140
125
  const revision = watcher?.revision ?? 0;
141
126
  const page = JSON.parse((await link.exchange("/v1/activity-page", (store) => activityBody(store, session, { end: pinnedEnd, position, ordinal, kinds, since }))).toString("utf8"));
142
127
  let receivedItems = false;
@@ -145,7 +130,6 @@ export async function* listActivity(link, session, options = {}) {
145
130
  }
146
131
  else {
147
132
  for (const row of page.items) {
148
- // Cancellation is honoured before each entry, and again after any read that took time.
149
133
  if (signal?.aborted)
150
134
  return;
151
135
  const { entry, reference } = entryOf(row);
@@ -165,9 +149,7 @@ export async function* listActivity(link, session, options = {}) {
165
149
  ordinal = row.ordinal;
166
150
  }
167
151
  if (page.more) {
168
- // A bounded read keeps the end the first page named; a following one asks again.
169
152
  pinnedEnd = options.follow ? null : page.end;
170
- // A Session token cannot stand in for rows not yet consumed.
171
153
  since = null;
172
154
  wait = FIRST_POLL_MS;
173
155
  continue;
@@ -175,8 +157,6 @@ export async function* listActivity(link, session, options = {}) {
175
157
  if (!options.follow)
176
158
  return;
177
159
  pinnedEnd = null;
178
- // Exhausted: everything the filter matches up to the end has been read, so the next poll starts at the end
179
- // rather than rescanning the rows between the last match and it.
180
160
  position = page.end;
181
161
  ordinal = null;
182
162
  since = page.since;
@@ -186,7 +166,6 @@ export async function* listActivity(link, session, options = {}) {
186
166
  if (receivedItems)
187
167
  wait = FIRST_POLL_MS;
188
168
  else if (idle) {
189
- // A bare internal Link has no local writes to observe; cancellation still ends its idle wait.
190
169
  await (watcher ? watcher.wait(revision, signal) : pause(undefined, signal));
191
170
  wait = FIRST_POLL_MS;
192
171
  }
@@ -203,7 +182,6 @@ export async function* listActivity(link, session, options = {}) {
203
182
  function dormant(kind) {
204
183
  return kind === "idle" || kind === "finished" || kind === "failed" || kind === "stopped";
205
184
  }
206
- /** Search public feed text newest first. Empty budget-limited pages still advance. */
207
185
  export async function* searchActivity(link, session, query, options = {}) {
208
186
  const bytes = Buffer.byteLength(query, "utf8");
209
187
  if (bytes === 0 || bytes > 256 || Buffer.from(query, "utf8").toString("utf8") !== query)
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Rui, type HostSettings, type ClientOptions, type ExitEvent } from "./client.ts";
2
2
  export { RuiRequestError, RuiStartError, RuiUnavailableError } from "./errors.ts";
3
- export { Session, Sessions, type AgentSpec, type ListSessionsOptions, type SessionArchiveState, type SessionArchiveResult, type SessionPinResult, type SessionCreate, type ModelSummary, type SendOptions, type SessionSpec, type SessionSummary, type SessionStatus, type SessionUpdate, type WriteOptions, } from "./sessions.ts";
3
+ export { Session, Sessions, type AgentSpec, type ActionStatus, type ActionSelection, type ListSessionsOptions, type SessionArchiveState, type SessionArchiveResult, type SessionPinResult, type SessionCreate, type ModelSummary, type SendOptions, type SessionSpec, type SessionSummary, type SessionStatus, type SessionUpdate, type WriteOptions, } from "./sessions.ts";
4
4
  export { FEED_KINDS, INLINE_TEXT_BYTES, type FeedEntry, type FeedKind, type ListActivityOptions, type SearchActivityOptions, type ActivitySearchEntry } from "./feed.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- // The package's public surface. Transport types stay internal (D19).
2
1
  export { Rui } from "./client.js";
3
2
  export { RuiRequestError, RuiStartError, RuiUnavailableError } from "./errors.js";
4
3
  export { Session, Sessions, } from "./sessions.js";
@@ -1,7 +1,6 @@
1
1
  export declare class SessionNotifications {
2
2
  #private;
3
3
  watch(session: string): WriteWatch;
4
- /** Rejects and releases every active follower, including one still reading its page. */
5
4
  fail(error: Error): void;
6
5
  notify(session: string): void;
7
6
  }
@@ -1,4 +1,3 @@
1
- // Owned by one Rui instance. Only active followers occupy the per-Session map.
2
1
  export class SessionNotifications {
3
2
  #sessions = new Map();
4
3
  watch(session) {
@@ -12,7 +11,6 @@ export class SessionNotifications {
12
11
  watches.add(watch);
13
12
  return watch;
14
13
  }
15
- /** Rejects and releases every active follower, including one still reading its page. */
16
14
  fail(error) {
17
15
  for (const watches of this.#sessions.values()) {
18
16
  for (const watch of watches)
@@ -2,12 +2,15 @@ import type { SessionNotifications } from "./notifications.ts";
2
2
  import { type ActivitySearchEntry, type SearchActivityOptions, type FeedEntry, type ListActivityOptions } from "./feed.ts";
3
3
  import { type ReplyLimits } from "./transport.ts";
4
4
  import type { components } from "./wire.ts";
5
- /** What a Session handle needs from the client. */
6
5
  export interface Link {
7
6
  readonly activity?: SessionNotifications;
8
7
  exchange(path: string, build: (store: string) => string, environment?: Buffer, limits?: ReplyLimits): Promise<Buffer>;
9
8
  }
10
9
  type Schemas = components["schemas"];
10
+ export type ActionStatus = Schemas["ReadActionReply"];
11
+ export type ActionSelection = Extract<Schemas["ActionBackgroundReply"]["answer"], {
12
+ status: "accepted";
13
+ }>["action_selection"];
11
14
  /** The Session settings the Host takes today. */
12
15
  export interface AgentSpec {
13
16
  /** The working directory for Bash. Required with `bash`, fixed for the Session's life. */
@@ -19,9 +22,9 @@ export interface AgentSpec {
19
22
  instructions?: string;
20
23
  /** JSON output schema object; `null` clears it. */
21
24
  outputSchema?: Record<string, unknown> | null;
22
- /** Tool names the Host offers, such as `bash` and `web_search`. */
25
+ /** Configured allowed tool names, such as `bash` and `web_search`. */
23
26
  tools: readonly string[];
24
- /** Tools loaded from the first model request. */
27
+ /** Loaded tool intent within `tools`; each Operation freezes its effective model offer. */
25
28
  loadedTools?: readonly string[];
26
29
  /** Tokens reserved for model output; null clears the override. */
27
30
  outputReservation?: number | null;
@@ -75,6 +78,8 @@ export interface SessionSummary {
75
78
  state: string;
76
79
  archiveState: SessionArchiveState;
77
80
  parent: string | null;
81
+ /** Session that started this Session, including a detached agent. */
82
+ creator: Schemas["SessionRow"]["creator"];
78
83
  }
79
84
  type CurrentReport = Extract<Schemas["InspectSessionReply"], {
80
85
  profile: "current";
@@ -93,7 +98,10 @@ export interface SessionStatus {
93
98
  label: CurrentReport["session"]["label"];
94
99
  model: CurrentReport["session"]["model"];
95
100
  effort: CurrentReport["session"]["reasoning_effort"];
101
+ /** Configured allowed tool names. */
96
102
  tools: CurrentReport["session"]["tools"];
103
+ /** Loaded tool intent; an active Operation keeps its frozen model offer. */
104
+ loadedTools: CurrentReport["session"]["loaded_tools"];
97
105
  permissionMode: CurrentReport["session"]["permission_mode"];
98
106
  latestOutcome: CurrentReport["work"]["latest_outcome"];
99
107
  }
@@ -102,9 +110,7 @@ export interface ModelSummary {
102
110
  id: string;
103
111
  known: boolean;
104
112
  }
105
- /** One plain wire spec for configure and connect-time presets. */
106
113
  export declare function agentSpec(spec: Partial<SessionSpec>): Schemas["Configuration"];
107
- /** `NAME=VALUE\0` for each entry the Host would keep (D121): a name that is not empty, holds no `=` or NUL and does not start with `RUI_`, and a value without NUL. The rest are left out, because after encoding the Host could not tell where an entry ended. */
108
114
  export declare function environmentBytes(env: Record<string, string> | undefined): Buffer;
109
115
  export declare class Session {
110
116
  #private;
@@ -141,6 +147,12 @@ export declare class Session {
141
147
  pin(options?: WriteOptions): Promise<SessionPinResult>;
142
148
  /** Removes this Session's pin without changing its work. */
143
149
  unpin(options?: WriteOptions): Promise<SessionPinResult>;
150
+ /** Releases the original call with an immutable receipt. Poll `readAction` for the sole final result. */
151
+ backgroundAction(action: string, options?: WriteOptions): Promise<ActionSelection>;
152
+ /** Selects an owned Action for stop. Reuse the key to recover a lost reply. */
153
+ stopAction(action: string, options?: WriteOptions): Promise<string | null>;
154
+ /** Reads an owned Action. Acceptance and attempted state do not assert a running process. */
155
+ readAction(action: string, offset?: string): Promise<ActionStatus>;
144
156
  /**
145
157
  * Cuts off the model call that is current now while the Session keeps going.
146
158
  * It takes no key: each call names the work it sees at that moment, so a
@@ -161,8 +173,6 @@ export declare class Sessions {
161
173
  /** Configured Sessions, newest first; archived Sessions are hidden by default. */
162
174
  list(options?: ListSessionsOptions): Promise<SessionSummary[]>;
163
175
  }
164
- /** The models each provider offers (D128). */
165
176
  export declare function models(link: Link): Promise<ModelSummary[]>;
166
- /** Holds every new Turn while paused; running work continues (D199). */
167
177
  export declare function setPaused(link: Link, paused: boolean): Promise<void>;
168
178
  export {};
package/dist/sessions.js CHANGED
@@ -1,11 +1,7 @@
1
- // Sessions: create, list, status, send, update, stop, interrupt and decide, plus the
2
- // model list and Host pause (D7, D8, D14 to D17, D121, D123, D128, D167,
3
- // D171). Every call is one request to a Host route that exists today.
4
1
  import { randomUUID } from "node:crypto";
5
2
  import { RuiRequestError } from "./errors.js";
6
3
  import { listActivity, searchActivity, readContent, readContentBytes } from "./feed.js";
7
4
  import { WIRE_VERSION } from "./transport.js";
8
- /** One plain wire spec for configure and connect-time presets. */
9
5
  export function agentSpec(spec) {
10
6
  return {
11
7
  ...(spec.workspace === undefined ? {} : { workspace: spec.workspace }),
@@ -39,13 +35,11 @@ function key(options) {
39
35
  function parse(reply) {
40
36
  return JSON.parse(reply.toString("utf8"));
41
37
  }
42
- /** Throws the Host's rejection or conflict; returns the accepted answer. */
43
38
  function accepted(answer) {
44
39
  if (answer.status !== "accepted")
45
40
  throw new RuiRequestError(answer.status, answer.code, "message" in answer ? answer.message : undefined);
46
41
  return answer;
47
42
  }
48
- /** `NAME=VALUE\0` for each entry the Host would keep (D121): a name that is not empty, holds no `=` or NUL and does not start with `RUI_`, and a value without NUL. The rest are left out, because after encoding the Host could not tell where an entry ended. */
49
43
  export function environmentBytes(env) {
50
44
  const forwarded = Object.entries(env ?? {}).filter(([name, entry]) => name !== "" && !name.startsWith("RUI_") && !/[=\0]/.test(name) && !entry.includes("\0"));
51
45
  return Buffer.from(forwarded.map(([name, entry]) => `${name}=${entry}\0`).join(""), "utf8");
@@ -100,6 +94,7 @@ export class Session {
100
94
  model: reply.session.model,
101
95
  effort: reply.session.reasoning_effort,
102
96
  tools: reply.session.tools,
97
+ loadedTools: reply.session.loaded_tools,
103
98
  permissionMode: reply.session.permission_mode,
104
99
  latestOutcome: reply.work.latest_outcome,
105
100
  };
@@ -188,6 +183,34 @@ export class Session {
188
183
  this.#link.activity?.notify(this.id);
189
184
  return { pinned: answer.pinned };
190
185
  }
186
+ /** Releases the original call with an immutable receipt. Poll `readAction` for the sole final result. */
187
+ async backgroundAction(action, options) {
188
+ const idempotencyKey = key(options);
189
+ const reply = parse(await this.#link.exchange("/v1/control/action-background", (store) => JSON.stringify({
190
+ version: WIRE_VERSION, kind: "action_background", store,
191
+ key: idempotencyKey, session: this.id, action,
192
+ })));
193
+ const answer = accepted(reply.answer);
194
+ this.#link.activity?.notify(this.id);
195
+ return answer.action_selection;
196
+ }
197
+ /** Selects an owned Action for stop. Reuse the key to recover a lost reply. */
198
+ async stopAction(action, options) {
199
+ const idempotencyKey = key(options);
200
+ const reply = parse(await this.#link.exchange("/v1/control/action-stop", (store) => JSON.stringify({
201
+ version: WIRE_VERSION, kind: "action_stop", store,
202
+ key: idempotencyKey, session: this.id, action,
203
+ })));
204
+ const answer = accepted(reply.answer);
205
+ this.#link.activity?.notify(this.id);
206
+ return answer.resolution_position;
207
+ }
208
+ /** Reads an owned Action. Acceptance and attempted state do not assert a running process. */
209
+ async readAction(action, offset = "0") {
210
+ return parse(await this.#link.exchange("/v1/read-action", (store) => JSON.stringify({
211
+ version: WIRE_VERSION, kind: "read_action", store, session: this.id, action, offset,
212
+ })));
213
+ }
191
214
  /**
192
215
  * Cuts off the model call that is current now while the Session keeps going.
193
216
  * It takes no key: each call names the work it sees at that moment, so a
@@ -213,7 +236,6 @@ export class Session {
213
236
  accepted(parse(await this.#link.exchange("/v1/control/model-interruption", body)).answer);
214
237
  }
215
238
  catch (error) {
216
- // The call ended before the cut reached it: nothing is left to cut.
217
239
  const gone = error instanceof RuiRequestError && (error.code === "operation_resolved" || error.code === "target_mismatch");
218
240
  if (!gone)
219
241
  throw error;
@@ -237,7 +259,6 @@ export class Session {
237
259
  this.#link.activity?.notify(this.id);
238
260
  }
239
261
  }
240
- /** Work states in which a model call is the current thing. */
241
262
  function modelCallCurrent(kind) {
242
263
  return kind === "working" || kind === "retrying" || kind === "pending";
243
264
  }
@@ -269,7 +290,7 @@ export class Sessions {
269
290
  ceiling: wireCeiling,
270
291
  })));
271
292
  for (const row of page.sessions) {
272
- summaries.push({ id: row.reference, label: row.label, state: row.work.state.kind, archiveState: row.archive_state, parent: row.parent });
293
+ summaries.push({ id: row.reference, label: row.label, state: row.work.state.kind, archiveState: row.archive_state, parent: row.parent, creator: row.creator });
273
294
  }
274
295
  if (page.next === null || !("after" in page.next))
275
296
  return summaries.reverse();
@@ -278,19 +299,16 @@ export class Sessions {
278
299
  }
279
300
  }
280
301
  }
281
- /** The models each provider offers (D128). */
282
302
  export async function models(link) {
283
303
  const reply = parse(await link.exchange("/v1/model-list", (store) => JSON.stringify({
284
304
  version: WIRE_VERSION,
285
305
  kind: "model_list",
286
306
  store,
287
307
  }), undefined, {
288
- // A live provider list can take longer than the default response wait.
289
308
  responseMs: 30_000,
290
309
  }));
291
310
  return reply.providers.flatMap((entry) => entry.models.map((model) => ({ provider: entry.provider, id: model.id, known: model.known })));
292
311
  }
293
- /** Holds every new Turn while paused; running work continues (D199). */
294
312
  export async function setPaused(link, paused) {
295
313
  await link.exchange("/v1/control/host-pause", (store) => JSON.stringify({
296
314
  version: WIRE_VERSION,