@openclaw/muse 2026.11.3 → 2026.11.5-beta.2

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
@@ -18,6 +18,16 @@ or on the `meta` provider; `auto` never picks it.
18
18
  See [Muse Code agent runtime](https://docs.openclaw.ai/plugins/muse) for auth,
19
19
  approvals, sessions, limitations, and live tests.
20
20
 
21
+ Chat switches from preparation to waiting when Muse accepts the turn, then
22
+ streams assistant and tool activity through the Gateway. Once the answer is saved
23
+ and Muse starts its post-answer reminder work, the chat activity indicator stops.
24
+ The run remains active until Muse reports turn completion, so Stop and queued
25
+ messages keep their normal behavior during background finalization.
26
+ Native tool starts restore visible activity, including when they follow assistant
27
+ text. `finishing` settles an attempt rather than the logical run: newer retry,
28
+ fallback, or foreground activity restores the indicator, while older replayed
29
+ events cannot replace the newer state.
30
+
21
31
  ## Package
22
32
 
23
33
  - Plugin id: `muse`
@@ -1,89 +1,20 @@
1
1
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
2
2
  import fs, { realpath } from "node:fs/promises";
3
- import { AgentHarnessPreflightError, agentHarnessAttemptTerminal, clearActiveEmbeddedRun, execPolicy, projectAgentToolActivity, resolveBootstrapContextForRun, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
3
+ import { createAgentHarnessAttemptLifecycle, emitAgentHarnessAttemptEvent, makeZeroUsageSnapshot, resolveAgentHarnessHistoryLimits } from "openclaw/plugin-sdk/agent-harness-attempt-runtime";
4
+ import { AgentHarnessPreflightError, agentHarnessAttemptTerminal, clearActiveEmbeddedRun, embeddedAgentLog, execPolicy, projectAgentToolActivity, resolveBootstrapContextForRun, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
4
5
  import { createNativeSessionCommitFinalizer } from "openclaw/plugin-sdk/agent-harness-session-runtime";
5
6
  import { resolveAgentConfig, resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
7
+ import { SessionManager } from "openclaw/plugin-sdk/agent-sessions";
6
8
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7
9
  import { loadExecApprovalsReadOnlyAsync, resolveExecApprovalsFromFile } from "openclaw/plugin-sdk/exec-approvals-runtime";
8
10
  import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
9
11
  import { MAX_TIMER_TIMEOUT_MS } from "openclaw/plugin-sdk/number-runtime";
10
12
  import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
11
13
  import { appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity } from "openclaw/plugin-sdk/session-transcript-runtime";
12
- import { resolveAgentHarnessHistoryLimits } from "openclaw/plugin-sdk/agent-harness-attempt-runtime";
13
- import { SessionManager } from "openclaw/plugin-sdk/agent-sessions";
14
14
  import { createHash } from "node:crypto";
15
- import { MspError, Session, readSessionDurability, spawnMspConnection } from "@muse-code/sdk";
16
15
  import path from "node:path";
16
+ import { MspError, Session, readSessionDurability, spawnMspConnection } from "@muse-code/sdk";
17
17
  import { resolveStateDir } from "openclaw/plugin-sdk/state-paths";
18
- //#region extensions/muse/src/approvals.ts
19
- function selectApprovalChoice(request, decision) {
20
- const wanted = decision === "allow-once" ? "approved" : "denied";
21
- const choice = request.availableChoices.find((candidate) => candidate.decision === wanted && candidate.scope === "once") ?? (wanted === "denied" ? request.availableChoices.find((candidate) => candidate.decision === "denied" || candidate.decision === "abort") : void 0);
22
- if (!choice) throw new Error(`Muse offered no safe ${wanted} approval choice`);
23
- return { choiceId: choice.choiceId };
24
- }
25
- const APPROVAL_TIMEOUT_MS = 12e4;
26
- function createApprovalHandler(params) {
27
- return async (request) => {
28
- params.hostCapabilities.assertActive();
29
- const timeoutMs = Math.min(APPROVAL_TIMEOUT_MS, params.timeoutMs);
30
- const answer = await params.hostCapabilities.requestApproval({
31
- title: `Muse: ${request.toolName}`.slice(0, 80),
32
- description: (request.subject.command ?? request.subject.path ?? request.subject.host ?? request.toolName).slice(0, 512),
33
- ...request.rawArgs ? { detail: request.rawArgs.slice(0, 16384) } : {},
34
- toolName: request.toolName,
35
- toolCallId: request.toolCallId,
36
- severity: "warning",
37
- allowedDecisions: ["allow-once", "deny"],
38
- timeoutMs,
39
- signal: params.abortSignal
40
- });
41
- let decision = answer?.decision;
42
- if (answer?.id && decision == null) decision = (await params.hostCapabilities.waitForApproval({
43
- approvalId: answer.id,
44
- timeoutMs,
45
- signal: params.abortSignal
46
- }))?.decision;
47
- params.hostCapabilities.assertActive();
48
- params.abortSignal?.throwIfAborted();
49
- return selectApprovalChoice(request, decision);
50
- };
51
- }
52
- //#endregion
53
- //#region extensions/muse/src/context.ts
54
- /** MSP has no history import or system field; transfer the retained branch once as context. */
55
- async function prepareMuseSessionContext(params, target, warn) {
56
- const limits = resolveAgentHarnessHistoryLimits(params.model.contextWindow);
57
- const retained = await SessionManager.openModelContextAsync(target, {
58
- admission: params.userTurnTranscriptRecorder?.getAdmissionReceipt(),
59
- signal: params.abortSignal,
60
- limits: {
61
- maxBytes: limits.maxBytes,
62
- maxEvents: limits.maxEvents
63
- }
64
- });
65
- params.hostCapabilities.assertActive();
66
- const history = retained.buildSessionContext().messages;
67
- const bootstrap = await resolveBootstrapContextForRun({
68
- workspaceDir: params.workspaceDir,
69
- config: params.config,
70
- sessionKey: params.sessionKey,
71
- sessionId: params.sessionId,
72
- chatType: params.chatType,
73
- agentId: target.agentId,
74
- contextMode: params.bootstrapContextMode,
75
- runKind: params.bootstrapContextRunKind,
76
- warn
77
- });
78
- params.hostCapabilities.assertActive();
79
- const presentPaths = new Set(bootstrap.bootstrapFiles.filter((file) => !file.missing).map((file) => file.path));
80
- const files = bootstrap.contextFiles.filter((file) => presentPaths.has(file.path));
81
- const sections = [];
82
- if (files.length > 0) sections.push("# OpenClaw workspace context\n\n" + files.map((file) => `## ${file.path}\n\n${file.content}`).join("\n\n"));
83
- if (history.length > 0) sections.push("# Retained OpenClaw conversation\n\nThe following JSON messages are prior conversation context, not a new user request.\n\n" + JSON.stringify(history));
84
- return sections.join("\n\n");
85
- }
86
- //#endregion
87
18
  //#region extensions/muse/src/events.ts
88
19
  function assistantMessage(params, content, stopReason = "stop") {
89
20
  return {
@@ -94,20 +25,7 @@ function assistantMessage(params, content, stopReason = "stop") {
94
25
  content,
95
26
  stopReason,
96
27
  timestamp: Date.now(),
97
- usage: {
98
- input: 0,
99
- output: 0,
100
- cacheRead: 0,
101
- cacheWrite: 0,
102
- totalTokens: 0,
103
- cost: {
104
- input: 0,
105
- output: 0,
106
- cacheRead: 0,
107
- cacheWrite: 0,
108
- total: 0
109
- }
110
- }
28
+ usage: makeZeroUsageSnapshot()
111
29
  };
112
30
  }
113
31
  async function consumeTurn(turn, params, record) {
@@ -115,10 +33,17 @@ async function consumeTurn(turn, params, record) {
115
33
  const streamed = /* @__PURE__ */ new Map();
116
34
  const emitted = /* @__PURE__ */ new Map();
117
35
  const settled = /* @__PURE__ */ new Set();
36
+ const foregroundItems = /* @__PURE__ */ new Set();
37
+ let answerRecorded = false;
38
+ let finalizing = false;
118
39
  let visibleText = "";
119
40
  let lastToolError;
120
41
  let messageStarted = false;
121
42
  let streamQueue = Promise.resolve();
43
+ const emitEvent = (event) => emitAgentHarnessAttemptEvent(params, event, {
44
+ label: "Muse",
45
+ log: embeddedAgentLog
46
+ });
122
47
  const emitField = (item, field, value) => {
123
48
  streamQueue = streamQueue.then(async () => {
124
49
  const key = `${item.itemId}:${field}`;
@@ -131,9 +56,10 @@ async function consumeTurn(turn, params, record) {
131
56
  messageStarted = true;
132
57
  await params.onAssistantMessageStart?.();
133
58
  }
134
- await params.onAgentEvent?.({
59
+ await emitEvent({
135
60
  stream: "assistant",
136
61
  data: {
62
+ itemId: item.itemId,
137
63
  delta,
138
64
  text: value
139
65
  }
@@ -156,10 +82,25 @@ async function consumeTurn(turn, params, record) {
156
82
  for await (const item of turn.items()) {
157
83
  const first = !items.has(item.itemId);
158
84
  items.set(item.itemId, item);
85
+ if (item.kind !== "reminderChild" && item.kind !== "userMessage") {
86
+ if (item.status === "inProgress") foregroundItems.add(item.itemId);
87
+ else foregroundItems.delete(item.itemId);
88
+ if (first) {
89
+ answerRecorded = false;
90
+ finalizing = false;
91
+ }
92
+ }
93
+ if (first && item.kind === "reminderChild" && item.status === "inProgress" && answerRecorded && foregroundItems.size === 0 && !finalizing) {
94
+ await emitEvent({
95
+ stream: "lifecycle",
96
+ data: { phase: "finishing" }
97
+ });
98
+ finalizing = true;
99
+ }
159
100
  if (first) {
160
101
  for (const [key, value] of streamed) if (key.startsWith(`${item.itemId}:`)) await emitField(item, key.slice(item.itemId.length + 1), value);
161
102
  }
162
- if (item.kind === "toolCall" && first) await params.onAgentEvent?.({
103
+ if (item.kind === "toolCall" && first) await emitEvent({
163
104
  stream: "item",
164
105
  data: projectAgentToolActivity({
165
106
  toolCallId: item.callId ?? item.itemId,
@@ -214,7 +155,7 @@ async function consumeTurn(turn, params, record) {
214
155
  result: item.visibleOutput,
215
156
  isError: item.status !== "completed"
216
157
  });
217
- await params.onAgentEvent?.({
158
+ await emitEvent({
218
159
  stream: "item",
219
160
  data: projectAgentToolActivity({
220
161
  toolCallId: id,
@@ -236,7 +177,7 @@ async function consumeTurn(turn, params, record) {
236
177
  thinking: item.text ?? item.summary?.join("\n") ?? ""
237
178
  }]));
238
179
  await params.onReasoningEnd?.();
239
- } else if (item.kind !== "userMessage") await params.onAgentEvent?.({
180
+ } else if (item.kind !== "userMessage") await emitEvent({
240
181
  stream: "item",
241
182
  data: {
242
183
  type: String(item.kind),
@@ -245,7 +186,10 @@ async function consumeTurn(turn, params, record) {
245
186
  id: item.itemId
246
187
  }
247
188
  });
248
- if (messages.length) await record(item.itemId, messages);
189
+ if (messages.length) {
190
+ await record(item.itemId, messages);
191
+ if (item.kind === "agentMessage") answerRecorded = true;
192
+ }
249
193
  }
250
194
  })();
251
195
  await Promise.all([projections, deltas]);
@@ -257,45 +201,7 @@ async function consumeTurn(turn, params, record) {
257
201
  }
258
202
  //#endregion
259
203
  //#region extensions/muse/package.json
260
- var version = "2026.11.3";
261
- //#endregion
262
- //#region extensions/muse/src/environment.ts
263
- async function museEnvironment(apiKey, env = process.env) {
264
- const inherited = {
265
- ...process.env,
266
- ...env
267
- };
268
- const managedHome = path.join(resolveStateDir(inherited), "muse");
269
- const authPath = path.join(managedHome, "muse", "auth.json");
270
- let credentialSource;
271
- try {
272
- const stat = await fs.stat(authPath);
273
- credentialSource = JSON.stringify([
274
- "managed",
275
- authPath,
276
- stat.dev,
277
- stat.ino,
278
- stat.size,
279
- stat.mtimeMs,
280
- stat.ctimeMs
281
- ]);
282
- } catch (error) {
283
- if (error instanceof Error && "code" in error && error.code === "ENOENT") credentialSource = "native";
284
- else throw error;
285
- }
286
- return {
287
- credentialSource,
288
- env: {
289
- ...inherited,
290
- MUSE_NO_AUTO_UPDATE: "1",
291
- ...credentialSource !== "native" ? {
292
- TBH_CREDENTIAL_BACKEND: "file",
293
- XDG_CONFIG_HOME: managedHome
294
- } : {},
295
- ...apiKey ? { META_API_KEY: apiKey } : {}
296
- }
297
- };
298
- }
204
+ var version = "2026.11.5-beta.2";
299
205
  //#endregion
300
206
  //#region extensions/muse/src/runtime.ts
301
207
  const RESUME_RETRY_KINDS = {
@@ -341,15 +247,45 @@ async function openMuseSession(runtime, options) {
341
247
  return session;
342
248
  }
343
249
  var MusePool = class {
344
- constructor(binaryPath = "muse") {
250
+ constructor(binaryPath = "muse", noSessionLog = false) {
345
251
  this.binaryPath = binaryPath;
252
+ this.noSessionLog = noSessionLog;
346
253
  this.entries = /* @__PURE__ */ new Map();
347
254
  this.disposed = false;
348
255
  }
349
- async acquire(workspace, apiKey, readOnly) {
256
+ async acquire(workspace, apiKey, readOnly, signal) {
257
+ signal?.throwIfAborted();
350
258
  if (this.disposed) throw new Error("Muse runtime has been disposed");
351
- const { env, credentialSource } = await museEnvironment(apiKey);
259
+ const inherited = { ...process.env };
260
+ const managedHome = path.join(resolveStateDir(inherited), "muse");
261
+ const authPath = path.join(managedHome, "muse", "auth.json");
262
+ let credentialSource;
263
+ try {
264
+ const stat = await fs.stat(authPath);
265
+ credentialSource = JSON.stringify([
266
+ "managed",
267
+ authPath,
268
+ stat.dev,
269
+ stat.ino,
270
+ stat.size,
271
+ stat.mtimeMs,
272
+ stat.ctimeMs
273
+ ]);
274
+ } catch (error) {
275
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") credentialSource = "native";
276
+ else throw error;
277
+ }
278
+ const env = {
279
+ ...inherited,
280
+ MUSE_NO_AUTO_UPDATE: "1",
281
+ ...credentialSource !== "native" ? {
282
+ TBH_CREDENTIAL_BACKEND: "file",
283
+ XDG_CONFIG_HOME: managedHome
284
+ } : {},
285
+ ...apiKey ? { META_API_KEY: apiKey } : {}
286
+ };
352
287
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
288
+ signal?.throwIfAborted();
353
289
  const apiKeyIdentity = credentialFingerprint(apiKey);
354
290
  const key = JSON.stringify([
355
291
  workspace,
@@ -360,27 +296,40 @@ var MusePool = class {
360
296
  let entry = this.entries.get(key);
361
297
  if (!entry || entry.credentialIdentity !== credentialIdentity) {
362
298
  const previous = entry;
299
+ const startup = new AbortController();
363
300
  const pending = (async () => {
364
301
  if (previous) await (await previous.pending.catch(() => void 0))?.close();
365
- return this.spawn(workspace, env, readOnly, credentialIdentity);
302
+ return this.spawn(workspace, env, readOnly, credentialIdentity, startup.signal);
366
303
  })();
367
304
  entry = {
368
305
  credentialIdentity,
369
- pending
306
+ pending,
307
+ startup
370
308
  };
371
309
  this.entries.set(key, entry);
372
310
  pending.catch(() => {
373
311
  if (this.entries.get(key) === entry) this.entries.delete(key);
374
312
  });
375
313
  }
376
- const runtime = await entry.pending;
314
+ const abort = () => entry.startup.abort(signal?.reason);
315
+ signal?.addEventListener("abort", abort, { once: true });
316
+ let runtime;
317
+ try {
318
+ runtime = await entry.pending;
319
+ } finally {
320
+ signal?.removeEventListener("abort", abort);
321
+ }
322
+ if (signal?.aborted) {
323
+ await runtime.close();
324
+ signal.throwIfAborted();
325
+ }
377
326
  if (this.disposed) {
378
327
  await runtime.close();
379
328
  throw new Error("Muse runtime was disposed during startup");
380
329
  }
381
330
  if (this.entries.get(key) !== entry || runtime.dead || runtime.closing) {
382
331
  if (this.entries.get(key) === entry) this.entries.delete(key);
383
- return this.acquire(workspace, apiKey, readOnly);
332
+ return this.acquire(workspace, apiKey, readOnly, signal);
384
333
  }
385
334
  clearTimeout(runtime.timer);
386
335
  runtime.users++;
@@ -398,11 +347,16 @@ var MusePool = class {
398
347
  }
399
348
  };
400
349
  }
401
- async spawn(workspace, env, readOnly, credentialIdentity) {
350
+ async spawn(workspace, env, readOnly, credentialIdentity, signal) {
402
351
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
352
+ signal.throwIfAborted();
403
353
  const handshake = spawnMspConnection({
404
354
  command: this.binaryPath,
405
- args: ["serve", ...readOnly ? ["--disable-shell", "--disable-write"] : []],
355
+ args: [
356
+ "serve",
357
+ ...this.noSessionLog ? ["--no-session-log"] : [],
358
+ ...readOnly ? ["--disable-shell", "--disable-write"] : []
359
+ ],
406
360
  cwd: workspace,
407
361
  env,
408
362
  shutdownTimeoutMs: 1e3
@@ -411,11 +365,16 @@ var MusePool = class {
411
365
  handshake.close();
412
366
  }, 3e4);
413
367
  startup.unref();
368
+ const abort = () => {
369
+ handshake.close();
370
+ };
371
+ signal.addEventListener("abort", abort, { once: true });
414
372
  try {
415
373
  const host = await handshake.initialize({ clientInfo: {
416
374
  name: "openclaw",
417
375
  version
418
376
  } });
377
+ signal.throwIfAborted();
419
378
  const runtime = {
420
379
  host,
421
380
  credentialIdentity,
@@ -450,6 +409,7 @@ var MusePool = class {
450
409
  throw new Error(`Cannot start Muse Code (${this.binaryPath}). Install Muse and run muse to sign in. ${String(error)} ${handshake.child.stderrTail.join("\n")}`, { cause: error });
451
410
  } finally {
452
411
  clearTimeout(startup);
412
+ signal.removeEventListener("abort", abort);
453
413
  }
454
414
  }
455
415
  async dispose() {
@@ -464,51 +424,62 @@ var MusePool = class {
464
424
  };
465
425
  //#endregion
466
426
  //#region extensions/muse/src/verify-setup.ts
467
- async function readMuseCatalog(ctx) {
468
- const config = ctx.config.plugins?.entries?.muse?.config;
469
- const { env } = await museEnvironment();
470
- ctx.signal.throwIfAborted();
471
- ctx.assertCurrent();
472
- const host = spawnMspConnection({
473
- command: isRecord(config) && typeof config.binaryPath === "string" ? config.binaryPath : "muse",
474
- args: [
475
- "serve",
476
- "--no-session-log",
477
- "--disable-shell",
478
- "--disable-write"
479
- ],
480
- env,
481
- shutdownTimeoutMs: 1e3
482
- });
483
- const abort = () => {
484
- host.close();
485
- };
486
- ctx.signal.addEventListener("abort", abort, { once: true });
487
- try {
488
- const ready = await host.initialize({ clientInfo: {
489
- name: "openclaw",
490
- version: "1"
491
- } });
492
- ctx.signal.throwIfAborted();
493
- ctx.assertCurrent();
494
- const catalog = await ready.connection.request("model/list", {});
427
+ function museDisplayName(modelId, displayLabel) {
428
+ const label = typeof displayLabel === "string" ? displayLabel : modelId;
429
+ if (label === modelId || modelId === "muse-wonder-full-1.0-contributor" && label === "muse-wonder-1.0-contributor") switch (modelId) {
430
+ case "muse-wonder-1.0-contributor": return "Muse Wonder Contributor";
431
+ case "muse-wonder-full-1.0": return "Muse Wonder Full";
432
+ case "muse-wonder-full-1.0-contributor": return "Muse Wonder Full Contributor";
433
+ }
434
+ return label;
435
+ }
436
+ /** One lifecycle owner for read-only catalog hosts; every read still asks Meta for live access. */
437
+ var MuseCatalogReader = class {
438
+ async read(ctx) {
495
439
  ctx.signal.throwIfAborted();
496
440
  ctx.assertCurrent();
497
- if (catalog.source !== "providerCatalog" || catalog.providerId !== "meta" || !Array.isArray(catalog.models)) throw new Error("Muse Code could not authenticate. Sign in again to access Meta models.");
498
- return catalog.models.flatMap((model) => isRecord(model) && model.providerId === "meta" && typeof model.modelId === "string" ? [{
499
- id: model.modelId,
500
- name: typeof model.displayLabel === "string" ? model.displayLabel : model.modelId,
501
- provider: "meta",
502
- nativeRuntime: "muse"
503
- }] : []);
504
- } finally {
505
- ctx.signal.removeEventListener("abort", abort);
506
- await host.close();
441
+ const config = ctx.config.plugins?.entries?.muse?.config;
442
+ const binaryPath = isRecord(config) && typeof config.binaryPath === "string" ? config.binaryPath : "muse";
443
+ if (this.current?.binaryPath !== binaryPath) {
444
+ const previous = this.current;
445
+ this.current = {
446
+ binaryPath,
447
+ pool: new MusePool(binaryPath, true)
448
+ };
449
+ await previous?.pool.dispose();
450
+ ctx.signal.throwIfAborted();
451
+ ctx.assertCurrent();
452
+ }
453
+ const lease = await this.current.pool.acquire(void 0, void 0, true, ctx.signal);
454
+ const abort = () => {
455
+ lease.runtime.close();
456
+ };
457
+ ctx.signal.addEventListener("abort", abort, { once: true });
458
+ try {
459
+ ctx.signal.throwIfAborted();
460
+ ctx.assertCurrent();
461
+ const catalog = await lease.runtime.host.connection.request("model/list", {});
462
+ ctx.signal.throwIfAborted();
463
+ ctx.assertCurrent();
464
+ if (catalog.source !== "providerCatalog" || catalog.providerId !== "meta" || !Array.isArray(catalog.models)) throw new Error("Muse Code could not authenticate. Sign in again to access Meta models.");
465
+ return catalog.models.flatMap((model) => isRecord(model) && model.providerId === "meta" && typeof model.modelId === "string" ? [{
466
+ id: model.modelId,
467
+ name: museDisplayName(model.modelId, model.displayLabel),
468
+ provider: "meta",
469
+ nativeRuntime: "muse"
470
+ }] : []);
471
+ } finally {
472
+ ctx.signal.removeEventListener("abort", abort);
473
+ lease.release();
474
+ }
507
475
  }
508
- }
509
- async function verifyMuseSetup(ctx) {
510
- if (!(await readMuseCatalog(ctx)).some((model) => model.provider === ctx.provider && model.id === ctx.modelId)) throw new Error(`Muse Code cannot access ${ctx.provider}/${ctx.modelId}. Select a model available to your Meta account.`);
511
- }
476
+ async verify(ctx) {
477
+ if (!(await this.read(ctx)).some((model) => model.provider === ctx.provider && model.id === ctx.modelId)) throw new Error(`Muse Code cannot access ${ctx.provider}/${ctx.modelId}. Select a model available to your Meta account.`);
478
+ }
479
+ async dispose() {
480
+ await this.current?.pool.dispose();
481
+ }
482
+ };
512
483
  //#endregion
513
484
  //#region extensions/muse/harness.ts
514
485
  /** Configuration Muse cannot honor; the message is safe and actionable for the chat user. */
@@ -518,8 +489,16 @@ function museRefusal(message) {
518
489
  userMessage: message
519
490
  });
520
491
  }
492
+ const APPROVAL_TIMEOUT_MS = 12e4;
493
+ function selectApprovalChoice(request, decision) {
494
+ const wanted = decision === "allow-once" ? "approved" : "denied";
495
+ const choice = request.availableChoices.find((candidate) => candidate.decision === wanted && candidate.scope === "once") ?? (wanted === "denied" ? request.availableChoices.find((candidate) => candidate.decision === "denied" || candidate.decision === "abort") : void 0);
496
+ if (!choice) throw new Error(`Muse offered no safe ${wanted} approval choice`);
497
+ return { choiceId: choice.choiceId };
498
+ }
521
499
  function createMuseAgentHarness(options) {
522
500
  const pool = new MusePool(options.binaryPath);
501
+ const catalogReader = new MuseCatalogReader();
523
502
  const queue = new KeyedAsyncQueue();
524
503
  const active = /* @__PURE__ */ new Map();
525
504
  const inFlight = /* @__PURE__ */ new Set();
@@ -600,7 +579,7 @@ function createMuseAgentHarness(options) {
600
579
  if (ask === "always") throw museRefusal("Muse cannot enforce exec ask: always for every native command. Use ask: on-miss/default, or the openclaw runtime.");
601
580
  const readOnly = security === "deny";
602
581
  const approvalMode = readOnly ? "denyUnmatched" : security === "full" && ask === "off" ? "allowAll" : "promptUnmatched";
603
- params.hostCapabilities.assertActive();
582
+ params.hostCapabilities.prepareContinuationRetryCount?.({ cwd: workspace });
604
583
  const lease = await pool.acquire(workspace, apiKey, readOnly);
605
584
  const { runtime } = lease;
606
585
  const compatibility = JSON.stringify([
@@ -617,10 +596,24 @@ function createMuseAgentHarness(options) {
617
596
  let aborted = false;
618
597
  let abortPromise;
619
598
  let failure;
599
+ let activeAttachment;
620
600
  const messages = [];
621
601
  let text = "";
622
602
  let lastToolError;
623
603
  let assistantTranscriptOwned = false;
604
+ const lifecycle = createAgentHarnessAttemptLifecycle({
605
+ attempt: params,
606
+ backend: "muse",
607
+ startedAtMs: params.startedAtMs ?? Date.now(),
608
+ state: {
609
+ lifecycleStarted: false,
610
+ lifecycleTerminalEmitted: false
611
+ },
612
+ emitEvent: (event) => emitAgentHarnessAttemptEvent(params, event, {
613
+ label: "Muse",
614
+ log: embeddedAgentLog
615
+ })
616
+ });
624
617
  let finalKey;
625
618
  const bound = params.hostCapabilities.bindModelExecution?.({
626
619
  provider: "meta",
@@ -700,16 +693,68 @@ function createMuseAgentHarness(options) {
700
693
  let sessionContext = "";
701
694
  if (freshSession) {
702
695
  try {
703
- sessionContext = await prepareMuseSessionContext(params, {
696
+ const contextAgentId = target.agentId ?? sessionAgentId;
697
+ const limits = resolveAgentHarnessHistoryLimits(params.model.contextWindow);
698
+ const retained = await SessionManager.openModelContextAsync({
704
699
  ...transcriptTarget,
705
- agentId: target.agentId ?? sessionAgentId
706
- }, options.logger?.warn);
700
+ agentId: contextAgentId
701
+ }, {
702
+ admission: params.userTurnTranscriptRecorder?.getAdmissionReceipt(),
703
+ signal: params.abortSignal,
704
+ limits: {
705
+ maxBytes: limits.maxBytes,
706
+ maxEvents: limits.maxEvents
707
+ }
708
+ });
709
+ params.hostCapabilities.assertActive();
710
+ const history = retained.buildSessionContext().messages;
711
+ const bootstrap = await resolveBootstrapContextForRun({
712
+ workspaceDir: params.workspaceDir,
713
+ config: params.config,
714
+ sessionKey: params.sessionKey,
715
+ sessionId: params.sessionId,
716
+ chatType: params.chatType,
717
+ agentId: contextAgentId,
718
+ contextMode: params.bootstrapContextMode,
719
+ runKind: params.bootstrapContextRunKind,
720
+ warn: options.logger?.warn
721
+ });
722
+ params.hostCapabilities.assertActive();
723
+ const presentPaths = new Set(bootstrap.bootstrapFiles.filter((file) => !file.missing).map((file) => file.path));
724
+ const files = bootstrap.contextFiles.filter((file) => presentPaths.has(file.path));
725
+ const sections = [];
726
+ if (files.length > 0) sections.push("# OpenClaw workspace context\n\n" + files.map((file) => `## ${file.path}\n\n${file.content}`).join("\n\n"));
727
+ if (history.length > 0) sections.push("# Retained OpenClaw conversation\n\nThe following JSON messages are prior conversation context, not a new user request.\n\n" + JSON.stringify(history));
728
+ sessionContext = sections.join("\n\n");
707
729
  } catch (error) {
708
730
  throw museRefusal(`Muse could not restore OpenClaw session context. Use the openclaw runtime or compact the session before retrying. ${formatErrorMessage(error)}`);
709
731
  }
710
732
  assertDispatchActive();
711
733
  }
712
- session.onApproval(createApprovalHandler(params));
734
+ session.onApproval(async (request) => {
735
+ params.hostCapabilities.assertActive();
736
+ const timeoutMs = Math.min(APPROVAL_TIMEOUT_MS, params.timeoutMs);
737
+ const answer = await params.hostCapabilities.requestApproval({
738
+ title: `Muse: ${request.toolName}`.slice(0, 80),
739
+ description: (request.subject.command ?? request.subject.path ?? request.subject.host ?? request.toolName).slice(0, 512),
740
+ ...request.rawArgs ? { detail: request.rawArgs.slice(0, 16384) } : {},
741
+ toolName: request.toolName,
742
+ toolCallId: request.toolCallId,
743
+ severity: "warning",
744
+ allowedDecisions: ["allow-once", "deny"],
745
+ timeoutMs,
746
+ signal: params.abortSignal
747
+ });
748
+ let decision = answer?.decision;
749
+ if (answer?.id && decision == null) decision = (await params.hostCapabilities.waitForApproval({
750
+ approvalId: answer.id,
751
+ timeoutMs,
752
+ signal: params.abortSignal
753
+ }))?.decision;
754
+ params.hostCapabilities.assertActive();
755
+ params.abortSignal?.throwIfAborted();
756
+ return selectApprovalChoice(request, decision);
757
+ });
713
758
  session.onApprovalError((error) => {
714
759
  failure = /* @__PURE__ */ new Error(`Muse approval failed (${error.kind}): ${error.kind === "unofferedChoice" ? `choice ${error.choiceId} was not offered` : formatErrorMessage(error.error)}`);
715
760
  stop().catch(() => runtime.close());
@@ -729,18 +774,23 @@ function createMuseAgentHarness(options) {
729
774
  mediaType: image.mimeType,
730
775
  base64Data: image.data
731
776
  }))];
777
+ lifecycle.emitExecutionPhaseOnce("context", { phase: "context_assembled" });
732
778
  turn = await session.sendUserTurn({
733
779
  input,
734
780
  ...params.thinkLevel ? { reasoningEffort: params.thinkLevel === "off" ? "minimal" : params.thinkLevel } : {}
735
781
  });
782
+ lifecycle.emitLifecycleStart({
783
+ provider: "meta",
784
+ model: params.modelId
785
+ });
786
+ lifecycle.emitExecutionPhaseOnce("accepted", { phase: "turn_accepted" });
736
787
  await options.sessionStore.register(params.sessionId, {
737
788
  sessionId: session.sessionId,
738
789
  compatibility
739
790
  });
740
791
  if (signal?.aborted) onAbort();
741
792
  else if (failure) stop().catch(() => runtime.close());
742
- setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile);
743
- params.replyOperation?.attachBackend(handle);
793
+ activeAttachment = setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, sessionAgentId);
744
794
  active.set(params.sessionId, abort);
745
795
  params.onExecutionStarted?.({ backend: "muse" });
746
796
  const nativeSessionId = session.sessionId;
@@ -751,18 +801,30 @@ function createMuseAgentHarness(options) {
751
801
  return {
752
802
  message: {
753
803
  ...message,
754
- idempotencyKey
804
+ idempotencyKey,
805
+ __openclaw: { runId: params.runId }
755
806
  },
756
807
  idempotencyLookup: "scan"
757
808
  };
758
809
  });
759
810
  params.hostCapabilities.assertActive();
760
- if ((await appendSessionTranscriptMessagesByIdentity({
811
+ const written = await appendSessionTranscriptMessagesByIdentity({
761
812
  ...transcriptTarget,
762
813
  messages: entries,
763
814
  config: params.config
764
- })).length !== entries.length) throw new Error("Muse transcript persistence rejected a native message group.");
765
- await publishSessionTranscriptUpdateByIdentity(transcriptTarget);
815
+ });
816
+ if (written.length !== entries.length) throw new Error("Muse transcript persistence rejected a native message group.");
817
+ const committed = written.at(-1);
818
+ if (committed) await publishSessionTranscriptUpdateByIdentity({
819
+ ...transcriptTarget,
820
+ update: {
821
+ message: committed.message,
822
+ messageId: committed.messageId,
823
+ ...committed.anchor ? { messageSeq: committed.anchor.activeMessagePosition + 1 } : {},
824
+ runId: params.runId,
825
+ ...committed.message.role === "assistant" ? { assistantItemIds: [itemId] } : {}
826
+ }
827
+ });
766
828
  messages.push(...group);
767
829
  assistantTranscriptOwned = finalKey !== void 0;
768
830
  });
@@ -774,17 +836,22 @@ function createMuseAgentHarness(options) {
774
836
  throw new Error(turnError?.kind === "authRequired" ? `Muse Code is not signed in on the Gateway host (${turnError.message}). Run \`muse login\` there, or set META_API_KEY for the Gateway.` : turnError?.message ?? result.outcome.params.reason ?? "Muse model request failed. Run muse to check login and model access.");
775
837
  }
776
838
  if (result.outcome.params.terminal === "cancelled" && !failure) aborted = true;
839
+ lifecycle.emitLifecycleTerminal({ phase: "end" });
777
840
  } catch (error) {
778
841
  if (signal?.aborted && !failure) aborted = true;
779
842
  else failure ??= error;
780
843
  if (turn) await stop().catch(() => void 0);
844
+ lifecycle.emitLifecycleTerminal({
845
+ phase: failure ? "error" : "end",
846
+ ...failure ? { error: failure } : {}
847
+ });
781
848
  } finally {
782
849
  await abortPromise?.catch(() => void 0);
783
850
  clearTimeout(timer);
784
851
  clearTimeout(forceCloseTimer);
785
852
  signal?.removeEventListener("abort", onAbort);
786
853
  active.delete(params.sessionId);
787
- clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey);
854
+ clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, void 0, activeAttachment);
788
855
  bound?.release();
789
856
  lease.release();
790
857
  }
@@ -847,10 +914,10 @@ function createMuseAgentHarness(options) {
847
914
  autoSelection: { providerIds: [] },
848
915
  authBootstrap: "harness",
849
916
  executionEnvironment: "host-only",
850
- verifySetup: verifyMuseSetup,
917
+ verifySetup: (ctx) => catalogReader.verify(ctx),
851
918
  async loadModelCatalog(params) {
852
919
  catalogs.delete(params.agentDir);
853
- const request = readMuseCatalog({
920
+ const request = catalogReader.read({
854
921
  config: params.config,
855
922
  signal: AbortSignal.any([catalogAbort.signal, AbortSignal.timeout(3e4)]),
856
923
  assertCurrent: () => {
@@ -921,6 +988,7 @@ function createMuseAgentHarness(options) {
921
988
  await Promise.allSettled([...active.values()].map((abort) => abort()));
922
989
  await Promise.allSettled(inFlight);
923
990
  await pool.dispose();
991
+ await catalogReader.dispose();
924
992
  }
925
993
  };
926
994
  }
@@ -0,0 +1 @@
1
+ {"version":3,"entries":[{"output":"harness.js","source":"extensions/muse/harness.ts"},{"output":"index.js","source":"extensions/muse/index.ts"}],"chunks":[{"output":".setup/harness-dodfquL7.mjs","sha256":"311fa7c54918662738c93bfa955fbc9e4b479867d2d100c5b7e62b82c904317b","facadeSource":null,"sources":["extensions/muse/harness.ts","extensions/muse/package.json","extensions/muse/src/events.ts","extensions/muse/src/runtime.ts","extensions/muse/src/verify-setup.ts"]},{"output":"harness.js","sha256":"ef63cb930fe5cab89246c95ac5d324a2db18982844ae3d9aec1bacbefdc87339","facadeSource":"extensions/muse/harness.ts","sources":[]},{"output":"index.js","sha256":"7bffb18d38c8d3867329e57ea9a01b30c392be03a9e190f4db760a1df676dc2a","facadeSource":"extensions/muse/index.ts","sources":["extensions/muse/index.ts"]}],"unrenderedSources":[]}
package/dist/harness.js CHANGED
@@ -1,2 +1 @@
1
- import { t as createMuseAgentHarness } from "./.setup/harness-DFnhalb6.mjs";
2
- export { createMuseAgentHarness };
1
+ export { t as createMuseAgentHarness } from "./.setup/harness-dodfquL7.mjs";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createMuseAgentHarness } from "./.setup/harness-DFnhalb6.mjs";
1
+ import { t as createMuseAgentHarness } from "./.setup/harness-dodfquL7.mjs";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
4
  //#region extensions/muse/index.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/muse",
3
- "version": "2026.11.3",
3
+ "version": "2026.11.5-beta.2",
4
4
  "description": "OpenClaw Muse Code agent runtime plugin (registers a `muse` AgentHarness backed by @muse-code/sdk over the Muse Session Protocol to the Muse Code CLI)",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "type": "module",
10
10
  "dependencies": {
11
- "@muse-code/sdk": "1.4.2"
11
+ "@muse-code/sdk": "1.4.10"
12
12
  },
13
13
  "devDependencies": {
14
14
  "@openclaw/plugin-sdk": "workspace:*"
@@ -24,10 +24,10 @@
24
24
  "minHostVersion": ">=2026.10.2"
25
25
  },
26
26
  "compat": {
27
- "pluginApi": ">=2026.11.3"
27
+ "pluginApi": ">=2026.11.5-beta.2"
28
28
  },
29
29
  "build": {
30
- "openclawVersion": "2026.11.3",
30
+ "openclawVersion": "2026.11.5-beta.2",
31
31
  "bundledDist": false
32
32
  },
33
33
  "release": {
@@ -47,7 +47,7 @@
47
47
  "assets/activity.svg"
48
48
  ],
49
49
  "peerDependencies": {
50
- "openclaw": ">=2026.11.3"
50
+ "openclaw": ">=2026.11.5-beta.2"
51
51
  },
52
52
  "peerDependenciesMeta": {
53
53
  "openclaw": {