@moxt-ai/mobius 0.0.106 → 0.0.107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ import { type NativeSessionCancel, type NativeSessionCommand, type NativeSessionTurnForkCommand } from "@moxt-ai/mobius-protocol";
2
+ import { WebSocket } from "undici";
3
+ import type { AuditStore } from "../audit/audit-store.ts";
4
+ import type { RelayConnectionDiagnostics } from "../relay-connection/diagnostics.ts";
5
+ import type { DaemonTimer } from "../relay-connection/timer.ts";
6
+ import type { NativeSessionService } from "./service.ts";
7
+ type NativeCommand = NativeSessionCommand | NativeSessionTurnForkCommand;
8
+ interface NativeRequestDependencies {
9
+ readonly audit: AuditStore;
10
+ readonly diagnostics: RelayConnectionDiagnostics;
11
+ readonly nativeSessions: NativeSessionService;
12
+ readonly signal: AbortSignal;
13
+ readonly socket: WebSocket;
14
+ readonly timer: DaemonTimer;
15
+ }
16
+ export declare function createNativeSessionRequestHandler(dependencies: NativeRequestDependencies): {
17
+ cancel: (command: NativeSessionCancel) => void;
18
+ handle: (command: NativeCommand) => void;
19
+ settle: () => Promise<void>;
20
+ };
21
+ export {};
22
+ //# sourceMappingURL=handle-native-requests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-native-requests.d.ts","sourceRoot":"","sources":["../../src/native-sessions/handle-native-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,EACpC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAE1D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEzD,KAAK,aAAa,GAAG,oBAAoB,GAAG,4BAA4B,CAAC;AASzE,UAAU,yBAAyB;IAC/B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,WAAW,EAAE,0BAA0B,CAAC;IACjD,QAAQ,CAAC,cAAc,EAAE,oBAAoB,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;CAC/B;AAED,wBAAgB,iCAAiC,CAAC,YAAY,EAAE,yBAAyB;sBAI5D,mBAAmB,KAAG,IAAI;sBAS1B,aAAa,KAAG,IAAI;kBAgGpB,OAAO,CAAC,IAAI,CAAC;EAKzC"}
@@ -0,0 +1,91 @@
1
+ import { NATIVE_SESSION_REQUEST_KIND, } from "@moxt-ai/mobius-protocol";
2
+ import { WebSocket } from "undici";
3
+ import { AcpExecutionError } from "../acp/session-manager.js";
4
+ import { operationErrorCode, reportOperationFailure, send } from "../daemon-session-commands.js";
5
+ export function createNativeSessionRequestHandler(dependencies) {
6
+ const { audit, diagnostics, nativeSessions, signal, socket, timer } = dependencies;
7
+ const pending = new Map();
8
+ const cancel = (command) => {
9
+ const request = pending.get(command.requestId);
10
+ if (request?.sessionId === command.sessionId) {
11
+ request.controller.abort(new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"));
12
+ }
13
+ };
14
+ const handle = (command) => {
15
+ const previous = [...pending.values()].filter((request) => request.agentId === command.agentId);
16
+ const parallelRead = command.kind === NATIVE_SESSION_REQUEST_KIND &&
17
+ (command.action === "linked-history" || command.action === "active-turn");
18
+ if (pending.has(command.requestId) ||
19
+ pending.size >= 4 ||
20
+ (!parallelRead && previous.some((request) => !request.controller.signal.aborted))) {
21
+ reportOperationFailure(socket, command.requestId, command.sessionId, new AcpExecutionError("Another native session operation is running", {}, "native_session_busy"));
22
+ return;
23
+ }
24
+ const controller = new AbortController();
25
+ const operationSignal = AbortSignal.any([signal, controller.signal]);
26
+ const timeout = timer.schedule(() => controller.abort(new AcpExecutionError("Native session operation timed out", {}, "native_session_timeout")), 90_000);
27
+ const completion = (async () => {
28
+ try {
29
+ operationSignal.throwIfAborted();
30
+ const skipPrevious = command.kind === NATIVE_SESSION_REQUEST_KIND && command.action === "active-turn";
31
+ if (previous.length > 0 && !skipPrevious) {
32
+ await new Promise((resolve, reject) => {
33
+ const onAbort = () => reject(operationSignal.reason);
34
+ operationSignal.addEventListener("abort", onAbort, { once: true });
35
+ void Promise.all(previous.map((request) => request.completion)).then(() => {
36
+ operationSignal.removeEventListener("abort", onAbort);
37
+ resolve();
38
+ }, (error) => {
39
+ operationSignal.removeEventListener("abort", onAbort);
40
+ reject(error);
41
+ });
42
+ });
43
+ }
44
+ operationSignal.throwIfAborted();
45
+ const result = command.kind === NATIVE_SESSION_REQUEST_KIND
46
+ ? await nativeSessions.execute(command, operationSignal)
47
+ : await nativeSessions.executeTurnFork(command, operationSignal);
48
+ if (socket.readyState === WebSocket.OPEN) {
49
+ send(socket, result);
50
+ }
51
+ }
52
+ catch (error) {
53
+ const failure = operationSignal.aborted
54
+ ? (controller.signal.reason ??
55
+ new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"))
56
+ : error;
57
+ const event = command.kind === NATIVE_SESSION_REQUEST_KIND
58
+ ? "native_session_operation_failed"
59
+ : "native_session_turn_fork_failed";
60
+ audit.record({
61
+ commandId: command.requestId,
62
+ sessionId: command.sessionId,
63
+ event,
64
+ details: { code: operationErrorCode(failure) },
65
+ });
66
+ diagnostics.daemonDiagnostic(event, command.requestId, {
67
+ ...(command.kind === NATIVE_SESSION_REQUEST_KIND ? { action: command.action } : {}),
68
+ agentId: command.agentId,
69
+ code: operationErrorCode(failure),
70
+ sessionId: command.sessionId,
71
+ }, failure);
72
+ reportOperationFailure(socket, command.requestId, command.sessionId, failure);
73
+ }
74
+ finally {
75
+ timeout.cancel();
76
+ pending.delete(command.requestId);
77
+ }
78
+ })();
79
+ pending.set(command.requestId, {
80
+ agentId: command.agentId,
81
+ sessionId: command.sessionId,
82
+ controller,
83
+ completion,
84
+ });
85
+ };
86
+ const settle = async () => {
87
+ await Promise.all([...pending.values()].map((request) => request.completion));
88
+ };
89
+ return { cancel, handle, settle };
90
+ }
91
+ //# sourceMappingURL=handle-native-requests.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-native-requests.js","sourceRoot":"","sources":["../../src/native-sessions/handle-native-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,2BAA2B,GAI9B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAuBjG,MAAM,UAAU,iCAAiC,CAAC,YAAuC;IACrF,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,YAAY,CAAC;IACnF,MAAM,OAAO,GAAG,IAAI,GAAG,EAA0B,CAAC;IAElD,MAAM,MAAM,GAAG,CAAC,OAA4B,EAAQ,EAAE;QAClD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC/C,IAAI,OAAO,EAAE,SAAS,KAAK,OAAO,CAAC,SAAS,EAAE,CAAC;YAC3C,OAAO,CAAC,UAAU,CAAC,KAAK,CACpB,IAAI,iBAAiB,CAAC,oCAAoC,EAAE,EAAE,EAAE,0BAA0B,CAAC,CAC9F,CAAC;QACN,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG,CAAC,OAAsB,EAAQ,EAAE;QAC5C,MAAM,QAAQ,GAAG,CAA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EAAE,OAAO,CAAC,SAAS;YAC5B,UAAU;YACV,UAAU;SACb,CAAC,CAAC;IACP,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG,KAAK,IAAmB,EAAE;QACrC,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;IAClF,CAAC,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AACtC,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import type { AuditStore } from "./audit/audit-store.ts";
2
- import { type DaemonConfig } from "./config.ts";
2
+ import type { DaemonConfig } from "./config.ts";
3
3
  import { type DaemonTimer } from "./relay-connection/timer.ts";
4
4
  export interface RunDaemonOptions {
5
5
  readonly onConnectionStatus?: (status: "online" | "reconnecting") => void;
@@ -1 +1 @@
1
- {"version":3,"file":"run-daemon.d.ts","sourceRoot":"","sources":["../src/run-daemon.ts"],"names":[],"mappings":"AAiDA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,KAAK,YAAY,EAA6C,MAAM,aAAa,CAAC;AA2B3F,OAAO,EAAE,KAAK,WAAW,EAAqB,MAAM,6BAA6B,CAAC;AAsFlF,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,GAAG,cAAc,KAAK,IAAI,CAAC;IAC1E,QAAQ,CAAC,8BAA8B,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;CAC3G;AAi9BD,wBAAsB,SAAS,CAC3B,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,WAAW,EACnB,KAAK,GAAE,WAA+B,EACtC,OAAO,GAAE,gBAAqB,GAC/B,OAAO,CAAC,IAAI,CAAC,CA0Lf"}
1
+ {"version":3,"file":"run-daemon.d.ts","sourceRoot":"","sources":["../src/run-daemon.ts"],"names":[],"mappings":"AA2CA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAwBhD,OAAO,EAAE,KAAK,WAAW,EAAqB,MAAM,6BAA6B,CAAC;AAsFlF,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,GAAG,cAAc,KAAK,IAAI,CAAC;IAC1E,QAAQ,CAAC,8BAA8B,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;CAC3G;AA8eD,wBAAsB,SAAS,CAC3B,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,WAAW,EACnB,KAAK,GAAE,WAA+B,EACtC,OAAO,GAAE,gBAAqB,GAC/B,OAAO,CAAC,IAAI,CAAC,CA6Lf"}
@@ -1,25 +1,25 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { styleText } from "node:util";
3
- import { AGENT_CATALOG_REFRESH_FAILED_KIND, AGENT_CATALOG_REFRESH_KIND, AGENT_CATALOG_REFRESHED_KIND, AGENT_INSTALL_CANCEL_KIND, AGENT_INSTALL_REQUEST_KIND, AGENT_SETTINGS_DISCOVER_KIND, AGENT_SETTINGS_DISCOVERY_FAILED_KIND, decodeServiceToDaemonMessage, decodeSessionLiveHistoryLoad, decodeSessionLiveHistoryPageLoad, FILE_FAILED_KIND, FILE_READ_KIND, NATIVE_SESSION_CANCEL_KIND, NATIVE_SESSION_REQUEST_KIND, NATIVE_SESSION_TURN_FORK_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_LIVE_HISTORY_LOAD_KIND, SESSION_LIVE_HISTORY_PAGE_LOAD_KIND, SESSION_PERMISSION_RESPOND_KIND, SESSION_PREPARE_KIND, SESSION_PROMPT_KIND, SessionPromptDisposition, WORKSPACE_LIST_KIND, } from "@moxt-ai/mobius-protocol";
3
+ import { AGENT_CATALOG_REFRESH_KIND, AGENT_INSTALL_CANCEL_KIND, AGENT_INSTALL_REQUEST_KIND, AGENT_SETTINGS_DISCOVER_KIND, decodeServiceToDaemonMessage, decodeSessionLiveHistoryLoad, decodeSessionLiveHistoryPageLoad, FILE_FAILED_KIND, FILE_READ_KIND, NATIVE_SESSION_CANCEL_KIND, NATIVE_SESSION_REQUEST_KIND, NATIVE_SESSION_TURN_FORK_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_LIVE_HISTORY_LOAD_KIND, SESSION_LIVE_HISTORY_PAGE_LOAD_KIND, SESSION_PERMISSION_RESPOND_KIND, SESSION_PREPARE_KIND, SESSION_PROMPT_KIND, SessionPromptDisposition, WORKSPACE_LIST_KIND, } from "@moxt-ai/mobius-protocol";
4
4
  import { WebSocket } from "undici";
5
- import { AcpConfigurationValueUnavailableError, AcpExecutionError, AcpSessionManager } from "./acp/session-manager.js";
5
+ import { AcpSessionManager } from "./acp/session-manager.js";
6
6
  import { MemoryAcpSessionStore } from "./acp/session-store.js";
7
- import { discoverAgentSettings } from "./agent-catalog/discover-agent-settings.js";
8
- import { discoverLocalAgentInventory, supportedLocalAgentSpecifications, } from "./agent-catalog/discover-local-agents.js";
7
+ import { supportedLocalAgentSpecifications } from "./agent-catalog/discover-local-agents.js";
8
+ import { createAgentCatalogRefreshHandler } from "./agent-catalog/handle-agent-catalog-refresh.js";
9
+ import { createAgentSettingsDiscoveryHandler } from "./agent-catalog/handle-agent-settings-discovery.js";
9
10
  import { AgentIntegrationDefinition } from "./agent-catalog/local-agent.js";
10
11
  import { publishAgentCatalog } from "./agent-catalog/publish-agent-catalog.js";
11
12
  import { AgentInstallationManager } from "./agent-installation/agent-installation-manager.js";
12
13
  import { FixedInstallationExecutor } from "./agent-installation/fixed-installation-executor.js";
13
14
  import { streamLocalFile } from "./artifacts/local-file-streamer.js";
14
15
  import { WorkspaceDirectoryService } from "./authorization/workspace-directory.js";
15
- import { DaemonLocalContext, withDaemonEnvironment } from "./config.js";
16
16
  import { DaemonDiagnosticLog } from "./daemon-diagnostic-log.js";
17
17
  import { AuditInstallationEvents, DaemonAcpObserver, DaemonInstallationObserver } from "./daemon-observers.js";
18
- import { agentSettingsFailureDetails, executePrompt, executeSessionConfigure, executeSessionLiveHistoryLoad, executeSessionLiveHistoryPageLoad, executeSessionPrepare, executeWorkspaceList, operationErrorCode, operationErrorMessage, reportOperationFailure, send, settleAbandonedTurn, } from "./daemon-session-commands.js";
18
+ import { executePrompt, executeSessionConfigure, executeSessionLiveHistoryLoad, executeSessionLiveHistoryPageLoad, executeSessionPrepare, executeWorkspaceList, reportOperationFailure, send, settleAbandonedTurn, } from "./daemon-session-commands.js";
19
19
  import { ActiveDaemonTurn, ActiveTurnReconciliationError, reconcileActiveTurns } from "./daemon-turn-reconciliation.js";
20
20
  import { readCodexFullHistory } from "./native-sessions/codex-history.js";
21
+ import { createNativeSessionRequestHandler } from "./native-sessions/handle-native-requests.js";
21
22
  import { NativeSessionService } from "./native-sessions/service.js";
22
- import { revalidateExecutable } from "./process/executable.js";
23
23
  import { connectRelay } from "./relay-connection/connect.js";
24
24
  import { DaemonOperationState } from "./relay-connection/daemon-operation-state.js";
25
25
  import { RelayConnectionDiagnostics } from "./relay-connection/diagnostics.js";
@@ -94,49 +94,6 @@ async function installDetectedAgentIntegrations(config, installations, signal) {
94
94
  }, signal);
95
95
  }
96
96
  }
