@muse-code/sdk 1.4.13 → 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.
@@ -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>;
@@ -0,0 +1,132 @@
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 { defaultRetryDelay, MspError } from "../connection/connection.js";
14
+ import { COMMAND_REJECTED_KIND } from "../pending/pending-command-set.js";
15
+ import { resendableUnqueue } from "./session.js";
16
+ /** Bound to the generated vocabularies so a misspelling fails `tsc`. */
17
+ const TEXT = "text";
18
+ const AGENT_MESSAGE = "agentMessage";
19
+ const COMPLETED = "completed";
20
+ const COMMENTARY = "commentary";
21
+ const ACCEPTED = "accepted";
22
+ const QUEUED = "queued";
23
+ /** FR-77912-2's reason for a call the session runtime did not take: nothing was written. */
24
+ const RUNTIME_BUSY = "runtime_busy";
25
+ export async function runTurn(host, input, options = {}) {
26
+ const { signal, ...submit } = options;
27
+ // An already-aborted signal rejects with its reason before anything is sent
28
+ // (the web-platform AbortSignal convention).
29
+ signal?.throwIfAborted();
30
+ const parts = typeof input === "string" ? [{ text: input, type: TEXT }] : [...input];
31
+ // A refused submit rejects with its own error, aborted or not: no turn
32
+ // exists for an abort to stop.
33
+ const turn = await host.sendUserTurn({ ...submit, input: parts });
34
+ const outcome = signal === undefined ? await turn.completed : await settleOrAbort(host, turn, signal);
35
+ const items = [];
36
+ // The turn has settled, so this replays the fold's items at their latest
37
+ // revision and ends; it never waits.
38
+ for await (const item of turn.items())
39
+ items.push(item);
40
+ return {
41
+ finalText: finalAnswerText(items),
42
+ items,
43
+ outcome,
44
+ turnId: turn.turnId,
45
+ usage: outcome.kind === "completed" ? outcome.params.usage : undefined,
46
+ };
47
+ }
48
+ const ABORTED = Symbol("aborted");
49
+ async function settleOrAbort(host, turn, signal) {
50
+ let onAbort = () => { };
51
+ const aborted = new Promise((resolve) => {
52
+ onAbort = () => resolve(ABORTED);
53
+ if (signal.aborted)
54
+ onAbort();
55
+ else
56
+ signal.addEventListener("abort", onAbort, { once: true });
57
+ });
58
+ let first;
59
+ try {
60
+ first = await Promise.race([turn.completed, aborted]);
61
+ }
62
+ finally {
63
+ signal.removeEventListener("abort", onAbort);
64
+ }
65
+ if (first !== ABORTED)
66
+ return first;
67
+ await stop(host, turn);
68
+ // The turn's end is the server's to report (INV-006). Waiting for it leaves
69
+ // the session idle when `run` rejects, and INV-014 settles this wait on
70
+ // every exit, host death included.
71
+ await turn.completed.catch(() => undefined);
72
+ throw signal.reason;
73
+ }
74
+ /**
75
+ * Unqueue the turn while this session holds its queued entry and no
76
+ * `turn/started` has folded; otherwise, or when the unqueue loses the launch
77
+ * race (tdd SS3.6 rejects it, never upgrading it to a cancel), cancel it. An
78
+ * unqueue the session runtime did not take (`runtime_busy`, ADR 77912 D1)
79
+ * wrote nothing, so it goes out again under its first `commandId` after the
80
+ * connection's backoff, with no cap, until the host decides it or the turn
81
+ * starts.
82
+ *
83
+ * A refused stop is not reported: whatever it answered, the turn-wait the
84
+ * caller awaits next is what reports how the turn ended.
85
+ */
86
+ async function stop(host, turn) {
87
+ const queued = host.pending
88
+ .list()
89
+ .some((entry) => entry.ack?.turnId === turn.turnId && entry.ack.disposition === QUEUED);
90
+ if (queued && !turn.observedStart) {
91
+ let unqueue;
92
+ for (let attempt = 1;; attempt += 1) {
93
+ try {
94
+ unqueue ??= host[resendableUnqueue](turn.turnId);
95
+ if ((await unqueue()).ack.status === ACCEPTED)
96
+ return;
97
+ break;
98
+ }
99
+ catch (error) {
100
+ // Lost the launch race, or refused: the turn may run, so cancel it below.
101
+ if (!untaken(error) || turn.observedStart)
102
+ break;
103
+ }
104
+ await defaultRetryDelay(attempt);
105
+ if (turn.observedStart)
106
+ break;
107
+ }
108
+ }
109
+ try {
110
+ await turn.cancel();
111
+ }
112
+ catch {
113
+ // The turn already ended, or the host is gone; the turn-wait reports which.
114
+ }
115
+ }
116
+ function untaken(error) {
117
+ return (error instanceof MspError &&
118
+ error.kind === COMMAND_REJECTED_KIND &&
119
+ error.data["reason"] === RUNTIME_BUSY);
120
+ }
121
+ function finalAnswerText(items) {
122
+ for (let index = items.length - 1; index >= 0; index -= 1) {
123
+ const item = items[index];
124
+ if (item !== undefined &&
125
+ item.kind === AGENT_MESSAGE &&
126
+ item.status === COMPLETED &&
127
+ item.messagePhase !== COMMENTARY) {
128
+ return item.text;
129
+ }
130
+ }
131
+ return undefined;
132
+ }
@@ -30,7 +30,8 @@ import type { GapFillFailureHandler } from "./gap-fill.js";
30
30
  import type { DiscardedSessions } from "./discarded.js";
31
31
  import type { HostDeathDischarge, HostDeathNotification, SessionDurabilityProfile } from "./host-death.js";
32
32
  import type { Turn } from "./turn-handle.js";
33
- import type { SessionResumeResult, SessionStartResult, UserInputAnswer, UserInputAnswerResult } from "../msp.js";
33
+ import type { RunOptions, RunResult } from "./run.js";
34
+ import type { ApprovalMode, CommandAcceptedResult, FeedbackSubmitParams, FeedbackSubmitResult, HookListResult, ModelSelection, PluginInstallResult, PluginInstallTarget, PluginListResult, ReasoningEffort, RecapRequestResult, SessionCompactParams, SessionCompactResult, SessionForkParams, SessionForkResult, SessionLeaveParams, SessionLeaveResult, SessionRenameResult, SessionResumeResult, SessionSetApprovalModeResult, SessionSetModelResult, SessionSetReasoningEffortResult, SessionSideChatResult, SessionStartResult, SkillListResult, SkillSetActivationParams, SkillSetActivationResult, SubagentOwnerReasonParams, TaskListResult, TurnInputPart, UserInputAnswer, UserInputAnswerResult, WorkflowControlResult, WorkflowResumeResult } from "../msp.js";
34
35
  /**
35
36
  * Which verb opened this session, and what it answered.
36
37
  *
@@ -47,6 +48,8 @@ export type SessionOpening = {
47
48
  readonly verb: "session/resume";
48
49
  readonly result: SessionResumeResult;
49
50
  };
51
+ /** The optional reason `interruptSubagent`/`stopSubagent`/`closeSubagent` record. */
52
+ export type SubagentReasonOptions = Readonly<Pick<SubagentOwnerReasonParams, "reason">>;
50
53
  /**
51
54
  * Options for constructing a `Session` directly. Sessions opened through
52
55
  * `MuseClient` are configured for you; build one yourself when you manage
@@ -235,7 +238,7 @@ export declare class Session<I = unknown> {
235
238
  * the fold has already settled returns its settled handle, so a wait
236
239
  * registered late resolves instead of hanging on an event that has passed.
237
240
  */
238
- turn(turnId: string): Turn;
241
+ turn(turnId: string): Turn<I>;
239
242
  /**
240
243
  * A host process exited. Classify it, and discharge SS2.13.3b if the profile
241
244
  * demands it (tasks.md T030b, FM-002).
@@ -268,7 +271,15 @@ export declare class Session<I = unknown> {
268
271
  * needs the fold: the entry's insertion point, which is the last item this
269
272
  * session holds at submission time.
270
273
  */
271
- sendUserTurn(options: SendUserTurnOptions<I>): Promise<Turn>;
274
+ sendUserTurn(options: SendUserTurnOptions<I>): Promise<Turn<I>>;
275
+ /**
276
+ * Run one turn to its end in a single call (FR-79108-1): submit `input`
277
+ * (a string is one text part), wait for the server to end the turn, and
278
+ * resolve its outcome, final answer text, items and usage. Pass
279
+ * `options.signal` to stop the turn; see {@link RunOptions}. Use
280
+ * `sendUserTurn` to stream items or deltas as they arrive.
281
+ */
282
+ run(input: string | readonly TurnInputPart[], options?: RunOptions): Promise<RunResult>;
272
283
  /** Answer approvals with `handler` (FR-019). See `ApprovalRouter`. */
273
284
  onApproval(handler: ApprovalHandler): void;
274
285
  /** Observe round trips that did not complete. See `ApprovalFailure`. */
@@ -280,6 +291,75 @@ export declare class Session<I = unknown> {
280
291
  * only when the server's `userInput/settled` arrives.
281
292
  */
282
293
  answerUserInput(userInputId: string, answers: readonly UserInputAnswer[]): Promise<UserInputAnswerResult>;
294
+ /** List this session's live background and foreground tasks (`task/list`). */
295
+ listTasks(): Promise<TaskListResult>;
296
+ /** List this session's user-invocable skills (`skill/list`). */
297
+ listSkills(): Promise<SkillListResult>;
298
+ /** List this session's installed hook rows (`hook/list`). */
299
+ listHooks(): Promise<HookListResult>;
300
+ /** Pause a live workflow run (`workflow/pause`). */
301
+ pauseWorkflow(workflowRunId: string): Promise<WorkflowControlResult>;
302
+ /** Resume a paused workflow run (`workflow/resume`). */
303
+ resumeWorkflow(workflowRunId: string): Promise<WorkflowResumeResult>;
304
+ /** Request a recap of this session (`recap/request`); admission only. */
305
+ requestRecap(): Promise<RecapRequestResult>;
306
+ /**
307
+ * Submit feedback about this session (`feedback/submit`). The host
308
+ * serves it only when the spawn requested the `feedback` capability
309
+ * (`requestedCapabilities: ["feedback"]`) and install policy allows
310
+ * it; without that grant the host refuses the command.
311
+ */
312
+ submitFeedback(input: Omit<FeedbackSubmitParams, "sessionId">): Promise<FeedbackSubmitResult>;
313
+ /**
314
+ * Open a side chat from this session (`session/sideChat`). Returns the wire
315
+ * result; opening a wired `Session` for the new side session is the
316
+ * caller's composition, as with a directly built `Session`.
317
+ */
318
+ openSideChat(): Promise<SessionSideChatResult>;
319
+ /**
320
+ * Fork this session into a new one (`session/fork`). Returns the wire
321
+ * result for the new session; opening a wired `Session` for it stays the
322
+ * caller's composition, as with `openSideChat`.
323
+ */
324
+ fork(options?: Readonly<Omit<SessionForkParams, "commandId" | "sessionId">>): Promise<SessionForkResult>;
325
+ /** Compact this session's context (`session/compact`); admission only, or `noop`. */
326
+ compact(options?: Readonly<Omit<SessionCompactParams, "commandId" | "sessionId">>): Promise<SessionCompactResult>;
327
+ /** Select the model for later model calls (`session/setModel`). */
328
+ setModel(model: ModelSelection): Promise<SessionSetModelResult>;
329
+ /** Set this session's standing reasoning effort (`session/setReasoningEffort`). */
330
+ setReasoningEffort(reasoningEffort: ReasoningEffort): Promise<SessionSetReasoningEffortResult>;
331
+ /** Select one of the host's preconfigured approval modes (`session/setApprovalMode`). */
332
+ setApprovalMode(mode: ApprovalMode): Promise<SessionSetApprovalModeResult>;
333
+ /** Set or change this session's stored name (`session/rename`). */
334
+ rename(name: string): Promise<SessionRenameResult>;
335
+ /**
336
+ * Release this session from the host (`session/leave`); `stop: true` also
337
+ * cancels unfinished work. Admission only: the host reports the release
338
+ * later as `session/leaveCompleted`.
339
+ */
340
+ leave(options?: Readonly<Omit<SessionLeaveParams, "commandId" | "sessionId">>): Promise<SessionLeaveResult>;
341
+ /** Queue a note into a running subagent (`subagent/sendMessage`). */
342
+ sendSubagentMessage(subagentId: string, body: string): Promise<CommandAcceptedResult>;
343
+ /** Queue a follow-up task for a subagent (`subagent/followupTask`). */
344
+ followupSubagentTask(subagentId: string, body: string): Promise<CommandAcceptedResult>;
345
+ /** Ask a subagent to yield at its next boundary (`subagent/interrupt`). */
346
+ interruptSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
347
+ /** Stop a running subagent (`subagent/stop`). */
348
+ stopSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
349
+ /** Resume a paused or recoverable subagent (`subagent/resume`). */
350
+ resumeSubagent(subagentId: string): Promise<CommandAcceptedResult>;
351
+ /** Reopen a stopped or closed subagent (`subagent/reopen`). */
352
+ reopenSubagent(subagentId: string): Promise<CommandAcceptedResult>;
353
+ /** Close a subagent as its owner (`subagent/close`). */
354
+ closeSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
355
+ /** Consume a subagent's ready result (`subagent/readResult`). */
356
+ readSubagentResult(subagentId: string): Promise<CommandAcceptedResult>;
357
+ /** List this session's installed plugins (`plugin/list`); a query, like `listTasks`. */
358
+ listPlugins(): Promise<PluginListResult>;
359
+ /** Install one plugin from a marketplace or a host folder (`plugin/install`). */
360
+ installPlugin(target: PluginInstallTarget): Promise<PluginInstallResult>;
361
+ /** Turn one skill on or off in one scope (`skill/setActivation`). */
362
+ setSkillActivation(options: Readonly<Omit<SkillSetActivationParams, "commandId" | "sessionId">>): Promise<SkillSetActivationResult>;
283
363
  /**
284
364
  * Stop the SS3.1.1 retry loop for one entry and take its input back
285
365
  * (SS4.13 "Abandoned").
@@ -28,6 +28,7 @@ import { GapFiller } from "./gap-fill.js";
28
28
  import { isAbnormalHostDeath, isItemInProgress, MuseHostDiedError, survivesHostDeath, } from "./host-death.js";
29
29
  import { MuseForeignSessionError, MuseSessionDiscardedError } from "../errors.js";
30
30
  import { TurnHandle } from "./turn-handle.js";
31
+ import { runTurn } from "./run.js";
31
32
  /**
32
33
  * True when a routed `approval/request` carries every member the approval
33
34
  * router reads: its `approvalId`, the requirement's `approvalId` and
@@ -47,6 +48,8 @@ function isRecord(value) {
47
48
  }
48
49
  /** Bound to the generated vocabulary so a misspelling fails `tsc`. */
49
50
  const USER_MESSAGE = "userMessage";
51
+ const ACCEPTED = "accepted";
52
+ const QUEUED = "queued";
50
53
  /**
51
54
  * The shared already-settled `io` for an event that triggered no I/O.
52
55
  *
@@ -55,6 +58,24 @@ const USER_MESSAGE = "userMessage";
55
58
  * neither a pending command nor an approval.
56
59
  */
57
60
  const NO_IO = Promise.resolve([]);
61
+ /**
62
+ * Module-private friend seam (never on the package barrel, like
63
+ * `connection.ts`'s `submissionTail`): `MuseClient` marks each session it
64
+ * opens, because its inbound pump drops what `apply` returns. A reclaim the
65
+ * fold retires while this session's own `unqueue()` for that turn is in
66
+ * flight is then held for that call (FR-81734-1).
67
+ *
68
+ * @internal
69
+ */
70
+ export const pumpDropsApplyResults = Symbol("Session.pumpDropsApplyResults");
71
+ /**
72
+ * Module-private friend seam (never on the package barrel): `Session.run`'s
73
+ * abort takes a queued turn back under one `commandId` and sends that same
74
+ * reclaim again while the session runtime does not take it (ADR 77912 D1).
75
+ *
76
+ * @internal
77
+ */
78
+ export const resendableUnqueue = Symbol("Session.resendableUnqueue");
58
79
  /**
59
80
  * One conversation with the agent.
60
81
  *
@@ -99,6 +120,80 @@ export class Session {
99
120
  * durable `item/completed` always lands the item.
100
121
  */
101
122
  #unattributedDeltas = new Map();
123
+ /** Set through {@link pumpDropsApplyResults} by `MuseClient`. */
124
+ #applyResultsDropped = false;
125
+ /** This session's own `unqueue()` calls awaiting their ack, counted per turn id. */
126
+ #unqueuesInFlight = new Map();
127
+ /**
128
+ * FR-81734-1: a reclaim the fold retired while its turn's own `unqueue()`
129
+ * was in flight on a session whose pump drops `apply`'s return. The call
130
+ * hands it out; it goes when the last in-flight call for the turn settles,
131
+ * so this holds at most one entry per in-flight call.
132
+ */
133
+ #heldReclaims = new Map();
134
+ /**
135
+ * The wire half of every turn handle's control verbs (FR-79106-1). Each
136
+ * refuses on a discarded or fold-only session before anything is sent;
137
+ * `steer` rides the SS4.13 submit path, and an accepted `unqueue` retires
138
+ * the queued entry at once (SS4.13 Reclaimed: "its own reclaim ack"); the
139
+ * later `turn/unqueued` then finds nothing left to retire. When
140
+ * `turn/unqueued` folds first under `MuseClient`, the fold's retirement is
141
+ * held for the call instead (FR-81734-1).
142
+ */
143
+ #turnControls = {
144
+ cancel: async (turnId) => (await this.#command("cancel", "turn/cancel", { turnId })),
145
+ interrupt: async (turnId, options) => (await this.#command("interrupt", "turn/interrupt", {
146
+ turnId,
147
+ ...(options.retract == null ? {} : { retract: options.retract }),
148
+ })),
149
+ steer: async (turnId, options) => {
150
+ this.#requireLiveConnection("steer");
151
+ return await this.#submit.steer(turnId, options, this.#lastFoldedItemId());
152
+ },
153
+ unqueue: async (turnId, commandId) => {
154
+ this.#unqueuesInFlight.set(turnId, (this.#unqueuesInFlight.get(turnId) ?? 0) + 1);
155
+ try {
156
+ const ack = (await this.#command("unqueue", "turn/unqueue", { turnId }, commandId));
157
+ const held = this.#heldReclaims.get(turnId);
158
+ if (held !== undefined) {
159
+ this.#heldReclaims.delete(turnId);
160
+ return { ack, retirement: held };
161
+ }
162
+ return { ack, retirement: ack.status === ACCEPTED ? this.#reclaimQueued(turnId) : undefined };
163
+ }
164
+ finally {
165
+ const left = (this.#unqueuesInFlight.get(turnId) ?? 1) - 1;
166
+ if (left > 0) {
167
+ this.#unqueuesInFlight.set(turnId, left);
168
+ }
169
+ else {
170
+ this.#unqueuesInFlight.delete(turnId);
171
+ this.#heldReclaims.delete(turnId);
172
+ }
173
+ }
174
+ },
175
+ };
176
+ /** @internal See {@link pumpDropsApplyResults}. */
177
+ [pumpDropsApplyResults]() {
178
+ this.#applyResultsDropped = true;
179
+ }
180
+ /** @internal See {@link resendableUnqueue}: each call of the result sends the same reclaim. */
181
+ [resendableUnqueue](turnId) {
182
+ const commandId = this.#requireLiveConnection("unqueue").mintCommandId();
183
+ return () => this.#turnControls.unqueue(turnId, commandId);
184
+ }
185
+ /** Retire this session's acked-queued entry for `turnId`, if it holds one. */
186
+ #reclaimQueued(turnId) {
187
+ const entry = this.#pending
188
+ .list()
189
+ .find((held) => held.ack?.turnId === turnId && held.ack.disposition === QUEUED);
190
+ if (entry === undefined)
191
+ return undefined;
192
+ const retired = this.#pending.observedReclaim(entry.commandId);
193
+ if (retired !== undefined)
194
+ this.#submit.forgetRetired([retired]);
195
+ return retired;
196
+ }
102
197
  constructor(options) {
103
198
  this.sessionId = options.sessionId;
104
199
  this.#durability = options.durability;
@@ -289,8 +384,14 @@ export class Session {
289
384
  // later be retired `terminalUnknown` by a discharge, which would be a
290
385
  // fabricated annotation about a command whose fate is known.
291
386
  const reclaimed = this.#pending.observedReclaim(known.params.commandId);
292
- if (reclaimed !== undefined)
387
+ if (reclaimed !== undefined) {
293
388
  retirements.push(reclaimed);
389
+ // FR-81734-1: nobody reads this return under `MuseClient`, so this
390
+ // session's own in-flight unqueue for the turn is where it can land.
391
+ if (this.#applyResultsDropped && this.#unqueuesInFlight.has(known.params.turnId)) {
392
+ this.#heldReclaims.set(known.params.turnId, reclaimed);
393
+ }
394
+ }
294
395
  break;
295
396
  }
296
397
  case "approval/requested":
@@ -327,6 +428,7 @@ export class Session {
327
428
  case "turn/retracted": // the turn still reaches its own terminal
328
429
  case "turn/retryScheduled": // non-terminal by contract (SS4.5.1)
329
430
  case "turn/modelRetryScheduled": // non-terminal by contract (SS4.5.1)
431
+ case "turn/modelAttemptStarted": // non-terminal by contract (SS4.5.1)
330
432
  case "turn/foregroundCompleted": // non-terminal by contract (SS4.5.12)
331
433
  case "approval/reviewing": // reviewer-held twin of approval/requested (tdd SS5.5.1): a notice, no decide is open
332
434
  case "approval/resolved":
@@ -416,7 +518,7 @@ export class Session {
416
518
  return this.#turns.get(turnId) ?? this.#mint(turnId);
417
519
  }
418
520
  #mint(turnId) {
419
- const fresh = new TurnHandle(turnId, () => this.#itemsOfTurn(turnId));
521
+ const fresh = new TurnHandle(turnId, () => this.#itemsOfTurn(turnId), this.#turnControls);
420
522
  this.#turns.set(turnId, fresh);
421
523
  return fresh;
422
524
  }
@@ -526,6 +628,16 @@ export class Session {
526
628
  const ack = await this.#submit.submit(options, this.#lastFoldedItemId());
527
629
  return this.#handle(ack.turnId);
528
630
  }
631
+ /**
632
+ * Run one turn to its end in a single call (FR-79108-1): submit `input`
633
+ * (a string is one text part), wait for the server to end the turn, and
634
+ * resolve its outcome, final answer text, items and usage. Pass
635
+ * `options.signal` to stop the turn; see {@link RunOptions}. Use
636
+ * `sendUserTurn` to stream items or deltas as they arrive.
637
+ */
638
+ run(input, options) {
639
+ return runTurn(this, input, options);
640
+ }
529
641
  // ---- FR-019 approval round trip (T031) ----------------------------------
530
642
  /** Answer approvals with `handler` (FR-019). See `ApprovalRouter`. */
531
643
  onApproval(handler) {
@@ -562,6 +674,182 @@ export class Session {
562
674
  }
563
675
  return ack;
564
676
  }
677
+ // ---- wire-present query and command facades -----------------------------
678
+ #requireLiveConnection(verb) {
679
+ if (this.#discharge?.kind === "discharged") {
680
+ throw new MuseSessionDiscardedError(`session ${this.sessionId} was discarded after an ephemeral host death; it cannot ${verb}`);
681
+ }
682
+ return this.#submit.requireConnection(verb);
683
+ }
684
+ // The four read-only lists (here and `MuseClient.listSessions`) ride
685
+ // `request()`, not `command()`: their wire params carry no `commandId`,
686
+ // and `command()` would retain one dedup entry per call for the whole
687
+ // connection lifetime — a polling caller would grow it without bound.
688
+ /** List this session's live background and foreground tasks (`task/list`). */
689
+ async listTasks() {
690
+ const ack = await this.#requireLiveConnection("listTasks").request("task/list", {
691
+ sessionId: this.sessionId,
692
+ });
693
+ return ack;
694
+ }
695
+ /** List this session's user-invocable skills (`skill/list`). */
696
+ async listSkills() {
697
+ const ack = await this.#requireLiveConnection("listSkills").request("skill/list", {
698
+ sessionId: this.sessionId,
699
+ });
700
+ return ack;
701
+ }
702
+ /** List this session's installed hook rows (`hook/list`). */
703
+ async listHooks() {
704
+ const ack = await this.#requireLiveConnection("listHooks").request("hook/list", {
705
+ sessionId: this.sessionId,
706
+ });
707
+ return ack;
708
+ }
709
+ /** Pause a live workflow run (`workflow/pause`). */
710
+ async pauseWorkflow(workflowRunId) {
711
+ const ack = await this.#requireLiveConnection("pauseWorkflow").command("workflow/pause", {
712
+ sessionId: this.sessionId,
713
+ workflowRunId,
714
+ });
715
+ return ack;
716
+ }
717
+ /** Resume a paused workflow run (`workflow/resume`). */
718
+ async resumeWorkflow(workflowRunId) {
719
+ const ack = await this.#requireLiveConnection("resumeWorkflow").command("workflow/resume", {
720
+ sessionId: this.sessionId,
721
+ workflowRunId,
722
+ });
723
+ return ack;
724
+ }
725
+ /** Request a recap of this session (`recap/request`); admission only. */
726
+ async requestRecap() {
727
+ const ack = await this.#requireLiveConnection("requestRecap").command("recap/request", {
728
+ sessionId: this.sessionId,
729
+ });
730
+ return ack;
731
+ }
732
+ /**
733
+ * Submit feedback about this session (`feedback/submit`). The host
734
+ * serves it only when the spawn requested the `feedback` capability
735
+ * (`requestedCapabilities: ["feedback"]`) and install policy allows
736
+ * it; without that grant the host refuses the command.
737
+ */
738
+ async submitFeedback(input) {
739
+ const ack = await this.#requireLiveConnection("submitFeedback").command("feedback/submit", {
740
+ ...input,
741
+ sessionId: this.sessionId,
742
+ });
743
+ return ack;
744
+ }
745
+ /**
746
+ * Open a side chat from this session (`session/sideChat`). Returns the wire
747
+ * result; opening a wired `Session` for the new side session is the
748
+ * caller's composition, as with a directly built `Session`.
749
+ */
750
+ async openSideChat() {
751
+ const ack = await this.#requireLiveConnection("openSideChat").command("session/sideChat", {
752
+ sessionId: this.sessionId,
753
+ });
754
+ return ack;
755
+ }
756
+ // ---- session control verbs (FR-79106-1) ---------------------------------
757
+ /** Send one session-scoped command; the connection mints its `commandId`. */
758
+ async #command(verb, method, params, commandId) {
759
+ return await this.#requireLiveConnection(verb).command(method, { ...params, sessionId: this.sessionId }, commandId === undefined ? undefined : { commandId });
760
+ }
761
+ /**
762
+ * Fork this session into a new one (`session/fork`). Returns the wire
763
+ * result for the new session; opening a wired `Session` for it stays the
764
+ * caller's composition, as with `openSideChat`.
765
+ */
766
+ async fork(options = {}) {
767
+ return (await this.#command("fork", "session/fork", { ...options }));
768
+ }
769
+ /** Compact this session's context (`session/compact`); admission only, or `noop`. */
770
+ async compact(options = {}) {
771
+ return (await this.#command("compact", "session/compact", { ...options }));
772
+ }
773
+ /** Select the model for later model calls (`session/setModel`). */
774
+ async setModel(model) {
775
+ return (await this.#command("setModel", "session/setModel", { model }));
776
+ }
777
+ /** Set this session's standing reasoning effort (`session/setReasoningEffort`). */
778
+ async setReasoningEffort(reasoningEffort) {
779
+ return (await this.#command("setReasoningEffort", "session/setReasoningEffort", {
780
+ reasoningEffort,
781
+ }));
782
+ }
783
+ /** Select one of the host's preconfigured approval modes (`session/setApprovalMode`). */
784
+ async setApprovalMode(mode) {
785
+ return (await this.#command("setApprovalMode", "session/setApprovalMode", {
786
+ mode,
787
+ }));
788
+ }
789
+ /** Set or change this session's stored name (`session/rename`). */
790
+ async rename(name) {
791
+ return (await this.#command("rename", "session/rename", { name }));
792
+ }
793
+ /**
794
+ * Release this session from the host (`session/leave`); `stop: true` also
795
+ * cancels unfinished work. Admission only: the host reports the release
796
+ * later as `session/leaveCompleted`.
797
+ */
798
+ async leave(options = {}) {
799
+ return (await this.#command("leave", "session/leave", { ...options }));
800
+ }
801
+ /** Queue a note into a running subagent (`subagent/sendMessage`). */
802
+ async sendSubagentMessage(subagentId, body) {
803
+ return await this.#subagent("sendSubagentMessage", "subagent/sendMessage", { body, subagentId });
804
+ }
805
+ /** Queue a follow-up task for a subagent (`subagent/followupTask`). */
806
+ async followupSubagentTask(subagentId, body) {
807
+ return await this.#subagent("followupSubagentTask", "subagent/followupTask", { body, subagentId });
808
+ }
809
+ /** Ask a subagent to yield at its next boundary (`subagent/interrupt`). */
810
+ async interruptSubagent(subagentId, options = {}) {
811
+ return await this.#subagent("interruptSubagent", "subagent/interrupt", { ...options, subagentId });
812
+ }
813
+ /** Stop a running subagent (`subagent/stop`). */
814
+ async stopSubagent(subagentId, options = {}) {
815
+ return await this.#subagent("stopSubagent", "subagent/stop", { ...options, subagentId });
816
+ }
817
+ /** Resume a paused or recoverable subagent (`subagent/resume`). */
818
+ async resumeSubagent(subagentId) {
819
+ return await this.#subagent("resumeSubagent", "subagent/resume", { subagentId });
820
+ }
821
+ /** Reopen a stopped or closed subagent (`subagent/reopen`). */
822
+ async reopenSubagent(subagentId) {
823
+ return await this.#subagent("reopenSubagent", "subagent/reopen", { subagentId });
824
+ }
825
+ /** Close a subagent as its owner (`subagent/close`). */
826
+ async closeSubagent(subagentId, options = {}) {
827
+ return await this.#subagent("closeSubagent", "subagent/close", { ...options, subagentId });
828
+ }
829
+ /** Consume a subagent's ready result (`subagent/readResult`). */
830
+ async readSubagentResult(subagentId) {
831
+ return await this.#subagent("readSubagentResult", "subagent/readResult", { subagentId });
832
+ }
833
+ async #subagent(verb, method, params) {
834
+ return (await this.#command(verb, method, params));
835
+ }
836
+ /** List this session's installed plugins (`plugin/list`); a query, like `listTasks`. */
837
+ async listPlugins() {
838
+ const ack = await this.#requireLiveConnection("listPlugins").request("plugin/list", {
839
+ sessionId: this.sessionId,
840
+ });
841
+ return ack;
842
+ }
843
+ /** Install one plugin from a marketplace or a host folder (`plugin/install`). */
844
+ async installPlugin(target) {
845
+ return (await this.#command("installPlugin", "plugin/install", { target }));
846
+ }
847
+ /** Turn one skill on or off in one scope (`skill/setActivation`). */
848
+ async setSkillActivation(options) {
849
+ return (await this.#command("setSkillActivation", "skill/setActivation", {
850
+ ...options,
851
+ }));
852
+ }
565
853
  // ---- consumer-driven SS4.13 retirement verbs ----------------------------
566
854
  /**
567
855
  * Stop the SS3.1.1 retry loop for one entry and take its input back