@openclaw/muse 2026.10.10-beta.5 → 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,90 +1,21 @@
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
- //#region extensions/muse/src/events.ts
18
+ // extensions/muse/src/events.ts
88
19
  function assistantMessage(params, content, stopReason = "stop") {
89
20
  return {
90
21
  role: "assistant",
@@ -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]);
@@ -255,49 +199,9 @@ async function consumeTurn(turn, params, record) {
255
199
  outcome: await turn.completed
256
200
  };
257
201
  }
258
- //#endregion
259
- //#region extensions/muse/package.json
260
- var version = "2026.10.10-beta.5";
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
- }
299
- //#endregion
300
- //#region extensions/muse/src/runtime.ts
202
+ // extensions/muse/package.json
203
+ var version = "2026.11.5-beta.1";
204
+ // extensions/muse/src/runtime.ts
301
205
  const RESUME_RETRY_KINDS = {
302
206
  sessionInUse: true,
303
207
  overloaded: true,
@@ -341,15 +245,45 @@ async function openMuseSession(runtime, options) {
341
245
  return session;
342
246
  }
343
247
  var MusePool = class {
344
- constructor(binaryPath = "muse") {
248
+ constructor(binaryPath = "muse", noSessionLog = false) {
345
249
  this.binaryPath = binaryPath;
250
+ this.noSessionLog = noSessionLog;
346
251
  this.entries = /* @__PURE__ */ new Map();
347
252
  this.disposed = false;
348
253
  }
349
- async acquire(workspace, apiKey, readOnly) {
254
+ async acquire(workspace, apiKey, readOnly, signal) {
255
+ signal?.throwIfAborted();
350
256
  if (this.disposed) throw new Error("Muse runtime has been disposed");
351
- 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
+ };
352
285
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
286
+ signal?.throwIfAborted();
353
287
  const apiKeyIdentity = credentialFingerprint(apiKey);
354
288
  const key = JSON.stringify([
355
289
  workspace,
@@ -360,27 +294,40 @@ var MusePool = class {
360
294
  let entry = this.entries.get(key);
361
295
  if (!entry || entry.credentialIdentity !== credentialIdentity) {
362
296
  const previous = entry;
297
+ const startup = new AbortController();
363
298
  const pending = (async () => {
364
299
  if (previous) await (await previous.pending.catch(() => void 0))?.close();
365
- return this.spawn(workspace, env, readOnly, credentialIdentity);
300
+ return this.spawn(workspace, env, readOnly, credentialIdentity, startup.signal);
366
301
  })();
367
302
  entry = {
368
303
  credentialIdentity,
369
- pending
304
+ pending,
305
+ startup
370
306
  };
371
307
  this.entries.set(key, entry);
372
308
  pending.catch(() => {
373
309
  if (this.entries.get(key) === entry) this.entries.delete(key);
374
310
  });
375
311
  }
376
- 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
+ }
377
324
  if (this.disposed) {
378
325
  await runtime.close();
379
326
  throw new Error("Muse runtime was disposed during startup");
380
327
  }
381
328
  if (this.entries.get(key) !== entry || runtime.dead || runtime.closing) {
382
329
  if (this.entries.get(key) === entry) this.entries.delete(key);
383
- return this.acquire(workspace, apiKey, readOnly);
330
+ return this.acquire(workspace, apiKey, readOnly, signal);
384
331
  }
385
332
  clearTimeout(runtime.timer);
386
333
  runtime.users++;
@@ -398,11 +345,16 @@ var MusePool = class {
398
345
  }
399
346
  };
400
347
  }
401
- async spawn(workspace, env, readOnly, credentialIdentity) {
348
+ async spawn(workspace, env, readOnly, credentialIdentity, signal) {
402
349
  if (this.disposed) throw new Error("Muse runtime was disposed during environment preparation");
350
+ signal.throwIfAborted();
403
351
  const handshake = spawnMspConnection({
404
352
  command: this.binaryPath,
405
- args: ["serve", ...readOnly ? ["--disable-shell", "--disable-write"] : []],
353
+ args: [
354
+ "serve",
355
+ ...this.noSessionLog ? ["--no-session-log"] : [],
356
+ ...readOnly ? ["--disable-shell", "--disable-write"] : []
357
+ ],
406
358
  cwd: workspace,
407
359
  env,
408
360
  shutdownTimeoutMs: 1e3
@@ -411,11 +363,16 @@ var MusePool = class {
411
363
  handshake.close();
412
364
  }, 3e4);
413
365
  startup.unref();
366
+ const abort = () => {
367
+ handshake.close();
368
+ };
369
+ signal.addEventListener("abort", abort, { once: true });
414
370
  try {
415
371
  const host = await handshake.initialize({ clientInfo: {
416
372
  name: "openclaw",
417
373
  version
418
374
  } });
375
+ signal.throwIfAborted();
419
376
  const runtime = {
420
377
  host,
421
378
  credentialIdentity,
@@ -450,6 +407,7 @@ var MusePool = class {
450
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 });
451
408
  } finally {
452
409
  clearTimeout(startup);
410
+ signal.removeEventListener("abort", abort);
453
411
  }
454
412
  }
455
413
  async dispose() {
@@ -462,55 +420,64 @@ var MusePool = class {
462
420
  }));
463
421
  }
464
422
  };
465
- //#endregion
466
- //#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", {});
423
+ // extensions/muse/src/verify-setup.ts
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) {
495
436
  ctx.signal.throwIfAborted();
496
437
  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();
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
+ }
507
472
  }
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
- }
512
- //#endregion
513
- //#region extensions/muse/harness.ts
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
+ };
480
+ // extensions/muse/harness.ts
514
481
  /** Configuration Muse cannot honor; the message is safe and actionable for the chat user. */