97
- // A refresh observes the machine through executable discovery, which depends on ambient state such
98
- // as PATH and the managed state directory. An Agent that was verified a moment ago is therefore not
99
- // necessarily uninstalled just because one discovery attempt failed to re-verify it. Keep the last
100
- // verified definition while the exact executable it was verified against still exists unchanged on
101
- // disk, so a transient probe failure cannot silently drop a working Agent. A genuine removal, or a
102
- // replaced executable, stops satisfying that check and is still reflected in the catalog.
103
- async function retainStillInstalledAgents(previous, refreshed, signal) {
104
- const refreshedIdentifiers = new Set(refreshed.map((agent) => agent.id));
105
- const retained = [];
106
- for (const agent of previous) {
107
- if (refreshedIdentifiers.has(agent.id)) {
108
- continue;
109
- }
110
- signal.throwIfAborted();
111
- if (await revalidateExecutable(agent.agentIdentity)) {
112
- retained.push(agent);
113
- }
114
- }
115
- return Object.freeze([...refreshed, ...retained]);
116
- }
117
- async function refreshAgentCatalog(config, resolveEnvironment, signal) {
118
- signal.throwIfAborted();
119
- const shellEnvironment = await resolveEnvironment(signal);
120
- const environment = new DaemonLocalContext(config.localContext.stateDirectory, shellEnvironment).environment;
121
- signal.throwIfAborted();
122
- const inventory = await discoverLocalAgentInventory({
123
- defaultWorkspace: config.defaultWorkspace,
124
- environment,
125
- signal,
126
- });
127
- const previousCatalog = config.catalog.read();
128
- const refreshedAgents = inventory.readyAgents().map((agent) => withDaemonEnvironment(agent, environment));
129
- const agents = await retainStillInstalledAgents(previousCatalog.agents, refreshedAgents, signal);
130
- const verifiedIdentifiers = new Set(agents.map((agent) => agent.id));
131
- config.catalog.transition(agents, inventory.installable.filter((agent) => !verifiedIdentifiers.has(agent.id)));
132
- try {
133
- await publishAgentCatalog(config, signal);
134
- }
135
- catch (error) {
136
- config.catalog.transition(previousCatalog.agents, previousCatalog.installableAgents);
137
- throw error;
138
- }
139
- }
140
97
  async function runRelayConnection(config, directories, audit, sessions, installations, installationObserver, nativeSessions, operations, publisher, activeTurns, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
141
98
  const relayUrl = new URL(config.relayUrl);
142
99
  relayUrl.searchParams.set("liveness", "1");
@@ -144,9 +101,33 @@ async function runRelayConnection(config, directories, audit, sessions, installa
144
101
  const reconnectingTurns = [...activeTurns.values()];
145
102
  diagnostics.connectionOpened(connectionEpoch);
146
103
  const connectionController = new AbortController();
147
- const nativeRequests = new Map();
148
- const agentSettingsDiscoveries = new Map();
149
- const agentCatalogRefreshes = new Map();
104
+ const handleSettingsDiscovery = createAgentSettingsDiscoveryHandler({
105
+ config,
106
+ directories,
107
+ audit,
108
+ sessions,
109
+ diagnostics,
110
+ socket,
111
+ signal: connectionController.signal,
112
+ timer,
113
+ });
114
+ const handleCatalogRefresh = createAgentCatalogRefreshHandler({
115
+ config,
116
+ audit,
117
+ diagnostics,
118
+ socket,
119
+ signal: connectionController.signal,
120
+ timer,
121
+ resolveEnvironment: resolveAgentCatalogEnvironment,
122
+ });
123
+ const nativeRequestHandler = createNativeSessionRequestHandler({
124
+ audit,
125
+ diagnostics,
126
+ nativeSessions,
127
+ signal: connectionController.signal,
128
+ socket,
129
+ timer,
130
+ });
150
131
  installationObserver.connect(socket);
151
132
  onConnected();
152
133
  try {
@@ -296,324 +277,19 @@ async function runRelayConnection(config, directories, audit, sessions, installa
296
277
  return;
297
278
  }
298
279
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
299
- const command = message;
300
- const pending = nativeRequests.get(command.requestId);
301
- if (pending?.sessionId === command.sessionId) {
302
- pending.controller.abort(new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"));
303
- }
280
+ nativeRequestHandler.cancel(message);
304
281
  return;
305
282
  }
306
283
  if (kind === AGENT_SETTINGS_DISCOVER_KIND) {
307
- const command = message;
308
- const existing = [...agentSettingsDiscoveries.values()].find((request) => request.agentId === command.agentId && !request.controller.signal.aborted);
309
- if ([...agentSettingsDiscoveries.values()].some((request) => request.requestIds.has(command.requestId))) {
310
- if (socket.readyState === WebSocket.OPEN) {
311
- send(socket, {
312
- code: "agent_settings_discovery_busy",
313
- kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
314
- message: "This settings discovery request is already running",
315
- requestId: command.requestId,
316
- });
317
- }
318
- return;
319
- }
320
- if (existing !== undefined &&
321
- existing.model === command.model &&
322
- existing.requestIds.size < 16) {
323
- existing.requestIds.add(command.requestId);
324
- return;
325
- }
326
- if (existing !== undefined) {
327
- if (socket.readyState === WebSocket.OPEN) {
328
- send(socket, {
329
- code: "agent_settings_discovery_busy",
330
- kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
331
- message: "Another settings discovery is already running for this Agent",
332
- requestId: command.requestId,
333
- });
334
- }
335
- return;
336
- }
337
- if (agentSettingsDiscoveries.size >= 4) {
338
- if (socket.readyState === WebSocket.OPEN) {
339
- send(socket, {
340
- code: "agent_settings_discovery_busy",
341
- kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
342
- message: "Too many Agent settings discoveries are running",
343
- requestId: command.requestId,
344
- });
345
- }
346
- return;
347
- }
348
- const controller = new AbortController();
349
- const requestIds = new Set([command.requestId]);
350
- const operationSignal = AbortSignal.any([connectionController.signal, controller.signal]);
351
- const timeout = timer.schedule(() => controller.abort(new AcpExecutionError("Agent settings discovery timed out", {}, "agent_settings_discovery_timeout")), 90_000);
352
- const completion = (async () => {
353
- try {
354
- const result = await discoverAgentSettings(command, config, directories, sessions, operationSignal);
355
- for (const diagnostic of result.unsupportedModels) {
356
- const details = agentSettingsFailureDetails(command.agentId, diagnostic);
357
- audit.record({
358
- commandId: command.requestId,
359
- details,
360
- event: "agent_settings_model_unsupported",
361
- sessionId: `agent-settings:${command.agentId}`,
362
- });
363
- diagnostics.daemonDiagnostic("agent_settings_model_unsupported", command.requestId, details);
364
- process.stderr.write(`Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_model_unsupported", requestId: command.requestId, ...details })}\n`);
365
- }
366
- for (const requestId of requestIds) {
367
- audit.record({
368
- commandId: requestId,
369
- details: {
370
- agentId: command.agentId,
371
- unsupportedModelCount: result.unsupportedModels.length.toString(),
372
- },
373
- event: "agent_settings_discovered",
374
- sessionId: `agent-settings:${command.agentId}`,
375
- });
376
- if (socket.readyState === WebSocket.OPEN) {
377
- send(socket, { ...result.event, requestId });
378
- }
379
- }
380
- }
381
- catch (error) {
382
- const failure = operationSignal.aborted
383
- ? (controller.signal.reason ??
384
- new AcpExecutionError("Agent settings discovery cancelled", {}, "agent_settings_discovery_cancelled"))
385
- : error;
386
- const details = agentSettingsFailureDetails(command.agentId, failure);
387
- for (const requestId of requestIds) {
388
- audit.record({
389
- commandId: requestId,
390
- details,
391
- event: "agent_settings_discovery_failed",
392
- sessionId: `agent-settings:${command.agentId}`,
393
- });
394
- }
395
- diagnostics.daemonDiagnostic("agent_settings_discovery_failed", command.requestId, details, failure);
396
- if (failure instanceof AcpConfigurationValueUnavailableError) {
397
- process.stderr.write(`Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_discovery_failed", requestId: command.requestId, ...details })}\n`);
398
- }
399
- if (socket.readyState === WebSocket.OPEN) {
400
- for (const requestId of requestIds) {
401
- send(socket, {
402
- code: operationErrorCode(failure),
403
- kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
404
- message: operationErrorMessage(failure),
405
- requestId,
406
- });
407
- }
408
- }
409
- }
410
- finally {
411
- timeout.cancel();
412
- agentSettingsDiscoveries.delete(command.requestId);
413
- }
414
- })();
415
- agentSettingsDiscoveries.set(command.requestId, {
416
- agentId: command.agentId,
417
- model: command.model,
418
- requestIds,
419
- completion,
420
- controller,
421
- });
284
+ handleSettingsDiscovery.handle(message);
422
285
  return;
423
286
  }
424
287
  if (kind === AGENT_CATALOG_REFRESH_KIND) {
425
- const command = message;
426
- if (agentCatalogRefreshes.has(command.requestId) || agentCatalogRefreshes.size > 0) {
427
- if (socket.readyState === WebSocket.OPEN) {
428
- send(socket, {
429
- code: "agent_catalog_refresh_busy",
430
- kind: AGENT_CATALOG_REFRESH_FAILED_KIND,
431
- message: "Another local Agent catalog refresh is already running",
432
- requestId: command.requestId,
433
- });
434
- }
435
- return;
436
- }
437
- const controller = new AbortController();
438
- const operationSignal = AbortSignal.any([connectionController.signal, controller.signal]);
439
- const timeout = timer.schedule(() => controller.abort(new AcpExecutionError("The local Agent catalog refresh timed out", {}, "agent_catalog_refresh_timeout")), 90_000);
440
- const completion = (async () => {
441
- try {
442
- await refreshAgentCatalog(config, resolveAgentCatalogEnvironment, operationSignal);
443
- audit.record({
444
- commandId: command.requestId,
445
- event: "agent_catalog_refreshed",
446
- sessionId: "agent-catalog",
447
- });
448
- if (socket.readyState === WebSocket.OPEN) {
449
- send(socket, {
450
- kind: AGENT_CATALOG_REFRESHED_KIND,
451
- requestId: command.requestId,
452
- });
453
- }
454
- }
455
- catch (error) {
456
- const failure = operationSignal.aborted
457
- ? (controller.signal.reason ??
458
- new AcpExecutionError("The local Agent catalog refresh was cancelled", {}, "agent_catalog_refresh_cancelled"))
459
- : error;
460
- audit.record({
461
- commandId: command.requestId,
462
- details: { code: operationErrorCode(failure) },
463
- event: "agent_catalog_refresh_failed",
464
- sessionId: "agent-catalog",
465
- });
466
- diagnostics.daemonDiagnostic("agent_catalog_refresh_failed", command.requestId, { code: operationErrorCode(failure) }, failure);
467
- if (socket.readyState === WebSocket.OPEN) {
468
- send(socket, {
469
- code: operationErrorCode(failure),
470
- kind: AGENT_CATALOG_REFRESH_FAILED_KIND,
471
- message: operationErrorMessage(failure),
472
- requestId: command.requestId,
473
- });
474
- }
475
- }
476
- finally {
477
- timeout.cancel();
478
- agentCatalogRefreshes.delete(command.requestId);
479
- }
480
- })();
481
- agentCatalogRefreshes.set(command.requestId, { completion, controller });
482
- return;
483
- }
484
- if (kind === NATIVE_SESSION_REQUEST_KIND) {
485
- const command = message;
486
- const previous = [...nativeRequests.values()].filter((request) => request.agentId === command.agentId);
487
- if (nativeRequests.has(command.requestId) ||
488
- nativeRequests.size >= 4 ||
489
- (command.action !== "linked-history" &&
490
- command.action !== "active-turn" &&
491
- previous.some((request) => !request.controller.signal.aborted))) {
492
- reportOperationFailure(socket, command.requestId, command.sessionId, new AcpExecutionError("Another native session operation is running", {}, "native_session_busy"));
493
- return;
494
- }
495
- const controller = new AbortController();
496
- const operationSignal = AbortSignal.any([connectionController.signal, controller.signal]);
497
- const timeout = timer.schedule(() => controller.abort(new AcpExecutionError("Native session operation timed out", {}, "native_session_timeout")), 90_000);
498
- const completion = (async () => {
499
- try {
500
- operationSignal.throwIfAborted();
501
- if (previous.length > 0 && command.action !== "active-turn") {
502
- await new Promise((resolve, reject) => {
503
- const cancel = () => reject(operationSignal.reason);
504
- operationSignal.addEventListener("abort", cancel, {
505
- once: true,
506
- });
507
- void Promise.all(previous.map((request) => request.completion)).then(() => {
508
- operationSignal.removeEventListener("abort", cancel);
509
- resolve();
510
- }, (error) => {
511
- operationSignal.removeEventListener("abort", cancel);
512
- reject(error);
513
- });
514
- });
515
- }
516
- operationSignal.throwIfAborted();
517
- const result = await nativeSessions.execute(command, operationSignal);
518
- if (socket.readyState === WebSocket.OPEN) {
519
- send(socket, result);
520
- }
521
- }
522
- catch (error) {
523
- const failure = operationSignal.aborted
524
- ? (controller.signal.reason ??
525
- new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"))
526
- : error;
527
- audit.record({
528
- commandId: command.requestId,
529
- sessionId: command.sessionId,
530
- event: "native_session_operation_failed",
531
- details: { code: operationErrorCode(failure) },
532
- });
533
- diagnostics.daemonDiagnostic("native_session_operation_failed", command.requestId, {
534
- action: command.action,
535
- agentId: command.agentId,
536
- code: operationErrorCode(failure),
537
- sessionId: command.sessionId,
538
- }, failure);
539
- reportOperationFailure(socket, command.requestId, command.sessionId, failure);
540
- }
541
- finally {
542
- timeout.cancel();
543
- nativeRequests.delete(command.requestId);
544
- }
545
- })();
546
- nativeRequests.set(command.requestId, {
547
- agentId: command.agentId,
548
- sessionId: command.sessionId,
549
- controller,
550
- completion,
551
- });
288
+ handleCatalogRefresh.handle(message);
552
289
  return;
553
290
  }
554
- if (kind === NATIVE_SESSION_TURN_FORK_KIND) {
555
- const command = message;
556
- const previous = [...nativeRequests.values()].filter((request) => request.agentId === command.agentId);
557
- if (nativeRequests.has(command.requestId) ||
558
- nativeRequests.size >= 4 ||
559
- previous.some((request) => !request.controller.signal.aborted)) {
560
- reportOperationFailure(socket, command.requestId, command.sessionId, new AcpExecutionError("Another native session operation is running", {}, "native_session_busy"));
561
- return;
562
- }
563
- const controller = new AbortController();
564
- const operationSignal = AbortSignal.any([connectionController.signal, controller.signal]);
565
- const timeout = timer.schedule(() => controller.abort(new AcpExecutionError("Native session operation timed out", {}, "native_session_timeout")), 90_000);
566
- const completion = (async () => {
567
- try {
568
- operationSignal.throwIfAborted();
569
- if (previous.length > 0) {
570
- await new Promise((resolve, reject) => {
571
- const cancel = () => reject(operationSignal.reason);
572
- operationSignal.addEventListener("abort", cancel, { once: true });
573
- void Promise.all(previous.map((request) => request.completion)).then(() => {
574
- operationSignal.removeEventListener("abort", cancel);
575
- resolve();
576
- }, (error) => {
577
- operationSignal.removeEventListener("abort", cancel);
578
- reject(error);
579
- });
580
- });
581
- }
582
- operationSignal.throwIfAborted();
583
- const result = await nativeSessions.executeTurnFork(command, operationSignal);
584
- if (socket.readyState === WebSocket.OPEN) {
585
- send(socket, result);
586
- }
587
- }
588
- catch (error) {
589
- const failure = operationSignal.aborted
590
- ? (controller.signal.reason ??
591
- new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"))
592
- : error;
593
- audit.record({
594
- commandId: command.requestId,
595
- details: { code: operationErrorCode(failure) },
596
- event: "native_session_turn_fork_failed",
597
- sessionId: command.sessionId,
598
- });
599
- diagnostics.daemonDiagnostic("native_session_turn_fork_failed", command.requestId, {
600
- agentId: command.agentId,
601
- code: operationErrorCode(failure),
602
- sessionId: command.sessionId,
603
- }, failure);
604
- reportOperationFailure(socket, command.requestId, command.sessionId, failure);
605
- }
606
- finally {
607
- timeout.cancel();
608
- nativeRequests.delete(command.requestId);
609
- }
610
- })();
611
- nativeRequests.set(command.requestId, {
612
- agentId: command.agentId,
613
- completion,
614
- controller,
615
- sessionId: command.sessionId,
616
- });
291
+ if (kind === NATIVE_SESSION_REQUEST_KIND || kind === NATIVE_SESSION_TURN_FORK_KIND) {
292
+ nativeRequestHandler.handle(message);
617
293
  return;
618
294
  }
619
295
  if (kind === RUNTIME_LIVENESS_READY_KIND) {
@@ -647,7 +323,8 @@ async function runRelayConnection(config, directories, audit, sessions, installa
647
323
  settleAbandonedTurn(publisher, operations, audit, cancellation);
648
324
  return;
649
325
  }
650
- if (!turn.requestCancellation()) {
326
+ const cancellationState = turn.requestCancellation();
327
+ if (cancellationState === "already-requested") {
651
328
  return;
652
329
  }
653
330
  audit.record({
@@ -655,6 +332,9 @@ async function runRelayConnection(config, directories, audit, sessions, installa
655
332
  event: "session_cancellation_requested",
656
333
  sessionId: cancellation.sessionId,
657
334
  });
335
+ if (cancellationState === "pending") {
336
+ return;
337
+ }
658
338
  void sessions.cancelPrompt(cancellation.sessionId).catch((error) => {
659
339
  console.error("Mobius daemon could not cancel the agent turn", error);
660
340
  });
@@ -783,9 +463,9 @@ async function runRelayConnection(config, directories, audit, sessions, installa
783
463
  finally {
784
464
  connectionController.abort();
785
465
  await Promise.all([
786
- ...[...nativeRequests.values()].map((request) => request.completion),
787
- ...[...agentSettingsDiscoveries.values()].map((request) => request.completion),
788
- ...[...agentCatalogRefreshes.values()].map((request) => request.completion),
466
+ nativeRequestHandler.settle(),
467
+ handleSettingsDiscovery.settle(),
468
+ handleCatalogRefresh.settle(),
789
469
  ]);
790
470
  }
791
471
  }
@@ -806,6 +486,9 @@ export async function runDaemon(config, audit, signal, timer = systemDaemonTimer
806
486
  const publisher = new DaemonSessionEventPublisher();
807
487
  const activeTurns = new Map();
808
488
  const recordSessionEvent = (sessionId, event) => {
489
+ for (const turn of activeTurns.values()) {
490
+ turn.recordInteraction(event);
491
+ }
809
492
  publisher.publish(sessionId, event);
810
493
  };
811
494
  const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {