@moxt-ai/mobius 0.0.96 → 0.0.99

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.
Files changed (92) hide show
  1. package/dist/acp/activity.d.ts.map +1 -1
  2. package/dist/acp/activity.js +13 -2
  3. package/dist/acp/activity.js.map +1 -1
  4. package/dist/acp/codex/agent.d.ts.map +1 -1
  5. package/dist/acp/codex/agent.js +19 -4
  6. package/dist/acp/codex/agent.js.map +1 -1
  7. package/dist/acp/process-session.d.ts +0 -2
  8. package/dist/acp/process-session.d.ts.map +1 -1
  9. package/dist/acp/process-session.js +5 -123
  10. package/dist/acp/process-session.js.map +1 -1
  11. package/dist/acp/session-manager.d.ts.map +1 -1
  12. package/dist/acp/session-manager.js +5 -5
  13. package/dist/acp/session-manager.js.map +1 -1
  14. package/dist/acp/session-state.d.ts +43 -0
  15. package/dist/acp/session-state.d.ts.map +1 -0
  16. package/dist/acp/session-state.js +87 -0
  17. package/dist/acp/session-state.js.map +1 -0
  18. package/dist/cli.js +5494 -12821
  19. package/dist/cli.js.map +4 -4
  20. package/dist/daemon-manager.d.ts +1 -1
  21. package/dist/daemon-manager.d.ts.map +1 -1
  22. package/dist/daemon-manager.js +1 -2
  23. package/dist/daemon-manager.js.map +1 -1
  24. package/dist/daemon-observers.d.ts +30 -0
  25. package/dist/daemon-observers.d.ts.map +1 -0
  26. package/dist/daemon-observers.js +137 -0
  27. package/dist/daemon-observers.js.map +1 -0
  28. package/dist/daemon-session-commands.d.ts +33 -0
  29. package/dist/daemon-session-commands.d.ts.map +1 -0
  30. package/dist/daemon-session-commands.js +522 -0
  31. package/dist/daemon-session-commands.js.map +1 -0
  32. package/dist/daemon-turn-reconciliation.d.ts +27 -0
  33. package/dist/daemon-turn-reconciliation.d.ts.map +1 -0
  34. package/dist/daemon-turn-reconciliation.js +121 -0
  35. package/dist/daemon-turn-reconciliation.js.map +1 -0
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +8894 -16221
  39. package/dist/index.js.map +4 -4
  40. package/dist/native-sessions/acp-adapter.d.ts +3 -0
  41. package/dist/native-sessions/acp-adapter.d.ts.map +1 -0
  42. package/dist/native-sessions/acp-adapter.js +7 -0
  43. package/dist/native-sessions/acp-adapter.js.map +1 -0
  44. package/dist/native-sessions/acp-history.d.ts +6 -0
  45. package/dist/native-sessions/acp-history.d.ts.map +1 -0
  46. package/dist/native-sessions/{claude-history.js → acp-history.js} +3 -3
  47. package/dist/native-sessions/acp-history.js.map +1 -0
  48. package/dist/native-sessions/agent-adapter.js +3 -3
  49. package/dist/native-sessions/agent-adapter.js.map +1 -1
  50. package/dist/native-sessions/chat-agent.d.ts +1 -0
  51. package/dist/native-sessions/chat-agent.d.ts.map +1 -1
  52. package/dist/native-sessions/chat-agent.js +12 -1
  53. package/dist/native-sessions/chat-agent.js.map +1 -1
  54. package/dist/native-sessions/live-history-page.d.ts +3 -0
  55. package/dist/native-sessions/live-history-page.d.ts.map +1 -0
  56. package/dist/native-sessions/live-history-page.js +81 -0
  57. package/dist/native-sessions/live-history-page.js.map +1 -0
  58. package/dist/pairing/pair-local-machine.js.map +1 -1
  59. package/dist/relay-connection/coalescing-activity-publisher.d.ts +10 -0
  60. package/dist/relay-connection/coalescing-activity-publisher.d.ts.map +1 -0
  61. package/dist/relay-connection/coalescing-activity-publisher.js +54 -0
  62. package/dist/relay-connection/coalescing-activity-publisher.js.map +1 -0
  63. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  64. package/dist/relay-connection/session-event-outbox.js +13 -48
  65. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  66. package/dist/relay-connection/session-event-publisher.d.ts +17 -0
  67. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -0
  68. package/dist/relay-connection/session-event-publisher.js +245 -0
  69. package/dist/relay-connection/session-event-publisher.js.map +1 -0
  70. package/dist/run-daemon.d.ts.map +1 -1
  71. package/dist/run-daemon.js +10 -1146
  72. package/dist/run-daemon.js.map +1 -1
  73. package/dist/runtime.d.ts +1 -1
  74. package/dist/runtime.d.ts.map +1 -1
  75. package/dist/runtime.js +5604 -12929
  76. package/dist/runtime.js.map +4 -4
  77. package/dist/storage/runtime-installation-store.d.ts +6 -14
  78. package/dist/storage/runtime-installation-store.d.ts.map +1 -1
  79. package/dist/storage/runtime-installation-store.js +16 -103
  80. package/dist/storage/runtime-installation-store.js.map +1 -1
  81. package/package.json +1 -4
  82. package/dist/acp/markdown-images.d.ts +0 -8
  83. package/dist/acp/markdown-images.d.ts.map +0 -1
  84. package/dist/acp/markdown-images.js +0 -55
  85. package/dist/acp/markdown-images.js.map +0 -1
  86. package/dist/native-sessions/claude-adapter.d.ts +0 -3
  87. package/dist/native-sessions/claude-adapter.d.ts.map +0 -1
  88. package/dist/native-sessions/claude-adapter.js +0 -7
  89. package/dist/native-sessions/claude-adapter.js.map +0 -1
  90. package/dist/native-sessions/claude-history.d.ts +0 -6
  91. package/dist/native-sessions/claude-history.d.ts.map +0 -1
  92. package/dist/native-sessions/claude-history.js.map +0 -1
@@ -1,309 +1,34 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { basename } from "node:path";
3
2
  import { styleText } from "node:util";
4
- import { AGENT_ACTIVITY_KIND, AGENT_ACTIVITY_NARRATION_KIND, AGENT_CATALOG_REFRESH_FAILED_KIND, AGENT_CATALOG_REFRESH_KIND, AGENT_CATALOG_REFRESHED_KIND, AGENT_INSTALL_CANCEL_KIND, AGENT_INSTALL_CANCELLED_KIND, AGENT_INSTALL_COMPLETED_KIND, AGENT_INSTALL_FAILED_KIND, AGENT_INSTALL_PROGRESS_KIND, AGENT_INSTALL_REQUEST_KIND, AGENT_INSTALL_STARTED_KIND, AGENT_MESSAGE_DELTA_KIND, AGENT_SETTINGS_DISCOVER_KIND, AGENT_SETTINGS_DISCOVERY_FAILED_KIND, decodeServiceToDaemonMessage, decodeSessionEventEnvelope, decodeSessionLiveHistoryLoad, decodeSessionLiveHistoryPageLoad, encodeDaemonToServiceMessage, encodeRecordedSessionEvent, FILE_FAILED_KIND, FILE_READ_KIND, NATIVE_SESSION_CANCEL_KIND, NATIVE_SESSION_REQUEST_KIND, NATIVE_SESSION_TURN_FORK_KIND, RUNTIME_DELIVERY_COMMITTED_KIND, RUNTIME_DELIVERY_KIND, RUNTIME_DELIVERY_RECEIVED_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_COMPLETED_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_EVENT_ACK_KIND, SESSION_EVENT_DEFERRED_KIND, SESSION_EVENT_REJECTED_KIND, SESSION_FAILED_KIND, SESSION_LIVE_HISTORY_LOAD_KIND, SESSION_LIVE_HISTORY_PAGE_LOAD_KIND, SESSION_PERMISSION_RESPOND_KIND, SESSION_PREPARE_KIND, SESSION_PROMPT_KIND, SESSION_STARTED_KIND, SessionPromptDisposition, WORKSPACE_LIST_KIND, } from "@moxt-ai/mobius-protocol";
5
- import { fetch, WebSocket } from "undici";
6
- import { agentForSessionConfiguration, applyCompleteSessionConfiguration, assertAppliedSessionConfiguration, } from "./acp/session-config/apply-session-configuration.js";
7
- import { AcpConfigurationValueUnavailableError, AcpExecutionError, AcpSessionManager, } from "./acp/session-manager.js";
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_DELIVERY_COMMITTED_KIND, RUNTIME_DELIVERY_KIND, RUNTIME_DELIVERY_RECEIVED_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_EVENT_ACK_KIND, SESSION_EVENT_DEFERRED_KIND, SESSION_EVENT_REJECTED_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
+ import { WebSocket } from "undici";
5
+ import { AcpConfigurationValueUnavailableError, AcpExecutionError, AcpSessionManager } from "./acp/session-manager.js";
8
6
  import { MemoryAcpSessionStore } from "./acp/session-store.js";
9
7
  import { discoverAgentSettings } from "./agent-catalog/discover-agent-settings.js";
10
8
  import { discoverLocalAgentInventory, supportedLocalAgentSpecifications, } from "./agent-catalog/discover-local-agents.js";
11
- import { AgentIntegrationDefinition, LocalAgentCatalogError, } from "./agent-catalog/local-agent.js";
9
+ import { AgentIntegrationDefinition } from "./agent-catalog/local-agent.js";
12
10
  import { publishAgentCatalog } from "./agent-catalog/publish-agent-catalog.js";
13
- import { AgentInstallationManager, CancelledInstallation, FailedInstallation, RequestedInstallation, RunningInstallation, SucceededInstallation, } from "./agent-installation/agent-installation-manager.js";
11
+ import { AgentInstallationManager } from "./agent-installation/agent-installation-manager.js";
14
12
  import { FixedInstallationExecutor } from "./agent-installation/fixed-installation-executor.js";
15
13
  import { streamLocalFile } from "./artifacts/local-file-streamer.js";
16
- import { LocalAuthorizationError } from "./authorization/local-authorization-error.js";
17
14
  import { WorkspaceDirectoryService } from "./authorization/workspace-directory.js";
18
15
  import { DaemonLocalContext, withDaemonEnvironment } from "./config.js";
19
16
  import { DaemonDiagnosticLog } from "./daemon-diagnostic-log.js";
20
- import { AccumulatingOperationMetrics } from "./infra/operation-metrics.js";
17
+ import { AuditInstallationEvents, DaemonAcpObserver, DaemonInstallationObserver } from "./daemon-observers.js";
18
+ import { agentSettingsFailureDetails, executePrompt, executeSessionConfigure, executeSessionLiveHistoryLoad, executeSessionLiveHistoryPageLoad, executeSessionPrepare, executeWorkspaceList, operationErrorCode, operationErrorMessage, reportFailure, reportOperationFailure, send, settleAbandonedTurn, } from "./daemon-session-commands.js";
19
+ import { ActiveDaemonTurn, ActiveTurnReconciliationError, reconcileActiveTurns } from "./daemon-turn-reconciliation.js";
21
20
  import { readCodexFullHistory } from "./native-sessions/codex-history.js";
22
21
  import { NativeSessionService } from "./native-sessions/service.js";
23
- import { environmentProxyDispatcher } from "./network/environment-proxy.js";
24
22
  import { revalidateExecutable } from "./process/executable.js";
25
- import { PromptArtifactError, resolvePromptArtifacts } from "./prompt-artifact-resolver.js";
26
- import { CoalescingNarrationPublisher } from "./relay-connection/coalescing-narration-publisher.js";
27
- import { CoalescingTextPublisher } from "./relay-connection/coalescing-text-publisher.js";
28
23
  import { connectRelay } from "./relay-connection/connect.js";
29
24
  import { RelayConnectionDiagnostics } from "./relay-connection/diagnostics.js";
30
25
  import { RelayConnectionLiveness } from "./relay-connection/liveness.js";
31
- import { relayHttpEndpoint, runtimeAuthorization } from "./relay-connection/runtime-authentication.js";
32
26
  import { isRuntimeRelayRevocation, RuntimeRelayRevokedError } from "./relay-connection/runtime-revocation.js";
33
- import { RuntimeDeliveryInboxCapacityError, SessionEventOutbox, SessionEventOutboxCapacityError, } from "./relay-connection/session-event-outbox.js";
27
+ import { RuntimeDeliveryInboxCapacityError, SessionEventOutbox } from "./relay-connection/session-event-outbox.js";
28
+ import { DaemonSessionEventPublisher } from "./relay-connection/session-event-publisher.js";
34
29
  import { systemDaemonTimer } from "./relay-connection/timer.js";
35
30
  const RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
36
- const AGENT_ACTIVITY_COALESCING_MILLISECONDS = 100;
37
- const AGENT_TEXT_COALESCING_MILLISECONDS = 100;
38
- // Mirrors the protocol's per-event text limit; a delta larger than this is
39
- // rejected by the Session event codec rather than truncated.
40
- const AGENT_TEXT_MAXIMUM_LENGTH = 100_000;
41
- const ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 20_000;
42
31
  const ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
