@muse-code/sdk 1.4.14 → 1.4.20

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,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
+ }
@@ -19,6 +19,7 @@
19
19
  * composition every earlier arm builds — stays valid and refuses the submit
20
20
  * verbs loudly rather than dropping a caller's input on the floor.
21
21
  */
22
+ import type { FoldExtension } from "../fold/extension.js";
22
23
  import { SessionFold } from "../fold/session-fold.js";
23
24
  import type { FoldOutcome, ViewEvent } from "../fold/session-fold.js";
24
25
  import { PendingCommandSet } from "../pending/pending-command-set.js";
@@ -26,11 +27,12 @@ import type { PendingRetirement, ReplayAnswer, SnapshotJoinFacts } from "../pend
26
27
  import type { Connection } from "../connection/connection.js";
27
28
  import type { ApprovalFailureHandler, ApprovalHandler } from "./approval.js";
28
29
  import type { SendUserTurnOptions } from "./turn-submit.js";
29
- import type { GapFillFailureHandler } from "./gap-fill.js";
30
+ import type { GapFillFailureHandler, WireFrame } from "./gap-fill.js";
30
31
  import type { DiscardedSessions } from "./discarded.js";
31
32
  import type { HostDeathDischarge, HostDeathNotification, SessionDurabilityProfile } from "./host-death.js";
32
- import type { Turn } from "./turn-handle.js";
33
- import type { SessionResumeResult, SessionStartResult, UserInputAnswer, UserInputAnswerResult } from "../msp.js";
33
+ import type { FoldedItem, Turn } from "./turn-handle.js";
34
+ import type { RunOptions, RunResult } from "./run.js";
35
+ 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
36
  /**
35
37
  * Which verb opened this session, and what it answered.
36
38
  *
@@ -47,6 +49,8 @@ export type SessionOpening = {
47
49
  readonly verb: "session/resume";
48
50
  readonly result: SessionResumeResult;
49
51
  };
52
+ /** The optional reason `interruptSubagent`/`stopSubagent`/`closeSubagent` record. */
53
+ export type SubagentReasonOptions = Readonly<Pick<SubagentOwnerReasonParams, "reason">>;
50
54
  /**
51
55
  * Options for constructing a `Session` directly. Sessions opened through
52
56
  * `MuseClient` are configured for you; build one yourself when you manage
@@ -77,6 +81,12 @@ export interface SessionOptions {
77
81
  readonly discarded?: DiscardedSessions;
78
82
  /** Set by `MuseClient`; see {@link SessionOpening}. */
79
83
  readonly opening?: SessionOpening;
84
+ /**
85
+ * Fold extensions for this session (FR-97527-3), consulted inside the
86
+ * one apply path. `MuseClient` forwards its own list here for every
87
+ * session it opens, so one registration covers both planes.
88
+ */
89
+ readonly extensions?: readonly FoldExtension[];
80
90
  }
81
91
  /**
82
92
  * The fold as a consumer may READ it.
@@ -193,6 +203,36 @@ export interface SessionApplyOutcome<I> {
193
203
  */
194
204
  readonly io: Promise<readonly PendingRetirement<I>[]>;
195
205
  }