515
482
  function museRefusal(message) {
516
483
  return new AgentHarnessPreflightError(message, {
@@ -518,8 +485,16 @@ function museRefusal(message) {
518
485
  userMessage: message
519
486
  });
520
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
+ }
521
495
  function createMuseAgentHarness(options) {
522
496
  const pool = new MusePool(options.binaryPath);
497
+ const catalogReader = new MuseCatalogReader();
523
498
  const queue = new KeyedAsyncQueue();
524
499
  const active = /* @__PURE__ */ new Map();
525
500
  const inFlight = /* @__PURE__ */ new Set();
@@ -600,7 +575,7 @@ function createMuseAgentHarness(options) {
600
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.");
601
576
  const readOnly = security === "deny";
602
577
  const approvalMode = readOnly ? "denyUnmatched" : security === "full" && ask === "off" ? "allowAll" : "promptUnmatched";
603
- params.hostCapabilities.assertActive();
578
+ params.hostCapabilities.prepareContinuationRetryCount?.({ cwd: workspace });
604
579
  const lease = await pool.acquire(workspace, apiKey, readOnly);
605
580
  const { runtime } = lease;
606
581
  const compatibility = JSON.stringify([
@@ -617,10 +592,24 @@ function createMuseAgentHarness(options) {
617
592
  let aborted = false;
618
593
  let abortPromise;
619
594
  let failure;
595
+ let activeAttachment;
620
596
  const messages = [];
621
597
  let text = "";
622
598
  let lastToolError;
623
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
+ });
624
613
  let finalKey;
625
614
  const bound = params.hostCapabilities.bindModelExecution?.({
626
615
  provider: "meta",
@@ -700,16 +689,68 @@ function createMuseAgentHarness(options) {
700
689
  let sessionContext = "";
701
690
  if (freshSession) {
702
691
  try {
703
- sessionContext = await prepareMuseSessionContext(params, {
692
+ const contextAgentId = target.agentId ?? sessionAgentId;
693
+ const limits = resolveAgentHarnessHistoryLimits(params.model.contextWindow);
694
+ const retained = await SessionManager.openModelContextAsync({
704
695
  ...transcriptTarget,
705
- agentId: target.agentId ?? sessionAgentId
706
- }, 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");
707
725
  } catch (error) {
708
726
  throw museRefusal(`Muse could not restore OpenClaw session context. Use the openclaw runtime or compact the session before retrying. ${formatErrorMessage(error)}`);
709
727
  }
710
728
  assertDispatchActive();
711
729
  }
712
- 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
+ });
713
754
  session.onApprovalError((error) => {
714
755
  failure = /* @__PURE__ */ new Error(`Muse approval failed (${error.kind}): ${error.kind === "unofferedChoice" ? `choice ${error.choiceId} was not offered` : formatErrorMessage(error.error)}`);
715
756
  stop().catch(() => runtime.close());
@@ -729,18 +770,23 @@ function createMuseAgentHarness(options) {
729
770
  mediaType: image.mimeType,
730
771
  base64Data: image.data
731
772
  }))];
773
+ lifecycle.emitExecutionPhaseOnce("context", { phase: "context_assembled" });
732
774
  turn = await session.sendUserTurn({
733
775
  input,
734
776
  ...params.thinkLevel ? { reasoningEffort: params.thinkLevel === "off" ? "minimal" : params.thinkLevel } : {}
735
777
  });
778
+ lifecycle.emitLifecycleStart({
779
+ provider: "meta",
780
+ model: params.modelId
781
+ });
782
+ lifecycle.emitExecutionPhaseOnce("accepted", { phase: "turn_accepted" });
736
783
  await options.sessionStore.register(params.sessionId, {
737
784
  sessionId: session.sessionId,
738
785
  compatibility
739
786
  });
740
787
  if (signal?.aborted) onAbort();
741
788
  else if (failure) stop().catch(() => runtime.close());
742
- setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile);
743
- params.replyOperation?.attachBackend(handle);
789
+ activeAttachment = setActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, sessionAgentId);
744
790
  active.set(params.sessionId, abort);
745
791
  params.onExecutionStarted?.({ backend: "muse" });
746
792
  const nativeSessionId = session.sessionId;
@@ -751,18 +797,30 @@ function createMuseAgentHarness(options) {
751
797
  return {
752
798
  message: {
753
799
  ...message,
754
- idempotencyKey
800
+ idempotencyKey,
801
+ __openclaw: { runId: params.runId }
755
802
  },
756
803
  idempotencyLookup: "scan"
757
804
  };
758
805
  });
759
806
  params.hostCapabilities.assertActive();
760
- if ((await appendSessionTranscriptMessagesByIdentity({
807
+ const written = await appendSessionTranscriptMessagesByIdentity({
761
808
  ...transcriptTarget,
762
809
  messages: entries,
763
810
  config: params.config
764
- })).length !== entries.length) throw new Error("Muse transcript persistence rejected a native message group.");
765
- 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
+ });
766
824
  messages.push(...group);
767
825
  assistantTranscriptOwned = finalKey !== void 0;
768
826
  });
@@ -774,17 +832,22 @@ function createMuseAgentHarness(options) {
774
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.");
775
833
  }
776
834
  if (result.outcome.params.terminal === "cancelled" && !failure) aborted = true;
835
+ lifecycle.emitLifecycleTerminal({ phase: "end" });
777
836
  } catch (error) {
778
837
  if (signal?.aborted && !failure) aborted = true;
779
838
  else failure ??= error;
780
839
  if (turn) await stop().catch(() => void 0);
840
+ lifecycle.emitLifecycleTerminal({
841
+ phase: failure ? "error" : "end",
842
+ ...failure ? { error: failure } : {}
843
+ });
781
844
  } finally {
782
845
  await abortPromise?.catch(() => void 0);
783
846
  clearTimeout(timer);
784
847
  clearTimeout(forceCloseTimer);
785
848
  signal?.removeEventListener("abort", onAbort);
786
849
  active.delete(params.sessionId);
787
- clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey);
850
+ clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile, void 0, activeAttachment);
788
851
  bound?.release();
