@openclaw/muse 2026.10.10 → 2026.11.5-beta.1

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,87 +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
- // 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
- // extensions/muse/src/context.ts
53
- /** MSP has no history import or system field; transfer the retained branch once as context. */
54
- async function prepareMuseSessionContext(params, target, warn) {
55
- const limits = resolveAgentHarnessHistoryLimits(params.model.contextWindow);
56
- const retained = await SessionManager.openModelContextAsync(target, {
57
- admission: params.userTurnTranscriptRecorder?.getAdmissionReceipt(),
58
- signal: params.abortSignal,
59
- limits: {
60
- maxBytes: limits.maxBytes,
61
- maxEvents: limits.maxEvents
62
- }
63
- });
64
- params.hostCapabilities.assertActive();
65
- const history = retained.buildSessionContext().messages;
66
- const bootstrap = await resolveBootstrapContextForRun({
67
- workspaceDir: params.workspaceDir,
68
- config: params.config,
69
- sessionKey: params.sessionKey,
70
- sessionId: params.sessionId,
71
- chatType: params.chatType,
72
- agentId: target.agentId,
73
- contextMode: params.bootstrapContextMode,
74
- runKind: params.bootstrapContextRunKind,
75
- warn
76
- });
77
- params.hostCapabilities.assertActive();
78
- const presentPaths = new Set(bootstrap.bootstrapFiles.filter((file) => !file.missing).map((file) => file.path));
79
- const files = bootstrap.contextFiles.filter((file) => presentPaths.has(file.path));
80
- const sections = [];
81
- if (files.length > 0) sections.push("# OpenClaw workspace context\n\n" + files.map((file) => `## ${file.path}\n\n${file.content}`).join("\n\n"));
82
- 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));
83
- return sections.join("\n\n");
84
- }
85
18
  // extensions/muse/src/events.ts