43
- class DaemonAcpObserver {
44
- #record;
45
- constructor(record) {
46
- this.#record = record;
47
- }
48
- onCommands = (event) => {
49
- this.#record(event.sessionId, event);
50
- return Promise.resolve();
51
- };
52
- onConfig = (event) => {
53
- this.#record(event.sessionId, event);
54
- return Promise.resolve();
55
- };
56
- onContent = (event) => {
57
- this.#record(event.sessionId, event);
58
- return Promise.resolve();
59
- };
60
- onElicitation = (event) => {
61
- this.#record(event.sessionId, event);
62
- return Promise.resolve();
63
- };
64
- onElicitationResolved = (event) => {
65
- this.#record(event.sessionId, event);
66
- return Promise.resolve();
67
- };
68
- onInfo = (event) => {
69
- this.#record(event.sessionId, event);
70
- return Promise.resolve();
71
- };
72
- onPermission = (event) => {
73
- this.#record(event.sessionId, event);
74
- return Promise.resolve();
75
- };
76
- onPermissionResolved = (event) => {
77
- this.#record(event.sessionId, event);
78
- return Promise.resolve();
79
- };
80
- onUsage = (event) => {
81
- this.#record(event.sessionId, event);
82
- return Promise.resolve();
83
- };
84
- }
85
- class AuditInstallationEvents {
86
- #audit;
87
- constructor(audit) {
88
- this.#audit = audit;
89
- }
90
- record = (event, requestId, agentId, details = {}) => {
91
- this.#audit.record({
92
- commandId: requestId,
93
- details,
94
- event,
95
- sessionId: `agent-installation:${agentId}`,
96
- });
97
- };
98
- }
99
- class DaemonInstallationObserver {
100
- #started = new Set();
101
- #socket = null;
102
- connect = (socket) => {
103
- this.#socket = socket;
104
- };
105
- disconnect = (socket) => {
106
- if (this.#socket === socket) {
107
- this.#socket = null;
108
- }
109
- };
110
- #send = (socket, message) => {
111
- try {
112
- send(socket, message);
113
- }
114
- catch {
115
- if (this.#socket === socket) {
116
- this.#socket = null;
117
- }
118
- }
119
- };
120
- onState = (state) => {
121
- const socket = this.#socket;
122
- if (socket === null || socket.readyState !== WebSocket.OPEN) {
123
- return Promise.resolve();
124
- }
125
- if (state instanceof RequestedInstallation) {
126
- return Promise.resolve();
127
- }
128
- if (state instanceof RunningInstallation) {
129
- if (!this.#started.has(state.requestId)) {
130
- this.#started.add(state.requestId);
131
- this.#send(socket, {
132
- agentId: state.agentId,
133
- kind: AGENT_INSTALL_STARTED_KIND,
134
- requestId: state.requestId,
135
- });
136
- }
137
- this.#send(socket, {
138
- agentId: state.agentId,
139
- kind: AGENT_INSTALL_PROGRESS_KIND,
140
- requestId: state.requestId,
141
- stage: state.stage,
142
- });
143
- return Promise.resolve();
144
- }
145
- if (state instanceof SucceededInstallation) {
146
- this.#send(socket, {
147
- agentId: state.agentId,
148
- authenticationMayBeRequired: state.authenticationMayBeRequired,
149
- kind: AGENT_INSTALL_COMPLETED_KIND,
150
- requestId: state.requestId,
151
- });
152
- return Promise.resolve();
153
- }
154
- if (state instanceof FailedInstallation) {
155
- this.#send(socket, {
156
- agentId: state.agentId,
157
- code: state.code,
158
- kind: AGENT_INSTALL_FAILED_KIND,
159
- message: state.message,
160
- requestId: state.requestId,
161
- });
162
- return Promise.resolve();
163
- }
164
- if (state instanceof CancelledInstallation) {
165
- this.#send(socket, {
166
- agentId: state.agentId,
167
- kind: AGENT_INSTALL_CANCELLED_KIND,
168
- requestId: state.requestId,
169
- });
170
- return Promise.resolve();
171
- }
172
- throw new Error("Unsupported Agent integration installation state");
173
- };
174
- }
175
- class ResolvedSessionDirectories {
176
- additionalDirectories;
177
- additionalDirectoryEntries;
178
- cwd;
179
- constructor(cwd, additionalDirectories, additionalDirectoryEntries) {
180
- this.additionalDirectories = additionalDirectories;
181
- this.additionalDirectoryEntries = additionalDirectoryEntries;
182
- this.cwd = cwd;
183
- }
184
- }
185
- class ActiveDaemonTurn {
186
- attemptId;
187
- command;
188
- #controller;
189
- #finished = Promise.withResolvers();
190
- #cancellationRequested = false;
191
- constructor(command, attemptId) {
192
- this.attemptId = attemptId;
193
- this.command = command;
194
- this.#controller = new AbortController();
195
- }
196
- abortDaemon = () => {
197
- this.#controller.abort();
198
- };
199
- finish = () => this.#finished.resolve();
200
- matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
201
- requestCancellation = () => {
202
- if (this.#cancellationRequested) {
203
- return false;
204
- }
205
- this.#cancellationRequested = true;
206
- return true;
207
- };
208
- get signal() {
209
- return this.#controller.signal;
210
- }
211
- get completion() {
212
- return this.#finished.promise;
213
- }
214
- }
215
- class ActiveTurnReconciliationError extends Error {
216
- code = "active_turn_reconciliation_failed";
217
- diagnosticDetails;
218
- relayErrorCode;
219
- terminal;
220
- constructor(message, options = {}) {
221
- super(message, options);
222
- this.name = "ActiveTurnReconciliationError";
223
- this.relayErrorCode = options.relayErrorCode ?? null;
224
- this.terminal = options.terminal ?? false;
225
- this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
226
- }
227
- }
228
- /**
229
- * The Relay reports a reconciliation conflict when the Attempt is no longer owned by this Runtime or has
230
- * already reached a terminal state. Retrying cannot change that outcome, so the daemon must abandon the
231
- * stale turn instead of replacing its connection forever.
232
- */
233
- const TERMINAL_RECONCILIATION_RELAY_CODES = new Set(["session_conflict"]);
234
- async function relayErrorCode(response) {
235
- try {
236
- const body = JSON.parse(await response.text());
237
- if (typeof body !== "object" || body === null) {
238
- return null;
239
- }
240
- const error = Reflect.get(body, "error");
241
- if (typeof error !== "object" || error === null) {
242
- return null;
243
- }
244
- const code = Reflect.get(error, "code");
245
- return typeof code === "string" && code.length > 0 ? code : null;
246
- }
247
- catch {
248
- return null;
249
- }
250
- }
251
- function activeTurnReconciliationEndpoint(config, turn) {
252
- const endpoint = relayHttpEndpoint(config.relayUrl);
253
- let channelPath = "";
254
- if (endpoint.pathname.endsWith("/daemon")) {
255
- channelPath = endpoint.pathname.slice(0, -"/daemon".length);
256
- }
257
- else {
258
- const runtimePath = "/v1/runtimes/connect";
259
- if (!endpoint.pathname.endsWith(runtimePath)) {
260
- throw new ActiveTurnReconciliationError("The Relay URL is invalid");
261
- }
262
- channelPath = `${endpoint.pathname.slice(0, -runtimePath.length)}/channels/${encodeURIComponent(config.channelId)}`;
263
- }
264
- endpoint.pathname = `${channelPath}/sessions/${encodeURIComponent(turn.command.sessionId)}/attempts/${encodeURIComponent(turn.attemptId)}/reconciliation`;
265
- return endpoint;
266
- }
267
- async function reconcileActiveTurn(config, turn, signal) {
268
- signal.throwIfAborted();
269
- const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
270
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
271
- let response;
272
- try {
273
- response = await fetch(activeTurnReconciliationEndpoint(config, turn), {
274
- body: JSON.stringify({ outcome: { kind: "running" } }),
275
- dispatcher: environmentProxyDispatcher,
276
- headers: { ...runtimeAuthorization(config.relayUrl), "content-type": "application/json" },
277
- method: "POST",
278
- signal: requestSignal,
279
- });
280
- }
281
- catch (error) {
282
- if (signal.aborted) {
283
- signal.throwIfAborted();
284
- }
285
- throw new ActiveTurnReconciliationError(timeoutSignal.aborted
286
- ? "The active Agent turn reconciliation timed out"
287
- : "The active Agent turn could not be reconciled", { cause: error });
288
- }
289
- if (!response.ok) {
290
- const errorCode = await relayErrorCode(response);
291
- const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
292
- throw new ActiveTurnReconciliationError(terminal
293
- ? `The Relay reported that the active Agent turn can no longer be reconciled (${errorCode})`
294
- : `The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`, { relayErrorCode: errorCode, terminal });
295
- }
296
- await response.body?.cancel();
297
- }
298
- async function reconcileActiveTurns(config, turns, signal) {
299
- await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config, turn, signal)));
300
- }
301
- function send(socket, message) {
302
- if (socket.readyState !== WebSocket.OPEN) {
303
- throw new Error("Relay connection is not open");
304
- }
305
- socket.send(encodeDaemonToServiceMessage(message));
306
- }
307
32
  function closeRelaySocket(socket, code, reason) {
308
33
  try {
309
34
  socket.close(code, reason);
@@ -318,867 +43,6 @@ function closeRelaySocket(socket, code, reason) {
318
43
  }
319
44
  }
320
45
  }
