ruicode 0.72.0 → 0.74.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
@@ -6,10 +6,13 @@ Starts a Rui Host as a child of your process and talks to it over its local sock
6
6
  import { Rui } from "ruicode";
7
7
 
8
8
  const rui = await Rui.connect({
9
- database: "/var/lib/myapp/rui-store",
10
- provider: { baseUrl: "https://api.openai.com/v1", key: process.env.OPENAI_API_KEY },
11
- tools: [{ name: "drift", url: "http://127.0.0.1:3000/mcp", bearerToken: process.env.MCP_TOKEN, callTimeoutMs: 30000 }],
12
- });
9
+ store: { sqlite: { dir: "/var/lib/myapp/rui-store" } },
10
+ providers: { openai: { endpoint: "https://api.openai.com/v1/responses", key: process.env.OPENAI_API_KEY! } },
11
+ tools: {
12
+ bash: { timeoutMs: 60000 },
13
+ mcp: { drift: { url: "http://127.0.0.1:3000/mcp", bearerToken: process.env.MCP_TOKEN!, callTimeoutMs: 30000 } },
14
+ },
15
+ }, { binary: "/path/to/rui" });
13
16
  rui.on("exit", ({ code, signal, restarting }) => console.warn("rui exited", { code, signal, restarting }));
14
17
  // ...
15
18
  await rui.close();
@@ -21,27 +24,109 @@ Run `npm install ruicode`.
21
24
  The `ruicode` package carries the client.
22
25
  The `rui` executable comes from the platform package beside it
23
26
  (`ruicode-linux-x64`, `ruicode-linux-arm64` or `ruicode-darwin-arm64`, installed as optional dependencies), else from `rui` on `PATH`.
24
- Pass `binary` to `Rui.connect` to name one yourself.
27
+ Pass `binary` in the second argument to `Rui.connect` to name one yourself.
25
28
 
26
29
  Bundled and custom binaries and their child Host launch are application-owned.
27
30
  Standalone client Upgrade does not mutate npm packages or blindly stop an application-owned Host, and reports installation separately from activation.
28
31
  There is no HTTP installer endpoint or background update polling; update the application's dependencies and lifecycle explicitly.
29
32
 
