@moxt-ai/mobius 0.0.94 → 0.0.98
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/dist/acp/activity.d.ts.map +1 -1
- package/dist/acp/activity.js +13 -2
- package/dist/acp/activity.js.map +1 -1
- package/dist/acp/codex/agent.d.ts.map +1 -1
- package/dist/acp/codex/agent.js +19 -4
- package/dist/acp/codex/agent.js.map +1 -1
- package/dist/acp/elicitation.d.ts +5 -0
- package/dist/acp/elicitation.d.ts.map +1 -0
- package/dist/acp/elicitation.js +186 -0
- package/dist/acp/elicitation.js.map +1 -0
- package/dist/acp/process-capacity.d.ts +12 -0
- package/dist/acp/process-capacity.d.ts.map +1 -0
- package/dist/acp/process-capacity.js +90 -0
- package/dist/acp/process-capacity.js.map +1 -0
- package/dist/acp/process-session.d.ts +164 -0
- package/dist/acp/process-session.d.ts.map +1 -0
- package/dist/acp/process-session.js +1182 -0
- package/dist/acp/process-session.js.map +1 -0
- package/dist/acp/session-config/apply-session-configuration.d.ts +9 -0
- package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -0
- package/dist/acp/session-config/apply-session-configuration.js +141 -0
- package/dist/acp/session-config/apply-session-configuration.js.map +1 -0
- package/dist/acp/session-manager.d.ts +4 -159
- package/dist/acp/session-manager.d.ts.map +1 -1
- package/dist/acp/session-manager.js +11 -1581
- package/dist/acp/session-manager.js.map +1 -1
- package/dist/acp/session-state.d.ts +43 -0
- package/dist/acp/session-state.d.ts.map +1 -0
- package/dist/acp/session-state.js +87 -0
- package/dist/acp/session-state.js.map +1 -0
- package/dist/acp/value-utils.d.ts +4 -0
- package/dist/acp/value-utils.d.ts.map +1 -0
- package/dist/acp/value-utils.js +10 -0
- package/dist/acp/value-utils.js.map +1 -0
- package/dist/agent-catalog/agent-settings-adapter.d.ts +5 -18
- package/dist/agent-catalog/agent-settings-adapter.d.ts.map +1 -1
- package/dist/agent-catalog/agent-settings-adapter.js +7 -161
- package/dist/agent-catalog/agent-settings-adapter.js.map +1 -1
- package/dist/agent-catalog/agent-settings-base.d.ts +26 -0
- package/dist/agent-catalog/agent-settings-base.d.ts.map +1 -0
- package/dist/agent-catalog/agent-settings-base.js +66 -0
- package/dist/agent-catalog/agent-settings-base.js.map +1 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.d.ts +5 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.js +6 -0
- package/dist/agent-catalog/agents/codex-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts +9 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.js +26 -0
- package/dist/agent-catalog/agents/deepseek-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts +9 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts.map +1 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.js +74 -0
- package/dist/agent-catalog/agents/opencode-settings-adapter.js.map +1 -0
- package/dist/agent-catalog/discover-agent-settings.d.ts +10 -0
- package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -0
- package/dist/agent-catalog/discover-agent-settings.js +252 -0
- package/dist/agent-catalog/discover-agent-settings.js.map +1 -0
- package/dist/cli.js +8187 -15444
- package/dist/cli.js.map +4 -4
- package/dist/config.js +2 -2
- package/dist/config.js.map +1 -1
- package/dist/daemon-manager.d.ts +1 -1
- package/dist/daemon-manager.d.ts.map +1 -1
- package/dist/daemon-manager.js +1 -2
- package/dist/daemon-manager.js.map +1 -1
- package/dist/daemon-session-commands.d.ts +33 -0
- package/dist/daemon-session-commands.d.ts.map +1 -0
- package/dist/daemon-session-commands.js +522 -0
- package/dist/daemon-session-commands.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8598 -15855
- package/dist/index.js.map +4 -4
- package/dist/native-sessions/acp-history.d.ts +6 -0
- package/dist/native-sessions/acp-history.d.ts.map +1 -0
- package/dist/native-sessions/acp-history.js +27 -0
- package/dist/native-sessions/acp-history.js.map +1 -0
- package/dist/native-sessions/agent-adapter.d.ts +17 -0
- package/dist/native-sessions/agent-adapter.d.ts.map +1 -0
- package/dist/native-sessions/agent-adapter.js +26 -0
- package/dist/native-sessions/agent-adapter.js.map +1 -0
- package/dist/native-sessions/chat-agent.d.ts +4 -0
- package/dist/native-sessions/chat-agent.d.ts.map +1 -0
- package/dist/native-sessions/chat-agent.js +16 -0
- package/dist/native-sessions/chat-agent.js.map +1 -0
- package/dist/native-sessions/claude-adapter.d.ts +3 -0
- package/dist/native-sessions/claude-adapter.d.ts.map +1 -0
- package/dist/native-sessions/claude-adapter.js +7 -0
- package/dist/native-sessions/claude-adapter.js.map +1 -0
- package/dist/native-sessions/codex-adapter.d.ts +3 -0
- package/dist/native-sessions/codex-adapter.d.ts.map +1 -0
- package/dist/native-sessions/codex-adapter.js +21 -0
- package/dist/native-sessions/codex-adapter.js.map +1 -0
- package/dist/native-sessions/live-history-page.d.ts +3 -0
- package/dist/native-sessions/live-history-page.d.ts.map +1 -0
- package/dist/native-sessions/live-history-page.js +81 -0
- package/dist/native-sessions/live-history-page.js.map +1 -0
- package/dist/native-sessions/opencode-adapter.d.ts +3 -0
- package/dist/native-sessions/opencode-adapter.d.ts.map +1 -0
- package/dist/native-sessions/opencode-adapter.js +7 -0
- package/dist/native-sessions/opencode-adapter.js.map +1 -0
- package/dist/native-sessions/service.d.ts +0 -2
- package/dist/native-sessions/service.d.ts.map +1 -1
- package/dist/native-sessions/service.js +25 -58
- package/dist/native-sessions/service.js.map +1 -1
- package/dist/pairing/pair-local-machine.js.map +1 -1
- package/dist/relay-connection/coalescing-activity-publisher.d.ts +10 -0
- package/dist/relay-connection/coalescing-activity-publisher.d.ts.map +1 -0
- package/dist/relay-connection/coalescing-activity-publisher.js +54 -0
- package/dist/relay-connection/coalescing-activity-publisher.js.map +1 -0
- package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
- package/dist/relay-connection/session-event-outbox.js +13 -48
- package/dist/relay-connection/session-event-outbox.js.map +1 -1
- package/dist/relay-connection/session-event-publisher.d.ts +17 -0
- package/dist/relay-connection/session-event-publisher.d.ts.map +1 -0
- package/dist/relay-connection/session-event-publisher.js +245 -0
- package/dist/relay-connection/session-event-publisher.js.map +1 -0
- package/dist/run-daemon.d.ts.map +1 -1
- package/dist/run-daemon.js +7 -1277
- package/dist/run-daemon.js.map +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +8023 -15278
- package/dist/runtime.js.map +4 -4
- package/dist/storage/runtime-installation-store.d.ts +6 -14
- package/dist/storage/runtime-installation-store.d.ts.map +1 -1
- package/dist/storage/runtime-installation-store.js +16 -103
- package/dist/storage/runtime-installation-store.js.map +1 -1
- package/package.json +1 -4
- package/dist/acp/markdown-images.d.ts +0 -8
- package/dist/acp/markdown-images.d.ts.map +0 -1
- package/dist/acp/markdown-images.js +0 -55
- package/dist/acp/markdown-images.js.map +0 -1
package/dist/run-daemon.js
CHANGED
|
@@ -1,43 +1,33 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { basename } from "node:path";
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
3
2
|
import { styleText } from "node:util";
|
|
4
|
-
import {
|
|
3
|
+
import { 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_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";
|
|
5
4
|
import { fetch, WebSocket } from "undici";
|
|
6
5
|
import { AcpConfigurationValueUnavailableError, AcpExecutionError, AcpSessionManager, } from "./acp/session-manager.js";
|
|
7
6
|
import { MemoryAcpSessionStore } from "./acp/session-store.js";
|
|
8
|
-
import {
|
|
9
|
-
import { discoverOpenCodeModelOptions } from "./agent-catalog/agents/opencode-agent.js";
|
|
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
|
|
9
|
+
import { AgentIntegrationDefinition } from "./agent-catalog/local-agent.js";
|
|
12
10
|
import { publishAgentCatalog } from "./agent-catalog/publish-agent-catalog.js";
|
|
13
11
|
import { AgentInstallationManager, CancelledInstallation, FailedInstallation, RequestedInstallation, RunningInstallation, SucceededInstallation, } 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 {
|
|
17
|
+
import { agentSettingsFailureDetails, executePrompt, executeSessionConfigure, executeSessionLiveHistoryLoad, executeSessionLiveHistoryPageLoad, executeSessionPrepare, executeWorkspaceList, operationErrorCode, operationErrorMessage, reportFailure, reportOperationFailure, send, settleAbandonedTurn, } from "./daemon-session-commands.js";
|
|
21
18
|
import { readCodexFullHistory } from "./native-sessions/codex-history.js";
|
|
22
19
|
import { NativeSessionService } from "./native-sessions/service.js";
|
|
23
20
|
import { environmentProxyDispatcher } from "./network/environment-proxy.js";
|
|
24
21
|
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
22
|
import { connectRelay } from "./relay-connection/connect.js";
|
|
29
23
|
import { RelayConnectionDiagnostics } from "./relay-connection/diagnostics.js";
|
|
30
24
|
import { RelayConnectionLiveness } from "./relay-connection/liveness.js";
|
|
31
25
|
import { relayHttpEndpoint, runtimeAuthorization } from "./relay-connection/runtime-authentication.js";
|
|
32
26
|
import { isRuntimeRelayRevocation, RuntimeRelayRevokedError } from "./relay-connection/runtime-revocation.js";
|
|
33
|
-
import { RuntimeDeliveryInboxCapacityError, SessionEventOutbox
|
|
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
31
|
const ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 20_000;
|
|
42
32
|
const ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
|
|
43
33
|
class DaemonAcpObserver {
|
|
@@ -172,16 +162,6 @@ class DaemonInstallationObserver {
|
|
|
172
162
|
throw new Error("Unsupported Agent integration installation state");
|
|
173
163
|
};
|
|
174
164
|
}
|
|
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
165
|
class ActiveDaemonTurn {
|
|
186
166
|
attemptId;
|
|
187
167
|
command;
|
|
@@ -298,12 +278,6 @@ async function reconcileActiveTurn(config, turn, signal) {
|
|
|
298
278
|
async function reconcileActiveTurns(config, turns, signal) {
|
|
299
279
|
await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config, turn, signal)));
|
|
300
280
|
}
|
|
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
281
|
function closeRelaySocket(socket, code, reason) {
|
|
308
282
|
try {
|
|
309
283
|
socket.close(code, reason);
|
|
@@ -318,1250 +292,6 @@ function closeRelaySocket(socket, code, reason) {
|
|
|
318
292
|
}
|
|
319
293
|
}
|
|
320
294
|
}
|
|
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
|
-
function isUnavailableModel(cause, modelSettingId, requestedModel) {
|
|
725
|
-
return (cause instanceof AcpConfigurationValueUnavailableError &&
|
|
726
|
-
cause.configId === modelSettingId &&
|
|
727
|
-
cause.requestedValue === requestedModel);
|
|
728
|
-
}
|
|
729
|
-
function unsupportedModelIds(unsupportedModels) {
|
|
730
|
-
return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
|
|
731
|
-
}
|
|
732
|
-
async function discoverAgentSettings(command, config, directories, sessions, signal) {
|
|
733
|
-
const agent = config.catalog.find(command.agentId);
|
|
734
|
-
const cwd = await directories.resolve(config.bindingId, "default", signal);
|
|
735
|
-
const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
|
|
736
|
-
additionalDirectories: [],
|
|
737
|
-
agent,
|
|
738
|
-
cwd,
|
|
739
|
-
signal,
|
|
740
|
-
});
|
|
741
|
-
const baseSnapshot = {
|
|
742
|
-
agentName: inspectedBaseSnapshot.agentName,
|
|
743
|
-
agentVersion: inspectedBaseSnapshot.agentVersion,
|
|
744
|
-
configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal),
|
|
745
|
-
};
|
|
746
|
-
const baseModel = modelOption(baseSnapshot.configOptions);
|
|
747
|
-
const unsupportedModels = [];
|
|
748
|
-
let selectedSnapshot = baseSnapshot;
|
|
749
|
-
if (command.model !== undefined) {
|
|
750
|
-
if (baseModel === undefined ||
|
|
751
|
-
baseModel.type !== "select" ||
|
|
752
|
-
!baseModel.values.some((value) => value.value === command.model)) {
|
|
753
|
-
unsupportedModels.push(new AcpConfigurationValueUnavailableError(baseModel?.id ?? "model", command.model, baseModel?.values.map((value) => value.value) ?? []));
|
|
754
|
-
}
|
|
755
|
-
else {
|
|
756
|
-
try {
|
|
757
|
-
selectedSnapshot = await sessions.inspectAgentSettings({
|
|
758
|
-
additionalDirectories: [],
|
|
759
|
-
agent,
|
|
760
|
-
cwd,
|
|
761
|
-
model: command.model,
|
|
762
|
-
signal,
|
|
763
|
-
});
|
|
764
|
-
}
|
|
765
|
-
catch (cause) {
|
|
766
|
-
signal.throwIfAborted();
|
|
767
|
-
if (!isUnavailableModel(cause, baseModel.id, command.model)) {
|
|
768
|
-
throw cause;
|
|
769
|
-
}
|
|
770
|
-
unsupportedModels.push(cause);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
const adapter = agentSettingsAdapterForAgent(agent.id);
|
|
775
|
-
const modelEffort = await discoverModelEffort(command, agent, adapter.modelEffortResolution, baseSnapshot.configOptions, selectedSnapshot.configOptions, unsupportedModels, cwd, sessions, signal);
|
|
776
|
-
const baseSettings = withoutUnsupportedModels(settingsFromSnapshot(agent, baseSnapshot.configOptions), baseModel?.id ?? "", modelEffort.unsupportedModelIds);
|
|
777
|
-
const settings = withoutUnsupportedModels(settingsFromSnapshot(agent, selectedSnapshot.configOptions), baseModel?.id ?? "", modelEffort.unsupportedModelIds);
|
|
778
|
-
return {
|
|
779
|
-
event: {
|
|
780
|
-
agentId: command.agentId,
|
|
781
|
-
agentName: selectedSnapshot.agentName,
|
|
782
|
-
agentVersion: selectedSnapshot.agentVersion,
|
|
783
|
-
kind: AGENT_SETTINGS_DISCOVERED_KIND,
|
|
784
|
-
modelEffort,
|
|
785
|
-
requestId: command.requestId,
|
|
786
|
-
settings,
|
|
787
|
-
settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort),
|
|
788
|
-
},
|
|
789
|
-
unsupportedModels,
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
function settingFromOption(option) {
|
|
793
|
-
return {
|
|
794
|
-
booleanValue: option.booleanValue,
|
|
795
|
-
category: option.category,
|
|
796
|
-
defaultValue: option.type === "boolean" ? "" : option.currentValue,
|
|
797
|
-
description: option.description,
|
|
798
|
-
id: option.id,
|
|
799
|
-
name: option.name,
|
|
800
|
-
type: option.type,
|
|
801
|
-
values: option.values,
|
|
802
|
-
};
|
|
803
|
-
}
|
|
804
|
-
function settingsFromSnapshot(agent, configOptions) {
|
|
805
|
-
const settings = [
|
|
806
|
-
...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
|
|
807
|
-
...configOptions.map(settingFromOption),
|
|
808
|
-
];
|
|
809
|
-
const identifiers = new Set();
|
|
810
|
-
for (const setting of settings) {
|
|
811
|
-
if (identifiers.has(setting.id)) {
|
|
812
|
-
throw new AcpExecutionError("The Agent returned duplicate setting identifiers", {}, "invalid_session_configuration");
|
|
813
|
-
}
|
|
814
|
-
identifiers.add(setting.id);
|
|
815
|
-
}
|
|
816
|
-
if (settings.length > 128) {
|
|
817
|
-
throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
|
|
818
|
-
}
|
|
819
|
-
return settings;
|
|
820
|
-
}
|
|
821
|
-
function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds) {
|
|
822
|
-
if (modelSettingId.length === 0 || unsupportedModelIds.length === 0) {
|
|
823
|
-
return settings;
|
|
824
|
-
}
|
|
825
|
-
const unsupported = new Set(unsupportedModelIds);
|
|
826
|
-
return settings.map((setting) => {
|
|
827
|
-
if (setting.id !== modelSettingId || setting.type !== "select") {
|
|
828
|
-
return setting;
|
|
829
|
-
}
|
|
830
|
-
return {
|
|
831
|
-
...setting,
|
|
832
|
-
defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
|
|
833
|
-
values: setting.values.filter((value) => !unsupported.has(value.value)),
|
|
834
|
-
};
|
|
835
|
-
});
|
|
836
|
-
}
|
|
837
|
-
function modelOption(options) {
|
|
838
|
-
return options.find((option) => option.id === "model" || option.category === "model");
|
|
839
|
-
}
|
|
840
|
-
function effortOption(options) {
|
|
841
|
-
return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
|
|
842
|
-
}
|
|
843
|
-
function unavailableModelEffort() {
|
|
844
|
-
return {
|
|
845
|
-
effortSettingId: "",
|
|
846
|
-
modelSettingId: "",
|
|
847
|
-
resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
|
|
848
|
-
unsupportedModelIds: [],
|
|
849
|
-
valuesByModel: {},
|
|
850
|
-
};
|
|
851
|
-
}
|
|
852
|
-
async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
|
|
853
|
-
const model = modelOption(initialOptions);
|
|
854
|
-
const unsupportedModels = initiallyUnsupportedModels;
|
|
855
|
-
if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE &&
|
|
856
|
-
resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
|
|
857
|
-
return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
|
|
858
|
-
}
|
|
859
|
-
if (model === undefined || model.type !== "select" || model.values.length === 0) {
|
|
860
|
-
return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
|
|
861
|
-
}
|
|
862
|
-
const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
|
|
863
|
-
additionalDirectories: [],
|
|
864
|
-
agent,
|
|
865
|
-
cwd,
|
|
866
|
-
model: modelValue,
|
|
867
|
-
signal,
|
|
868
|
-
})).configOptions;
|
|
869
|
-
const valuesByModel = {};
|
|
870
|
-
if (resolution === "complete") {
|
|
871
|
-
const effort = effortOption(initialOptions);
|
|
872
|
-
if (effort === undefined || effort.type !== "select" || effort.values.length < 2) {
|
|
873
|
-
return {
|
|
874
|
-
...unavailableModelEffort(),
|
|
875
|
-
unsupportedModelIds: unsupportedModelIds(unsupportedModels),
|
|
876
|
-
};
|
|
877
|
-
}
|
|
878
|
-
for (const value of model.values) {
|
|
879
|
-
if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
882
|
-
try {
|
|
883
|
-
const selectedEffort = effortOption(await inspectModel(value.value));
|
|
884
|
-
valuesByModel[value.value] = selectedEffort?.type === "select" ? selectedEffort.values : [];
|
|
885
|
-
}
|
|
886
|
-
catch (cause) {
|
|
887
|
-
signal.throwIfAborted();
|
|
888
|
-
if (!isUnavailableModel(cause, model.id, value.value)) {
|
|
889
|
-
throw cause;
|
|
890
|
-
}
|
|
891
|
-
unsupportedModels.push(cause);
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
return {
|
|
895
|
-
effortSettingId: effort.id,
|
|
896
|
-
modelSettingId: model.id,
|
|
897
|
-
resolution: "complete",
|
|
898
|
-
unsupportedModelIds: unsupportedModelIds(unsupportedModels),
|
|
899
|
-
valuesByModel,
|
|
900
|
-
};
|
|
901
|
-
}
|
|
902
|
-
if (command.model !== undefined) {
|
|
903
|
-
const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
|
|
904
|
-
const selectedEffort = effortOption(selectedOptions);
|
|
905
|
-
if (!modelUnsupported) {
|
|
906
|
-
valuesByModel[command.model] = selectedEffort?.type === "select" ? selectedEffort.values : [];
|
|
907
|
-
}
|
|
908
|
-
return {
|
|
909
|
-
effortSettingId: selectedEffort?.id ?? "",
|
|
910
|
-
modelSettingId: model.id,
|
|
911
|
-
resolution: "on_model_selection",
|
|
912
|
-
unsupportedModelIds: unsupportedModelIds(unsupportedModels),
|
|
913
|
-
valuesByModel,
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
// No model was named, so the Agent answered about its own default model — one
|
|
917
|
-
// whose effort option an Agent may withhold. Resolve that model's capability
|
|
918
|
-
// too, or a session that never switches models can never offer an effort.
|
|
919
|
-
const defaultModel = model.type === "select" ? model.currentValue : "";
|
|
920
|
-
const reportedEffort = effortOption(selectedOptions);
|
|
921
|
-
let selectedEffort = reportedEffort;
|
|
922
|
-
if (defaultModel.length > 0 && reportedEffort === undefined) {
|
|
923
|
-
try {
|
|
924
|
-
selectedEffort = effortOption(await inspectModel(defaultModel));
|
|
925
|
-
}
|
|
926
|
-
catch (cause) {
|
|
927
|
-
signal.throwIfAborted();
|
|
928
|
-
if (!isUnavailableModel(cause, model.id, defaultModel)) {
|
|
929
|
-
throw cause;
|
|
930
|
-
}
|
|
931
|
-
unsupportedModels.push(cause);
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
if (defaultModel.length > 0 &&
|
|
935
|
-
!unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
|
|
936
|
-
valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
|
|
937
|
-
}
|
|
938
|
-
return {
|
|
939
|
-
effortSettingId: selectedEffort?.id ?? "",
|
|
940
|
-
modelSettingId: model.id,
|
|
941
|
-
resolution: "on_model_selection",
|
|
942
|
-
unsupportedModelIds: unsupportedModelIds(unsupportedModels),
|
|
943
|
-
valuesByModel,
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
|
|
947
|
-
// A dynamic effort lookup adds one model's settings and values to an
|
|
948
|
-
// otherwise stable Agent capability document. It must not look like the
|
|
949
|
-
// Agent's settings changed each time a caller switches models.
|
|
950
|
-
const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE
|
|
951
|
-
? modelEffort
|
|
952
|
-
: {
|
|
953
|
-
effortSettingId: "",
|
|
954
|
-
modelSettingId: modelEffort.modelSettingId,
|
|
955
|
-
resolution: modelEffort.resolution,
|
|
956
|
-
unsupportedModelIds: modelEffort.unsupportedModelIds,
|
|
957
|
-
valuesByModel: {},
|
|
958
|
-
};
|
|
959
|
-
return createHash("sha256")
|
|
960
|
-
.update(JSON.stringify({
|
|
961
|
-
adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
|
|
962
|
-
agentId: agent.id,
|
|
963
|
-
agentVersion: agent.agentVersion,
|
|
964
|
-
modelEffort: revisionModelEffort,
|
|
965
|
-
reportedAgentVersion,
|
|
966
|
-
settings,
|
|
967
|
-
}))
|
|
968
|
-
.digest("hex");
|
|
969
|
-
}
|
|
970
|
-
async function executeWorkspaceList(socket, command, directories, audit, signal) {
|
|
971
|
-
try {
|
|
972
|
-
const listing = await directories.list(command.bindingId, command.directoryId, signal);
|
|
973
|
-
audit.record({
|
|
974
|
-
commandId: command.requestId,
|
|
975
|
-
event: "workspace_list_authorized",
|
|
976
|
-
sessionId: "workspace-browser",
|
|
977
|
-
});
|
|
978
|
-
send(socket, {
|
|
979
|
-
bindingId: command.bindingId,
|
|
980
|
-
directoryId: listing.directoryId,
|
|
981
|
-
directoryLabel: listing.directoryLabel,
|
|
982
|
-
entries: listing.entries,
|
|
983
|
-
kind: "workspace.entries",
|
|
984
|
-
parentDirectoryId: listing.parentDirectoryId,
|
|
985
|
-
requestId: command.requestId,
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
catch (error) {
|
|
989
|
-
reportOperationFailure(socket, command.requestId, "", error);
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
async function executeSessionPrepare(publisher, socket, command, config, directories, audit, sessions, signal) {
|
|
993
|
-
const metrics = new AccumulatingOperationMetrics();
|
|
994
|
-
try {
|
|
995
|
-
const readyEvent = await metrics.measure("prepare-total", async () => {
|
|
996
|
-
const resolved = await metrics.measure("workspace-resolve", async () => await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal));
|
|
997
|
-
const agent = config.catalog.find(command.agentId);
|
|
998
|
-
const preparation = {
|
|
999
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1000
|
-
agent,
|
|
1001
|
-
cwd: resolved.cwd,
|
|
1002
|
-
sessionId: command.sessionId,
|
|
1003
|
-
signal,
|
|
1004
|
-
};
|
|
1005
|
-
const prepared = command.transient === true
|
|
1006
|
-
? await sessions.inspectSession(preparation, metrics)
|
|
1007
|
-
: await sessions.prepareSession(preparation, metrics);
|
|
1008
|
-
const configuration = command.configuration;
|
|
1009
|
-
const configOptions = configuration === undefined
|
|
1010
|
-
? prepared.configOptions
|
|
1011
|
-
: await metrics.measure("configuration", async () => await sessions.configureSession({
|
|
1012
|
-
...preparation,
|
|
1013
|
-
booleanValue: configuration.booleanValue,
|
|
1014
|
-
configId: configuration.configId,
|
|
1015
|
-
requestId: command.requestId,
|
|
1016
|
-
value: configuration.value,
|
|
1017
|
-
valueType: configuration.valueType,
|
|
1018
|
-
}));
|
|
1019
|
-
const listing = await metrics.measure("workspace-list", async () => await directories.list(config.bindingId, command.directoryId, signal));
|
|
1020
|
-
audit.record({
|
|
1021
|
-
commandId: command.requestId,
|
|
1022
|
-
event: "session_prepared",
|
|
1023
|
-
sessionId: command.sessionId,
|
|
1024
|
-
});
|
|
1025
|
-
if (command.configuration !== undefined) {
|
|
1026
|
-
audit.record({
|
|
1027
|
-
commandId: command.requestId,
|
|
1028
|
-
event: "session_configured",
|
|
1029
|
-
sessionId: command.sessionId,
|
|
1030
|
-
});
|
|
1031
|
-
publisher.recordRuntime(command.sessionId, {
|
|
1032
|
-
configOptions,
|
|
1033
|
-
kind: "session.config.updated",
|
|
1034
|
-
requestId: command.requestId,
|
|
1035
|
-
sessionId: command.sessionId,
|
|
1036
|
-
});
|
|
1037
|
-
}
|
|
1038
|
-
const event = {
|
|
1039
|
-
additionalDirectories: resolved.additionalDirectoryEntries,
|
|
1040
|
-
agentId: command.agentId,
|
|
1041
|
-
agentName: prepared.agentName,
|
|
1042
|
-
agentVersion: prepared.agentVersion,
|
|
1043
|
-
capabilities: prepared.capabilities,
|
|
1044
|
-
commands: prepared.commands,
|
|
1045
|
-
configOptions,
|
|
1046
|
-
directoryId: command.directoryId,
|
|
1047
|
-
directoryLabel: listing.directoryLabel,
|
|
1048
|
-
kind: "session.ready",
|
|
1049
|
-
requestId: command.requestId,
|
|
1050
|
-
restored: prepared.restored,
|
|
1051
|
-
sessionId: command.sessionId,
|
|
1052
|
-
runtimeTimings: metrics.snapshot(),
|
|
1053
|
-
};
|
|
1054
|
-
// An inspection-only preparation has no Session on the Relay, so this readiness is a reply
|
|
1055
|
-
// rather than a record: committing it would be rejected as an unknown Session and quarantine
|
|
1056
|
-
// an event that can never be replayed. The direct send below still delivers it.
|
|
1057
|
-
if (command.transient !== true) {
|
|
1058
|
-
metrics.measureSync("readiness-commit", () => {
|
|
1059
|
-
publisher.recordRuntime(command.sessionId, event);
|
|
1060
|
-
});
|
|
1061
|
-
}
|
|
1062
|
-
return event;
|
|
1063
|
-
});
|
|
1064
|
-
send(socket, {
|
|
1065
|
-
...readyEvent,
|
|
1066
|
-
runtimeTimings: metrics.snapshot(),
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1069
|
-
catch (error) {
|
|
1070
|
-
audit.record({
|
|
1071
|
-
commandId: command.requestId,
|
|
1072
|
-
details: {
|
|
1073
|
-
agentId: command.agentId,
|
|
1074
|
-
code: operationErrorCode(error),
|
|
1075
|
-
},
|
|
1076
|
-
event: "session_prepare_failed",
|
|
1077
|
-
sessionId: command.sessionId,
|
|
1078
|
-
});
|
|
1079
|
-
reportOperationFailure(socket, command.requestId, command.sessionId, error, metrics.snapshot());
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
function liveHistoryCursor(sessionId, endIndex) {
|
|
1083
|
-
return Buffer.from(JSON.stringify({ endIndex, sessionId }), "utf8").toString("base64url");
|
|
1084
|
-
}
|
|
1085
|
-
function liveHistoryEndIndex(cursor, sessionId) {
|
|
1086
|
-
try {
|
|
1087
|
-
if (!/^[A-Za-z0-9_-]{1,512}$/u.test(cursor)) {
|
|
1088
|
-
throw new Error("Invalid cursor alphabet");
|
|
1089
|
-
}
|
|
1090
|
-
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
1091
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1092
|
-
throw new Error("Invalid cursor shape");
|
|
1093
|
-
}
|
|
1094
|
-
const record = Object.fromEntries(Object.entries(value));
|
|
1095
|
-
if (Object.keys(record).sort().join(",") !== "endIndex,sessionId" ||
|
|
1096
|
-
record["sessionId"] !== sessionId ||
|
|
1097
|
-
typeof record["endIndex"] !== "number" ||
|
|
1098
|
-
!Number.isSafeInteger(record["endIndex"]) ||
|
|
1099
|
-
record["endIndex"] < 0) {
|
|
1100
|
-
throw new Error("Invalid cursor target");
|
|
1101
|
-
}
|
|
1102
|
-
return record["endIndex"];
|
|
1103
|
-
}
|
|
1104
|
-
catch (cause) {
|
|
1105
|
-
throw new AcpExecutionError("The native Session history cursor is invalid", { cause }, "invalid_cursor");
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
function liveHistoryCoveredTurnRanges(history) {
|
|
1109
|
-
const ranges = [];
|
|
1110
|
-
let historyIndex = history.messages.length;
|
|
1111
|
-
for (const commandId of history.coveredCommandIds) {
|
|
1112
|
-
let assistantStartIndex = historyIndex;
|
|
1113
|
-
while (assistantStartIndex > 0 && history.messages[assistantStartIndex - 1]?.role === "assistant") {
|
|
1114
|
-
assistantStartIndex -= 1;
|
|
1115
|
-
}
|
|
1116
|
-
const userIndex = assistantStartIndex - 1;
|
|
1117
|
-
if (assistantStartIndex === historyIndex || history.messages[userIndex]?.role !== "user") {
|
|
1118
|
-
break;
|
|
1119
|
-
}
|
|
1120
|
-
ranges.push({ assistantEndIndex: historyIndex, assistantStartIndex, commandId, userIndex });
|
|
1121
|
-
historyIndex = userIndex;
|
|
1122
|
-
}
|
|
1123
|
-
return ranges;
|
|
1124
|
-
}
|
|
1125
|
-
function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
|
|
1126
|
-
if (history.status === "unavailable") {
|
|
1127
|
-
if (cursor !== null) {
|
|
1128
|
-
throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
|
|
1129
|
-
}
|
|
1130
|
-
return { cause: history.cause, nextCursor: null, status: "unavailable" };
|
|
1131
|
-
}
|
|
1132
|
-
const endIndex = cursor === null ? history.messages.length : liveHistoryEndIndex(cursor, sessionId);
|
|
1133
|
-
if (endIndex > history.messages.length) {
|
|
1134
|
-
throw new AcpExecutionError("The native Session history cursor is invalid", {}, "invalid_cursor");
|
|
1135
|
-
}
|
|
1136
|
-
const startIndex = Math.max(0, endIndex - limit);
|
|
1137
|
-
const coveredMessageIds = new Set(history.coveredMessageIds);
|
|
1138
|
-
const ranges = liveHistoryCoveredTurnRanges(history);
|
|
1139
|
-
return {
|
|
1140
|
-
coveredCommandIds: ranges
|
|
1141
|
-
.filter((range) => range.userIndex >= startIndex && range.assistantEndIndex <= endIndex)
|
|
1142
|
-
.map((range) => range.commandId),
|
|
1143
|
-
coveredMessageIds: ranges.flatMap((range) => [
|
|
1144
|
-
...(range.userIndex >= startIndex &&
|
|
1145
|
-
range.userIndex < endIndex &&
|
|
1146
|
-
coveredMessageIds.has(`${range.commandId}:user`)
|
|
1147
|
-
? [`${range.commandId}:user`]
|
|
1148
|
-
: []),
|
|
1149
|
-
...(range.assistantStartIndex >= startIndex &&
|
|
1150
|
-
range.assistantEndIndex <= endIndex &&
|
|
1151
|
-
coveredMessageIds.has(`${range.commandId}:agent`)
|
|
1152
|
-
? [`${range.commandId}:agent`]
|
|
1153
|
-
: []),
|
|
1154
|
-
]),
|
|
1155
|
-
messages: history.messages.slice(startIndex, endIndex),
|
|
1156
|
-
nextCursor: startIndex > 0 ? liveHistoryCursor(sessionId, startIndex) : null,
|
|
1157
|
-
status: "available",
|
|
1158
|
-
truncated: history.truncated,
|
|
1159
|
-
};
|
|
1160
|
-
}
|
|
1161
|
-
async function executeSessionLiveHistoryLoad(socket, command, config, directories, audit, sessions, signal) {
|
|
1162
|
-
try {
|
|
1163
|
-
const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
|
|
1164
|
-
const history = await sessions.loadSessionHistory({
|
|
1165
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1166
|
-
agent: config.catalog.find(command.agentId),
|
|
1167
|
-
cwd: resolved.cwd,
|
|
1168
|
-
sessionId: command.sessionId,
|
|
1169
|
-
signal,
|
|
1170
|
-
});
|
|
1171
|
-
signal.throwIfAborted();
|
|
1172
|
-
audit.record({
|
|
1173
|
-
commandId: command.requestId,
|
|
1174
|
-
event: "session_history_loaded",
|
|
1175
|
-
sessionId: command.sessionId,
|
|
1176
|
-
});
|
|
1177
|
-
send(socket, {
|
|
1178
|
-
history,
|
|
1179
|
-
kind: "session.live-history.loaded",
|
|
1180
|
-
requestId: command.requestId,
|
|
1181
|
-
sessionId: command.sessionId,
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
catch (error) {
|
|
1185
|
-
if (signal.aborted) {
|
|
1186
|
-
return;
|
|
1187
|
-
}
|
|
1188
|
-
audit.record({
|
|
1189
|
-
commandId: command.requestId,
|
|
1190
|
-
details: { code: operationErrorCode(error) },
|
|
1191
|
-
event: "session_history_unavailable",
|
|
1192
|
-
sessionId: command.sessionId,
|
|
1193
|
-
});
|
|
1194
|
-
send(socket, {
|
|
1195
|
-
history: {
|
|
1196
|
-
status: "unavailable",
|
|
1197
|
-
cause: { code: operationErrorCode(error), message: operationErrorMessage(error) },
|
|
1198
|
-
},
|
|
1199
|
-
kind: "session.live-history.loaded",
|
|
1200
|
-
requestId: command.requestId,
|
|
1201
|
-
sessionId: command.sessionId,
|
|
1202
|
-
});
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
async function executeSessionLiveHistoryPageLoad(socket, command, config, directories, audit, sessions, signal) {
|
|
1206
|
-
try {
|
|
1207
|
-
const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
|
|
1208
|
-
const history = await sessions.loadSessionHistory({
|
|
1209
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1210
|
-
agent: config.catalog.find(command.agentId),
|
|
1211
|
-
cwd: resolved.cwd,
|
|
1212
|
-
sessionId: command.sessionId,
|
|
1213
|
-
signal,
|
|
1214
|
-
});
|
|
1215
|
-
signal.throwIfAborted();
|
|
1216
|
-
const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
|
|
1217
|
-
audit.record({
|
|
1218
|
-
commandId: command.requestId,
|
|
1219
|
-
event: "session_history_loaded",
|
|
1220
|
-
sessionId: command.sessionId,
|
|
1221
|
-
});
|
|
1222
|
-
send(socket, {
|
|
1223
|
-
kind: "session.live-history.page.loaded",
|
|
1224
|
-
page,
|
|
1225
|
-
requestId: command.requestId,
|
|
1226
|
-
sessionId: command.sessionId,
|
|
1227
|
-
});
|
|
1228
|
-
}
|
|
1229
|
-
catch (error) {
|
|
1230
|
-
if (signal.aborted) {
|
|
1231
|
-
return;
|
|
1232
|
-
}
|
|
1233
|
-
audit.record({
|
|
1234
|
-
commandId: command.requestId,
|
|
1235
|
-
details: { code: operationErrorCode(error) },
|
|
1236
|
-
event: "session_history_unavailable",
|
|
1237
|
-
sessionId: command.sessionId,
|
|
1238
|
-
});
|
|
1239
|
-
send(socket, {
|
|
1240
|
-
kind: "session.live-history.page.loaded",
|
|
1241
|
-
page: {
|
|
1242
|
-
status: "unavailable",
|
|
1243
|
-
cause: { code: operationErrorCode(error), message: operationErrorMessage(error) },
|
|
1244
|
-
nextCursor: null,
|
|
1245
|
-
},
|
|
1246
|
-
requestId: command.requestId,
|
|
1247
|
-
sessionId: command.sessionId,
|
|
1248
|
-
});
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
async function executeSessionConfigure(publisher, socket, command, config, directories, audit, sessions, signal) {
|
|
1252
|
-
try {
|
|
1253
|
-
const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
|
|
1254
|
-
const configOptions = await sessions.configureSession({
|
|
1255
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1256
|
-
agent: config.catalog.find(command.agentId),
|
|
1257
|
-
booleanValue: command.booleanValue,
|
|
1258
|
-
configId: command.configId,
|
|
1259
|
-
cwd: resolved.cwd,
|
|
1260
|
-
requestId: command.requestId,
|
|
1261
|
-
sessionId: command.sessionId,
|
|
1262
|
-
signal,
|
|
1263
|
-
value: command.value,
|
|
1264
|
-
valueType: command.valueType,
|
|
1265
|
-
});
|
|
1266
|
-
audit.record({
|
|
1267
|
-
commandId: command.requestId,
|
|
1268
|
-
event: "session_configured",
|
|
1269
|
-
sessionId: command.sessionId,
|
|
1270
|
-
});
|
|
1271
|
-
publisher.recordRuntime(command.sessionId, {
|
|
1272
|
-
configOptions,
|
|
1273
|
-
kind: "session.config.updated",
|
|
1274
|
-
requestId: command.requestId,
|
|
1275
|
-
sessionId: command.sessionId,
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
catch (error) {
|
|
1279
|
-
if (signal.aborted) {
|
|
1280
|
-
signal.throwIfAborted();
|
|
1281
|
-
}
|
|
1282
|
-
reportOperationFailure(socket, command.requestId, command.sessionId, error);
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
async function executePrompt(outbox, publisher, command, config, directories, audit, sessions, attemptId, activateAttempt, timer, signal) {
|
|
1286
|
-
const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
|
|
1287
|
-
publisher.recordAttempt(command.sessionId, daemonActivity(command, activity), attemptId);
|
|
1288
|
-
});
|
|
1289
|
-
const narration = new CoalescingNarrationPublisher(timer, (increment) => {
|
|
1290
|
-
publisher.recordAttempt(command.sessionId, {
|
|
1291
|
-
activityId: increment.activityId,
|
|
1292
|
-
activityType: increment.activityType,
|
|
1293
|
-
commandId: command.commandId,
|
|
1294
|
-
kind: AGENT_ACTIVITY_NARRATION_KIND,
|
|
1295
|
-
sequence: increment.sequence,
|
|
1296
|
-
sessionId: command.sessionId,
|
|
1297
|
-
text: increment.text,
|
|
1298
|
-
}, attemptId);
|
|
1299
|
-
}, AGENT_ACTIVITY_COALESCING_MILLISECONDS, AGENT_TEXT_MAXIMUM_LENGTH);
|
|
1300
|
-
const text = new CoalescingTextPublisher(timer, (messageId, delta) => {
|
|
1301
|
-
publisher.recordAttempt(command.sessionId, {
|
|
1302
|
-
commandId: command.commandId,
|
|
1303
|
-
kind: AGENT_MESSAGE_DELTA_KIND,
|
|
1304
|
-
messageId,
|
|
1305
|
-
sessionId: command.sessionId,
|
|
1306
|
-
text: delta,
|
|
1307
|
-
}, attemptId);
|
|
1308
|
-
}, AGENT_TEXT_COALESCING_MILLISECONDS, AGENT_TEXT_MAXIMUM_LENGTH);
|
|
1309
|
-
try {
|
|
1310
|
-
const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
|
|
1311
|
-
const agent = config.catalog.find(command.agentId);
|
|
1312
|
-
if (command.disposition === SessionPromptDisposition.Queue &&
|
|
1313
|
-
!outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
|
|
1314
|
-
throw new AcpExecutionError("The queued prompt target is unavailable", {}, "prompt_queue_target_unavailable");
|
|
1315
|
-
}
|
|
1316
|
-
const appliedSettings = command.sessionConfigurations === undefined
|
|
1317
|
-
? undefined
|
|
1318
|
-
: agentForSessionConfiguration(agent, command.sessionConfigurations);
|
|
1319
|
-
const executionAgent = appliedSettings?.agent ?? agent;
|
|
1320
|
-
const sessionConfigurations = appliedSettings?.sessionConfigurations;
|
|
1321
|
-
if (command.sessionConfigurations !== undefined) {
|
|
1322
|
-
const prepared = await sessions.prepareExecutionSession({
|
|
1323
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1324
|
-
agent: executionAgent,
|
|
1325
|
-
cwd: resolved.cwd,
|
|
1326
|
-
sessionId: command.sessionId,
|
|
1327
|
-
signal,
|
|
1328
|
-
});
|
|
1329
|
-
if (command.disposition === SessionPromptDisposition.Steer) {
|
|
1330
|
-
// Steering cannot reconfigure a running Agent, so the Turn snapshot
|
|
1331
|
-
// only has to agree with the settings this live Session exposes. The
|
|
1332
|
-
// snapshot comes from Agent settings discovery, so it may name options
|
|
1333
|
-
// that the running Session does not expose at all.
|
|
1334
|
-
assertAppliedSessionConfiguration(prepared.configOptions, sessionConfigurations ?? []);
|
|
1335
|
-
}
|
|
1336
|
-
else {
|
|
1337
|
-
await applyCompleteSessionConfiguration(sessions, audit, prepared.configOptions, sessionConfigurations ?? [], executionAgent, resolved.cwd, resolved.additionalDirectories, command.commandId, command.sessionId, signal);
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
audit.record({
|
|
1341
|
-
commandId: command.commandId,
|
|
1342
|
-
event: "session_authorized",
|
|
1343
|
-
sessionId: command.sessionId,
|
|
1344
|
-
});
|
|
1345
|
-
outbox.transitionExecution(command.commandId, "running");
|
|
1346
|
-
publisher.recordAttempt(command.sessionId, {
|
|
1347
|
-
commandId: command.commandId,
|
|
1348
|
-
kind: SESSION_STARTED_KIND,
|
|
1349
|
-
attemptId,
|
|
1350
|
-
sessionId: command.sessionId,
|
|
1351
|
-
}, attemptId);
|
|
1352
|
-
activateAttempt();
|
|
1353
|
-
const attachments = await resolvePromptArtifacts(config, command, signal);
|
|
1354
|
-
let stopReason;
|
|
1355
|
-
if (command.disposition === SessionPromptDisposition.Steer) {
|
|
1356
|
-
await sessions.steerPrompt({
|
|
1357
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1358
|
-
agent: executionAgent,
|
|
1359
|
-
commandId: command.commandId,
|
|
1360
|
-
cwd: resolved.cwd,
|
|
1361
|
-
images: attachments.images,
|
|
1362
|
-
prompt: command.prompt,
|
|
1363
|
-
resources: attachments.resources,
|
|
1364
|
-
sessionId: command.sessionId,
|
|
1365
|
-
signal,
|
|
1366
|
-
targetCommandId: command.targetCommandId,
|
|
1367
|
-
});
|
|
1368
|
-
stopReason = "steered";
|
|
1369
|
-
}
|
|
1370
|
-
else {
|
|
1371
|
-
const result = await sessions.runPrompt({
|
|
1372
|
-
additionalDirectories: resolved.additionalDirectories,
|
|
1373
|
-
agent: executionAgent,
|
|
1374
|
-
commandId: command.commandId,
|
|
1375
|
-
cwd: resolved.cwd,
|
|
1376
|
-
disposition: command.disposition,
|
|
1377
|
-
images: attachments.images,
|
|
1378
|
-
onActivity: activities.record,
|
|
1379
|
-
onNarration: (increment) => {
|
|
1380
|
-
narration.record(increment);
|
|
1381
|
-
return Promise.resolve();
|
|
1382
|
-
},
|
|
1383
|
-
onText: (delta, messageId) => {
|
|
1384
|
-
text.record(messageId, delta);
|
|
1385
|
-
return Promise.resolve();
|
|
1386
|
-
},
|
|
1387
|
-
prompt: command.prompt,
|
|
1388
|
-
resources: attachments.resources,
|
|
1389
|
-
sessionId: command.sessionId,
|
|
1390
|
-
signal,
|
|
1391
|
-
targetCommandId: command.targetCommandId,
|
|
1392
|
-
});
|
|
1393
|
-
stopReason = result.stopReason;
|
|
1394
|
-
}
|
|
1395
|
-
text.flush();
|
|
1396
|
-
narration.flush();
|
|
1397
|
-
activities.flush();
|
|
1398
|
-
publisher.recordAttempt(command.sessionId, {
|
|
1399
|
-
commandId: command.commandId,
|
|
1400
|
-
kind: SESSION_COMPLETED_KIND,
|
|
1401
|
-
sessionId: command.sessionId,
|
|
1402
|
-
stopReason,
|
|
1403
|
-
}, attemptId);
|
|
1404
|
-
outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
|
|
1405
|
-
audit.record({
|
|
1406
|
-
commandId: command.commandId,
|
|
1407
|
-
event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
|
|
1408
|
-
sessionId: command.sessionId,
|
|
1409
|
-
});
|
|
1410
|
-
}
|
|
1411
|
-
catch (error) {
|
|
1412
|
-
text.flush();
|
|
1413
|
-
narration.flush();
|
|
1414
|
-
activities.flush();
|
|
1415
|
-
audit.record({
|
|
1416
|
-
commandId: command.commandId,
|
|
1417
|
-
event: "session_failed",
|
|
1418
|
-
sessionId: command.sessionId,
|
|
1419
|
-
});
|
|
1420
|
-
const code = operationErrorCode(error);
|
|
1421
|
-
reportFailure(publisher, command, code === "session_operation_failed" ? "agent_execution_failed" : code, code === "session_operation_failed"
|
|
1422
|
-
? "The local agent could not complete the request"
|
|
1423
|
-
: operationErrorMessage(error), attemptId);
|
|
1424
|
-
outbox.transitionExecution(command.commandId, "failed");
|
|
1425
|
-
console.error("Mobius daemon command failed", error);
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
function invalidSessionConfiguration(message) {
|
|
1429
|
-
return new AcpExecutionError(message, {}, "invalid_session_configuration");
|
|
1430
|
-
}
|
|
1431
|
-
function agentForSessionConfiguration(agent, selections) {
|
|
1432
|
-
try {
|
|
1433
|
-
return applyAgentLaunchSettings(agent, selections);
|
|
1434
|
-
}
|
|
1435
|
-
catch (error) {
|
|
1436
|
-
if (error instanceof Error) {
|
|
1437
|
-
throw invalidSessionConfiguration(error.message);
|
|
1438
|
-
}
|
|
1439
|
-
throw error;
|
|
1440
|
-
}
|
|
1441
|
-
}
|
|
1442
|
-
function validateSessionConfigurationSelection(option, selection) {
|
|
1443
|
-
if (option.type !== selection.valueType) {
|
|
1444
|
-
throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
|
|
1445
|
-
}
|
|
1446
|
-
if (option.type === "boolean") {
|
|
1447
|
-
if (selection.value.length > 0) {
|
|
1448
|
-
throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
|
|
1449
|
-
}
|
|
1450
|
-
return;
|
|
1451
|
-
}
|
|
1452
|
-
if (selection.booleanValue) {
|
|
1453
|
-
throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
|
|
1454
|
-
}
|
|
1455
|
-
if (!option.values.some((value) => value.value === selection.value)) {
|
|
1456
|
-
throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
|
|
1457
|
-
}
|
|
1458
|
-
}
|
|
1459
|
-
function sessionConfigurationSelectionIsAvailable(option, selection) {
|
|
1460
|
-
if (option.type !== selection.valueType) {
|
|
1461
|
-
return false;
|
|
1462
|
-
}
|
|
1463
|
-
if (option.type === "boolean") {
|
|
1464
|
-
return selection.value.length === 0;
|
|
1465
|
-
}
|
|
1466
|
-
return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
|
|
1467
|
-
}
|
|
1468
|
-
function sessionConfigurationMatches(option, selection) {
|
|
1469
|
-
validateSessionConfigurationSelection(option, selection);
|
|
1470
|
-
return option.type === "boolean"
|
|
1471
|
-
? option.booleanValue === selection.booleanValue
|
|
1472
|
-
: option.currentValue === selection.value;
|
|
1473
|
-
}
|
|
1474
|
-
function sessionConfigurationPriority(selection, options) {
|
|
1475
|
-
const option = options.find((candidate) => candidate.id === selection.configId);
|
|
1476
|
-
if (selection.configId === "model" || option?.category === "model") {
|
|
1477
|
-
return 0;
|
|
1478
|
-
}
|
|
1479
|
-
if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
|
|
1480
|
-
return 1;
|
|
1481
|
-
}
|
|
1482
|
-
if (option?.category === "model_config") {
|
|
1483
|
-
return 2;
|
|
1484
|
-
}
|
|
1485
|
-
return 3;
|
|
1486
|
-
}
|
|
1487
|
-
function assertAppliedSessionConfiguration(options, selections) {
|
|
1488
|
-
const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
|
|
1489
|
-
for (const option of options) {
|
|
1490
|
-
const selection = selectionsById.get(option.id);
|
|
1491
|
-
if (selection === undefined || !sessionConfigurationSelectionIsAvailable(option, selection)) {
|
|
1492
|
-
continue;
|
|
1493
|
-
}
|
|
1494
|
-
if (!sessionConfigurationMatches(option, selection)) {
|
|
1495
|
-
throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
|
|
1496
|
-
}
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
function unavailableSessionConfigurationCategory(selection) {
|
|
1500
|
-
if (selection.configId === "model") {
|
|
1501
|
-
return "model";
|
|
1502
|
-
}
|
|
1503
|
-
if (selection.configId === "reasoning_effort") {
|
|
1504
|
-
return "thought_level";
|
|
1505
|
-
}
|
|
1506
|
-
return "unknown";
|
|
1507
|
-
}
|
|
1508
|
-
async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
|
|
1509
|
-
const option = options.find((candidate) => candidate.id === selection.configId);
|
|
1510
|
-
if (option === undefined) {
|
|
1511
|
-
warnIgnoredSetting(audit, "session_configuration_setting_ignored", commandId, sessionId, agent.id, selection, unavailableSessionConfigurationCategory(selection), "setting_unavailable");
|
|
1512
|
-
return options;
|
|
1513
|
-
}
|
|
1514
|
-
if (option.type !== selection.valueType) {
|
|
1515
|
-
warnIgnoredSetting(audit, "session_configuration_setting_ignored", commandId, sessionId, agent.id, selection, option.category, "setting_schema_mismatch");
|
|
1516
|
-
return options;
|
|
1517
|
-
}
|
|
1518
|
-
if ((option.type === "boolean" && selection.value.length > 0) ||
|
|
1519
|
-
(option.type === "select" && selection.booleanValue)) {
|
|
1520
|
-
warnIgnoredSetting(audit, "session_configuration_setting_ignored", commandId, sessionId, agent.id, selection, option.category, "selection_schema_mismatch");
|
|
1521
|
-
return options;
|
|
1522
|
-
}
|
|
1523
|
-
if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
|
|
1524
|
-
warnIgnoredSetting(audit, "session_configuration_setting_ignored", commandId, sessionId, agent.id, selection, option.category, "value_unavailable");
|
|
1525
|
-
return options;
|
|
1526
|
-
}
|
|
1527
|
-
if (sessionConfigurationMatches(option, selection)) {
|
|
1528
|
-
return options;
|
|
1529
|
-
}
|
|
1530
|
-
return await sessions.configureSession({
|
|
1531
|
-
additionalDirectories,
|
|
1532
|
-
agent,
|
|
1533
|
-
booleanValue: selection.booleanValue,
|
|
1534
|
-
configId: selection.configId,
|
|
1535
|
-
cwd,
|
|
1536
|
-
requestId: `cfg_${randomUUID()}`,
|
|
1537
|
-
sessionId,
|
|
1538
|
-
signal,
|
|
1539
|
-
value: selection.value,
|
|
1540
|
-
valueType: selection.valueType,
|
|
1541
|
-
});
|
|
1542
|
-
}
|
|
1543
|
-
async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
|
|
1544
|
-
let options = initialOptions;
|
|
1545
|
-
const orderedSelections = selections.toSorted((left, right) => {
|
|
1546
|
-
const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
|
|
1547
|
-
return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
|
|
1548
|
-
});
|
|
1549
|
-
for (const selection of orderedSelections) {
|
|
1550
|
-
options = await applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal);
|
|
1551
|
-
}
|
|
1552
|
-
assertAppliedSessionConfiguration(options, selections);
|
|
1553
|
-
}
|
|
1554
|
-
function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
|
|
1555
|
-
const details = {
|
|
1556
|
-
agentId,
|
|
1557
|
-
category,
|
|
1558
|
-
configId: selection.configId,
|
|
1559
|
-
reason,
|
|
1560
|
-
requestedValue: selection.value,
|
|
1561
|
-
};
|
|
1562
|
-
audit.record({ commandId, details, event, sessionId });
|
|
1563
|
-
process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}\n`);
|
|
1564
|
-
}
|
|
1565
295
|
function waitForRelayRetry(signal, timer) {
|
|
1566
296
|
if (signal.aborted) {
|
|
1567
297
|
return Promise.resolve();
|