@muse-code/sdk 1.4.14 → 1.4.15

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
@@ -48,20 +48,40 @@ exact version, and read the changelog before moving off it.
48
48
  import { MuseClient } from "@muse-code/sdk";
49
49
 
50
50
  const client = await MuseClient.spawn({
51
- museBin: "muse",
52
51
  args: ["serve"],
53
52
  clientInfo: { name: "my-app", version: "1.0.0" },
54
53
  });
55
54
 
56
55
  const session = await client.startSession({ workspaceRoot: process.cwd() });
57
56
 
57
+ const result = await session.run("Summarize this repository.");
58
+ console.log(result.finalText);
59
+
60
+ await client.close();
61
+ ```
62
+
63
+ `session.run` sends one turn and resolves when the turn has ended, with the
64
+ outcome, the final answer text, the turn's items, and its token usage. A turn
65
+ that failed or was cancelled still resolves; read `result.outcome` to tell.
66
+ The final answer is the last completed agent message that is not commentary.
67
+ Pass input parts instead of a string, and the turn options as the second
68
+ argument:
69
+ `session.run(parts, { reasoningEffort: "high" })`.
70
+
71
+ To stop it, pass an `AbortSignal`, for example
72
+ `session.run(prompt, { signal: AbortSignal.timeout(60_000) })`. A turn still
73
+ waiting in the queue is taken back, and a running turn is cancelled. `run`
74
+ then waits for the turn to end and rejects with the signal's reason. An
75
+ already-aborted signal sends nothing.
76
+
77
+ To follow a turn as it runs, send it yourself and read its items:
78
+
79
+ ```ts
58
80
  const turn = await session.sendUserTurn({
59
81
  input: [{ type: "text", text: "Summarize this repository." }],
60
82
  });
61
83
  for await (const item of turn.items()) console.log(item);
62
84
  await turn.completed;
63
-
64
- await client.close();
65
85
  ```
66
86
 
67
87
  `turn.items()` replays what the session already holds before its live tail;
@@ -113,10 +133,25 @@ if (prompt !== undefined && question !== undefined) {
113
133
  }
114
134
  ```
115
135
 
136
+ To stop a running turn, call `turn.interrupt()` (the stop gesture; pass
137
+ `{ retract: true }` to also take the prompt back) or `turn.cancel()`. Both are
138
+ requests: the turn is over when `turn.completed` settles. `turn.steer({ input })`
139
+ adds input to the running turn, and `turn.unqueue()` takes back a queued one.
140
+ The session itself can `fork`, `compact`, `rename`, and `leave`, and switch its
141
+ model, reasoning effort, or approval mode (`setModel`, `setReasoningEffort`,
142
+ `setApprovalMode`); `client.listModels()` lists the models it accepts.
143
+
116
144
  Status: developer preview. The facade — spawn, session open/resume, turns,
117
145
  approvals, questions, and recovery after dropped deliveries — is complete and covered by
118
146
  the conformance suites in the source repository.
119
147
 
148
+ ## Not yet available
149
+
150
+ `@muse-code/acp` is not published on npm and is not part of this public
151
+ repository. There is no supported ACP adapter to install today; please do not
152
+ depend on that package name. If an ACP adapter ships, it will be announced in
153
+ a public release.
154
+
120
155
  ## Documentation
121
156
 
122
157
  - Guides, cookbook recipes, and the protocol reference:
@@ -131,7 +131,8 @@ export function createUuidV7Mint() {
131
131
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
132
132
  };
133
133
  }