30
- `Rui.connect` writes the Store, the provider settings, MCP bearer tokens and a private runtime directory to the child's stdin.
31
- The optional `provider.caFile` names a PEM file to trust exclusively for that provider instead of system CAs, on macOS as on Linux (for example `provider: { baseUrl: "https://localhost:8443/v1", key: "local-key", caFile: "/path/to/ca.pem" }`).
32
- It travels in the launch frame, not argv or the environment; do not add `--provider-ca-file` to a launched Host.
33
- The path must be nonempty, contain no NUL bytes and fit the platform's path limit; relative paths use the Host's working directory, and a file that cannot be loaded or a peer that cannot be verified fails without falling back to system trust.
34
- `database` accepts a SQLite directory or a `mysql://USER:PASSWORD@HOST[:PORT]/DATABASE` URL.
33
+ ## Host settings and migration
34
+
35
+ The breaking signature is `Rui.connect(settings: HostSettings, options?: ClientOptions)`.
36
+ `HostSettings` is derived recursively from the generated settings schema, not a second list of supported Host options.
37
+ Every configured Adapter is available, including `providers.codex`, `providers.chatgpt`, `tools.bash`, `network`, `execution` and either Store.
38
+ For example, `providers: { codex: {} }` uses the Codex Adapter's saved sign-in.
39
+ Likewise, `providers: { chatgpt: {} }` uses the ChatGPT Adapter's saved sign-in (not an API key).
40
+ To select another private saved sign-in file, use `providers: { chatgpt: { credentialFile: "/private/chatgpt.json" } }`.
41
+ For example, a sign-in provider, MySQL, MCP and a preset can share one start:
42
+
43
+ ```ts
44
+ const rui = await Rui.connect({
45
+ store: { mysql: { url: { env: "MYSQL_URL" } } },
46
+ providers: { chatgpt: {} }, // Or { credentialFile: "/private/chatgpt.json" }.
47
+ tools: { mcp: { drift: { url: "http://127.0.0.1:3000/mcp" } } },
48
+ presets: { drift: {
49
+ provider: "chatgpt", model: "gpt-6.1-sol", effort: "low", compactAt: 100000,
50
+ workspace: "/workspace", tools: ["drift_tool"], permissionMode: "bypass",
51
+ } },
52
+ });
53
+ const session = await rui.sessions.create({ preset: "drift" });
54
+ ```
55
+
56
+ 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
+ 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
+ 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:
71
+
72
+ ```ts
73
+ await Rui.connect({
74
+ store: { sqlite: { dir: "/data/store" } },
75
+ providers: { openai: { endpoint: "https://api.openai.com/v1/responses", key: "secret" } },
76
+ network: { caFile: "/trust.pem" },
77
+ tools: { mcp: { drift: { url: "http://127.0.0.1:3000/mcp", bearerToken: "token", callTimeoutMs: 30000 } } },
78
+ execution: { activeCapacity: 2, paused: true }, presets: {},
79
+ }, { binary: "/path/to/rui", lockWaitMs: 5000 });
80
+ ```
81
+
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) |
100
+
101
+ Secret strings are a TypeScript input convenience: the pipe serializer wraps each as `{ value: "secret" }`.
102
+ Explicit `{ value: "secret" }`, `{ file: "/private/key" }`, `{ env: "NAME" }`, and the generated owner/default forms are also accepted where the schema allows them.
103
+ 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.
106
+ 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
+ Literal keys, tokens and MySQL URLs travel only in stdin, never argv, environment or disk; an explicitly selected environment source is inherited instead.
108
+ 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.
109
+ Do not log settings or enable process dumps around secrets.
110
+
111
+ OS-byte paths and secret-source environment names accept `string`, `Uint8Array` (including Node `Buffer`), or the generated closed `{ hex: "2fff" }` form.
112
+ Strings keep their UTF-8 encoding; byte arrays become lowercase hexadecimal objects without lossy decoding.
113
+ The client uses a private symlink alias for socket transport when a caller chooses an interface directory, so non-UTF-8 interface bytes do not pass through Node's string-only socket path API.
114
+ The Host still applies each Adapter's path restrictions: byte-capable transport does not make a non-UTF-8 SQLite canonical Store identity valid.
115
+
116
+ `network.caFile` names a PEM file to trust exclusively instead of system CAs, on macOS as on Linux.
117
+ Omit it or use `null` for system trust; an empty string is not a reset and is refused by provider transport validation.
118
+ Relative paths use the Host's working directory, and a file that cannot be loaded or a peer that cannot be verified fails without falling back to system trust.
119
+ MySQL URLs have the form `mysql://USER:PASSWORD@HOST[:PORT]/DATABASE`.
35
120
  For a Unix socket, use its percent-encoded absolute path in place of HOST; TCP verifies TLS.
36
121
  For MySQL TCP URLs, the only query option is `ssl-ca=/absolute/path/to/ca.pem` (the path may be percent-encoded), which replaces system trust with that PEM bundle alone; socket URLs and verification-disabling options are refused.
37
122
  The MySQL database must already contain the DDL from `rui store schema --engine mysql`.
38
- The key, tokens and MySQL URL never reach the child's argv, environment or disk.
39
- Readiness discovers the MySQL Store's stable opaque id, which the client uses on requests instead of the URL.
123
+ The client waits for its own child's readiness instance and verifies that exact instance over the socket before adopting a Host; an existing Host in a caller-supplied interface directory is never substituted.
124
+ Readiness discovers the Host's canonical Store identity, which the client uses on subsequent requests; MySQL uses its stable opaque id, never the URL.
40
125
  MySQL readiness also reports `innodb_doublewrite`, including `OFF`.
41
- The child gets only `PATH`, `HOME` and `TMPDIR` from your environment.
42
126
  Shell commands the agent runs execute as your user; Rui is not a sandbox.
43
127
 
44
- The child lives as long as its stdin stays open, so it stops when your process ends.
128
+ With the default `interface.lifetime: "stdin"`, the Host stops when your process ends.
129
+ 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.
45
130
  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.
46
131
  Automatic restarts retry `store_locked` and `mysql_unreachable`; calls waiting on a failed attempt receive `RuiUnavailableError`.
47
132
  Initial connect still rejects `mysql_unreachable` immediately.
@@ -78,12 +163,12 @@ Pass an AbortSignal as `signal` to end the iterator immediately even while it sl
78
163
 
79
164
  ## Development
80
165
 
81
- `src/wire.ts` is generated from the repository's `openapi.json`, which the Host build emits from its wire types.
166
+ `src/wire.ts` and the runtime input-codec descriptor `src/settings-kinds.ts` are generated from the repository's `openapi.json`, which the Host build emits from its types.
82
167
 
