ruicode 0.88.1 → 0.92.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
@@ -23,7 +23,8 @@ await rui.close();
23
23
  Run `npm install ruicode`.
24
24
  The `ruicode` package carries the client.
25
25
  The `rui` executable comes from the platform package beside it
26
- (`ruicode-linux-x64`, `ruicode-linux-arm64` or `ruicode-darwin-arm64`, installed as optional dependencies), else from `rui` on `PATH`.
26
+ (`ruicode-linux-x64`, `ruicode-linux-arm64` or `ruicode-darwin-arm64`, installed as optional dependencies).
27
+ npm refuses to install `ruicode` on Windows; on other systems without a platform package, `Rui.connect` refuses with `RuiUnavailableError` and names the supported platforms.
27
28
  Pass `binary` in the second argument to `Rui.connect` to name one yourself.
28
29
 
29
30
  Bundled and custom binaries and their child Host launch are application-owned.
@@ -56,18 +57,7 @@ const session = await rui.sessions.create({ preset: "drift" });
56
57
  The client defaults omitted or null `interface.dir` to its private temporary directory and omitted `interface.lifetime` to `"stdin"`; an explicit non-null directory or `"stdin"`/`"detached"` lifetime wins.
57
58
  It sends the document to `rui host serve --settings -` using a four-byte big-endian byte length followed by UTF-8 JSON, not argv or environment flags.
58
59
 
59
- Before:
60
-
61
- ```ts
62
- await Rui.connect({
63
- database: "/data/store",
64
- provider: { baseUrl: "https://api.openai.com/v1", key: "secret", caFile: "/trust.pem" },
65
- tools: [{ name: "drift", url: "http://127.0.0.1:3000/mcp", bearerToken: "token", callTimeoutMs: 30000 }],
66
- activeCapacity: 2, paused: true, presets: {}, binary: "/path/to/rui", lockWaitMs: 5000,
67
- });
68
- ```
69
-
70
- After:
60
+ Client options such as the binary path and lock wait go in a separate second argument:
71
61
 
72
62
  ```ts
73
63
  await Rui.connect({
@@ -79,30 +69,14 @@ await Rui.connect({
79
69
  }, { binary: "/path/to/rui", lockWaitMs: 5000 });
80
70
  ```
81
71
 
82
- Every former `ConnectOptions` field moves as follows:
83
-
84
- | Before | After |
85
- | --- | --- |
86
- | `database` (directory) | `settings.store.sqlite.dir` |
87
- | `database` (MySQL URL) | `settings.store.mysql.url` (a secret source or pipe-only string) |
88
- | `provider.baseUrl` | `settings.providers.openai.endpoint`: append `/responses` to the former base URL (trim trailing `/` first) |
89
- | `provider.key` | `settings.providers.openai.key` (a secret source or pipe-only string) |
90
- | `provider.caFile` | `settings.network.caFile` (Host-wide, for all providers) |
91
- | `tools[].name` | The key in `settings.tools.mcp[name]` |
92
- | `tools[].url` | `settings.tools.mcp[name].url` |
93
- | `tools[].bearerToken` | `settings.tools.mcp[name].bearerToken` (a secret source or pipe-only string) |
94
- | `tools[].callTimeoutMs` | `settings.tools.mcp[name].callTimeoutMs` |
95
- | `activeCapacity` | `settings.execution.activeCapacity` |
96
- | `paused` | `settings.execution.paused` |
97
- | `presets` | `settings.presets`, using the existing `AgentSpec` writer |
98
- | `binary` | `options.binary` |
99
- | `lockWaitMs` | `options.lockWaitMs` (still defaults to 120000 ms) |
72
+ `options.lockWaitMs` defaults to 120000 ms.
100
73
 
101
74
  Secret strings are a TypeScript input convenience: the pipe serializer wraps each as `{ value: "secret" }`.
102
75
  Explicit `{ value: "secret" }`, `{ file: "/private/key" }`, `{ env: "NAME" }`, and the generated owner/default forms are also accepted where the schema allows them.
103
76
  Literal values are permitted only for pipe-origin documents, never settings files.
104
- The child inherits `PATH`, `HOME` and `TMPDIR`, plus only the environment variables explicitly named by secret `{ env: ... }` sources in the document.
105
- Unreferenced application, proxy and provider-override environment variables are not inherited.
77
+ The child inherits `PATH`, `HOME`, `TMPDIR`, the proxy variables (`https_proxy`, `HTTPS_PROXY`, `no_proxy`, `NO_PROXY`) and the trust variables (`SSL_CERT_FILE`, `SSL_CERT_DIR`) its transport reads (`TRANSPORT_ENVIRONMENT`, generated from the Host), plus only the environment variables explicitly named by secret `{ env: ... }` sources in the document.
78
+ So a Host started behind the application's proxy or private CA reaches its provider and models.dev; a proxy URL that is not `http://` refuses the start with `proxy_unusable`.
79
+ Other application and provider-override environment variables are not inherited.
106
80
  Node can pass environment names only as Unicode strings: a non-UTF-8 byte name is refused with `settings_invalid` and its leaf path rather than silently selecting another key; use a file source instead.