206
+ /**
207
+ * One inbound frame as a session applies it: a view notification, a frame an
208
+ * SS4.8 fill spliced in from a page, or the frame a re-sent server request is
209
+ * folded as (`approval/request` as itself, `userInput/request` as its
210
+ * `userInput/requested` twin).
211
+ */
212
+ export type ViewFrame = WireFrame;
213
+ /**
214
+ * One event a session folded, as `Session.events()` yields it: the event and
215
+ * what folding it changed, self-contained because the loop body may run after
216
+ * later events folded (FR-97336-1). Optional members may be added; a consumer
217
+ * reads the ones it knows.
218
+ */
219
+ export interface SessionEvent<I = unknown> {
220
+ /** The protocol event, as the session applied it. */
221
+ readonly frame: ViewFrame;
222
+ /**
223
+ * What it changed: the value `Session.apply` returned for a live event. An
224
+ * event a gap fill spliced in carries its fold result and no retirements or
225
+ * I/O of its own: those settle on the `view/gap` event's `io`.
226
+ */
227
+ readonly outcome: SessionApplyOutcome<I>;
228
+ /** For an item event that changed the item: the item as it stood after this event. */
229
+ readonly item?: FoldedItem;
230
+ }
231
+ /** Options for `Session.events()`. */
232
+ export interface SessionEventsOptions {
233
+ /** Aborting it ends the stream, as `return()` does. */
234
+ readonly signal?: AbortSignal;
235
+ }
196
236
  /**
197
237
  * One conversation with the agent.
198
238
  *
@@ -228,6 +268,21 @@ export declare class Session<I = unknown> {
228
268
  readonly method: string;
229
269
  readonly params?: unknown;
230
270
  }): SessionApplyOutcome<I>;
271
+ /**
272
+ * Every event this session folds from now on, with what it changed
273
+ * (FR-97336-1). Live from the call, never replayed: read `fold`, then call
274
+ * this in the same tick, and nothing is missed, including the events
275
+ * folded while `startSession`/`resumeSession` was in flight. Each folded
276
+ * event is yielded once, in arrival order; the events a gap fill splices in
277
+ * are yielded when applied, in order. Buffered like `turn.items()`, so a slow
278
+ * reader never holds folding up.
279
+ *
280
+ * `break`, `return()` or `options.signal` ends it. It finishes the way a
281
+ * turn's `items()` does when the host dies: it ends after an ephemeral
282
+ * host's death, and rejects with `MuseHostDiedError` after a durable one's,
283
+ * once the events it already buffered are read.
284
+ */
285
+ events(options?: SessionEventsOptions): AsyncIterableIterator<SessionEvent<I>>;
231
286
  /** Observe SS4.8 fills that did not complete. See `MuseGapFillError`. */
232
287
  onGapError(handler: GapFillFailureHandler): void;
233
288
  /**
@@ -235,7 +290,7 @@ export declare class Session<I = unknown> {
235
290
  * the fold has already settled returns its settled handle, so a wait
236
291
  * registered late resolves instead of hanging on an event that has passed.
237
292
  */
238
- turn(turnId: string): Turn;
293
+ turn(turnId: string): Turn<I>;
239
294
  /**
240
295
  * A host process exited. Classify it, and discharge SS2.13.3b if the profile
241
296
  * demands it (tasks.md T030b, FM-002).
@@ -268,7 +323,15 @@ export declare class Session<I = unknown> {
268
323
  * needs the fold: the entry's insertion point, which is the last item this
269
324
  * session holds at submission time.
270
325
  */
271
- sendUserTurn(options: SendUserTurnOptions<I>): Promise<Turn>;
326
+ sendUserTurn(options: SendUserTurnOptions<I>): Promise<Turn<I>>;
327
+ /**
328
+ * Run one turn to its end in a single call (FR-79108-1): submit `input`
329
+ * (a string is one text part), wait for the server to end the turn, and
330
+ * resolve its outcome, final answer text, items and usage. Pass
331
+ * `options.signal` to stop the turn; see {@link RunOptions}. Use
332
+ * `sendUserTurn` to stream items or deltas as they arrive.
333
+ */
334
+ run(input: string | readonly TurnInputPart[], options?: RunOptions): Promise<RunResult>;
272
335
  /** Answer approvals with `handler` (FR-019). See `ApprovalRouter`. */
273
336
  onApproval(handler: ApprovalHandler): void;
274
337
  /** Observe round trips that did not complete. See `ApprovalFailure`. */
@@ -280,6 +343,77 @@ export declare class Session<I = unknown> {
280
343
  * only when the server's `userInput/settled` arrives.
281
344
  */
282
345
  answerUserInput(userInputId: string, answers: readonly UserInputAnswer[]): Promise<UserInputAnswerResult>;
346
+ /** List this session's live background and foreground tasks (`task/list`). */
347
+ listTasks(): Promise<TaskListResult>;
348
+ /** List this session's user-invocable skills (`skill/list`). */
349
+ listSkills(): Promise<SkillListResult>;
350
+ /** List this session's installed hook rows (`hook/list`). */
351
+ listHooks(): Promise<HookListResult>;
352
+ /** Pause a live workflow run (`workflow/pause`). */
353
+ pauseWorkflow(workflowRunId: string): Promise<WorkflowControlResult>;
354
+ /** Resume a paused workflow run (`workflow/resume`). */
355
+ resumeWorkflow(workflowRunId: string): Promise<WorkflowResumeResult>;
356
+ /** Request a recap of this session (`recap/request`); admission only. */
357
+ requestRecap(): Promise<RecapRequestResult>;
358
+ /**
359
+ * Submit feedback about this session (`feedback/submit`). The host
360
+ * serves it only when the spawn requested the `feedback` capability
361
+ * (`requestedCapabilities: ["feedback"]`) and install policy allows
362
+ * it; without that grant the host refuses the call. Its wire params
363
+ * define no `commandId` (each call is one submit; the wire contract
364
+ * attaches no dedup), so it rides `request()` and mints none.
365
+ */
366
+ submitFeedback(input: Omit<FeedbackSubmitParams, "sessionId">): Promise<FeedbackSubmitResult>;
367
+ /**
368
+ * Open a side chat from this session (`session/sideChat`). Returns the wire
369
+ * result; opening a wired `Session` for the new side session is the
370
+ * caller's composition, as with a directly built `Session`.
371
+ */
372
+ openSideChat(): Promise<SessionSideChatResult>;
373
+ /**
374
+ * Fork this session into a new one (`session/fork`). Returns the wire
375
+ * result for the new session; opening a wired `Session` for it stays the
376
+ * caller's composition, as with `openSideChat`.
377
+ */
378
+ fork(options?: Readonly<Omit<SessionForkParams, "commandId" | "sessionId">>): Promise<SessionForkResult>;
379
+ /** Compact this session's context (`session/compact`); admission only, or `noop`. */
380
+ compact(options?: Readonly<Omit<SessionCompactParams, "commandId" | "sessionId">>): Promise<SessionCompactResult>;
381
+ /** Select the model for later model calls (`session/setModel`). */
382
+ setModel(model: ModelSelection): Promise<SessionSetModelResult>;
383
+ /** Set this session's standing reasoning effort (`session/setReasoningEffort`). */
384
+ setReasoningEffort(reasoningEffort: ReasoningEffort): Promise<SessionSetReasoningEffortResult>;
385
+ /** Select one of the host's preconfigured approval modes (`session/setApprovalMode`). */
386
+ setApprovalMode(mode: ApprovalMode): Promise<SessionSetApprovalModeResult>;
387
+ /** Set or change this session's stored name (`session/rename`). */
388
+ rename(name: string): Promise<SessionRenameResult>;
389
+ /**
390
+ * Release this session from the host (`session/leave`); `stop: true` also
391
+ * cancels unfinished work. Admission only: the host reports the release
392
+ * later as `session/leaveCompleted`.
393
+ */
394
+ leave(options?: Readonly<Omit<SessionLeaveParams, "commandId" | "sessionId">>): Promise<SessionLeaveResult>;
395
+ /** Queue a note into a running subagent (`subagent/sendMessage`). */
396
+ sendSubagentMessage(subagentId: string, body: string): Promise<CommandAcceptedResult>;
397
+ /** Queue a follow-up task for a subagent (`subagent/followupTask`). */
398
+ followupSubagentTask(subagentId: string, body: string): Promise<CommandAcceptedResult>;
399
+ /** Ask a subagent to yield at its next boundary (`subagent/interrupt`). */
400
+ interruptSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
401
+ /** Stop a running subagent (`subagent/stop`). */
402
+ stopSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
403
+ /** Resume a paused or recoverable subagent (`subagent/resume`). */
404
+ resumeSubagent(subagentId: string): Promise<CommandAcceptedResult>;
405
+ /** Reopen a stopped or closed subagent (`subagent/reopen`). */
406
+ reopenSubagent(subagentId: string): Promise<CommandAcceptedResult>;
407
+ /** Close a subagent as its owner (`subagent/close`). */
408
+ closeSubagent(subagentId: string, options?: SubagentReasonOptions): Promise<CommandAcceptedResult>;
409
+ /** Consume a subagent's ready result (`subagent/readResult`). */
410
+ readSubagentResult(subagentId: string): Promise<CommandAcceptedResult>;
411
+ /** List this session's installed plugins (`plugin/list`); a query, like `listTasks`. */
412
+ listPlugins(): Promise<PluginListResult>;
413
+ /** Install one plugin from a marketplace or a host folder (`plugin/install`). */
414
+ installPlugin(target: PluginInstallTarget): Promise<PluginInstallResult>;
415
+ /** Turn one skill on or off in one scope (`skill/setActivation`). */
416
+ setSkillActivation(options: Readonly<Omit<SkillSetActivationParams, "commandId" | "sessionId">>): Promise<SkillSetActivationResult>;
283
417
  /**
284
418
  * Stop the SS3.1.1 retry loop for one entry and take its input back
285
419
  * (SS4.13 "Abandoned").