86
19
  function assistantMessage(params, content, stopReason = "stop") {
87
20
  return {
@@ -92,20 +25,7 @@ function assistantMessage(params, content, stopReason = "stop") {
92
25
  content,
93
26
  stopReason,
94
27
  timestamp: Date.now(),
95
- usage: {
96
- input: 0,
97
- output: 0,
98
- cacheRead: 0,
99
- cacheWrite: 0,
100
- totalTokens: 0,
101
- cost: {
102
- input: 0,
103
- output: 0,
104
- cacheRead: 0,
105
- cacheWrite: 0,
106
- total: 0
107
- }
108
- }
28
+ usage: makeZeroUsageSnapshot()
109
29
  };
110
30
  }
111
31
  async function consumeTurn(turn, params, record) {
@@ -113,10 +33,17 @@ async function consumeTurn(turn, params, record) {
113
33
  const streamed = /* @__PURE__ */ new Map();
114
34
  const emitted = /* @__PURE__ */ new Map();
115
35
  const settled = /* @__PURE__ */ new Set();
36
+ const foregroundItems = /* @__PURE__ */ new Set();
37
+ let answerRecorded = false;
38
+ let finalizing = false;
116
39
  let visibleText = "";
117
40
  let lastToolError;
118
41
  let messageStarted = false;
119
42
  let streamQueue = Promise.resolve();
43
+ const emitEvent = (event) => emitAgentHarnessAttemptEvent(params, event, {
44
+ label: "Muse",
45
+ log: embeddedAgentLog
46
+ });
120
47
  const emitField = (item, field, value) => {
121
48
  streamQueue = streamQueue.then(async () => {
122
49
  const key = `${item.itemId}:${field}`;
@@ -129,9 +56,10 @@ async function consumeTurn(turn, params, record) {
129
56
  messageStarted = true;
130
57
  await params.onAssistantMessageStart?.();
131
58
  }
132
- await params.onAgentEvent?.({
59
+ await emitEvent({
133
60
  stream: "assistant",
134
61
  data: {
62
+ itemId: item.itemId,
135
63
  delta,
136
64
  text: value
137
65
  }
@@ -154,10 +82,25 @@ async function consumeTurn(turn, params, record) {
154
82
  for await (const item of turn.items()) {
155
83
  const first = !items.has(item.itemId);
156
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
+ }
157
100
  if (first) {
158
101
  for (const [key, value] of streamed) if (key.startsWith(`${item.itemId}:`)) await emitField(item, key.slice(item.itemId.length + 1), value);
159
102
  }
160
- if (item.kind === "toolCall" && first) await params.onAgentEvent?.({
103
+ if (item.kind === "toolCall" && first) await emitEvent({
161
104
  stream: "item",
162
105
  data: projectAgentToolActivity({
163
106
  toolCallId: item.callId ?? item.itemId,
@@ -212,7 +155,7 @@ async function consumeTurn(turn, params, record) {
212
155
  result: item.visibleOutput,
213
156
  isError: item.status !== "completed"
214
157
  });
215
- await params.onAgentEvent?.({
158
+ await emitEvent({
216
159
  stream: "item",
217
160
  data: projectAgentToolActivity({
218
161
  toolCallId: id,
@@ -234,7 +177,7 @@ async function consumeTurn(turn, params, record) {
234
177
  thinking: item.text ?? item.summary?.join("\n") ?? ""
235
178
  }]));
236
179
  await params.onReasoningEnd?.();
237
- } else if (item.kind !== "userMessage") await params.onAgentEvent?.({
180
+ } else if (item.kind !== "userMessage") await emitEvent({
238
181
  stream: "item",
239
182
  data: {
240
183
  type: String(item.kind),
@@ -243,7 +186,10 @@ async function consumeTurn(turn, params, record) {
243
186
  id: item.itemId
244
187
  }
245
188
  });
246
- 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
+ }
247
193
  }
248
194
  })();
249
195
  await Promise.all([projections, deltas]);
@@ -254,44 +200,7 @@ async function consumeTurn(turn, params, record) {
254
200
  };
255
201
  }
256
202
  // extensions/muse/package.json
257
- var version = "2026.10.10";
258
- // extensions/muse/src/environment.ts
259
- async function museEnvironment(apiKey, env = process.env) {
260
- const inherited = {
261
- ...process.env,
262
- ...env
263
- };
264
- const managedHome = path.join(resolveStateDir(inherited), "muse");
265
- const authPath = path.join(managedHome, "muse", "auth.json");
266
- let credentialSource;
267
- try {
268
- const stat = await fs.stat(authPath);
269
- credentialSource = JSON.stringify([
270
- "managed",
271
- authPath,
272
- stat.dev,
273
- stat.ino,
274
- stat.size,
275
- stat.mtimeMs,
276
- stat.ctimeMs
277
- ]);
278
- } catch (error) {
279
- if (error instanceof Error && "code" in error && error.code === "ENOENT") credentialSource = "native";
280
- else throw error;
281
- }
282
- return {
283
- credentialSource,
284
- env: {
285
- ...inherited,
286
- MUSE_NO_AUTO_UPDATE: "1",
287
- ...credentialSource !== "native" ? {
288
- TBH_CREDENTIAL_BACKEND: "file",
289
- XDG_CONFIG_HOME: managedHome
290
- } : {},
291
- ...apiKey ? { META_API_KEY: apiKey } : {}
292
- }
293
- };
294
- }
203
+ var version = "2026.11.5-beta.1";
295
204
  // extensions/muse/src/runtime.ts
296
205
  const RESUME_RETRY_KINDS = {
297
206
  sessionInUse: true,
@@ -336,15 +245,45 @@ async function openMuseSession(runtime, options) {
336
245
  return session;
337
246
  }
338
247
  var MusePool = class {
339
- constructor(binaryPath = "muse") {
248
+ constructor(binaryPath = "muse", noSessionLog = false) {
340
249
  this.binaryPath = binaryPath;
250
+ this.noSessionLog = noSessionLog;
341
251
  this.entries = /* @__PURE__ */ new Map();
342
252
  this.disposed = false;
343
253
  }
344
- async acquire(workspace, apiKey, readOnly) {
254
+ async acquire(workspace, apiKey, readOnly, signal) {
255
+ signal?.throwIfAborted();
345
256
  if (this.disposed) throw new Error("Muse runtime has been disposed");
346
- const { env, credentialSource } = await museEnvironment(apiKey);
257
+ const inherited = { ...process.env };
258
+ const managedHome = path.join(resolveStateDir(inherited), "muse");
259
+ const authPath = path.join(managedHome, "muse", "auth.json");
260
+ let credentialSource;
261
+ try {
262
+ const stat = await fs.stat(authPath);
263
+ credentialSource = JSON.stringify([
264
+ "managed",
265
+ authPath,
266
+ stat.dev,
267
+ stat.ino,
268
+ stat.size,
269
+ stat.mtimeMs,
270
+ stat.ctimeMs
271
+ ]);
272
+ } catch (error) {
273
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") credentialSource = "native";
274
+ else throw error;
275
+ }
276
+ const env = {
277
+ ...inherited,
278
+ MUSE_NO_AUTO_UPDATE: "1",
279
+ ...credentialSource !== "native" ? {
280
+ TBH_CREDENTIAL_BACKEND: "file",
281
+ XDG_CONFIG_HOME: managedHome
282
+ } : {},
283
+ ...apiKey ? { META_API_KEY: apiKey } : {}
284
+ };
347
285
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
286
+ signal?.throwIfAborted();
348
287
  const apiKeyIdentity = credentialFingerprint(apiKey);
349
288
  const key = JSON.stringify([
350
289
  workspace,
@@ -355,27 +294,40 @@ var MusePool = class {
355
294
  let entry = this.entries.get(key);
356
295
  if (!entry || entry.credentialIdentity !== credentialIdentity) {
357
296
  const previous = entry;
297
+ const startup = new AbortController();
358
298
  const pending = (async () => {
359
299
  if (previous) await (await previous.pending.catch(() => void 0))?.close();
360
- return this.spawn(workspace, env, readOnly, credentialIdentity);
300
+ return this.spawn(workspace, env, readOnly, credentialIdentity, startup.signal);
361
301
  })();
362
302
  entry = {
363
303
  credentialIdentity,
364
- pending
304
+ pending,
305
+ startup
365
306
  };
366
307
  this.entries.set(key, entry);
367
308
  pending.catch(() => {
368
309
  if (this.entries.get(key) === entry) this.entries.delete(key);
369
310
  });
370
311
  }
371
- const runtime = await entry.pending;
312
+ const abort = () => entry.startup.abort(signal?.reason);
313
+ signal?.addEventListener("abort", abort, { once: true });
314
+ let runtime;
315
+ try {
316
+ runtime = await entry.pending;
317
+ } finally {
318
+ signal?.removeEventListener("abort", abort);
319
+ }
320
+ if (signal?.aborted) {
321
+ await runtime.close();
322
+ signal.throwIfAborted();
323
+ }
372
324
  if (this.disposed) {
373
325
  await runtime.close();
374
326
  throw new Error("Muse runtime was disposed during startup");
375
327
  }
376
328
  if (this.entries.get(key) !== entry || runtime.dead || runtime.closing) {
377
329
  if (this.entries.get(key) === entry) this.entries.delete(key);
378
- return this.acquire(workspace, apiKey, readOnly);
330
+ return this.acquire(workspace, apiKey, readOnly, signal);
379
331
  }
380
332
  clearTimeout(runtime.timer);
381
333
  runtime.users++;
@@ -393,11 +345,16 @@ var MusePool = class {
393
345
  }
394
346
  };
395
347
  }
396
- async spawn(workspace, env, readOnly, credentialIdentity) {
348
+ async spawn(workspace, env, readOnly, credentialIdentity, signal) {
397
349
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
350
+ signal.throwIfAborted();
398
351
  const handshake = spawnMspConnection({
399
352
  command: this.binaryPath,
400
- args: ["serve", ...readOnly ? ["--disable-shell", "--disable-write"] : []],
353
+ args: [
354
+ "serve",
355
+ ...this.noSessionLog ? ["--no-session-log"] : [],
356
+ ...readOnly ? ["--disable-shell", "--disable-write"] : []
357
+ ],
401
358
  cwd: workspace,
402
359
  env,
403
360
  shutdownTimeoutMs: 1e3
@@ -406,11 +363,16 @@ var MusePool = class {
406
363
  handshake.close();
407
364
  }, 3e4);
408
365
  startup.unref();
366
+ const abort = () => {
367
+ handshake.close();
368
+ };
369
+ signal.addEventListener("abort", abort, { once: true });
409
370
  try {
410
371
  const host = await handshake.initialize({ clientInfo: {
411
372
  name: "openclaw",
412
373
  version
413
374
  } });
375
+ signal.throwIfAborted();
414
376
  const runtime = {
415
377
  host,
416
378
  credentialIdentity,
@@ -445,6 +407,7 @@ var MusePool = class {
445
407
  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 });
446
408
  } finally {
447
409
  clearTimeout(startup);
410
+ signal.removeEventListener("abort", abort);
448
411
  }
449
412
  }
450
413
  async dispose() {
@@ -458,51 +421,62 @@ var MusePool = class {
458
421
  }
459
422
  };
460
423
  // extensions/muse/src/verify-setup.ts
461
- async function readMuseCatalog(ctx) {
462
- const config = ctx.config.plugins?.entries?.muse?.config;
463
- const { env } = await museEnvironment();
464
- ctx.signal.throwIfAborted();
465
- ctx.assertCurrent();
466
- const host = spawnMspConnection({
467
- command: isRecord(config) && typeof config.binaryPath === "string" ? config.binaryPath : "muse",
468
- args: [
469
- "serve",
470
- "--no-session-log",
471
- "--disable-shell",
472
- "--disable-write"
473
- ],
474
- env,
475
- shutdownTimeoutMs: 1e3
476
- });
477
- const abort = () => {
478
- host.close();
479
- };
480
- ctx.signal.addEventListener("abort", abort, { once: true });
481
- try {
482
- const ready = await host.initialize({ clientInfo: {
483
- name: "openclaw",
484
- version: "1"
485
- } });
486
- ctx.signal.throwIfAborted();
487
- ctx.assertCurrent();
488
- const catalog = await ready.connection.request("model/list", {});
424
+ function museDisplayName(modelId, displayLabel) {
425
+ const label = typeof displayLabel === "string" ? displayLabel : modelId;
426
+ if (label === modelId || modelId === "muse-wonder-full-1.0-contributor" && label === "muse-wonder-1.0-contributor") switch (modelId) {
427
+ case "muse-wonder-1.0-contributor": return "Muse Wonder Contributor";
428
+ case "muse-wonder-full-1.0": return "Muse Wonder Full";
429
+ case "muse-wonder-full-1.0-contributor": return "Muse Wonder Full Contributor";
430
+ }
431
+ return label;
432
+ }
433
+ /** One lifecycle owner for read-only catalog hosts; every read still asks Meta for live access. */
434
+ var MuseCatalogReader = class {
435
+ async read(ctx) {
489
436
  ctx.signal.throwIfAborted();
490
437
  ctx.assertCurrent();
491
- 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.");
492
- return catalog.models.flatMap((model) => isRecord(model) && model.providerId === "meta" && typeof model.modelId === "string" ? [{
493
- id: model.modelId,
494
- name: typeof model.displayLabel === "string" ? model.displayLabel : model.modelId,
495
- provider: "meta",
496
- nativeRuntime: "muse"
497
- }] : []);
498
- } finally {
499
- ctx.signal.removeEventListener("abort", abort);
500
- await host.close();
438
+ const config = ctx.config.plugins?.entries?.muse?.config;
439
+ const binaryPath = isRecord(config) && typeof config.binaryPath === "string" ? config.binaryPath : "muse";
440
+ if (this.current?.binaryPath !== binaryPath) {
441
+ const previous = this.current;
442
+ this.current = {
443
+ binaryPath,
444
+ pool: new MusePool(binaryPath, true)
445
+ };
446
+ await previous?.pool.dispose();
447
+ ctx.signal.throwIfAborted();
448
+ ctx.assertCurrent();
449
+ }
450
+ const lease = await this.current.pool.acquire(void 0, void 0, true, ctx.signal);
451
+ const abort = () => {
452
+ lease.runtime.close();
453
+ };
454
+ ctx.signal.addEventListener("abort", abort, { once: true });
455
+ try {
456
+ ctx.signal.throwIfAborted();
457
+ ctx.assertCurrent();
458
+ const catalog = await lease.runtime.host.connection.request("model/list", {});
459
+ ctx.signal.throwIfAborted();
460
+ ctx.assertCurrent();
461
+ 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.");
462
+ return catalog.models.flatMap((model) => isRecord(model) && model.providerId === "meta" && typeof model.modelId === "string" ? [{
463
+ id: model.modelId,
464
+ name: museDisplayName(model.modelId, model.displayLabel),
465
+ provider: "meta",
466
+ nativeRuntime: "muse"
467
+ }] : []);
468
+ } finally {
469
+ ctx.signal.removeEventListener("abort", abort);
470
+ lease.release();
471
+ }
501
472
  }
502
- }
503
- async function verifyMuseSetup(ctx) {
504
- 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.`);
505
- }
473
+ async verify(ctx) {
474
+ 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.`);
475
+ }
476
+ async dispose() {
477
+ await this.current?.pool.dispose();
478
+ }
479
+ };
506
480
  // extensions/muse/harness.ts
507
481
  /** Configuration Muse cannot honor; the message is safe and actionable for the chat user. */
508
482
  function museRefusal(message) {
@@ -511,8 +485,16 @@ function museRefusal(message) {
511
485
  userMessage: message
512
486
  });
513
487
  }
488
+ const APPROVAL_TIMEOUT_MS = 12e4;
489
+ function selectApprovalChoice(request, decision) {
490
+ const wanted = decision === "allow-once" ? "approved" : "denied";
491
+ 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);
492
+ if (!choice) throw new Error(`Muse offered no safe ${wanted} approval choice`);
493
+ return { choiceId: choice.choiceId };
494
+ }
514
495
  function createMuseAgentHarness(options) {
515
496
  const pool = new MusePool(options.binaryPath);
497
+ const catalogReader = new MuseCatalogReader();
516
498
  const queue = new KeyedAsyncQueue();
517
499
  const active = /* @__PURE__ */ new Map();
518
500
  const inFlight = /* @__PURE__ */ new Set();
@@ -593,7 +575,7 @@ function createMuseAgentHarness(options) {
593
575
  if (ask === "always") throw museRefusal("Muse cannot enforce exec ask: always for every native command. Use ask: on-miss/default, or the openclaw runtime.");
594
576
  const readOnly = security === "deny";
595
577
  const approvalMode = readOnly ? "denyUnmatched" : security === "full" && ask === "off" ? "allowAll" : "promptUnmatched";
596
- params.hostCapabilities.assertActive();
578
+ params.hostCapabilities.prepareContinuationRetryCount?.({ cwd: workspace });
597
579
  const lease = await pool.acquire(workspace, apiKey, readOnly);
598
580
  const { runtime } = lease;
599
581
  const compatibility = JSON.stringify([
@@ -610,10 +592,24 @@ function createMuseAgentHarness(options) {
610
592
  let aborted = false;
611
593
  let abortPromise;
612
594
  let failure;
595
+ let activeAttachment;
613
596
  const messages = [];
614
597
  let text = "";
615
598
  let lastToolError;
616
599
  let assistantTranscriptOwned = false;
600
+ const lifecycle = createAgentHarnessAttemptLifecycle({
601
+ attempt: params,
602
+ backend: "muse",
603
+ startedAtMs: params.startedAtMs ?? Date.now(),
604
+ state: {
605
+ lifecycleStarted: false,
606
+ lifecycleTerminalEmitted: false
607
+ },
608
+ emitEvent: (event) => emitAgentHarnessAttemptEvent(params, event, {
609
+ label: "Muse",
610
+ log: embeddedAgentLog
611
+ })
612
+ });
617
613
  let finalKey;
618
614
  const bound = params.hostCapabilities.bindModelExecution?.({
619
615
  provider: "meta",
@@ -693,16 +689,68 @@ function createMuseAgentHarness(options) {
693
689
  let sessionContext = "";
694
690
  if (freshSession) {
695
691
  try {
696
- sessionContext = await prepareMuseSessionContext(params, {
692
+ const contextAgentId = target.agentId ?? sessionAgentId;
693
+ const limits = resolveAgentHarnessHistoryLimits(params.model.contextWindow);
694
+ const retained = await SessionManager.openModelContextAsync({
697
695
  ...transcriptTarget,
698
- agentId: target.agentId ?? sessionAgentId
699
- }, options.logger?.warn);
696
+ agentId: contextAgentId
697
+ }, {
698
+ admission: params.userTurnTranscriptRecorder?.getAdmissionReceipt(),
699
+ signal: params.abortSignal,
700
+ limits: {
701
+ maxBytes: limits.maxBytes,
702
+ maxEvents: limits.maxEvents
703
+ }
704
+ });
705
+ params.hostCapabilities.assertActive();
706
+ const history = retained.buildSessionContext().messages;
707
+ const bootstrap = await resolveBootstrapContextForRun({
708
+ workspaceDir: params.workspaceDir,
709
+ config: params.config,
710
+ sessionKey: params.sessionKey,
711
+ sessionId: params.sessionId,
712
+ chatType: params.chatType,
713
+ agentId: contextAgentId,
714
+ contextMode: params.bootstrapContextMode,
715
+ runKind: params.bootstrapContextRunKind,
716
+ warn: options.logger?.warn
717
+ });
718
+ params.hostCapabilities.assertActive();
719
+ const presentPaths = new Set(bootstrap.bootstrapFiles.filter((file) => !file.missing).map((file) => file.path));
720
+ const files = bootstrap.contextFiles.filter((file) => presentPaths.has(file.path));
721
+ const sections = [];
722
+ if (files.length > 0) sections.push("# OpenClaw workspace context\n\n" + files.map((file) => `## ${file.path}\n\n${file.content}`).join("\n\n"));
723
+ 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));
724
+ sessionContext = sections.join("\n\n");
700
725
  } catch (error) {
701
726
  throw museRefusal(`Muse could not restore OpenClaw session context. Use the openclaw runtime or compact the session before retrying. ${formatErrorMessage(error)}`);
702
727
  }
703
728
  assertDispatchActive();
704
729
  }
705
- session.onApproval(createApprovalHandler(params));
730
+ session.onApproval(async (request) => {
731
+ params.hostCapabilities.assertActive();
732
+ const timeoutMs = Math.min(APPROVAL_TIMEOUT_MS, params.timeoutMs);
733
+ const answer = await params.hostCapabilities.requestApproval({
734
+ title: `Muse: ${request.toolName}`.slice(0, 80),
735
+ description: (request.subject.command ?? request.subject.path ?? request.subject.host ?? request.toolName).slice(0, 512),
736
+ ...request.rawArgs ? { detail: request.rawArgs.slice(0, 16384) } : {},
737
+ toolName: request.toolName,
738
+ toolCallId: request.toolCallId,
739
+ severity: "warning",
740
+ allowedDecisions: ["allow-once", "deny"],
741
+ timeoutMs,
742
+ signal: params.abortSignal
743
+ });
744
+ let decision = answer?.decision;
745
+ if (answer?.id && decision == null) decision = (await params.hostCapabilities.waitForApproval({
746
+ approvalId: answer.id,
747
+ timeoutMs,
748
+ signal: params.abortSignal
749
+ }))?.decision;
750
+ params.hostCapabilities.assertActive();
751
+ params.abortSignal?.throwIfAborted();
752
+ return selectApprovalChoice(request, decision);
753
+ });
706
754
  session.onApprovalError((error) => {
707
755
  failure = /* @__PURE__ */ new Error(`Muse approval failed (${error.kind}): ${error.kind === "unofferedChoice" ? `choice ${error.choiceId} was not offered` : formatErrorMessage(error.error)}`);
708
756
  stop().catch(() => runtime.close());
@@ -722,18 +770,23 @@ function createMuseAgentHarness(options) {
722
770
  mediaType: image.mimeType,
723
771
  base64Data: image.data
724
772
  }))];
773
+ lifecycle.emitExecutionPhaseOnce("context", { phase: "context_assembled" });
725
774
  turn = await session.sendUserTurn({
726
775
  input,
727
776
  ...params.thinkLevel ? { reasoningEffort: params.thinkLevel === "off" ? "minimal" : params.thinkLevel } : {}
728
777
  });
778
+ lifecycle.emitLifecycleStart({
779
+ provider: "meta",
780
+ model: params.modelId
781
+ });
782
+ lifecycle.emitExecutionPhaseOnce("accepted", { phase: "turn_accepted" });
729
783
  await options.sessionStore.register(params.sessionId, {
730
784
  sessionId: session.sessionId,
731
785
  compatibility
732
786
  });
733
787
  if (signal?.aborted) onAbort();
734
788
  else if (failure) stop().catch(() => runtime.close());
735
- setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile);
736
- params.replyOperation?.attachBackend(handle);
789
+ activeAttachment = setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, sessionAgentId);
737
790
  active.set(params.sessionId, abort);
738
791
  params.onExecutionStarted?.({ backend: "muse" });
739
792
  const nativeSessionId = session.sessionId;
@@ -744,18 +797,30 @@ function createMuseAgentHarness(options) {
744
797
  return {
745
798
  message: {
746
799
  ...message,
747
- idempotencyKey
800
+ idempotencyKey,
801
+ __openclaw: { runId: params.runId }
748
802
  },
749
803
  idempotencyLookup: "scan"
750
804
  };
751
805
  });
752
806
  params.hostCapabilities.assertActive();
753
- if ((await appendSessionTranscriptMessagesByIdentity({
807
+ const written = await appendSessionTranscriptMessagesByIdentity({
754
808
  ...transcriptTarget,
755
809
  messages: entries,
756
810
  config: params.config
757
- })).length !== entries.length) throw new Error("Muse transcript persistence rejected a native message group.");
758
- await publishSessionTranscriptUpdateByIdentity(transcriptTarget);
811
+ });
812
+ if (written.length !== entries.length) throw new Error("Muse transcript persistence rejected a native message group.");
813
+ const committed = written.at(-1);
814
+ if (committed) await publishSessionTranscriptUpdateByIdentity({
815
+ ...transcriptTarget,
816
+ update: {
817
+ message: committed.message,
818
+ messageId: committed.messageId,
819
+ ...committed.anchor ? { messageSeq: committed.anchor.activeMessagePosition + 1 } : {},
820
+ runId: params.runId,
821
+ ...committed.message.role === "assistant" ? { assistantItemIds: [itemId] } : {}
822
+ }
823
+ });
759
824
  messages.push(...group);
760
825
  assistantTranscriptOwned = finalKey !== void 0;
761
826
  });
@@ -767,17 +832,22 @@ function createMuseAgentHarness(options) {
767
832
  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.");
768
833
  }
769
834
  if (result.outcome.params.terminal === "cancelled" && !failure) aborted = true;
835
+ lifecycle.emitLifecycleTerminal({ phase: "end" });
770
836
  } catch (error) {
771
837
  if (signal?.aborted && !failure) aborted = true;
772
838
  else failure ??= error;
773
839
  if (turn) await stop().catch(() => void 0);
840
+ lifecycle.emitLifecycleTerminal({
841
+ phase: failure ? "error" : "end",
842
+ ...failure ? { error: failure } : {}
843
+ });
774
844
  } finally {
775
845
  await abortPromise?.catch(() => void 0);
776
846
  clearTimeout(timer);
777
847
  clearTimeout(forceCloseTimer);
778
848
  signal?.removeEventListener("abort", onAbort);
779
849
  active.delete(params.sessionId);
780
- clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey);
850
+ clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, void 0, activeAttachment);
781
851
  bound?.release();
782
852
  lease.release();
783
853
  }
@@ -840,10 +910,10 @@ function createMuseAgentHarness(options) {
840
910
  autoSelection: { providerIds: [] },
841
911
  authBootstrap: "harness",
842
912
  executionEnvironment: "host-only",
843
- verifySetup: verifyMuseSetup,
913
+ verifySetup: (ctx) => catalogReader.verify(ctx),
844
914
  async loadModelCatalog(params) {
845
915
  catalogs.delete(params.agentDir);
846
- const request = readMuseCatalog({
916
+ const request = catalogReader.read({
847
917
  config: params.config,
848
918
  signal: AbortSignal.any([catalogAbort.signal, AbortSignal.timeout(3e4)]),
849
919
  assertCurrent: () => {
@@ -914,6 +984,7 @@ function createMuseAgentHarness(options) {
914
984
  await Promise.allSettled([...active.values()].map((abort) => abort()));
915
985
  await Promise.allSettled(inFlight);
916
986
  await pool.dispose();
987
+ await catalogReader.dispose();
917
988
  }
918
989
  };
919
990
  }
@@ -1 +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-BE1UlT5K.mjs","sha256":"f632e90afa517661e17cc47c94780c500572cce7a4ca09266250e9b7324833bb","facadeSource":null,"sources":["extensions/muse/harness.ts","extensions/muse/package.json","extensions/muse/src/approvals.ts","extensions/muse/src/context.ts","extensions/muse/src/environment.ts","extensions/muse/src/events.ts","extensions/muse/src/runtime.ts","extensions/muse/src/verify-setup.ts"]},{"output":"harness.js","sha256":"3347234c22f5bee34c5221df344fe1867f6edeaf3c7b351dfb1a15d3ec9129f0","facadeSource":"extensions/muse/harness.ts","sources":[]},{"output":"index.js","sha256":"48f3372887a30b51f50f40532ef2d41cf9302d1d6168377c83b13c2bd414da5a","facadeSource":"extensions/muse/index.ts","sources":["extensions/muse/index.ts"]}],"unrenderedSources":[]}
1
+ {"version":3,"entries":[{"output":"harness.js","source":"extensions/muse/harness.ts"},{"output":"index.js","source":"extensions/muse/index.ts"}],"chunks":[{"output":".setup/harness-6lNgeL7M.mjs","sha256":"a013c4e99f8a5b51c8ff95ce4898ee455d3e8f3fd813dced2a9182106c41fe09","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":"d72c6c052db9c9dd9ef484a4b556b8959eeddbb62adfaf663d1edb2b626e219c","facadeSource":"extensions/muse/harness.ts","sources":[]},{"output":"index.js","sha256":"9d4cf66a36fdab4523136d7d3137f9a966de30176bb85941ce7a3d0ec8e0ede7","facadeSource":"extensions/muse/index.ts","sources":["extensions/muse/index.ts"]}],"unrenderedSources":[]}
package/dist/harness.js CHANGED
@@ -1 +1 @@
1
- export { t as createMuseAgentHarness } from "./.setup/harness-BE1UlT5K.mjs";
1
+ export { t as createMuseAgentHarness } from "./.setup/harness-6lNgeL7M.mjs";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createMuseAgentHarness } from "./.setup/harness-BE1UlT5K.mjs";
1
+ import { t as createMuseAgentHarness } from "./.setup/harness-6lNgeL7M.mjs";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
4
  // extensions/muse/index.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/muse",
3
- "version": "2026.10.10",
3
+ "version": "2026.11.5-beta.1",
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.10.10"
27
+ "pluginApi": ">=2026.11.5-beta.1"
28
28
  },
29
29
  "build": {
30
- "openclawVersion": "2026.10.10",
30
+ "openclawVersion": "2026.11.5-beta.1",
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.10.10"
50
+ "openclaw": ">=2026.11.5-beta.1"
51
51
  },
52
52
  "peerDependenciesMeta": {
53
53
  "openclaw": {