83
168
  ```sh
84
169
  npm ci
85
170
  npm run generate # after openapi.json changes
86
- npm run check # wire.ts is fresh, and the package type-checks
171
+ npm run check # both generated files are fresh, and the package type-checks
87
172
  RUI_BINARY=../../zig-out/bin/rui npm test
88
173
  ```
89
174
 
@@ -91,7 +176,8 @@ RUI_BINARY=../../zig-out/bin/rui npm test
91
176
  It publishes nothing. `node scripts/publish.mjs <dir>` publishes them, dependencies first, skipping versions npm already has; each release runs it in the `npm_publish` job.
92
177
 
93
178
  The repository's `zig build ts-client` runs the tests against the Rui it builds.
94
- The real-Host feed test uses a local HTTPS provider and the `openssl` command to generate its temporary test certificate; no live provider credentials are needed.
179
+ The real-Host feed and settings tests use local HTTPS providers and `openssl` for temporary certificates; no live provider credentials are needed.
180
+ The settings process test also runs on MySQL when `RUI_TEST_MYSQL_SOCKET`, `RUI_TEST_MYSQL_ROOT_PASSWORD` and `RUI_TEST_MYSQL_ADMIN` are supplied by the existing live-engine suite.
95
181
 
96
182
  ## Session settings
97
183
 
@@ -124,8 +210,8 @@ Creation copies the preset, with every supplied field (including `null`) overrid
124
210
 