134
- async function defaultRetryDelay(attempt) {
134
+ /** @internal The jittered backoff `command` retries with; `Session.run` reuses it. */
135
+ export async function defaultRetryDelay(attempt) {
135
136
  const ceilingMs = Math.min(2_000, 50 * 2 ** Math.max(0, attempt - 1));
136
137
  const delayMs = Math.floor(Math.random() * (ceilingMs + 1));
137
138
  await new Promise((resolve) => setTimeout(resolve, delayMs));
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Host discovery for `MuseClient.spawn` (FR-79107-1), mirroring the Rust SDK's
3
+ * `discover_muse_bin` and the Python SDK's: an explicit `museBin` wins and is
4
+ * returned verbatim (existence is the spawn's to prove), else the first
5
+ * executable `muse` on the process `PATH` — `muse.exe` on Windows, as in Rust.
6
+ * The package does not bundle a host, so no host is a typed error raised
7
+ * before any process is started.
8
+ */
9
+ /**
10
+ * Resolve the host binary. `path` and `platform` are parameters, not reads, so
11
+ * tests drive them; `MuseClient.spawn` passes the process's own. An empty
12
+ * `PATH` entry is skipped rather than read as the working directory.
13
+ */
14
+ export declare function discoverMuseBin(museBin: string | undefined, path: string | undefined, platform: NodeJS.Platform): Promise<string>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Host discovery for `MuseClient.spawn` (FR-79107-1), mirroring the Rust SDK's
3
+ * `discover_muse_bin` and the Python SDK's: an explicit `museBin` wins and is
4
+ * returned verbatim (existence is the spawn's to prove), else the first
5
+ * executable `muse` on the process `PATH` — `muse.exe` on Windows, as in Rust.
6
+ * The package does not bundle a host, so no host is a typed error raised
7
+ * before any process is started.
8
+ */
9
+ import { stat } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { MuseHostDiscoveryError } from "../errors.js";
12
+ /**
13
+ * Resolve the host binary. `path` and `platform` are parameters, not reads, so
14
+ * tests drive them; `MuseClient.spawn` passes the process's own. An empty
15
+ * `PATH` entry is skipped rather than read as the working directory.
16
+ */
17
+ export async function discoverMuseBin(museBin, path, platform) {
18
+ if (museBin !== undefined)
19
+ return museBin;
20
+ const windows = platform === "win32";
21
+ const name = windows ? "muse.exe" : "muse";
22
+ for (const directory of (path ?? "").split(windows ? ";" : ":")) {
23
+ if (directory === "")
24
+ continue;
25
+ const candidate = join(directory, name);
26
+ if (await isExecutable(candidate, windows))
27
+ return candidate;
28
+ }
29
+ throw new MuseHostDiscoveryError();
30
+ }
31
+ async function isExecutable(candidate, windows) {
32
+ try {
33
+ const found = await stat(candidate);
34
+ return found.isFile() && (windows || (found.mode & 0o111) !== 0);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
@@ -69,3 +69,40 @@ export declare class PermissionProfileNotApplied extends Error {
69
69
  readonly sessionId: string;
70
70
  constructor(requested: string, served: string | null, sessionId: string);
71
71
  }
72
+ /** The developer-docs compatibility page the host-discovery error cites. */
73
+ export declare const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/compatibility/";
74
+ /**
75
+ * No host binary was given and no executable `muse` is on `PATH` (FR-79107-1).
76
+ * Raised by `MuseClient.spawn` before any process is started. The package does
77
+ * not bundle a host; install Muse Code or pass `museBin`.
78
+ */
79
+ export declare class MuseHostDiscoveryError extends Error {
80
+ /** The spawn option that names an explicit host path. */
81
+ readonly parameter = "museBin";
82
+ /** The page listing the host versions this SDK supports. */
83
+ readonly compatibilityUrl = "https://meta-models.github.io/muse-code-sdk/compatibility/";
84
+ constructor();
85
+ }
86
+ /**
87
+ * `MuseClient.command` was asked to send a method whose state the facade owns
88
+ * (FR-79107-2). Sending it raw would bypass that state, so it is refused
89
+ * before anything is written; use the facade verb instead.
90
+ */
91
+ export declare class MuseFacadeOwnedMethodError extends Error {
92
+ /** The refused wire method. */
93
+ readonly method: string;
94
+ constructor(method: string);
95
+ }
96
+ /**
97
+ * A session open asked for something the host did not grant on this
98
+ * connection (FR-79107-3): today, per-session MCP servers (`config.mcpServers`)
99
+ * without the `sessionMcp` capability. Refused before anything is sent; the
100
+ * client stays usable, and an open without that request still goes through.
101
+ */
102
+ export declare class MuseCapabilityNotGrantedError extends Error {
103
+ /** The capability the request needs. */
104
+ readonly capability: string;
105
+ /** The wire method that was refused. */
106
+ readonly method: string;
107
+ constructor(capability: string, method: string, reason: string);
108
+ }
@@ -74,3 +74,55 @@ export class PermissionProfileNotApplied extends Error {
74
74
  this.sessionId = sessionId;
75
75
  }
76
76
  }
77
+ /** The developer-docs compatibility page the host-discovery error cites. */
78
+ export const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/compatibility/";
79
+ /**
80
+ * No host binary was given and no executable `muse` is on `PATH` (FR-79107-1).
81
+ * Raised by `MuseClient.spawn` before any process is started. The package does
82
+ * not bundle a host; install Muse Code or pass `museBin`.
83
+ */
84
+ export class MuseHostDiscoveryError extends Error {
85
+ /** The spawn option that names an explicit host path. */
86
+ parameter = "museBin";
87
+ /** The page listing the host versions this SDK supports. */
88
+ compatibilityUrl = COMPATIBILITY_PAGE_URL;
89
+ constructor() {
90
+ super("no muse host found: pass museBin=<path to a muse binary> or put `muse` on PATH. " +
91
+ "The package does not bundle a host; supported host versions are listed on the " +
92
+ `compatibility page's TypeScript row: ${COMPATIBILITY_PAGE_URL}`);
93
+ this.name = "MuseHostDiscoveryError";
94
+ }
95
+ }
96
+ /**
97
+ * `MuseClient.command` was asked to send a method whose state the facade owns
98
+ * (FR-79107-2). Sending it raw would bypass that state, so it is refused
99
+ * before anything is written; use the facade verb instead.
100
+ */
101
+ export class MuseFacadeOwnedMethodError extends Error {
102
+ /** The refused wire method. */
103
+ method;
104
+ constructor(method) {
105
+ super(`${method} is sent by the facade itself and cannot go through MuseClient.command; ` +
106
+ "use the facade verb that owns it");
107
+ this.name = "MuseFacadeOwnedMethodError";
108
+ this.method = method;
109
+ }
110
+ }
111
+ /**
112
+ * A session open asked for something the host did not grant on this
113
+ * connection (FR-79107-3): today, per-session MCP servers (`config.mcpServers`)
114
+ * without the `sessionMcp` capability. Refused before anything is sent; the
115
+ * client stays usable, and an open without that request still goes through.
116
+ */
117
+ export class MuseCapabilityNotGrantedError extends Error {
118
+ /** The capability the request needs. */
119
+ capability;
120
+ /** The wire method that was refused. */
121
+ method;
122
+ constructor(capability, method, reason) {
123
+ super(`${method} was not sent: ${reason}`);
124
+ this.name = "MuseCapabilityNotGrantedError";
125
+ this.capability = capability;
126
+ this.method = method;
127
+ }
128
+ }
@@ -35,21 +35,34 @@
35
35
  * chain close that gap — add a member upstream and the BUILD fails here until
36
36
  * it is forwarded (or explicitly allow-listed as unforwardable).
37
37
  */
38
- import type { Connection } from "../connection/connection.js";
38
+ import type { CommandOptions, Connection } from "../connection/connection.js";
39
39
  import type { ExitClassification, SpawnedMspConnection } from "../connection/spawn.js";
40
40
  import type { SessionDurabilityProfile } from "./host-death.js";
41
41
  import type { ApprovalFailureHandler, ApprovalHandler } from "./approval.js";
42
42
  import { Session } from "./session.js";
43
- import type { InitializeParams, InitializeResult, SessionResumeParams, SessionStartParams } from "../msp.js";
43
+ import type { InitializeParams, InitializeResult, ModelListParams, ModelListResult, MspMethod, SessionListParams, SessionListResult, SessionResumeParams, SessionStartParams, UsageReadResult } from "../msp.js";
44
+ /**
45
+ * The wire methods whose state the facade owns, refused by `command`
46
+ * (FR-79107-2). `initialize` is the handshake `spawn` runs; `session/start` and
47
+ * `session/resume` register the `Session` the pump routes to; `turn/start`,
48
+ * `turn/steer`, `turn/unqueue`, `approval/decide`, and `userInput/answer`
49
+ * carry the pending-command, approval, and answer state their verbs keep (a
50
+ * steer is a pending submission and an accepted unqueue retires its queued
51
+ * entry); `view/page` is the gap fill's; and
52
+ * `view/subscribe`/`view/unsubscribe` change the subscription set the pump
53
+ * routes by, so a raw unsubscribe would silently starve a live `Session`.
54
+ */
55
+ declare const FACADE_OWNED_METHODS: readonly ["initialize", "session/start", "session/resume", "turn/start", "turn/steer", "turn/unqueue", "approval/decide", "userInput/answer", "view/page", "view/subscribe", "view/unsubscribe"];
56
+ type FacadeOwnedMethod = (typeof FACADE_OWNED_METHODS)[number];
44
57
  /**
45
58
  * Caller-facing options for `session/start` (tdd SS2.5.1).
46
59
  *
47
- * `config` is excluded as well as `commandId` until the facade implements the
48
- * required `sessionMcp` grant check and forwarding; `previousSessionId` is
49
- * excluded because the facade starts root sessions, and `spawnedBy` because
50
- * the facade does not expose a spawner yet.
60
+ * `commandId` is excluded because the connection mints it; `previousSessionId`
61
+ * and `switchPolicy` because the facade starts root sessions, and `spawnedBy`
62
+ * because the facade does not expose a spawner yet. `config.mcpServers` needs
63
+ * the host's `sessionMcp` grant (FR-79107-3).
51
64
  */
52
- export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "config" | "previousSessionId" | "spawnedBy"> & {
65
+ export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "previousSessionId" | "switchPolicy" | "spawnedBy"> & {
53
66
  /**
54
67
  * Require the `permissionProfile` selection (TEST-42624-10): when set,
55
68
  * the client proves the committed selection equals the requested id —
@@ -60,8 +73,11 @@ export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId"
60
73
  */
61
74
  requirePermissionProfile?: boolean;
62
75
  }>;
63
- /** Caller-facing options for `session/resume` (tdd SS2.5.2). */
64
- export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId" | "config"> & {
76
+ /**
77
+ * Caller-facing options for `session/resume` (tdd SS2.5.2). `config.mcpServers`
78
+ * needs the host's `sessionMcp` grant, as at start (FR-79107-3).
79
+ */
80
+ export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId"> & {
65
81
  /**
66
82
  * Answers this session's approvals from its first frame, so an approval
67
83
  * the host re-sends right after the resume reply reaches it. The same
@@ -99,16 +115,25 @@ export interface MuseClientOptions {
99
115
  */
100
116
  readonly host?: SpawnedMspConnection;
101
117
  }
102
- /** What `MuseClient.spawn` needs: FR-018's `{ museBin, args?, env? }`, plus the handshake. */
118
+ /** What `MuseClient.spawn` needs: FR-018's `{ museBin?, args?, env? }`, plus the handshake. */
103
119
  export interface MuseClientSpawnOptions {
104
- readonly museBin: string;
120
+ /**
121
+ * The host binary. Omitted means the first executable `muse` on the
122
+ * process's `PATH` (FR-79107-1); with neither, `spawn` rejects with
123
+ * `MuseHostDiscoveryError` before starting anything.
124
+ */
125
+ readonly museBin?: string;
105
126
  readonly args?: readonly string[];
106
127
  readonly cwd?: string;
107
128
  /** REPLACES the child's environment (PATH included) — spread `process.env` to extend it. */
108
129
  readonly env?: NodeJS.ProcessEnv;
109
130
  /** Client identification, forwarded verbatim into `initialize` (SS1.4). */
110
131
  readonly clientInfo: InitializeParams["clientInfo"];
111
- /** Capability posture; absent means all defaults. */
132
+ /**
133
+ * Capability posture; absent means all defaults. `spawn` adds `sessionMcp`
134
+ * to `requestedCapabilities` (keeping yours) so per-session MCP servers can
135
+ * be granted (ADR 32760 D3).
136
+ */
112
137
  readonly capabilities?: InitializeParams["capabilities"];
113
138
  /** Raw stderr chunks, drained from process birth and never parsed (INV-010). */
114
139
  readonly onStderr?: (chunk: string) => void;
@@ -135,6 +160,9 @@ export declare class MuseClient {
135
160
  * absent/unrecognized distinction load-bearing, and a caller re-deriving it
136
161
  * by hand is a caller that can get it wrong.
137
162
  *
163
+ * Rejects with {@link MuseHostDiscoveryError} before starting anything when
164
+ * `museBin` is omitted and no executable `muse` is on `PATH`.
165
+ *
138
166
  * Rejects with {@link MuseHostStartError} when the host is lost before the
139
167
  * handshake completes (the binary could not be spawned, or the process
140
168
  * ended first — exit code or signal plus the bounded stderr tail;
@@ -170,6 +198,41 @@ export declare class MuseClient {
170
198
  * server answers.
171
199
  */
172
200
  resumeSession(options: ResumeSessionOptions): Promise<Session>;
201
+ /**
202
+ * List stored sessions (`session/list`), including text search via
203
+ * `filter.text`. A read-only list: rides `request()`, not `command()`
204
+ * (see `Session.listTasks`).
205
+ */
206
+ listSessions(options?: SessionListParams): Promise<SessionListResult>;
207
+ /**
208
+ * List the models the host accepts in `Session.setModel` (`model/list`).
209
+ * With `sessionId`, that session's current model is flagged `isActive`. A
210
+ * query: rides `request()`, like `listSessions`.
211
+ */
212
+ listModels(options?: ModelListParams): Promise<ModelListResult>;
213
+ /**
214
+ * Read the host's last-observed subscription usage (`usage/read`) without a
215
+ * model call; `usage` is absent when the host has observed nothing.
216
+ */
217
+ readUsage(): Promise<UsageReadResult>;
218
+ /**
219
+ * Send a wire method directly (FR-79107-2), typically one the facade does
220
+ * not wrap, through the
221
+ * same `Connection.command()` the verbs use: the connection mints the
222
+ * `commandId`, retries a nothing-admitted refusal under the same id, and
223
+ * checks the ack's echo. `options` are that seam's own.
224
+ *
225
+ * Refused before anything is written, with `MuseFacadeOwnedMethodError`:
226
+ * the methods whose state the facade owns (`FACADE_OWNED_METHODS`). Frames
227
+ * the command causes still reach your sessions through the client's one
228
+ * inbound pump; this sends and returns the ack, nothing more. Params and
229
+ * ack stay untyped objects: the generated types carry no method-to-params
230
+ * map, and restating one here would drift from the schema.
231
+ *
232
+ * Each call keeps one fixed-size fingerprint for the connection's lifetime
233
+ * (FR-45137-1), so prefer a facade verb for a query you poll.
234
+ */
235
+ command(method: Exclude<MspMethod, FacadeOwnedMethod>, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
173
236
  /**
174
237
  * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
175
238
  * is not reported to your sessions as a host death.
@@ -187,3 +250,4 @@ export declare class MuseClient {
187
250
  */
188
251
  close(): Promise<void>;
189
252
  }
253
+ export {};
@@ -35,23 +35,25 @@
35
35
  * chain close that gap — add a member upstream and the BUILD fails here until
36
36
  * it is forwarded (or explicitly allow-listed as unforwardable).
37
37
  */
38
+ import { discoverMuseBin } from "../connection/discovery.js";
38
39
  import { initializeAnswered, spawnMspConnection } from "../connection/spawn.js";
39
- import { MuseSessionDiscardedError, PermissionProfileNotApplied } from "../errors.js";
40
+ import { MuseCapabilityNotGrantedError, MuseFacadeOwnedMethodError, MuseSessionDiscardedError, PermissionProfileNotApplied, } from "../errors.js";
40
41
  import { DiscardedSessions } from "./discarded.js";
41
42
  import { isAbnormalHostDeath, readSessionDurability } from "./host-death.js";
42
43
  import { MspError, ProtocolError } from "../connection/connection.js";
43
44
  import { hostStartFailure } from "./host-start.js";
44
- import { Session } from "./session.js";
45
+ import { pumpDropsApplyResults, Session } from "./session.js";
45
46
  /**
46
- * Every `StartParams` member `startSession` forwards. `config` is temporarily
47
- * excluded until the facade can pair forwarding with the required
48
- * `sessionMcp` grant check, `previousSessionId` is excluded because the
49
- * facade starts root sessions (the predecessor link belongs to a client that
50
- * switches sessions), and `spawnedBy` because the facade does not expose a
51
- * spawner yet.
47
+ * Every `StartParams` member `startSession` forwards. `config` is forwarded
48
+ * only behind the `sessionMcp` grant check (`#forwardConfig`),
49
+ * `previousSessionId` is excluded because the facade starts root sessions
50
+ * (the predecessor link belongs to a client that switches sessions, as does
51
+ * the `switchPolicy` member), and `spawnedBy` because the facade does not
52
+ * expose a spawner yet.
52
53
  */
53
54
  const START_FORWARDED = [
54
55
  "approvalMode",
56
+ "config",
55
57
  "providerId",
56
58
  "sessionId",
57
59
  "workspaceRoot",
@@ -61,10 +63,56 @@ const START_FORWARDED = [
61
63
  "recoveryMode",
62
64
  ];
63
65
  /**
64
- * Every `ResumeParams` member `resumeSession` forwards. `config` has the same
65
- * temporary capability-check boundary as the start facade above.
66
+ * Every `ResumeParams` member `resumeSession` forwards; `config` rides the
67
+ * same `sessionMcp` grant check as the start facade above.
66
68
  */
67
- const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history", "modelId", "permissionProfile", "recoveryMode"];
69
+ const RESUME_FORWARDED = [
70
+ "sessionId",
71
+ "config",
72
+ "cursor",
73
+ "excludeItems",
74
+ "history",
75
+ "modelId",
76
+ "permissionProfile",
77
+ "recoveryMode",
78
+ ];
79
+ /**
80
+ * The wire methods whose state the facade owns, refused by `command`
81
+ * (FR-79107-2). `initialize` is the handshake `spawn` runs; `session/start` and
82
+ * `session/resume` register the `Session` the pump routes to; `turn/start`,
83
+ * `turn/steer`, `turn/unqueue`, `approval/decide`, and `userInput/answer`
84
+ * carry the pending-command, approval, and answer state their verbs keep (a
85
+ * steer is a pending submission and an accepted unqueue retires its queued
86
+ * entry); `view/page` is the gap fill's; and
87
+ * `view/subscribe`/`view/unsubscribe` change the subscription set the pump
88
+ * routes by, so a raw unsubscribe would silently starve a live `Session`.
89
+ */
90
+ const FACADE_OWNED_METHODS = [
91
+ "initialize",
92
+ "session/start",
93
+ "session/resume",
94
+ "turn/start",
95
+ "turn/steer",
96
+ "turn/unqueue",
97
+ "approval/decide",
98
+ "userInput/answer",
99
+ "view/page",
100
+ "view/subscribe",
101
+ "view/unsubscribe",
102
+ ];
103
+ const FACADE_OWNED = new Set(FACADE_OWNED_METHODS);
104
+ /** Every `SessionListParams` member `listSessions` forwards. */
105
+ const LIST_FORWARDED = ["cursor", "filter", "limit", "updatedAfter", "workspaceRoot"];
106
+ /**
107
+ * The caller's capability posture with `sessionMcp` added to its requests,
108
+ * each requested name once (ADR 32760 D3: the facade requests the grant its
109
+ * `config` forwarding checks). A host grants only what was requested.
110
+ */
111
+ function withSessionMcpRequested(capabilities) {
112
+ const requested = new Set(capabilities?.requestedCapabilities ?? []);
113
+ requested.add("sessionMcp");
114
+ return { ...capabilities, requestedCapabilities: [...requested] };
115
+ }
68
116
  /**
69
117
  * The committed profile id a session snapshot claims, or null when the
70
118
  * snapshot is silent (the stable bundle strips the member; absent and null
@@ -202,6 +250,9 @@ export class MuseClient {
202
250
  * absent/unrecognized distinction load-bearing, and a caller re-deriving it
203
251
  * by hand is a caller that can get it wrong.
204
252
  *
253
+ * Rejects with {@link MuseHostDiscoveryError} before starting anything when
254
+ * `museBin` is omitted and no executable `muse` is on `PATH`.
255
+ *
205
256
  * Rejects with {@link MuseHostStartError} when the host is lost before the
206
257
  * handshake completes (the binary could not be spawned, or the process
207
258
  * ended first — exit code or signal plus the bounded stderr tail;
@@ -212,8 +263,11 @@ export class MuseClient {
212
263
  * no schema fingerprint.
213
264
  */
214
265
  static async spawn(options) {
266
+ // The process's own PATH, never `options.env`'s: the host is found the
267
+ // way the Rust and Python SDKs find it, whatever environment it gets.
268
+ const command = await discoverMuseBin(options.museBin, process.env["PATH"], process.platform);
215
269
  const handshake = spawnMspConnection({
216
- command: options.museBin,
270
+ command,
217
271
  ...(options.args === undefined ? {} : { args: options.args }),
218
272
  ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
219
273
  ...(options.env === undefined ? {} : { env: options.env }),
@@ -226,7 +280,7 @@ export class MuseClient {
226
280
  try {
227
281
  spawned = await handshake.initialize({
228
282
  clientInfo: options.clientInfo,
229
- ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }),
283
+ capabilities: withSessionMcpRequested(options.capabilities),
230
284
  });
231
285
  }
232
286
  catch (error) {
@@ -303,6 +357,8 @@ export class MuseClient {
303
357
  // other start members (undefined stays omitted).
304
358
  if (options.permissionProfile != null)
305
359
  params.permissionProfile = options.permissionProfile;
360
+ if (options.config != null)
361
+ params.config = this.#forwardConfig("session/start", options.config);
306
362
  // TEST-42624-10: a caller that requires its selection proves it, never
307
363
  // assuming the host default. The flag without the member is API misuse
308
364
  // (plain Error, like the other misuse guards here), raised pre-wire.
@@ -376,11 +432,76 @@ export class MuseClient {
376
432
  params.recoveryMode = options.recoveryMode;
377
433
  if (options.permissionProfile != null)
378
434
  params.permissionProfile = options.permissionProfile;
435
+ if (options.config != null)
436
+ params.config = this.#forwardConfig("session/resume", options.config);
379
437
  return this.#open("session/resume", params, (raw) => ({
380
438
  result: raw,
381
439
  verb: "session/resume",
382
440
  }), { onApproval: options.onApproval, onApprovalError: options.onApprovalError });
383
441
  }
442
+ /**
443
+ * List stored sessions (`session/list`), including text search via
444
+ * `filter.text`. A read-only list: rides `request()`, not `command()`
445
+ * (see `Session.listTasks`).
446
+ */
447
+ async listSessions(options = {}) {
448
+ const params = {};
449
+ if (options.cursor != null)
450
+ params["cursor"] = options.cursor;
451
+ if (options.filter != null)
452
+ params["filter"] = options.filter;
453
+ if (options.limit != null)
454
+ params["limit"] = options.limit;
455
+ if (options.updatedAfter != null)
456
+ params["updatedAfter"] = options.updatedAfter;
457
+ if (options.workspaceRoot != null)
458
+ params["workspaceRoot"] = options.workspaceRoot;
459
+ const ack = await this.#connection.request("session/list", params);
460
+ return ack;
461
+ }
462
+ /**
463
+ * List the models the host accepts in `Session.setModel` (`model/list`).
464
+ * With `sessionId`, that session's current model is flagged `isActive`. A
465
+ * query: rides `request()`, like `listSessions`.
466
+ */
467
+ async listModels(options = {}) {
468
+ const params = {};
469
+ if (options.sessionId != null)
470
+ params["sessionId"] = options.sessionId;
471
+ const ack = await this.#connection.request("model/list", params);
472
+ return ack;
473
+ }
474
+ /**
475
+ * Read the host's last-observed subscription usage (`usage/read`) without a
476
+ * model call; `usage` is absent when the host has observed nothing.
477
+ */
478
+ async readUsage() {
479
+ const ack = await this.#connection.request("usage/read");
480
+ return ack;
481
+ }
482
+ /**
483
+ * Send a wire method directly (FR-79107-2), typically one the facade does
484
+ * not wrap, through the
485
+ * same `Connection.command()` the verbs use: the connection mints the
486
+ * `commandId`, retries a nothing-admitted refusal under the same id, and
487
+ * checks the ack's echo. `options` are that seam's own.
488
+ *
489
+ * Refused before anything is written, with `MuseFacadeOwnedMethodError`:
490
+ * the methods whose state the facade owns (`FACADE_OWNED_METHODS`). Frames
491
+ * the command causes still reach your sessions through the client's one
492
+ * inbound pump; this sends and returns the ack, nothing more. Params and
493
+ * ack stay untyped objects: the generated types carry no method-to-params
494
+ * map, and restating one here would drift from the schema.
495
+ *
496
+ * Each call keeps one fixed-size fingerprint for the connection's lifetime
497
+ * (FR-45137-1), so prefer a facade verb for a query you poll.
498
+ */
499
+ async command(method, params, options) {
500
+ // The type binds TypeScript callers; this binds plain-JS ones.
501
+ if (FACADE_OWNED.has(method))
502
+ throw new MuseFacadeOwnedMethodError(method);
503
+ return this.#connection.command(method, params, options);
504
+ }
384
505
  /**
385
506
  * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
386
507
  * is not reported to your sessions as a host death.
@@ -441,6 +562,8 @@ export class MuseClient {
441
562
  session.onApprovalError(approvals.onApprovalError);
442
563
  if (approvals.onApproval !== undefined)
443
564
  session.onApproval(approvals.onApproval);
565
+ // `#route` drops what `apply` returns (FR-81734-1).
566
+ session[pumpDropsApplyResults]();
444
567
  this.#sessions.add(session);
445
568
  // The frames that named this session while its verb was in flight fold
446
569
  // NOW, in arrival order — synchronously, so nothing the pump routes next
@@ -453,6 +576,20 @@ export class MuseClient {
453
576
  }
454
577
  return session;
455
578
  }
579
+ /**
580
+ * The `config` to forward, or a typed refusal before anything is sent
581
+ * (FR-79107-3). Per-session MCP servers need the `sessionMcp` grant in the
582
+ * handshake this client was built with (`spawn` requests it; a caller's own
583
+ * handshake must request it too); a client given no handshake cannot show
584
+ * it. A config naming no server needs no grant, as on the host (ADR 32760 D3).
585
+ */
586
+ #forwardConfig(method, config) {
587
+ if (config.mcpServers == null || Object.keys(config.mcpServers).length === 0)
588
+ return config;
589
+ if (this.#initializeResult?.grantedCapabilities.includes("sessionMcp") === true)
590
+ return config;
591
+ throw new MuseCapabilityNotGrantedError("sessionMcp", method, "config.mcpServers needs the sessionMcp grant, which this connection's handshake does not hold (MuseClient.spawn requests it; a host withholds it when per-session MCP is turned off)");
592
+ }
456
593
  #assertReattachAllowed(sessionId) {
457
594
  // Two facts, both recorded by an ephemeral discharge: THIS session was
458
595
  // discarded, or this client's own ephemeral host died (in which case there
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `Session.run` — one call from a prompt to the turn's final answer (spec
3
+ * 14990 FR-79108-1).
4
+ *
5
+ * Built only from facade verbs the session already has: `sendUserTurn`, the
6
+ * turn-wait, `items()`, and `unqueue`/`cancel` for an abort; the abort's
7
+ * unqueue goes through the session's internal `resendableUnqueue`, the same
8
+ * control holding one `commandId` across resends. It holds no state
9
+ * of its own and reaches the fold and the pending set only through those verbs
10
+ * and the read-only pending view, so every SS4.13 rule keeps applying exactly
11
+ * as it does for a hand-written `sendUserTurn` loop.
12
+ */
13
+ import type { TokenUsage, TurnInputPart } from "../msp.js";
14
+ import { type Session } from "./session.js";
15
+ import type { FoldedItem, TurnOutcome } from "./turn-handle.js";
16
+ import type { SendUserTurnOptions } from "./turn-submit.js";
17
+ /**
18
+ * What `run` forwards to `turn/start`, plus the abort signal. Composed from
19
+ * `SendUserTurnOptions`, so a new `turn/start` member reaches `run` with no
20
+ * edit here. `composerInput` is left out: `run` hands back no SS4.13
21
+ * retirement, so there is nothing for it to restore.
22
+ */
23
+ export type RunOptions = Readonly<Omit<SendUserTurnOptions<unknown>, "input" | "composerInput">> & {
24
+ /**
25
+ * Stops the turn. An already-aborted signal rejects at once and sends
26
+ * nothing. An abort while the turn is queued sends `turn/unqueue`, and
27
+ * `turn/cancel` if the turn launched first; while it runs, `turn/cancel`.
28
+ * `run` then waits for the server to end the turn and rejects with
29
+ * `signal.reason`. An abort once the turn has ended sends nothing.
30
+ */
31
+ readonly signal?: AbortSignal;
32
+ };
33
+ /** What `run` resolves to once the server has ended the turn. */
34
+ export interface RunResult {
35
+ readonly turnId: string;
36
+ /** The server-authored outcome; a failed or cancelled turn still resolves. */
37
+ readonly outcome: TurnOutcome;
38
+ /**
39
+ * The `text` of the turn's last `agentMessage` item (in first-opened order)
40
+ * that completed and is not `"commentary"`: an absent or unknown
41
+ * `messagePhase` on a completed item reads as `"finalAnswer"`. `undefined`
42
+ * when the turn produced no such item.
43
+ */
44
+ readonly finalText: string | undefined;
45
+ /** The turn's items as the fold holds them at the end, in first-opened order. */
46
+ readonly items: readonly FoldedItem[];
47
+ /** The turn's token usage from `turn/completed`; absent on other outcomes. */
48
+ readonly usage: TokenUsage | undefined;
49
+ }
50
+ export declare function runTurn<I>(host: Session<I>, input: string | readonly TurnInputPart[], options?: RunOptions): Promise<RunResult>;