321
- class DaemonSessionEventConnectionState {
322
- }
323
- class DisconnectedDaemonSessionEventState extends DaemonSessionEventConnectionState {
324
- disconnect = () => this;
325
- matches = () => false;
326
- send = () => false;
327
- }
328
- class ConnectedDaemonSessionEventState extends DaemonSessionEventConnectionState {
329
- #socket;
330
- constructor(socket) {
331
- super();
332
- this.#socket = socket;
333
- }
334
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
335
- matches = (socket) => socket === this.#socket;
336
- send = (message) => {
337
- if (this.#socket.readyState !== WebSocket.OPEN) {
338
- return false;
339
- }
340
- try {
341
- this.#socket.send(encodeDaemonToServiceMessage(message));
342
- return true;
343
- }
344
- catch {
345
- // The in-memory outbox retains the event for the replacement connection.
346
- return false;
347
- }
348
- };
349
- }
350
- const SESSION_EVENT_REPLAY_WINDOW = 16;
351
- const SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
352
- const SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
353
- /**
354
- * Events that settle a Turn reserve capacity streaming events cannot consume. A
355
- * completed narrative activity carries the text that supersedes its increments, so it
356
- * is the only event that can settle a streamed narration; without the reservation the
357
- * snapshot could be shed after its increments were, losing the text entirely.
358
- */
359
- function reservesSessionEventCapacity(event) {
360
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
361
- return true;
362
- }
363
- return (event.kind === AGENT_ACTIVITY_KIND &&
364
- (event.activityType === "progress" || event.activityType === "reasoning") &&
365
- (event.status === "completed" || event.status === "failed"));
366
- }
367
- class InFlightSessionEvent {
368
- byteLength;
369
- sourceKey;
370
- constructor(sourceKey, byteLength) {
371
- this.byteLength = byteLength;
372
- this.sourceKey = sourceKey;
373
- }
374
- }
375
- function sessionEventSourceKey(envelope) {
376
- return envelope.source.kind === "attempt"
377
- ? `attempt:${envelope.sessionId}:${envelope.source.attemptId}`
378
- : `runtime:${envelope.sessionId}`;
379
- }
380
- class DaemonSessionEventPublisher {
381
- #outbox;
382
- #inFlightEvents = new Map();
383
- #pausedSources = new Map();
384
- #shedEventKinds = new Set();
385
- #timer;
386
- #inFlightBytes = 0;
387
- #connection = new DisconnectedDaemonSessionEventState();
388
- constructor(outbox, timer) {
389
- this.#outbox = outbox;
390
- this.#timer = timer;
391
- }
392
- connect = (socket) => {
393
- this.#connection = new ConnectedDaemonSessionEventState(socket);
394
- this.#clearInFlight();
395
- this.#publishNextBatch();
396
- };
397
- disconnect = (socket) => {
398
- if (!this.#connection.matches(socket)) {
399
- return;
400
- }
401
- this.#connection = this.#connection.disconnect(socket);
402
- this.#clearInFlight();
403
- };
404
- recordAttempt = (sessionId, event, attemptId) => {
405
- const encoded = encodeRecordedSessionEvent(event);
406
- if (reservesSessionEventCapacity(event)) {
407
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
408
- }
409
- else {
410
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
411
- }
412
- this.#publishNextBatch();
413
- };
414
- recordRuntime = (sessionId, event) => {
415
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
416
- this.#publishNextBatch();
417
- };
418
- /**
419
- * Enqueue a standard event, shedding it instead of ending the daemon when the
420
- * in-memory outbox is full.
421
- *
422
- * A capacity error used to escape the coalescing timer that publishes activities,
423
- * so the process exited and every restart died on the same retained backlog. A full
424
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
425
- * superseded by the completed snapshot, so they are shed first, and any other streaming
426
- * event is shed only at the wall rather than terminating the daemon.
427
- */
428
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
429
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
430
- this.#reportShedEvent(kind);
431
- return;
432
- }
433
- try {
434
- this.#outbox.enqueue(sessionId, encoded, attemptId);
435
- }
436
- catch (error) {
437
- if (!(error instanceof SessionEventOutboxCapacityError)) {
438
- throw error;
439
- }
440
- this.#reportShedEvent(kind);
441
- }
442
- };
443
- /**
444
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
445
- * Streaming events are shed before this budget is reached, so a Turn's terminal
446
- * events and the completed snapshot that carries its narration still land; a drop
447
- * here is the last resort for a backlog no acknowledgement can drain.
448
- */
449
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
450
- try {
451
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
452
- }
453
- catch (error) {
454
- if (!(error instanceof SessionEventOutboxCapacityError)) {
455
- throw error;
456
- }
457
- this.#reportShedEvent(kind);
458
- }
459
- };
460
- #reportShedEvent = (kind) => {
461
- if (this.#shedEventKinds.has(kind)) {
462
- return;
463
- }
464
- this.#shedEventKinds.add(kind);
465
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
466
- };
467
- acknowledge = (acknowledgement) => {
468
- if (!this.#outbox.acknowledge(acknowledgement)) {
469
- return;
470
- }
471
- this.#removeInFlight(acknowledgement.eventId);
472
- this.#publishNextBatch();
473
- };
474
- quarantine = (rejection) => {
475
- const quarantined = this.#outbox.quarantine(rejection);
476
- if (!quarantined) {
477
- return false;
478
- }
479
- this.#removeInFlight(rejection.eventId);
480
- this.#publishNextBatch();
481
- return true;
482
- };
483
- defer = (deferred) => {
484
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
485
- if (inFlight === undefined) {
486
- return;
487
- }
488
- this.#clearInFlightSource(inFlight.sourceKey);
489
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
490
- this.#pausedSources.set(inFlight.sourceKey, this.#timer.schedule(() => {
491
- this.#pausedSources.delete(inFlight.sourceKey);
492
- this.#publishNextBatch();
493
- }, deferred.retryAfterMilliseconds));
494
- }
495
- this.#publishNextBatch();
496
- };
497
- close = () => {
498
- for (const task of this.#pausedSources.values()) {
499
- task.cancel();
500
- }
501
- this.#pausedSources.clear();
502
- this.#clearInFlight();
503
- };
504
- #publishNextBatch = () => {
505
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
506
- const sourceCounts = new Map();
507
- for (const inFlight of this.#inFlightEvents.values()) {
508
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
509
- }
510
- const saturatedSources = [...sourceCounts.entries()]
511
- .filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW)
512
- .map(([sourceKey]) => sourceKey);
513
- const batch = this.#outbox.pendingSourceHeads(SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size, [...this.#inFlightEvents.keys()], [...this.#pausedSources.keys(), ...saturatedSources]);
514
- let sent = 0;
515
- for (const encoded of batch) {
516
- const envelope = decodeSessionEventEnvelope(encoded);
517
- const sourceKey = sessionEventSourceKey(envelope);
518
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
519
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
520
- continue;
521
- }
522
- const byteLength = new TextEncoder().encode(encoded).byteLength;
523
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
524
- continue;
525
- }
526
- if (!this.#connection.send(envelope)) {
527
- this.#clearInFlight();
528
- return;
529
- }
530
- this.#inFlightEvents.set(envelope.eventId, new InFlightSessionEvent(sourceKey, byteLength));
531
- this.#inFlightBytes += byteLength;
532
- sourceCounts.set(sourceKey, sourceCount + 1);
533
- sent += 1;
534
- }
535
- if (sent === 0) {
536
- return;
537
- }
538
- }
539
- };
540
- #removeInFlight = (eventId) => {
541
- const inFlight = this.#inFlightEvents.get(eventId);
542
- if (inFlight === undefined) {
543
- return;
544
- }
545
- this.#inFlightEvents.delete(eventId);
546
- this.#inFlightBytes -= inFlight.byteLength;
547
- };
548
- #clearInFlight = () => {
549
- this.#inFlightEvents.clear();
550
- this.#inFlightBytes = 0;
551
- };
552
- #clearInFlightSource = (sourceKey) => {
553
- for (const [eventId, inFlight] of this.#inFlightEvents) {
554
- if (inFlight.sourceKey !== sourceKey) {
555
- continue;
556
- }
557
- this.#inFlightEvents.delete(eventId);
558
- this.#inFlightBytes -= inFlight.byteLength;
559
- }
560
- };
561
- }
562
- class CoalescingDaemonActivityPublisher {
563
- #pending = new Map();
564
- #publish;
565
- #publishedActivityIds = new Set();
566
- #scheduled = new Map();
567
- #timer;
568
- constructor(timer, publish) {
569
- this.#publish = publish;
570
- this.#timer = timer;
571
- }
572
- flush = () => {
573
- const activities = [...this.#pending.values()].sort((left, right) => left.sequence - right.sequence);
574
- for (const task of this.#scheduled.values()) {
575
- task.cancel();
576
- }
577
- this.#pending.clear();
578
- this.#scheduled.clear();
579
- for (const activity of activities) {
580
- this.#publish(activity);
581
- }
582
- };
583
- record = (activity) => {
584
- if (activity.status !== "pending" && activity.status !== "running") {
585
- this.#discardPending(activity.activityId);
586
- this.#publishedActivityIds.add(activity.activityId);
587
- this.#publish(activity);
588
- return Promise.resolve();
589
- }
590
- if (!this.#publishedActivityIds.has(activity.activityId)) {
591
- this.#publishedActivityIds.add(activity.activityId);
592
- this.#publish(activity);
593
- return Promise.resolve();
594
- }
595
- this.#pending.set(activity.activityId, activity);
596
- if (!this.#scheduled.has(activity.activityId)) {
597
- this.#scheduled.set(activity.activityId, this.#timer.schedule(() => this.#flushActivity(activity.activityId), AGENT_ACTIVITY_COALESCING_MILLISECONDS));
598
- }
599
- return Promise.resolve();
600
- };
601
- #discardPending = (activityId) => {
602
- this.#scheduled.get(activityId)?.cancel();
603
- this.#scheduled.delete(activityId);
604
- this.#pending.delete(activityId);
605
- };
606
- #flushActivity = (activityId) => {
607
- const activity = this.#pending.get(activityId);
608
- this.#discardPending(activityId);
609
- if (activity !== undefined) {
610
- this.#publish(activity);
611
- }
612
- };
613
- }
614
- function daemonActivity(command, activity) {
615
- return {
616
- activityId: activity.activityId,
617
- activityType: activity.activityType,
618
- commandId: command.commandId,
619
- content: activity.content,
620
- detail: activity.detail,
621
- input: activity.input,
622
- kind: AGENT_ACTIVITY_KIND,
623
- locations: activity.locations,
624
- name: activity.name,
625
- output: activity.output,
626
- sequence: activity.sequence,
627
- sessionId: command.sessionId,
628
- status: activity.status,
629
- title: activity.title,
630
- toolKind: activity.toolKind,
631
- };
632
- }
633
- function reportFailure(publisher, command, code, message, attemptId) {
634
- publisher.recordAttempt(command.sessionId, {
635
- code,
636
- commandId: command.commandId,
637
- kind: SESSION_FAILED_KIND,
638
- message,
639
- sessionId: command.sessionId,
640
- }, attemptId);
641
- }
642
- /**
643
- * Settles a Turn claimed by this live Runtime when its active process can no longer execute.
644
- * A lost connection can deliver cancellation after the process has stopped; the in-memory
645
- * receipt identifies the Attempt that should be reported as failed.
646
- */
647
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
648
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
649
- if (attemptId === null) {
650
- console.warn("Mobius daemon ignored cancellation for an inactive turn");
651
- return;
652
- }
653
- audit.record({
654
- commandId: cancellation.commandId,
655
- event: "session_abandoned_turn_settled",
656
- sessionId: cancellation.sessionId,
657
- });
658
- reportFailure(publisher, cancellation, "agent_execution_abandoned", "The local Agent execution was abandoned before it completed", attemptId);
659
- outbox.transitionExecution(cancellation.commandId, "failed");
660
- }
661
- function operationErrorCode(error) {
662
- if (error instanceof AcpExecutionError ||
663
- error instanceof LocalAuthorizationError ||
664
- error instanceof LocalAgentCatalogError ||
665
- error instanceof PromptArtifactError) {
666
- return error.code;
667
- }
668
- return "session_operation_failed";
669
- }
670
- function operationErrorMessage(error) {
671
- if (error instanceof AcpExecutionError ||
672
- error instanceof LocalAuthorizationError ||
673
- error instanceof LocalAgentCatalogError ||
674
- error instanceof PromptArtifactError) {
675
- return error.message;
676
- }
677
- return "The local agent operation could not be completed";
678
- }
679
- function agentSettingsFailureDetails(agentId, failure) {
680
- const details = { agentId, code: operationErrorCode(failure) };
681
- if (!(failure instanceof AcpConfigurationValueUnavailableError)) {
682
- return details;
683
- }
684
- return {
685
- ...details,
686
- configId: failure.configId,
687
- offeredValueCount: failure.offeredValueCount.toString(),
688
- offeredValues: JSON.stringify(failure.offeredValues),
689
- requestedValue: failure.requestedValue,
690
- };
691
- }
692
- function reportOperationFailure(socket, requestId, sessionId, error, runtimeTimings = []) {
693
- if (socket.readyState !== WebSocket.OPEN) {
694
- return;
695
- }
696
- send(socket, {
697
- code: operationErrorCode(error),
698
- kind: "session.operation.failed",
699
- message: operationErrorMessage(error),
700
- requestId,
701
- ...(runtimeTimings.length === 0 ? {} : { runtimeTimings }),
702
- sessionId,
703
- });
704
- }
705
- async function resolveSessionDirectories(directories, bindingId, directoryId, additionalDirectoryIds, signal) {
706
- const cwd = await directories.resolve(bindingId, directoryId, signal);
707
- const additionalDirectories = [];
708
- const additionalDirectoryEntries = [];
709
- const unique = new Set([cwd]);
710
- for (const additionalDirectoryId of additionalDirectoryIds) {
711
- const directory = await directories.resolve(bindingId, additionalDirectoryId, signal);
712
- if (unique.has(directory)) {
713
- throw new LocalAuthorizationError("Workspace directories must resolve to distinct locations");
714
- }
715
- unique.add(directory);
716
- additionalDirectories.push(directory);
717
- additionalDirectoryEntries.push({
718
- directoryId: additionalDirectoryId,
719
- name: basename(directory),
720
- });
721
- }
722
- return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
723
- }
724
- async function executeWorkspaceList(socket, command, directories, audit, signal) {
725
- try {
726
- const listing = await directories.list(command.bindingId, command.directoryId, signal);
727
- audit.record({
728
- commandId: command.requestId,
729
- event: "workspace_list_authorized",
730
- sessionId: "workspace-browser",
731
- });
732
- send(socket, {
733
- bindingId: command.bindingId,
734
- directoryId: listing.directoryId,
735
- directoryLabel: listing.directoryLabel,
736
- entries: listing.entries,
737
- kind: "workspace.entries",
738
- parentDirectoryId: listing.parentDirectoryId,
739
- requestId: command.requestId,
740
- });
741
- }
742
- catch (error) {
743
- reportOperationFailure(socket, command.requestId, "", error);
744
- }
745
- }
746
- async function executeSessionPrepare(publisher, socket, command, config, directories, audit, sessions, signal) {
747
- const metrics = new AccumulatingOperationMetrics();
748
- try {
749
- const readyEvent = await metrics.measure("prepare-total", async () => {
750
- const resolved = await metrics.measure("workspace-resolve", async () => await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal));
751
- const agent = config.catalog.find(command.agentId);
752
- const preparation = {
753
- additionalDirectories: resolved.additionalDirectories,
754
- agent,
755
- cwd: resolved.cwd,
756
- sessionId: command.sessionId,
757
- signal,
758
- };
759
- const prepared = command.transient === true
760
- ? await sessions.inspectSession(preparation, metrics)
761
- : await sessions.prepareSession(preparation, metrics);
762
- const configuration = command.configuration;
763
- const configOptions = configuration === undefined
764
- ? prepared.configOptions
765
- : await metrics.measure("configuration", async () => await sessions.configureSession({
766
- ...preparation,
767
- booleanValue: configuration.booleanValue,
768
- configId: configuration.configId,
769
- requestId: command.requestId,
770
- value: configuration.value,
771
- valueType: configuration.valueType,
772
- }));
773
- const listing = await metrics.measure("workspace-list", async () => await directories.list(config.bindingId, command.directoryId, signal));
774
- audit.record({
775
- commandId: command.requestId,
776
- event: "session_prepared",
777
- sessionId: command.sessionId,
778
- });
779
- if (command.configuration !== undefined) {
780
- audit.record({
781
- commandId: command.requestId,
782
- event: "session_configured",
783
- sessionId: command.sessionId,
784
- });
785
- publisher.recordRuntime(command.sessionId, {
786
- configOptions,
787
- kind: "session.config.updated",
788
- requestId: command.requestId,
789
- sessionId: command.sessionId,
790
- });
791
- }
792
- const event = {
793
- additionalDirectories: resolved.additionalDirectoryEntries,
794
- agentId: command.agentId,
795
- agentName: prepared.agentName,
796
- agentVersion: prepared.agentVersion,
797
- capabilities: prepared.capabilities,
798
- commands: prepared.commands,
799
- configOptions,
800
- directoryId: command.directoryId,
801
- directoryLabel: listing.directoryLabel,
802
- kind: "session.ready",
803
- requestId: command.requestId,
804
- restored: prepared.restored,
805
- sessionId: command.sessionId,
806
- runtimeTimings: metrics.snapshot(),
807
- };
808
- // An inspection-only preparation has no Session on the Relay, so this readiness is a reply
809
- // rather than a record: committing it would be rejected as an unknown Session and quarantine
810
- // an event that can never be replayed. The direct send below still delivers it.
811
- if (command.transient !== true) {
812
- metrics.measureSync("readiness-commit", () => {
813
- publisher.recordRuntime(command.sessionId, event);
814
- });
815
- }
816
- return event;
817
- });
818
- send(socket, {
819
- ...readyEvent,
820
- runtimeTimings: metrics.snapshot(),
821
- });
822
- }
823
- catch (error) {
824
- audit.record({
825
- commandId: command.requestId,
826
- details: {
827
- agentId: command.agentId,
828
- code: operationErrorCode(error),
829
- },
830
- event: "session_prepare_failed",
831
- sessionId: command.sessionId,
832
- });
833
- reportOperationFailure(socket, command.requestId, command.sessionId, error, metrics.snapshot());
834
- }
835
- }
836
- function liveHistoryCursor(sessionId, endIndex) {
837
- return Buffer.from(JSON.stringify({ endIndex, sessionId }), "utf8").toString("base64url");
838
- }
839
- function liveHistoryEndIndex(cursor, sessionId) {
840
- try {
841
- if (!/^[A-Za-z0-9_-]{1,512}$/u.test(cursor)) {
842
- throw new Error("Invalid cursor alphabet");
843
- }
844
- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
845
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
846
- throw new Error("Invalid cursor shape");
847
- }
848
- const record = Object.fromEntries(Object.entries(value));
849
- if (Object.keys(record).sort().join(",") !== "endIndex,sessionId" ||
850
- record["sessionId"] !== sessionId ||
851
- typeof record["endIndex"] !== "number" ||
852
- !Number.isSafeInteger(record["endIndex"]) ||
853
- record["endIndex"] < 0) {
854
- throw new Error("Invalid cursor target");
855
- }
856
- return record["endIndex"];
857
- }
858
- catch (cause) {
859
- throw new AcpExecutionError("The native Session history cursor is invalid", { cause }, "invalid_cursor");
860
- }
861
- }
862
- function liveHistoryCoveredTurnRanges(history) {
863
- const ranges = [];
864
- let historyIndex = history.messages.length;
865
- for (const commandId of history.coveredCommandIds) {
866
- let assistantStartIndex = historyIndex;
867
- while (assistantStartIndex > 0 && history.messages[assistantStartIndex - 1]?.role === "assistant") {
868
- assistantStartIndex -= 1;
869
- }
870
- const userIndex = assistantStartIndex - 1;
871
- if (assistantStartIndex === historyIndex || history.messages[userIndex]?.role !== "user") {
872
- break;
873
- }
874
- ranges.push({ assistantEndIndex: historyIndex, assistantStartIndex, commandId, userIndex });
875
- historyIndex = userIndex;
876
- }
877
- return ranges;
878
- }
879
- function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
880
- if (history.status === "unavailable") {
881
- if (cursor !== null) {
882
- throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
883
- }
884
- return { cause: history.cause, nextCursor: null, status: "unavailable" };
885
- }
886
- const endIndex = cursor === null ? history.messages.length : liveHistoryEndIndex(cursor, sessionId);
887
- if (endIndex > history.messages.length) {
888
- throw new AcpExecutionError("The native Session history cursor is invalid", {}, "invalid_cursor");
889
- }
890
- const startIndex = Math.max(0, endIndex - limit);
891
- const coveredMessageIds = new Set(history.coveredMessageIds);
892
- const ranges = liveHistoryCoveredTurnRanges(history);
893
- return {
894
- coveredCommandIds: ranges
895
- .filter((range) => range.userIndex >= startIndex && range.assistantEndIndex <= endIndex)
896
- .map((range) => range.commandId),
897
- coveredMessageIds: ranges.flatMap((range) => [
898
- ...(range.userIndex >= startIndex &&
899
- range.userIndex < endIndex &&
900
- coveredMessageIds.has(`${range.commandId}:user`)
901
- ? [`${range.commandId}:user`]
902
- : []),
903
- ...(range.assistantStartIndex >= startIndex &&
904
- range.assistantEndIndex <= endIndex &&
905
- coveredMessageIds.has(`${range.commandId}:agent`)
906
- ? [`${range.commandId}:agent`]
907
- : []),
908
- ]),
909
- messages: history.messages.slice(startIndex, endIndex),
910
- nextCursor: startIndex > 0 ? liveHistoryCursor(sessionId, startIndex) : null,
911
- status: "available",
912
- truncated: history.truncated,
913
- };
914
- }
915
- async function executeSessionLiveHistoryLoad(socket, command, config, directories, audit, sessions, signal) {
916
- try {
917
- const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
918
- const history = await sessions.loadSessionHistory({
919
- additionalDirectories: resolved.additionalDirectories,
920
- agent: config.catalog.find(command.agentId),
921
- cwd: resolved.cwd,
922
- sessionId: command.sessionId,
923
- signal,
924
- });
925
- signal.throwIfAborted();
926
- audit.record({
927
- commandId: command.requestId,
928
- event: "session_history_loaded",
929
- sessionId: command.sessionId,
930
- });
931
- send(socket, {
932
- history,
933
- kind: "session.live-history.loaded",
934
- requestId: command.requestId,
935
- sessionId: command.sessionId,
936
- });
937
- }
938
- catch (error) {
939
- if (signal.aborted) {
940
- return;
941
- }
942
- audit.record({
943
- commandId: command.requestId,
944
- details: { code: operationErrorCode(error) },
945
- event: "session_history_unavailable",
946
- sessionId: command.sessionId,
947
- });
948
- send(socket, {
949
- history: {
950
- status: "unavailable",
951
- cause: { code: operationErrorCode(error), message: operationErrorMessage(error) },
952
- },
953
- kind: "session.live-history.loaded",
954
- requestId: command.requestId,
955
- sessionId: command.sessionId,
956
- });
957
- }
958
- }
959
- async function executeSessionLiveHistoryPageLoad(socket, command, config, directories, audit, sessions, signal) {
960
- try {
961
- const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
962
- const history = await sessions.loadSessionHistory({
963
- additionalDirectories: resolved.additionalDirectories,
964
- agent: config.catalog.find(command.agentId),
965
- cwd: resolved.cwd,
966
- sessionId: command.sessionId,
967
- signal,
968
- });
969
- signal.throwIfAborted();
970
- const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
971
- audit.record({
972
- commandId: command.requestId,
973
- event: "session_history_loaded",
974
- sessionId: command.sessionId,
975
- });
976
- send(socket, {
977
- kind: "session.live-history.page.loaded",
978
- page,
979
- requestId: command.requestId,
980
- sessionId: command.sessionId,
981
- });
982
- }
983
- catch (error) {
984
- if (signal.aborted) {
985
- return;
986
- }
987
- audit.record({
988
- commandId: command.requestId,
989
- details: { code: operationErrorCode(error) },
990
- event: "session_history_unavailable",
991
- sessionId: command.sessionId,
992
- });
993
- send(socket, {
994
- kind: "session.live-history.page.loaded",
995
- page: {
996
- status: "unavailable",
997
- cause: { code: operationErrorCode(error), message: operationErrorMessage(error) },
998
- nextCursor: null,
999
- },
1000
- requestId: command.requestId,
1001
- sessionId: command.sessionId,
1002
- });
1003
- }
1004
- }
1005
- async function executeSessionConfigure(publisher, socket, command, config, directories, audit, sessions, signal) {
1006
- try {
1007
- const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
1008
- const configOptions = await sessions.configureSession({
1009
- additionalDirectories: resolved.additionalDirectories,
1010
- agent: config.catalog.find(command.agentId),
1011
- booleanValue: command.booleanValue,
1012
- configId: command.configId,
1013
- cwd: resolved.cwd,
1014
- requestId: command.requestId,
1015
- sessionId: command.sessionId,
1016
- signal,
1017
- value: command.value,
1018
- valueType: command.valueType,
1019
- });
1020
- audit.record({
1021
- commandId: command.requestId,
1022
- event: "session_configured",
1023
- sessionId: command.sessionId,
1024
- });
1025
- publisher.recordRuntime(command.sessionId, {
1026
- configOptions,
1027
- kind: "session.config.updated",
1028
- requestId: command.requestId,
1029
- sessionId: command.sessionId,
1030
- });
1031
- }
1032
- catch (error) {
1033
- if (signal.aborted) {
1034
- signal.throwIfAborted();
1035
- }
1036
- reportOperationFailure(socket, command.requestId, command.sessionId, error);
1037
- }
1038
- }
1039
- async function executePrompt(outbox, publisher, command, config, directories, audit, sessions, attemptId, activateAttempt, timer, signal) {
1040
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
1041
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity), attemptId);
1042
- });
1043
- const narration = new CoalescingNarrationPublisher(timer, (increment) => {
1044
- publisher.recordAttempt(command.sessionId, {
1045
- activityId: increment.activityId,
1046
- activityType: increment.activityType,
1047
- commandId: command.commandId,
1048
- kind: AGENT_ACTIVITY_NARRATION_KIND,
1049
- sequence: increment.sequence,
1050
- sessionId: command.sessionId,
1051
- text: increment.text,
1052
- }, attemptId);
1053
- }, AGENT_ACTIVITY_COALESCING_MILLISECONDS, AGENT_TEXT_MAXIMUM_LENGTH);
1054
- const text = new CoalescingTextPublisher(timer, (messageId, delta) => {
1055
- publisher.recordAttempt(command.sessionId, {
1056
- commandId: command.commandId,
1057
- kind: AGENT_MESSAGE_DELTA_KIND,
1058
- messageId,
1059
- sessionId: command.sessionId,
1060
- text: delta,
1061
- }, attemptId);
1062
- }, AGENT_TEXT_COALESCING_MILLISECONDS, AGENT_TEXT_MAXIMUM_LENGTH);
1063
- try {
1064
- const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
1065
- const agent = config.catalog.find(command.agentId);
1066
- if (command.disposition === SessionPromptDisposition.Queue &&
1067
- !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
1068
- throw new AcpExecutionError("The queued prompt target is unavailable", {}, "prompt_queue_target_unavailable");
1069
- }
1070
- const appliedSettings = command.sessionConfigurations === undefined
1071
- ? undefined
1072
- : agentForSessionConfiguration(agent, command.sessionConfigurations);
1073
- const executionAgent = appliedSettings?.agent ?? agent;
1074
- const sessionConfigurations = appliedSettings?.sessionConfigurations;
1075
- if (command.sessionConfigurations !== undefined) {
1076
- const prepared = await sessions.prepareExecutionSession({
1077
- additionalDirectories: resolved.additionalDirectories,
1078
- agent: executionAgent,
1079
- cwd: resolved.cwd,
1080
- sessionId: command.sessionId,
1081
- signal,
1082
- });
1083
- if (command.disposition === SessionPromptDisposition.Steer) {
1084
- // Steering cannot reconfigure a running Agent, so the Turn snapshot
1085
- // only has to agree with the settings this live Session exposes. The
1086
- // snapshot comes from Agent settings discovery, so it may name options
1087
- // that the running Session does not expose at all.
1088
- assertAppliedSessionConfiguration(prepared.configOptions, sessionConfigurations ?? []);
1089
- }
1090
- else {
1091
- await applyCompleteSessionConfiguration(sessions, audit, prepared.configOptions, sessionConfigurations ?? [], executionAgent, resolved.cwd, resolved.additionalDirectories, command.commandId, command.sessionId, signal);
1092
- }
1093
- }
1094
- audit.record({
1095
- commandId: command.commandId,
1096
- event: "session_authorized",
1097
- sessionId: command.sessionId,
1098
- });
1099
- outbox.transitionExecution(command.commandId, "running");
1100
- publisher.recordAttempt(command.sessionId, {
1101
- commandId: command.commandId,
1102
- kind: SESSION_STARTED_KIND,
1103
- attemptId,
1104
- sessionId: command.sessionId,
1105
- }, attemptId);
1106
- activateAttempt();
1107
- const attachments = await resolvePromptArtifacts(config, command, signal);
1108
- let stopReason;
1109
- if (command.disposition === SessionPromptDisposition.Steer) {
1110
- await sessions.steerPrompt({
1111
- additionalDirectories: resolved.additionalDirectories,
1112
- agent: executionAgent,
1113
- commandId: command.commandId,
1114
- cwd: resolved.cwd,
1115
- images: attachments.images,
1116
- prompt: command.prompt,
1117
- resources: attachments.resources,
1118
- sessionId: command.sessionId,
1119
- signal,
1120
- targetCommandId: command.targetCommandId,
1121
- });
1122
- stopReason = "steered";
1123
- }
1124
- else {
1125
- const result = await sessions.runPrompt({
1126
- additionalDirectories: resolved.additionalDirectories,
1127
- agent: executionAgent,
1128
- commandId: command.commandId,
1129
- cwd: resolved.cwd,
1130
- disposition: command.disposition,
1131
- images: attachments.images,
1132
- onActivity: activities.record,
1133
- onNarration: (increment) => {
1134
- narration.record(increment);
1135
- return Promise.resolve();
1136
- },
1137
- onText: (delta, messageId) => {
1138
- text.record(messageId, delta);
1139
- return Promise.resolve();
1140
- },
1141
- prompt: command.prompt,
1142
- resources: attachments.resources,
1143
- sessionId: command.sessionId,
1144
- signal,
1145
- targetCommandId: command.targetCommandId,
1146
- });
1147
- stopReason = result.stopReason;
1148
- }
1149
- text.flush();
1150
- narration.flush();
1151
- activities.flush();
1152
- publisher.recordAttempt(command.sessionId, {
1153
- commandId: command.commandId,
1154
- kind: SESSION_COMPLETED_KIND,
1155
- sessionId: command.sessionId,
1156
- stopReason,
1157
- }, attemptId);
1158
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
1159
- audit.record({
1160
- commandId: command.commandId,
1161
- event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
1162
- sessionId: command.sessionId,
1163
- });
1164
- }
1165
- catch (error) {
1166
- text.flush();
1167
- narration.flush();
1168
- activities.flush();
1169
- audit.record({
1170
- commandId: command.commandId,
1171
- event: "session_failed",
1172
- sessionId: command.sessionId,
1173
- });
1174
- const code = operationErrorCode(error);
1175
- reportFailure(publisher, command, code === "session_operation_failed" ? "agent_execution_failed" : code, code === "session_operation_failed"
1176
- ? "The local agent could not complete the request"
1177
- : operationErrorMessage(error), attemptId);
1178
- outbox.transitionExecution(command.commandId, "failed");
1179
- console.error("Mobius daemon command failed", error);
1180
- }
1181
- }
1182
46
  function waitForRelayRetry(signal, timer) {
1183
47
  if (signal.aborted) {
1184
48
  return Promise.resolve();