125
211
  ```ts
126
212
  const rui = await Rui.connect({
127
- database: "/var/lib/myapp/rui-store",
128
- provider: { baseUrl: "https://api.openai.com/v1", key: process.env.OPENAI_API_KEY! },
213
+ store: { sqlite: { dir: "/var/lib/myapp/rui-store" } },
214
+ providers: { openai: { endpoint: "https://api.openai.com/v1/responses", key: process.env.OPENAI_API_KEY! } },
129
215
  presets: {
130
216
  review: { model: "gpt-6.1-sol", effort: "low", compactAt: 100000, tools: [], permissionMode: "ask" },
131
217
  },
package/dist/client.d.ts CHANGED
@@ -1,38 +1,17 @@
1
1
  import { EventEmitter } from "node:events";
2
+ import { type HostSettings } from "./settings.ts";
2
3
  import { SessionNotifications } from "./notifications.ts";
3
4
  import { RuiStartError } from "./errors.ts";
4
- import { Session, Sessions, type AgentSpec, type ModelSummary } from "./sessions.ts";
5
+ import { Session, Sessions, type ModelSummary } from "./sessions.ts";
5
6
  import { type ReplyLimits } from "./transport.ts";
6
7
  import type { components } from "./wire.ts";
7
8
  type Schemas = components["schemas"];
8
- export interface McpServer {
9
- name: string;
10
- url: string;
11
- bearerToken: string;
12
- callTimeoutMs: number;
13
- }
14
- export interface ConnectOptions {
15
- /** The MCP servers whose tools Sessions may name. */
16
- tools?: McpServer[];
17
- /** The Store: a SQLite directory or a mysql:// URL, sent only in the stdin launch frame.
18
- * MySQL TCP accepts only ssl-ca=<absolute PEM path> (percent encoding allowed) for exclusive CA trust; sockets refuse it and verification cannot be disabled. */
19
- database: string;
20
- /** The OpenAI-compatible provider. Only the key Adapter is offered to a launched Host (D149). */
21
- provider: {
22
- baseUrl: string;
23
- key: string;
24
- /** Trust only this PEM file for this provider, instead of system CAs. Sent in the launch frame. */
25
- caFile?: string;
26
- };
27
- /** How many Turns may run at once. Left out, the Host picks its default. */
28
- activeCapacity?: number;
29
- /** Named creation specs, held only by this Host. No default preset is selected. */
30
- presets?: Record<string, AgentSpec>;
31
- /** How long connect keeps retrying while another Host holds the Store (D183, D198). Default 120 000. */
9
+ export type { HostSettings } from "./settings.ts";
10
+ /** Options belonging to the client, not the Host settings document. */
11
+ export interface ClientOptions {
12
+ /** How long connect retries another Host's Store lock. Default 120 000 ms. */
32
13
  lockWaitMs?: number;
33
- /** Opens the Host with Turns held, as if `rui.pause()` had just run (D196); `rui.resume()` lifts it. A restarted Host opens paused again. */
34
- paused?: boolean;
35
- /** The `rui` executable. Default: the one from the installed platform package, else `rui` on PATH. */
14
+ /** Default: the installed platform package's executable, else rui on PATH. */
36
15
  binary?: string;
37
16
  }
38
17
  /** Fires on every child exit, including one the client restarts from (D129). */
@@ -44,9 +23,11 @@ export interface ExitEvent {
44
23
  type HostInfo = components["schemas"]["HostInfoReply"];
45
24
  interface Launch {
46
25
  binary: string;
47
- frame: Schemas["LaunchFrame"];
26
+ document: Buffer;
27
+ interfaceDir: NonNullable<NonNullable<Schemas["HostSettings"]["interface"]>["dir"]>;
28
+ aliasReady?: Promise<void>;
29
+ detached: boolean;
48
30
  socketPath: string;
49
- store: string;
50
31
  env: NodeJS.ProcessEnv;
51
32
  }
52
33
  export declare class Rui extends EventEmitter<{
@@ -59,7 +40,7 @@ export declare class Rui extends EventEmitter<{
59
40
  readonly sessions: Sessions;
60
41
  private constructor();
61
42
  /** Starts Rui as a child of this process and resolves once it is ready. */
62
- static connect(options: ConnectOptions): Promise<Rui>;
43
+ static connect(settings: HostSettings, options?: ClientOptions): Promise<Rui>;
63
44
  /** A handle on an existing Session. Does no I/O: an unknown id fails on the first call (D16). */
64
45
  getSession(id: string): Session;
65
46
  /** The models each provider offers. */
@@ -89,9 +70,10 @@ export declare class Rui extends EventEmitter<{
89
70
  /** The latest host-info reply. Internal. */
90
71
  get hostInfo(): HostInfo | undefined;
91
72
  }
92
- export declare function launchFor(options: ConnectOptions, runtimeDir: string): Launch;
73
+ export declare function launchFor(settings: HostSettings, runtimeDir: string, options?: ClientOptions): Launch;
93
74
  /** One length-prefixed JSON frame: a 4-byte big-endian length, then UTF-8 JSON (D130). */
94
- export declare function encodeFrame(frame: Schemas["LaunchFrame"]): Buffer;
75
+ export declare function encodeSettings(document: Schemas["HostSettings"]): Buffer;
76
+ /** Only the fixed leading child receipt is authoritative; later path bytes are not records. */
77
+ export declare function readinessInstance(prefix: Buffer): string | undefined;
95
78
  /** The refusal a child wrote as its one stdout line, `{"rui_start_error":{code,message}}` (D211). */
96
79
  export declare function startError(output: string): RuiStartError | undefined;
97
- export {};
package/dist/client.js CHANGED
@@ -1,21 +1,22 @@
1
- // Rui.connect starts the Host as a child of this process, hands it the launch
2
- // frame on stdin and waits until it answers host-info on the socket in its
3
- // private runtimeDir (D107, D112, D130, D131). The child lives as long as its
4
- // stdin stays open (D5, D118). A child that exits on its own is restarted with
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
5
6
  // capped backoff, and calls in flight are retried once the new Host is ready;
6
7
  // every write carries a request key, so a retry is safe (D118, D129).
7
8
  import { spawn } from "node:child_process";
8
9
  import { EventEmitter } from "node:events";
9
- import { mkdtemp, realpath, rm, stat } from "node:fs/promises";
10
+ import { mkdtemp, rm, stat, symlink } from "node:fs/promises";
10
11
  import { tmpdir } from "node:os";
11
- import { join, resolve } from "node:path";
12
+ import { dirname, join } from "node:path";
12
13
  import { setTimeout as sleep } from "node:timers/promises";
14
+ import { pipeSettings } from "./settings.js";
13
15
  import { SessionNotifications } from "./notifications.js";
14
16
  import { resolveBinary } from "./binary.js";
15
17
  import { RuiStartError, RuiUnavailableError } from "./errors.js";
16
18
  import { agentSpec, models, Session, Sessions, setPaused } from "./sessions.js";
17
19
  import { ConnectionError, post, WIRE_VERSION } from "./transport.js";
18
- const FRAME_VERSION = 1;
19
20
  const SOCKET_NAME = "rui.sock";
20
21
  const DEFAULT_LOCK_WAIT_MS = 120_000;
21
22
  const LOCK_RETRY_MS = 500;
@@ -24,6 +25,7 @@ const MAX_RESTART_MS = 30_000;
24
25
  /** The Host bounds its own shutdown at 10 s (D118); this leaves room for the exit to arrive. */
25
26
  const CLOSE_GRACE_MS = 15_000;
26
27
  const READY_POLL_MS = 25;
28
+ const READINESS_RECEIPT_BYTES = Buffer.byteLength("ready instance=") + 32 + 1;
27
29
  /** How long a refused connection waits for the child's exit before it counts as unanswered. */
28
30
  const EXIT_NOTICE_MS = 2_000;
29
31
  /** Transient refusals during automatic restart, not initial connect. */
@@ -60,10 +62,11 @@ export class Rui extends EventEmitter {
60
62
  this.#adopt(host);
61
63
  }
62
64
  /** Starts Rui as a child of this process and resolves once it is ready. */
63
- static async connect(options) {
65
+ static async connect(settings, options = {}) {
64
66
  const runtimeDir = await mkdtemp(join(tmpdir(), "rui-"));
67
+ let launch;
65
68
  try {
66
- const launch = launchFor(options, runtimeDir);
69
+ launch = launchFor(settings, runtimeDir, options);
67
70
  const deadline = Date.now() + (options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS);
68
71
  for (;;) {
69
72
  try {
@@ -79,6 +82,8 @@ export class Rui extends EventEmitter {
79
82
  }
80
83
  }
81
84
  catch (error) {
85
+ if (launch)
86
+ disposeLaunch(launch);
82
87
  await rm(runtimeDir, { recursive: true, force: true });
83
88
  throw error;
84
89
  }
@@ -111,15 +116,22 @@ export class Rui extends EventEmitter {
111
116
  this.#fail(new RuiUnavailableError("the Rui client is closed"));
112
117
  const child = this.#child;
113
118
  this.#host = undefined;
114
- if (child && child.exitCode === null && child.signalCode === null) {
115
- const exited = exitOf(child);
116
- child.stdin?.end();
117
- const timer = setTimeout(() => child.kill("SIGKILL"), CLOSE_GRACE_MS);
118
- const exit = await exited;
119
- clearTimeout(timer);
120
- this.emit("exit", { ...exit, restarting: false });
119
+ try {
120
+ if (child && child.exitCode === null && child.signalCode === null) {
121
+ const exited = exitOf(child);
122
+ child.stdin?.end();
123
+ if (this.#launch.detached)
124
+ child.kill("SIGTERM");
125
+ const timer = setTimeout(() => child.kill("SIGKILL"), CLOSE_GRACE_MS);
126
+ const exit = await exited;
127
+ clearTimeout(timer);
128
+ this.emit("exit", { ...exit, restarting: false });
129
+ }
130
+ }
131
+ finally {
132
+ disposeLaunch(this.#launch);
133
+ await rm(this.#runtimeDir, { recursive: true, force: true });
121
134
  }
122
- await rm(this.#runtimeDir, { recursive: true, force: true });
123
135
  }
124
136
  /**
125
137
  * Sends one request to the ready Host. A call that finds the child gone
@@ -229,36 +241,84 @@ export class Rui extends EventEmitter {
229
241
  if (retryable)
230
242
  return this.#scheduleRestart();
231
243
  this.#dead = new RuiUnavailableError(`the Rui Host cannot restart: ${error.message}`, { cause: error });
244
+ disposeLaunch(this.#launch);
232
245
  }
233
246
  }
234
247
  }
235
- export function launchFor(options, runtimeDir) {
236
- // A URL is passed through; anything else is a SQLite Store directory.
237
- const store = /^[a-z][a-z0-9+.-]*:\/\//i.test(options.database) ? options.database : resolve(options.database);
238
- const frame = {
239
- v: FRAME_VERSION,
240
- store,
241
- runtimeDir,
242
- ...(options.activeCapacity === undefined ? {} : { activeCapacity: options.activeCapacity }),
243
- ...(options.paused ? { paused: true } : {}),
244
- ...(options.presets === undefined ? {} : {
245
- presets: Object.fromEntries(Object.entries(options.presets).map(([name, spec]) => [name, presetFor(spec)])),
246
- }),
247
- provider: {
248
- kind: "openai_key", baseUrl: options.provider.baseUrl, key: options.provider.key,
249
- ...(options.provider.caFile === undefined ? {} : { caFile: options.provider.caFile }),
250
- },
251
- // Only the Host's fields are copied: it refuses unknown ones.
252
- mcpServers: (options.tools ?? []).map(({ name, url, bearerToken, callTimeoutMs }) => ({ name, url, bearerToken, callTimeoutMs })),
253
- };
254
- // The child gets only what it needs to find programs and its home (D185).
255
- const env = {};
248
+ export function launchFor(settings, runtimeDir, options = {}) {
249
+ // Inherit program/home lookup plus only the secret sources this document names.
250
+ const env = Object.create(null);
256
251
  for (const name of ["PATH", "HOME", "TMPDIR"]) {
257
252
  const value = process.env[name];
258
253
  if (value !== undefined)
259
254
  env[name] = value;
260
255
  }
261
- return { binary: resolveBinary(options.binary), frame, socketPath: join(runtimeDir, SOCKET_NAME), store, env };
256
+ let document = pipeSettings(settings, (source, path) => {
257
+ const name = environmentName(source, path);
258
+ if (name === undefined)
259
+ return;
260
+ const value = process.env[name];
261
+ if (value !== undefined)
262
+ env[name] = value;
263
+ });
264
+ let interfaceDir = runtimeDir;
265
+ let detached = false;
266
+ if (document !== null && typeof document === "object" && !Array.isArray(document)) {
267
+ if (Object.hasOwn(document, "presets") && document.presets !== undefined) {
268
+ // Presets retain their existing friendly spec writer after settings normalization.
269
+ const presets = document.presets;
270
+ document = { ...document, presets: Object.fromEntries(Object.entries(presets).map(([name, spec]) => [name, presetFor(spec)])) };
271
+ }
272
+ const supplied = Object.hasOwn(document, "interface") && document.interface !== undefined ? document.interface : {};
273
+ if (supplied !== null && typeof supplied === "object" && !Array.isArray(supplied)) {
274
+ // Choose client defaults once, from canonical own data; invalid groups reach the Host unchanged.
275
+ const selected = {
276
+ ...supplied,
277
+ ...(!Object.hasOwn(supplied, "dir") || supplied.dir == null ? { dir: runtimeDir } : {}),
278
+ ...(!Object.hasOwn(supplied, "lifetime") || supplied.lifetime === undefined ? { lifetime: "stdin" } : {}),
279
+ };
280
+ document = { ...document, interface: selected };
281
+ interfaceDir = selected.dir; // The single default choice above supplies every omitted/null directory.
282
+ detached = selected.lifetime !== "stdin";
283
+ }
284
+ }
285
+ return {
286
+ binary: resolveBinary(options.binary), document: encodeSettings(document), interfaceDir,
287
+ socketPath: join(runtimeDir, "interface", SOCKET_NAME), env, detached,
288
+ };
289
+ }
290
+ /** Release all restart-owned secret bytes/references on every terminal transition. */
291
+ function disposeLaunch(launch) {
292
+ launch.document.fill(0);
293
+ for (const name of Object.keys(launch.env))
294
+ delete launch.env[name];
295
+ }
296
+ /** Consume the byte codec's canonical JSON value before allowing any Node environment lookup.
297
+ * Malformed values stay in the document for Host refusal; Host bounds remain its own. */
298
+ function environmentName(source, path) {
299
+ let name;
300
+ if (typeof source === "string")
301
+ name = source;
302
+ else {
303
+ if (source === null || typeof source !== "object")
304
+ return undefined;
305
+ const fields = Object.keys(source);
306
+ if (fields.length !== 1 || fields[0] !== "hex")
307
+ return undefined;
308
+ const hex = source.hex;
309
+ if (typeof hex !== "string")
310
+ return undefined;
311
+ if (hex.length % 2 !== 0 || /[^0-9a-f]/.test(hex))
312
+ return undefined;
313
+ try {
314
+ name = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(Buffer.from(hex, "hex"));
315
+ }
316
+ catch {
317
+ throw new RuiStartError("settings_invalid", `${path}: Node requires UTF-8 environment names; use a file source for OS-byte names`);
318
+ }
319
+ }
320
+ // Node truncates NUL and replaces lone UTF-16 surrogates; neither may choose another key.
321
+ return name.length !== 0 && !/[\0=\uD800-\uDFFF]/u.test(name) ? name : undefined;
262
322
  }
263
323
  /** Presets and Session mutation requests use the same wire writer. */
264
324
  function presetFor(spec) {
@@ -268,7 +328,7 @@ function presetFor(spec) {
268
328
  async function start(launch, spawned) {
269
329
  let child;
270
330
  try {
271
- child = spawn(launch.binary, ["host", "serve", "--launch-frame"], {
331
+ child = spawn(launch.binary, ["host", "serve", "--settings", "-"], {
272
332
  env: launch.env,
273
333
  stdio: ["pipe", "pipe", "inherit"],
274
334
  });
@@ -278,7 +338,25 @@ async function start(launch, spawned) {
278
338
  }
279
339
  spawned(child);
280
340
  const stdout = [];
281
- child.stdout?.on("data", (chunk) => stdout.push(chunk));
341
+ // This fixed prefix precedes every caller-controlled path in the child's record.
342
+ const receipt = Buffer.alloc(READINESS_RECEIPT_BYTES);
343
+ let receiptBytes = 0;
344
+ let readyInstance;
345
+ let outputBytes = 0;
346
+ const capture = (chunk) => {
347
+ if (receiptBytes < receipt.length) {
348
+ receiptBytes += chunk.copy(receipt, receiptBytes, 0, receipt.length - receiptBytes);
349
+ if (receiptBytes === receipt.length)
350
+ readyInstance = readinessInstance(receipt);
351
+ }
352
+ if (outputBytes + chunk.length <= 64 * 1024) {
353
+ stdout.push(chunk);
354
+ outputBytes += chunk.length;
355
+ }
356
+ else
357
+ chunk.fill(0);
358
+ };
359
+ child.stdout?.on("data", capture);
282
360
  const outputEnded = new Promise((done) => child.stdout?.once("close", done));
283
361
  const launchError = new Promise((done) => child.once("error", done));
284
362
  const exited = exitOf(child);
@@ -287,62 +365,97 @@ async function start(launch, spawned) {
287
365
  child.stdout?.unref();
288
366
  child.stdin?.unref();
289
367
  child.stdin?.on("error", () => { });
290
- child.stdin?.write(encodeFrame(launch.frame));
291
- let ended;
292
- void exited.then((exit) => (ended ??= exit));
293
- void launchError.then((error) => (ended ??= error));
294
- while (ended === undefined) {
295
- const info = await probe(launch).catch((error) => {
296
- if (error instanceof ConnectionError)
297
- return undefined;
298
- child.kill("SIGKILL");
299
- throw new AttemptFailed(error, undefined);
300
- });
301
- if (info)
302
- return { child, instance: info.instance, info, exited };
303
- await sleep(READY_POLL_MS);
368
+ // write owns this copy until its callback; retain the restart document separately.
369
+ const bytes = Buffer.from(launch.document);
370
+ const wipeWrite = () => bytes.fill(0);
371
+ child.stdin?.once("close", wipeWrite);
372
+ child.stdin?.write(bytes, () => {
373
+ bytes.fill(0);
374
+ child.stdin?.off("close", wipeWrite);
375
+ });
376
+ try {
377
+ let ended;
378
+ void exited.then((exit) => (ended ??= exit));
379
+ void launchError.then((error) => (ended ??= error));
380
+ while (ended === undefined) {
381
+ const info = readyInstance === undefined ? undefined : await probe(launch, readyInstance).catch(async (error) => {
382
+ if (error instanceof ConnectionError)
383
+ return undefined;
384
+ child.kill("SIGKILL");
385
+ throw new AttemptFailed(error, await exited);
386
+ });
387
+ if (info)
388
+ return { child, instance: info.instance, info, exited };
389
+ await sleep(READY_POLL_MS);
390
+ }
391
+ if (ended instanceof Error) {
392
+ throw new AttemptFailed(new RuiUnavailableError(`could not start ${launch.binary}: ${ended.message}`, { cause: ended }), undefined);
393
+ }
394
+ // The refusal line is written before the exit; give the pipe a moment to deliver it.
395
+ await Promise.race([outputEnded, sleep(1_000)]);
396
+ const output = Buffer.concat(stdout);
397
+ let refusal;
398
+ try {
399
+ refusal = startError(output.toString("utf8"));
400
+ }
401
+ finally {
402
+ output.fill(0);
403
+ }
404
+ throw new AttemptFailed(refusal ?? new RuiUnavailableError(`rui exited before it was ready (code ${ended.code}, signal ${ended.signal})`), ended);
304
405
  }
305
- if (ended instanceof Error) {
306
- throw new AttemptFailed(new RuiUnavailableError(`could not start ${launch.binary}: ${ended.message}`, { cause: ended }), undefined);
406
+ finally {
407
+ child.stdout?.off("data", capture);
408
+ child.stdout?.on("data", (chunk) => chunk.fill(0));
409
+ receipt.fill(0);
410
+ for (const chunk of stdout)
411
+ chunk.fill(0);
412
+ stdout.length = 0;
307
413
  }
308
- // The refusal line is written before the exit; give the pipe a moment to deliver it.
309
- await Promise.race([outputEnded, sleep(1_000)]);
310
- const refusal = startError(Buffer.concat(stdout).toString("utf8"));
311
- throw new AttemptFailed(refusal ?? new RuiUnavailableError(`rui exited before it was ready (code ${ended.code}, signal ${ended.signal})`), ended);
312
414
  }
313
- async function probe(launch) {
415
+ /** Readiness proves the Host admitted the path; decoding and alias effects belong after it. */
416
+ async function createInterfaceAlias(launch) {
417
+ const dir = launch.interfaceDir;
418
+ const target = typeof dir === "string" ? dir : Buffer.from(dir.hex, "hex");
419
+ // An ASCII alias lets Node's string-only socket API reach OS-byte directories.
420
+ await symlink(target, dirname(launch.socketPath));
421
+ }
422
+ async function probe(launch, instance) {
423
+ await (launch.aliasReady ??= createInterfaceAlias(launch));
314
424
  try {
315
425
  await stat(launch.socketPath);
316
426
  }
317
427
  catch {
318
428
  return undefined;
319
429
  }
320
- // The Host names a SQLite Store by its canonical path, which exists once the socket does.
321
- let store = launch.store.startsWith("mysql://") ? "" : launch.store;
322
- if (store !== "" && !store.includes("://")) {
323
- try {
324
- store = await realpath(store);
325
- }
326
- catch {
327
- return undefined;
328
- }
329
- }
330
430
  const body = JSON.stringify({
331
431
  version: WIRE_VERSION,
332
432
  kind: "host_info",
333
- store,
433
+ store: "",
334
434
  });
335
- const reply = await post({ socketPath: launch.socketPath, path: "/v1/host-info", body });
336
- return JSON.parse(reply.toString("utf8"));
435
+ const reply = await post({ socketPath: launch.socketPath, path: "/v1/host-info", body, instance });
436
+ const info = JSON.parse(reply.toString("utf8"));
437
+ if (info.instance !== instance)
438
+ throw new RuiUnavailableError("the Host socket did not match the started child's readiness instance");
439
+ return info;
337
440
  }
338
441
  /** One length-prefixed JSON frame: a 4-byte big-endian length, then UTF-8 JSON (D130). */
339
- export function encodeFrame(frame) {
340
- const json = Buffer.from(JSON.stringify(frame));
341
- const out = Buffer.alloc(4 + json.length);
342
- out.writeUInt32BE(json.length, 0);
343
- json.copy(out, 4);
344
- json.fill(0);
345
- return out;
442
+ export function encodeSettings(document) {
443
+ const json = Buffer.from(JSON.stringify(document));
444
+ try {
445
+ const out = Buffer.alloc(4 + json.length);
446
+ out.writeUInt32BE(json.length, 0);
447
+ json.copy(out, 4);
448
+ return out;
449
+ }
450
+ finally {
451
+ json.fill(0);
452
+ }
453
+ }
454
+ /** Only the fixed leading child receipt is authoritative; later path bytes are not records. */
455
+ export function readinessInstance(prefix) {
456
+ if (prefix.length !== READINESS_RECEIPT_BYTES)
457
+ return undefined;
458
+ return /^ready instance=([0-9a-f]{32}) $/.exec(prefix.toString("latin1"))?.[1];
346
459
  }
347
460
  /** The refusal a child wrote as its one stdout line, `{"rui_start_error":{code,message}}` (D211). */
348
461
  export function startError(output) {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Rui, type ConnectOptions, type ExitEvent, type McpServer } from "./client.ts";
1
+ export { Rui, type HostSettings, type ClientOptions, type ExitEvent } from "./client.ts";
2
2
  export { RuiRequestError, RuiStartError, RuiUnavailableError } from "./errors.ts";
3
3
  export { Session, Sessions, type AgentSpec, type ListSessionsOptions, type SessionArchiveState, type SessionArchiveResult, 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";
@@ -80,6 +80,7 @@ type CurrentReport = Extract<Schemas["InspectSessionReply"], {
80
80
  /** Current Host facts. Decimal counts, times and IDs remain lossless strings. */
81
81
  export interface SessionStatus {
82
82
  archiveState: SessionArchiveState;
83
+ /** `working` includes owed attached-tree work, including unpublished child endings. */
83
84
  state: CurrentReport["work"]["state"]["kind"];
84
85
  since: CurrentReport["work"]["state"]["since"];
85
86
  turn: CurrentReport["work"]["turn"];