107
81
  Literal keys, tokens and MySQL URLs travel only in stdin, never argv, environment or disk; an explicitly selected environment source is inherited instead.
108
82
  The client erases its mutable serialized buffers after writes and on close or failed connect; JavaScript strings, including caller-owned inputs and temporary JSON strings, cannot be reliably erased.
@@ -128,14 +102,16 @@ Shell commands the agent runs execute as your user; Rui is not a sandbox.
128
102
  With the default `interface.lifetime: "stdin"`, the Host stops when your process ends.
129
103
  An explicit `"detached"` lifetime does not stop on stdin closure; `rui.close()` still explicitly disposes its child and removes only the client-owned temporary directory, not a caller-supplied interface directory.
130
104
  If it exits on its own, the client restarts it, waiting 0.5 s and doubling up to 30 s, and sends calls in flight again once the new Host is ready.
131
- Automatic restarts retry `store_locked` and `mysql_unreachable`; calls waiting on a failed attempt receive `RuiUnavailableError`.
105
+ Automatic restarts retry `store_locked` and `mysql_unreachable`; calls waiting on a failed attempt receive `RuiUnavailableError`. A fenced Store is different: see `RuiStoreFailedError` below.
132
106
  Initial connect still rejects `mysql_unreachable` immediately.
133
107
 
134
108
  Errors:
135
109
 
136
110
  - `RuiStartError { code, message }`: Rui refused to open, for example `store_locked` once `lockWaitMs` (default 120 s) has passed.
137
- - `RuiRequestError { code }`: Rui rejected one request.
111
+ - `RuiRequestError { code, missing }`: Rui rejected one request. Its `message` is the Host's detail when it sent one, else the plain sentence the `rui` CLI prints for that `code`.
138
112
  - `RuiUnavailableError`: the child is gone.
113
+ - A connection error from a Host that is still running surfaces after up to about 16 s: the client waits `CLOSE_GRACE_MS` (15 s) for the Host to exit, then up to 1 s for its stdout to drain. The wait exists so a late `store_fenced` line is never missed, so it is deliberate and not a hang.
114
+ - `RuiStoreFailedError` (`code` `store_failed`): the Store was fenced under this client, from a `canonical_store_failure` reply or a MySQL Host's `store_fenced` line before it exits. The client latches it once: every pending and later call rejects with this same error and the Host is not restarted. Close the client and connect again.
139
115
 
140
116
  For `sessions.create` and `session.update`, `mcp_server_unavailable` means a requested tool is unknown and at least one configured MCP server has no tools, including no saved copies.
141
117
  The error's `message` names the unavailable server(s) that may provide the name; it does not assert ownership.
@@ -145,7 +121,7 @@ A creating Message uses the same request rule, and `start_agent` reports it as a
145
121
 
146
122
  ## Session feed
147
123
 
148
- `session.listActivity()` reads to the current end; `{ follow: true }` follows new entries.
124
+ `session.listActivity()` reads to the current end. `session.watch({ after })` follows new entries; `listActivity({ follow: true })` is the same iterator.
149
125
  Feed entries are a discriminated union: `switch (entry.kind)` narrows to that wire row's fields.
150
126
  A `model_call` entry is one resolved model Operation at its admission position: `model`, nullable `servedModel`, nullable `inputTokens`, `outputTokens`, `cachedTokens`, `latencyMs`, `firstEventMs`, plus `status` and `attempts`.
151
127
  Counts and durations remain decimal strings (or null); both timings describe the **final attempt**, and `firstEventMs` measures the first HTTP response event, not the first token.