789
852
  lease.release();
790
853
  }
@@ -847,10 +910,10 @@ function createMuseAgentHarness(options) {
847
910
  autoSelection: { providerIds: [] },
848
911
  authBootstrap: "harness",
849
912
  executionEnvironment: "host-only",
850
- verifySetup: verifyMuseSetup,
913
+ verifySetup: (ctx) => catalogReader.verify(ctx),
851
914
  async loadModelCatalog(params) {
852
915
  catalogs.delete(params.agentDir);
853
- const request = readMuseCatalog({
916
+ const request = catalogReader.read({
854
917
  config: params.config,
855
918
  signal: AbortSignal.any([catalogAbort.signal, AbortSignal.timeout(3e4)]),
856
919
  assertCurrent: () => {
@@ -921,8 +984,8 @@ function createMuseAgentHarness(options) {
921
984
  await Promise.allSettled([...active.values()].map((abort) => abort()));
922
985
  await Promise.allSettled(inFlight);
923
986
  await pool.dispose();
987
+ await catalogReader.dispose();
924
988
  }
925
989
  };
926
990
  }
927
- //#endregion
928
991
  export { createMuseAgentHarness as t };
@@ -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-DfNdbAyu.mjs","sha256":"dd80d6155d5dc9157d48583a82e4a0cdba740d3dc3b7f68d879ed77831bc848d","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":"8ed7dc5819f57125379c249b12411136b45cd9428df3298cca1047dedd85249a","facadeSource":"extensions/muse/harness.ts","sources":[]},{"output":"index.js","sha256":"49c4e08fb3a078e6ea602f77000b01ec11e9a89f2f9c6b969f17bcb2ac16ba47","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-DfNdbAyu.mjs";
1
+ export { t as createMuseAgentHarness } from "./.setup/harness-6lNgeL7M.mjs";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { t as createMuseAgentHarness } from "./.setup/harness-DfNdbAyu.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
- //#region extensions/muse/index.ts
4
+ // extensions/muse/index.ts
5
5
  var muse_default = definePluginEntry({
6
6
  id: "muse",
7
7
  name: "Muse Code agent runtime",
@@ -38,5 +38,4 @@ var muse_default = definePluginEntry({
38
38
  api.registerAgentHarness(harness);
39
39
  }
40
40
  });
41
- //#endregion
42
41
  export { muse_default as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/muse",
3
- "version": "2026.10.10-beta.5",
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-beta.5"
27
+ "pluginApi": ">=2026.11.5-beta.1"
28
28
  },
29
29
  "build": {
30
- "openclawVersion": "2026.10.10-beta.5",
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-beta.5"
50
+ "openclaw": ">=2026.11.5-beta.1"
51
51
  },
52
52
  "peerDependenciesMeta": {
53
53
  "openclaw": {