@@ -170,11 +146,12 @@ for await (const entry of session.listActivity()) {
170
146
 
171
147
  The example uses `writeFile` from `node:fs/promises`.
172
148
 
173
- Following polls with backoff from 250 ms to 2 s only while the Session is busy.
174
- An empty page in `idle`, `finished`, `failed`, or `stopped` state with nothing queued puts the iterator to sleep **without a timer**.
175
- It wakes after a successful `send`, `update`, `decide`, `interrupt`, `stop`, `archive`, or `unarchive` through any handle for that Session ID on the same Rui instance, then starts polling again at 250 ms.
176
- Writes from another process to the same Store are **not noticed while idle** (nor are writes through another Rui instance).
177
- Pass an AbortSignal as `signal` to end the iterator immediately even while it sleeps.
149
+ Following holds one line to the Host per Rui instance, shared by every watcher. The Host nudges the client when a watched Session commits, and each nudge reads that watcher's feed from its own cursor, so each row arrives once and in order.
150
+ An idle Session makes no requests; there is no polling timer.
151
+ A reconnect or a Host restart re-reads every watched cursor, so nothing is lost while the line was down.
152
+ Commits the Host makes, from this instance or any other client, reach every watcher of the Session the same way.
153
+ A Store failure ends every watcher with `RuiStoreFailedError`, as it ends every call. A refused line that answers `503 line_capacity_exhausted` ends its watchers with `RuiRequestError` (code `line_capacity_exhausted`); the client does not retry it.
154
+ Pass an AbortSignal as `signal` to end the iterator immediately, even while it waits.
178
155
 
179
156
  ## Development
180
157
 
@@ -266,7 +243,7 @@ New Messages are rejected with `session_archiving` during settlement, and `unarc
266
243
  A later Message to an archived Session restores it transactionally before admitting new work.
267
244
  `unarchive()` restores only organization and never resumes stopped work.
268
245
  Replaying an archive request with its original key does not archive again after a later restore.
269
- Both methods notify local activity followers without submitting a Message or starting work.
246
+ Both methods submit no Message and start no work; a watcher sees the change only through the Host's nudge.
270
247
 
271
248
  ## Stop one Action
272
249
 
package/dist/binary.d.ts CHANGED
@@ -1,7 +1,9 @@
1
+ /** The one table of platforms Rui builds for: Node's platform, then architecture, to the npm package holding rui. */
1
2
  export declare const PLATFORM_PACKAGES: Record<string, Record<string, string>>;
2
3
  export interface BinaryLookup {
3
4
  platform?: string;
4
5
  arch?: string;
5
6
  from?: string;
6
7
  }
8
+ /** The rui to start: `binary` when given, else the platform package's. Never a guess from PATH. */
7
9
  export declare function resolveBinary(binary: string | undefined, lookup?: BinaryLookup): string;
package/dist/binary.js CHANGED
@@ -1,19 +1,29 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { dirname, join } from "node:path";
3
+ import { RuiUnavailableError } from "./errors.js";
4
+ /** The one table of platforms Rui builds for: Node's platform, then architecture, to the npm package holding rui. */
3
5
  export const PLATFORM_PACKAGES = {
4
6
  linux: { x64: "ruicode-linux-x64", arm64: "ruicode-linux-arm64" },
5
7
  darwin: { arm64: "ruicode-darwin-arm64" },
6
8
  };
9
+ // pack.mjs PLATFORMS publishes these packages, with glibc required on Linux; TS-10 checks the two tables agree.
10
+ const SUPPORTED = `Rui runs on ${Object.entries(PLATFORM_PACKAGES)
11
+ .map(([platform, arches]) => `${platform === "linux" ? "glibc Linux" : platform} on ${Object.keys(arches).join(" or ")}`)
12
+ .join(", and ")}.`;
13
+ /** The rui to start: `binary` when given, else the platform package's. Never a guess from PATH. */
7
14
  export function resolveBinary(binary, lookup = {}) {
8
15
  if (binary !== undefined)
9
16
  return binary;
10
- const name = PLATFORM_PACKAGES[lookup.platform ?? process.platform]?.[lookup.arch ?? process.arch];
11
- if (name === undefined)
12
- return "rui";
17
+ const platform = lookup.platform ?? process.platform;
18
+ const arch = lookup.arch ?? process.arch;
19
+ const name = PLATFORM_PACKAGES[platform]?.[arch];
20
+ if (name === undefined) {
21
+ throw new RuiUnavailableError(`Rui has no build for ${platform} on ${arch}. ${SUPPORTED} Pass \`binary\` to Rui.connect to use a rui you built.`);
22
+ }
13
23
  try {
14
24
  return join(dirname(createRequire(lookup.from ?? import.meta.url).resolve(`${name}/package.json`)), "bin", "rui");
15
25
  }
16
- catch {
17
- return "rui";
26
+ catch (error) {
27
+ throw new RuiUnavailableError(`The ${name} package, which holds the rui executable, is not installed. npm skips it when optional dependencies are omitted or this system does not match it, such as musl Linux. ${SUPPORTED} Reinstall ruicode with optional dependencies, or pass \`binary\` to Rui.connect.`, { cause: error });
18
28
  }
19
29
  }
package/dist/client.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import { type HostSettings, type PreparedSettings } from "./settings.ts";
3
- import { SessionNotifications } from "./notifications.ts";
3
+ import { Follows } from "./follow.ts";
4
4
  import { RuiStartError } from "./errors.ts";
5
- import { Session, Sessions, type ModelSummary } from "./sessions.ts";
5
+ import { Session, Sessions, type ModelSummary, type ToolReloadOutcome } from "./sessions.ts";
6
6
  import { type ReplyLimits } from "./transport.ts";
7
7
  import type { components } from "./wire.ts";
8
8
  type Schemas = components["schemas"];
@@ -11,7 +11,7 @@ export type { HostSettings } from "./settings.ts";
11
11
  export interface ClientOptions {
12
12
  /** How long connect retries another Host's Store lock. Default 120 000 ms. */
13
13
  lockWaitMs?: number;
14
- /** Default: the installed platform package's executable, else rui on PATH. */
14
+ /** Default: the installed platform package's executable; `connect` refuses when there is none. */
15
15
  binary?: string;
16
16
  }
17
17
  /** Fires on every child exit, including one the client restarts from (D129). */
@@ -34,7 +34,8 @@ export declare class Rui extends EventEmitter<{
34
34
  exit: [ExitEvent];
35
35
  }> {
36
36
  #private;
37
- readonly activity: SessionNotifications;
37
+ /** The one line this client holds for every watcher, and the registry of the Sessions they follow. */
38
+ readonly follows: Follows;
38
39
  /** Create and list Sessions. */
39
40
  readonly sessions: Sessions;
40
41
  private constructor();
@@ -47,6 +48,11 @@ export declare class Rui extends EventEmitter<{
47
48
  /** Holds every new Turn until `resume`. Running work continues. */
48
49
  pause(): Promise<void>;
49
50
  resume(): Promise<void>;
51
+ /**
52
+ * Lists one MCP server, or every configured server when `server` is omitted, again, and resolves once each list has
53
+ * landed. Rejects with RuiWaitTimeoutError after 60 s.
54
+ */
55
+ reloadTools(server?: string): Promise<ToolReloadOutcome[]>;
50
56
  /**
51
57
  * Closes the child's stdin and resolves once it has exited, bounded by the
52
58
  * Host's 10 s shutdown (D129). Later calls fail with RuiUnavailableError.
@@ -57,6 +63,12 @@ export declare class Rui extends EventEmitter<{
57
63
  get pid(): number | undefined;
58
64
  get hostInfo(): HostInfo | undefined;
59
65
  }
66
+ /**
67
+ * The application's environment a child Host inherits: process basics, and the proxy and trust variables its transport
68
+ * reads, so a Host behind a proxy or a private CA reaches its provider and models.dev. Secrets reach it only through
69
+ * `{ env }` sources in the settings.
70
+ */
71
+ export declare const INHERITED_ENVIRONMENT: readonly ["PATH", "HOME", "TMPDIR", "https_proxy", "HTTPS_PROXY", "no_proxy", "NO_PROXY", "SSL_CERT_FILE", "SSL_CERT_DIR"];
60
72
  export declare function launchFor(settings: HostSettings, runtimeDir: string, options?: ClientOptions): Launch;
61
73
  export declare function encodeSettings(document: Schemas["HostSettings"]): Buffer;
62
74
  export declare function readinessInstance(prefix: Buffer): string | undefined;
package/dist/client.js CHANGED
@@ -3,12 +3,16 @@ import { EventEmitter } from "node:events";
3
3
  import { mkdtemp, rm, stat, symlink } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
+ import { StringDecoder } from "node:string_decoder";
6
7
  import { setTimeout as sleep } from "node:timers/promises";
7
8
  import { prepareSettings } from "./settings.js";
8
- import { SessionNotifications } from "./notifications.js";
9
+ import { Follows } from "./follow.js";
10
+ import { readPage } from "./feed.js";
11
+ import { Line, LineProtocolError } from "./line.js";
9
12
  import { resolveBinary } from "./binary.js";
10
- import { RuiStartError, RuiUnavailableError } from "./errors.js";
11
- import { models, Session, Sessions, setPaused } from "./sessions.js";
13
+ import { TRANSPORT_ENVIRONMENT } from "./host-environment.js";
14
+ import { RuiRequestError, RuiStartError, RuiStoreFailedError, RuiUnavailableError } from "./errors.js";
15
+ import { models, reloadTools, Session, Sessions, setPaused } from "./sessions.js";
12
16
  import { ConnectionError, post, WIRE_VERSION } from "./transport.js";
13
17
  const SOCKET_NAME = "rui.sock";
14
18
  const DEFAULT_LOCK_WAIT_MS = 120_000;
@@ -18,7 +22,8 @@ const MAX_RESTART_MS = 30_000;
18
22
  const CLOSE_GRACE_MS = 15_000;
19
23
  const READY_POLL_MS = 25;
20
24
  const READINESS_RECEIPT_BYTES = Buffer.byteLength("ready instance=") + 32 + 1;
21
- const EXIT_NOTICE_MS = 2_000;
25
+ const OUTPUT_GRACE_MS = 1_000;
26
+ const MAX_LINE_CHARS = 64 * 1024;
22
27
  const RETRYABLE_START_CODES = new Set(["store_locked", "mysql_unreachable"]);
23
28
  class AttemptFailed extends Error {
24
29
  error;
@@ -39,7 +44,17 @@ export class Rui extends EventEmitter {
39
44
  #restart;
40
45
  #closing;
41
46
  #dead;
42
- activity = new SessionNotifications();
47
+ #storeFailed;
48
+ /** The one line this client holds for every watcher, and the registry of the Sessions they follow. */
49
+ follows = new Follows((session, request) => readPage(this, session, request), { watch: (sessions) => this.#watchLine(sessions) });
50
+ #line;
51
+ #lineSessions = [];
52
+ #silentCloses = 0;
53
+ #opening = false;
54
+ #lineHandler = {
55
+ frame: (frame) => this.#lineFrame(frame),
56
+ closed: (line, error) => this.#lineClosed(line, error),
57
+ };
43
58
  /** Create and list Sessions. */
44
59
  sessions = new Sessions(this);
45
60
  constructor(launch, runtimeDir, host) {
@@ -90,6 +105,13 @@ export class Rui extends EventEmitter {
90
105
  resume() {
91
106
  return setPaused(this, false);
92
107
  }
108
+ /**
109
+ * Lists one MCP server, or every configured server when `server` is omitted, again, and resolves once each list has
110
+ * landed. Rejects with RuiWaitTimeoutError after 60 s.
111
+ */
112
+ reloadTools(server) {
113
+ return reloadTools(this, server);
114
+ }
93
115
  /**
94
116
  * Closes the child's stdin and resolves once it has exited, bounded by the
95
117
  * Host's 10 s shutdown (D129). Later calls fail with RuiUnavailableError.
@@ -135,15 +157,36 @@ export class Rui extends EventEmitter {
135
157
  });
136
158
  }
137
159
  catch (error) {
138
- if (!(error instanceof ConnectionError))
139
- throw error;
140
- const gone = await Promise.race([host.exited.then(() => true), sleep(EXIT_NOTICE_MS, false)]);
141
- if (!gone || retried)
142
- throw new RuiUnavailableError("the Rui Host did not answer", { cause: error });
160
+ await this.#retryAfter(host, error, retried);
143
161
  retried = true;
144
162
  }
145
163
  }
146
164
  }
165
+ /**
166
+ * The one classification of a failed attempt against `host`, shared by `call` and the line. A canonical Store failure
167
+ * latches. A dispatch_fenced reply is classified only once the Host has exited, since stop and cleanup phases also send it.
168
+ * A lost connection or a host_stopping reply settles the Host, then allows one retry; only the line (GET /v1/line) receives a
169
+ * host_stopping reply. Returns when the attempt may be
170
+ * retried; otherwise throws the error the caller reports.
171
+ */
172
+ async #retryAfter(host, error, retried) {
173
+ if (this.#storeFailed)
174
+ throw this.#storeFailed;
175
+ if (error instanceof RuiRequestError && isCanonicalFailure(error))
176
+ throw this.#latchStoreFailed(error);
177
+ if (error instanceof RuiRequestError && isDispatchFenced(error)) {
178
+ await settle(host);
179
+ throw this.#storeFailed ?? error;
180
+ }
181
+ const stopping = error instanceof RuiRequestError && error.code === "host_stopping";
182
+ if (!(error instanceof ConnectionError || stopping))
183
+ throw error;
184
+ const gone = await settle(host);
185
+ if (this.#storeFailed)
186
+ throw this.#storeFailed;
187
+ if (!gone || retried)
188
+ throw new RuiUnavailableError("the Rui Host did not answer", { cause: error });
189
+ }
147
190
  async exchange(path, build, environment, limits) {
148
191
  const host = await this.#ready();
149
192
  return this.call(path, build(host.info.store), environment, limits);
@@ -155,9 +198,13 @@ export class Rui extends EventEmitter {
155
198
  return this.#host?.info;
156
199
  }
157
200
  #ready() {
201
+ if (this.#closing)
202
+ return Promise.reject(new RuiUnavailableError("the Rui client is closed"));
203
+ if (this.#storeFailed)
204
+ return Promise.reject(this.#storeFailed);
158
205
  if (this.#host)
159
206
  return Promise.resolve(this.#host);
160
- const failed = this.#dead ?? (this.#closing ? new RuiUnavailableError("the Rui client is closed") : undefined);
207
+ const failed = this.#dead;
161
208
  if (failed)
162
209
  return Promise.reject(failed);
163
210
  this.#restart?.ref();
@@ -169,21 +216,127 @@ export class Rui extends EventEmitter {
169
216
  this.#backoff = FIRST_RESTART_MS;
170
217
  for (const waiter of this.#waiters.splice(0))
171
218
  waiter.resolve(host);
172
- void host.exited.then((exit) => {
219
+ void host.fenced.then((cause) => this.#latchStoreFailed(cause));
220
+ void host.exited.then(async (exit) => {
221
+ await drained(host);
173
222
  if (this.#closing || this.#host !== host)
174
223
  return;
175
224
  this.#host = undefined;
176
- this.emit("exit", { ...exit, restarting: true });
225
+ this.emit("exit", { ...exit, restarting: this.#storeFailed === undefined });
177
226
  this.#scheduleRestart();
178
227
  });
179
228
  }
229
+ /**
230
+ * The one owner of the Store-failed latch. Every fence signal reaches it: a canonical 500 reply (`isCanonicalFailure`), and the
231
+ * `store_fenced` line. The first latch wins, rejects the pending calls with the same error and stops restarts.
232
+ */
233
+ #latchStoreFailed(cause) {
234
+ if (this.#storeFailed)
235
+ return this.#storeFailed;
236
+ this.#storeFailed = new RuiStoreFailedError({ cause });
237
+ clearTimeout(this.#restart);
238
+ this.#fail(this.#storeFailed);
239
+ return this.#storeFailed;
240
+ }
180
241
  #fail(error) {
181
- this.activity.fail(error);
242
+ this.follows.fail(error);
182
243
  for (const waiter of this.#waiters.splice(0))
183
244
  waiter.reject(error);
184
245
  }
246
+ /** The line's watched set. Empty closes the line; otherwise an open line is sent the set, and a closed one reopens. */
247
+ #watchLine(sessions) {
248
+ this.#lineSessions = sessions;
249
+ if (sessions.length === 0) {
250
+ const line = this.#line;
251
+ this.#line = undefined;
252
+ line?.close();
253
+ return;
254
+ }
255
+ if (this.#line)
256
+ this.#line.watch(sessions);
257
+ else
258
+ this.#openLine();
259
+ }
260
+ #openLine() {
261
+ if (this.#opening)
262
+ return;
263
+ this.#opening = true;
264
+ this.#connectLine()
265
+ .catch((error) => this.follows.fail(error instanceof Error ? error : new RuiUnavailableError(String(error))))
266
+ .finally(() => {
267
+ this.#opening = false;
268
+ // A watch that arrived while this attempt was ending saw it as running, so it is opened here.
269
+ if (this.#lineSessions.length > 0 && !this.#line && !this.#closing && !this.#storeFailed)
270
+ this.#openLine();
271
+ });
272
+ }
273
+ /**
274
+ * Opens the line on the current Host and sends it the watched set; the Host nudges each listed Session, so every watcher
275
+ * re-reads from its cursor. A refused or lost attempt follows the restart path, as `call` does: wait for the child to exit,
276
+ * then reconnect to the Host that replaces it, once.
277
+ */
278
+ async #connectLine() {
279
+ for (let attempt = 1;; attempt++) {
280
+ const host = await this.#ready();
281
+ try {
282
+ const line = await Line.open({ socketPath: this.#launch.socketPath, instance: host.instance, handler: this.#lineHandler });
283
+ if (!line.isOpen)
284
+ throw new ConnectionError("the line closed while it opened");
285
+ if (this.#lineSessions.length === 0 || this.#closing) {
286
+ line.close();
287
+ return;
288
+ }
289
+ this.#line = line;
290
+ line.watch(this.#lineSessions);
291
+ return;
292
+ }
293
+ catch (error) {
294
+ if (this.#storeFailed)
295
+ return;
296
+ await this.#retryAfter(host, error, attempt > 1);
297
+ }
298
+ }
299
+ }
300
+ #lineFrame(frame) {
301
+ // Only an answer to a watch set resets the count of closes: `hello` and `ping` arrive whether or not the Host read it.
302
+ if (frame.type === "changed" || frame.type === "resync" || frame.type === "failed")
303
+ this.#silentCloses = 0;
304
+ switch (frame.type) {
305
+ case "changed":
306
+ this.follows.nudge(frame.session);
307
+ return;
308
+ case "resync":
309
+ this.follows.nudgeAll();
310
+ return;
311
+ case "failed":
312
+ // `host_stopping` needs no action: the Host closes the line, and the close reconnects once the child restarts.
313
+ if (frame.code === "store_failed")
314
+ this.#latchStoreFailed(new RuiUnavailableError("the Rui Host's line reported store_failed"));
315
+ return;
316
+ default:
317
+ return;
318
+ }
319
+ }
320
+ #lineClosed(line, error) {
321
+ if (this.#line !== line)
322
+ return;
323
+ this.#line = undefined;
324
+ if (this.#closing || this.#storeFailed || this.#lineSessions.length === 0)
325
+ return;
326
+ if (error instanceof LineProtocolError) {
327
+ this.follows.fail(new RuiUnavailableError("the Rui Host sent a malformed line frame", { cause: error }));
328
+ return;
329
+ }
330
+ // A Host restart closes a line once and then answers its successor. A line that closes twice without answering a watch
331
+ // set is not a restart: the Host refuses that set, so reconnecting would repeat it.
332
+ if (++this.#silentCloses > 1) {
333
+ this.follows.fail(new RuiUnavailableError("the Rui Host closed its line twice without a frame"));
334
+ return;
335
+ }
336
+ this.#openLine();
337
+ }
185
338
  #scheduleRestart() {
186
- if (this.#closing)
339
+ if (this.#closing || this.#storeFailed)
187
340
  return;
188
341
  const delay = this.#backoff;
189
342
  this.#backoff = Math.min(this.#backoff * 2, MAX_RESTART_MS);
@@ -192,6 +345,8 @@ export class Rui extends EventEmitter {
192
345
  this.#restart.unref();
193
346
  }
194
347
  async #restartNow() {
348
+ if (this.#storeFailed)
349
+ return;
195
350
  try {
196
351
  const host = await start(this.#launch, (child) => {
197
352
  this.#child = child;
@@ -200,6 +355,12 @@ export class Rui extends EventEmitter {
200
355
  host.child.stdin?.end();
201
356
  return;
202
357
  }
358
+ if (this.#storeFailed) {
359
+ host.child.stdin?.end();
360
+ if (this.#launch.detached)
361
+ host.child.kill("SIGTERM");
362
+ return;
363
+ }
203
364
  this.#adopt(host);
204
365
  }
205
366
  catch (failure) {
@@ -218,9 +379,15 @@ export class Rui extends EventEmitter {
218
379
  }
219
380
  }
220
381
  }
382
+ /**
383
+ * The application's environment a child Host inherits: process basics, and the proxy and trust variables its transport
384
+ * reads, so a Host behind a proxy or a private CA reaches its provider and models.dev. Secrets reach it only through
385
+ * `{ env }` sources in the settings.
386
+ */
387
+ export const INHERITED_ENVIRONMENT = ["PATH", "HOME", "TMPDIR", ...TRANSPORT_ENVIRONMENT];
221
388
  export function launchFor(settings, runtimeDir, options = {}) {
222
389
  const env = Object.create(null);
223
- for (const name of ["PATH", "HOME", "TMPDIR"]) {
390
+ for (const name of INHERITED_ENVIRONMENT) {
224
391
  const value = process.env[name];
225
392
  if (value !== undefined)
226
393
  env[name] = value;
@@ -267,8 +434,27 @@ async function start(launch, spawned) {
267
434
  chunk.fill(0);
268
435
  };
269
436
  child.stdout?.on("data", capture);
437
+ const decoder = new StringDecoder("utf8");
438
+ let pending = "";
439
+ const fenceIn = (line) => {
440
+ const refusal = line.includes("store_fenced") ? startError(line) : undefined;
441
+ if (refusal?.code === "store_fenced")
442
+ fence(refusal);
443
+ };
444
+ const watch = (chunk) => {
445
+ const lines = (pending + decoder.write(chunk)).split("\n");
446
+ chunk.fill(0);
447
+ pending = lines.pop() ?? "";
448
+ if (pending.length > MAX_LINE_CHARS)
449
+ pending = "";
450
+ for (const line of lines)
451
+ fenceIn(line);
452
+ };
270
453
  const outputEnded = new Promise((done) => child.stdout?.once("close", done));
271
454
  const launchError = new Promise((done) => child.once("error", done));
455
+ let fence;
456
+ const fenced = new Promise((done) => (fence = done));
457
+ let ready = false;
272
458
  const exited = exitOf(child);
273
459
  child.unref();
274
460
  child.stdout?.unref();
@@ -292,8 +478,13 @@ async function start(launch, spawned) {
292
478
  child.kill("SIGKILL");
293
479
  throw new AttemptFailed(error, await exited);
294
480
  });
295
- if (info)
296
- return { child, instance: info.instance, info, exited };
481
+ if (info) {
482
+ child.stdout?.off("data", capture);
483
+ child.stdout?.on("data", watch);
484
+ void outputEnded.then(() => fenceIn(pending));
485
+ ready = true;
486
+ return { child, instance: info.instance, info, exited, output: outputEnded, fenced };
487
+ }
297
488
  await sleep(READY_POLL_MS);
298
489
  }
299
490
  if (ended instanceof Error) {
@@ -311,14 +502,51 @@ async function start(launch, spawned) {
311
502
  throw new AttemptFailed(refusal ?? new RuiUnavailableError(`rui exited before it was ready (code ${ended.code}, signal ${ended.signal})`), ended);
312
503
  }
313
504
  finally {
314
- child.stdout?.off("data", capture);
315
- child.stdout?.on("data", (chunk) => chunk.fill(0));
505
+ if (!ready) {
506
+ child.stdout?.off("data", capture);
507
+ child.stdout?.on("data", (chunk) => chunk.fill(0));
508
+ }
316
509
  receipt.fill(0);
317
510
  for (const chunk of stdout)
318
511
  chunk.fill(0);
319
512
  stdout.length = 0;
320
513
  }
321
514
  }
515
+ /** The Host's 500 reply for a fenced Store, the stable signal the Store fence latches on. */
516
+ function isCanonicalFailure(error) {
517
+ return error.type === "invocation_error" && error.code === "canonical_store_failure";
518
+ }
519
+ /** The Host's 503 reply while it is not in its open phase: a stop, a cleanup fence or a Store fence. Not a signal alone. */
520
+ function isDispatchFenced(error) {
521
+ return error.type === "host_unavailable" && error.code === "dispatch_fenced";
522
+ }
523
+ /** Resolves with `done`, or with `fallback` once `ms` passes. The timer is cleared as soon as the wait settles. */
524
+ async function bounded(done, ms, fallback) {
525
+ const cancel = new AbortController();
526
+ try {
527
+ return await Promise.race([done, sleep(ms, fallback, { signal: cancel.signal })]);
528
+ }
529
+ catch {
530
+ return fallback;
531
+ }
532
+ finally {
533
+ cancel.abort();
534
+ }
535
+ }
536
+ /**
537
+ * Waits for a lost or fenced child to exit, bounded by the shutdown grace (D129), then for its stdout to drain so a final
538
+ * `store_fenced` line has been read. Resolves whether the child exited in time.
539
+ */
540
+ async function settle(host) {
541
+ const gone = await bounded(host.exited.then(() => true), CLOSE_GRACE_MS, false);
542
+ if (gone)
543
+ await drained(host);
544
+ return gone;
545
+ }
546
+ /** Lets a stopped child's stdout deliver its final lines, bounded so a grandchild holding the pipe cannot stall us. */
547
+ async function drained(host) {
548
+ await bounded(host.output, OUTPUT_GRACE_MS, undefined);
549
+ }
322
550
  async function createInterfaceAlias(launch) {
323
551
  const dir = launch.interfaceDir;
324
552
  const target = typeof dir === "string" ? dir : Buffer.from(dir.hex, "hex");
package/dist/errors.d.ts CHANGED
@@ -17,13 +17,22 @@ type RequestErrorType = Schemas["ErrorReply"]["type"] | Status<Extract<RequestAn
17
17
  code: string;
18
18
  }>>;
19
19
  type StartErrorCode = Schemas["StartError"]["rui_start_error"]["code"];
20
- /** Rui rejected one request. `code` is the Host's rejection code; `message` preserves advisory detail when provided. */
20
+ /** A setting a new Session lacked, named by a `missing_settings` rejection. */
21
+ export type MissingSetting = NonNullable<Extract<RequestAnswer, {
22
+ missing: unknown;
23
+ }>["missing"]>[number];
24
+ /**
25
+ * Rui rejected one request. `code` is the Host's rejection code. The message is the Host's advisory detail when it sent
26
+ * one, else the Host catalog's plain sentence for `code`, with any missing settings and the code.
27
+ */
21
28
  export declare class RuiRequestError extends Error {
22
29
  readonly name = "RuiRequestError";
23
30
  readonly code: RequestErrorCode;
24
31
  /** The Host's error class, such as `invocation_error` or `busy`. */
25
32
  readonly type: RequestErrorType;
26
- constructor(type: RequestErrorType, code: RequestErrorCode, message?: string | null);
33
+ /** Every setting a new Session lacked, set exactly when `code` is `missing_settings`. */
34
+ readonly missing: readonly MissingSetting[] | undefined;
35
+ constructor(type: RequestErrorType, code: RequestErrorCode, message?: string | null, missing?: readonly MissingSetting[] | null);
27
36
  }
28
37
  /** Rui refused to open. `code` is one of the refusal codes at open (D136). */
29
38
  export declare class RuiStartError extends Error {
@@ -38,9 +47,27 @@ export declare class RuiUnavailableError extends Error {
38
47
  cause?: unknown;
39
48
  });
40
49
  }
50
+ /**
51
+ * The Store was fenced under this client: the Host answered `canonical_store_failure`, or a MySQL Host wrote `store_fenced`
52
+ * before it exited. The client latches it once, so every pending and later call rejects with this same error, and it does
53
+ * not restart the Host. Close the client and connect again to use a new Host.
54
+ */
55
+ export declare class RuiStoreFailedError extends Error {
56
+ readonly name = "RuiStoreFailedError";
57
+ readonly code: "store_failed";
58
+ constructor(options?: {
59
+ cause?: unknown;
60
+ });
61
+ }
41
62
  /** The entry contains parts; read an individual part instead. */
42
63
  export declare class ContentIsPartsError extends Error {
43
64
  readonly name = "ContentIsPartsError";
44
65
  constructor();
45
66
  }
67
+ /** A wait ended before its condition held. `code` is `wait_timed_out`, the same code the CLI's wait reports. */
68
+ export declare class RuiWaitTimeoutError extends Error {
69
+ readonly name = "RuiWaitTimeoutError";
70
+ readonly code: "wait_timed_out";
71
+ constructor(message: string);
72
+ }
46
73
  export {};