@qlairoslabs/acp-client 0.12.1 → 0.13.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG-consumer-fixes.md +17 -10
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +984 -6
- package/MIGRATION-0.10-to-0.12.md +4 -1
- package/MIGRATION-0.12-to-0.13.md +288 -0
- package/README.md +17 -16
- package/package.json +11 -2
- package/src/acp-client-handlers.ts +48 -0
- package/src/activity.ts +3 -0
- package/src/adapters.ts +25 -0
- package/src/agent/adoption/provider-attachment.ts +33 -0
- package/src/agent/adoption/provider-session-delete.ts +1 -1
- package/src/agent/adoption/provider-sessions.ts +3 -2
- package/src/agent/append-assistant-message.ts +91 -0
- package/src/agent/config.ts +54 -6
- package/src/agent/conversation-manager.ts +95 -158
- package/src/agent/manager-settings.ts +1 -0
- package/src/agent/native-channel-lifecycle.ts +111 -0
- package/src/agent/native-operations.ts +39 -0
- package/src/agent/persisted-lifecycle.ts +44 -4
- package/src/agent/persistence-policy/context.ts +13 -0
- package/src/agent/persistence-policy/resolver.ts +7 -0
- package/src/agent/persistence-policy/types.ts +1 -0
- package/src/agent/record-capture.ts +1 -0
- package/src/agent-adapter-registry.ts +33 -7
- package/src/agent-conversation-contracts.ts +14 -1
- package/src/agent-conversation-errors.ts +8 -0
- package/src/agent-conversation-owner.ts +9 -4
- package/src/agent-session-config.ts +137 -0
- package/src/agent-session.ts +440 -934
- package/src/agent.ts +168 -0
- package/src/capabilities.ts +2 -0
- package/src/checkpointing/recovery.ts +3 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +56 -96
- package/src/connection-attempt.ts +95 -0
- package/src/controller-connection.ts +115 -0
- package/src/controller.ts +158 -148
- package/src/conversation-controller/capabilities.ts +88 -0
- package/src/conversation-controller/contracts.ts +208 -0
- package/src/conversation-controller/factory.ts +39 -0
- package/src/conversation-controller/guards.ts +98 -0
- package/src/conversation-controller/index.ts +20 -0
- package/src/conversation-startup.ts +35 -0
- package/src/conversation-turns/backend-turns.ts +373 -0
- package/src/conversation-turns/clear-operations.ts +37 -0
- package/src/conversation-turns/context.ts +135 -0
- package/src/conversation-turns/index.ts +4 -0
- package/src/conversation-turns/record-helpers.ts +75 -0
- package/src/conversation-turns/recording.ts +235 -0
- package/src/conversation-turns/run-turn.ts +367 -0
- package/src/conversation-turns/turn-run.ts +57 -0
- package/src/errors.ts +41 -0
- package/src/handoff-options.ts +81 -0
- package/src/identity/checkpoint-backed.ts +1 -1
- package/src/index.ts +59 -3
- package/src/internal-inference/coordination/manager.ts +11 -0
- package/src/internal-inference/runtime/harness-runtime.ts +4 -4
- package/src/launcher.ts +37 -2
- package/src/media/parts.ts +5 -0
- package/src/message-status.ts +83 -0
- package/src/metering/engine.ts +39 -64
- package/src/metering/measurement-provenance.ts +36 -0
- package/src/metering/native/durability.ts +115 -0
- package/src/metering/native/ledger.ts +104 -0
- package/src/metering/native/operation.ts +85 -0
- package/src/metering/native/projection.ts +114 -0
- package/src/metering/native/proof.ts +51 -0
- package/src/metering/native/requirements.ts +10 -0
- package/src/metering/native/retirement.ts +92 -0
- package/src/metering/native/source.ts +90 -0
- package/src/metering/record.ts +38 -1
- package/src/metering/state.ts +13 -3
- package/src/native/approvals.ts +186 -0
- package/src/native/capabilities.ts +17 -0
- package/src/native/channel-changes.ts +211 -0
- package/src/native/connection.ts +56 -0
- package/src/native/controller.ts +592 -0
- package/src/native/delegation-sender.ts +26 -0
- package/src/native/errors.ts +35 -0
- package/src/native/functions.ts +156 -0
- package/src/native/host-config.ts +59 -0
- package/src/native/host.ts +978 -0
- package/src/native/item-receipts.ts +15 -0
- package/src/native/metering.ts +12 -0
- package/src/native/records.ts +166 -0
- package/src/native/recovery.ts +186 -0
- package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
- package/src/native/reminders/idle.ts +70 -0
- package/src/native/reminders/limits.ts +19 -0
- package/src/native/reminders/notifications.ts +29 -0
- package/src/native/reminders/routine-guard.ts +66 -0
- package/src/native/reminders/routine-schedule.ts +25 -0
- package/src/native/reminders/routine-wire.ts +21 -0
- package/src/native/reminders/schedule.ts +97 -0
- package/src/native/reminders/service.ts +280 -0
- package/src/native/reminders/supervisor.ts +91 -0
- package/src/native/reminders/sync.ts +301 -0
- package/src/native/reminders/wire.ts +197 -0
- package/src/native/submission-withdrawal.ts +65 -0
- package/src/native/usage.ts +15 -0
- package/src/native/worker-delivery.ts +61 -0
- package/src/native-harness/README.md +726 -0
- package/src/native-harness/package.json +24 -0
- package/src/native-harness/scripts/build-routine-zones.py +47 -0
- package/src/native-harness/src/capabilities/context/build.ts +59 -0
- package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
- package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
- package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
- package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
- package/src/native-harness/src/capabilities/context/session.ts +93 -0
- package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
- package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
- package/src/native-harness/src/capabilities/model/runner.ts +116 -0
- package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
- package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
- package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
- package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
- package/src/native-harness/src/capabilities/model/usage.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
- package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
- package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
- package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
- package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
- package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
- package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
- package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
- package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
- package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
- package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
- package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
- package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
- package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
- package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
- package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
- package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
- package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
- package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
- package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
- package/src/native-harness/src/client.ts +18 -0
- package/src/native-harness/src/contracts/agent.ts +105 -0
- package/src/native-harness/src/contracts/config-permissions.ts +49 -0
- package/src/native-harness/src/contracts/context.ts +112 -0
- package/src/native-harness/src/contracts/events.ts +47 -0
- package/src/native-harness/src/contracts/input-limits.ts +7 -0
- package/src/native-harness/src/contracts/inspection.ts +22 -0
- package/src/native-harness/src/contracts/loop.ts +31 -0
- package/src/native-harness/src/contracts/model-execution.ts +83 -0
- package/src/native-harness/src/contracts/operator-controls.ts +106 -0
- package/src/native-harness/src/contracts/output.ts +13 -0
- package/src/native-harness/src/contracts/protocol.ts +320 -0
- package/src/native-harness/src/contracts/reminders.ts +134 -0
- package/src/native-harness/src/contracts/routines.ts +20 -0
- package/src/native-harness/src/contracts/scenario.ts +42 -0
- package/src/native-harness/src/contracts/session-file.ts +20 -0
- package/src/native-harness/src/contracts/session.ts +184 -0
- package/src/native-harness/src/contracts/storage.ts +597 -0
- package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
- package/src/native-harness/src/contracts/tools.ts +133 -0
- package/src/native-harness/src/governance/permissions/gate.ts +129 -0
- package/src/native-harness/src/governance/policy/resolve.ts +32 -0
- package/src/native-harness/src/index.ts +322 -0
- package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
- package/src/native-harness/src/interfaces/cli/development.ts +145 -0
- package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
- package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
- package/src/native-harness/src/interfaces/cli/main.ts +47 -0
- package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
- package/src/native-harness/src/interfaces/cli/start.ts +106 -0
- package/src/native-harness/src/interfaces/client.ts +225 -0
- package/src/native-harness/src/interfaces/inspector/index.html +283 -0
- package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
- package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
- package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
- package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
- package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
- package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
- package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
- package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
- package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
- package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
- package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
- package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
- package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
- package/src/native-harness/src/kernel/channels.ts +409 -0
- package/src/native-harness/src/kernel/loop.ts +45 -0
- package/src/native-harness/src/runtime/config/development.ts +23 -0
- package/src/native-harness/src/runtime/config/managed.ts +2 -0
- package/src/native-harness/src/runtime/config/paths.ts +33 -0
- package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
- package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
- package/src/native-harness/src/runtime/reminders.ts +66 -0
- package/src/native-harness/src/state/storage/archive.ts +257 -0
- package/src/native-harness/src/state/storage/engine.ts +1204 -0
- package/src/native-harness/src/state/storage/inference.ts +124 -0
- package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
- package/src/native-harness/src/state/storage/memory.ts +354 -0
- package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
- package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
- package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
- package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
- package/src/native-harness/src/state/storage/retrieval.ts +122 -0
- package/src/native-harness/src/state/storage/routine-row.ts +25 -0
- package/src/native-harness/src/state/storage/script-identity.ts +7 -0
- package/src/native-harness/src/state/storage/session-file.ts +85 -0
- package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
- package/src/native-harness/src/state/storage/sqlite.ts +632 -0
- package/src/native-harness/src/testing.ts +190 -0
- package/src/native-harness/src/util/config.ts +66 -0
- package/src/native-harness/src/util/intake.ts +7 -0
- package/src/native-harness/src/util/json.ts +41 -0
- package/src/native-harness/src/util/message-position.ts +3 -0
- package/src/native-harness/src/util/reminder-schedule.ts +44 -0
- package/src/native-harness/src/util/schema.ts +40 -0
- package/src/native-harness/src/util/timeline-text.ts +72 -0
- package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
- package/src/native-harness/tsconfig.json +20 -0
- package/src/observation/agent-event-bus.ts +44 -18
- package/src/observation/index.ts +1 -0
- package/src/operations/contracts.ts +11 -3
- package/src/operations/errors.ts +5 -0
- package/src/operations/stale-policy.ts +1 -1
- package/src/operations/supervisor.ts +34 -10
- package/src/orchestrator/acp-delivery.ts +68 -0
- package/src/orchestrator/assignments.ts +27 -0
- package/src/orchestrator/busy.ts +15 -0
- package/src/orchestrator/config.ts +41 -0
- package/src/orchestrator/consumer-api.ts +24 -0
- package/src/orchestrator/contracts.ts +71 -0
- package/src/orchestrator/durable-assignments.ts +111 -0
- package/src/orchestrator/native-delegation.ts +103 -0
- package/src/orchestrator/orchestrator.ts +318 -0
- package/src/orchestrator/permissions.ts +28 -0
- package/src/orchestrator/policy.ts +44 -0
- package/src/orchestrator/pool.ts +123 -0
- package/src/orchestrator/tool-descriptions.ts +11 -0
- package/src/permissions/acp.ts +18 -0
- package/src/permissions/arrival.ts +13 -0
- package/src/permissions/consumer-config.ts +19 -0
- package/src/permissions/conversation.ts +288 -0
- package/src/permissions/matcher.ts +87 -0
- package/src/permissions/outcome.ts +26 -0
- package/src/permissions/policy.ts +86 -0
- package/src/permissions/request.ts +26 -0
- package/src/persistence/activity-projection.ts +1 -0
- package/src/persistence/backend.ts +34 -1
- package/src/persistence/channels.ts +23 -0
- package/src/persistence/index.ts +4 -0
- package/src/persistence/protocol-method.ts +5 -0
- package/src/persistence/reminder-wake.ts +49 -0
- package/src/persistence/reminders.ts +385 -0
- package/src/persistence/sqlite-backend.ts +84 -6
- package/src/persistence/sqlite-channels.ts +65 -0
- package/src/persistence/sqlite-reminders.ts +85 -0
- package/src/persistence/sqlite-schema.ts +108 -3
- package/src/persistence/sqlite-worker-delivery.ts +374 -0
- package/src/persistence/sqlite-workers.ts +59 -0
- package/src/persistence/worker-delivery-contract.ts +104 -0
- package/src/persistence/worker-terminal-reason.ts +29 -0
- package/src/persistence/workers.ts +19 -0
- package/src/provider-notices.ts +137 -0
- package/src/repl/commands.ts +2 -2
- package/src/steering/combine.ts +3 -1
- package/src/steering/contracts.ts +11 -2
- package/src/steering/controller.ts +3 -2
- package/src/terminals.ts +9 -6
- package/src/transport/acp-transport.ts +24 -14
- package/src/types.ts +15 -12
- package/src/updates.ts +14 -2
- package/src/wire-log.ts +1 -1
package/src/agent-session.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { protocolMethod } from "./persistence/protocol-method.ts";
|
|
2
|
+
import { ReminderError } from "./native/reminders/schedule.ts";
|
|
1
3
|
// AgentConversation — one durable conversation and the library's compatibility front
|
|
2
4
|
// face. Existing consumers still import this constructor as `AgentSession`; both names
|
|
3
5
|
// refer to the same class while the new agent-level owner is introduced.
|
|
4
6
|
//
|
|
5
7
|
// It owns identity (our `agentSessionId`, adapter, mode, internalSessionId, title) and persistence, and
|
|
6
|
-
// HOLDS
|
|
8
|
+
// HOLDS a ConversationController (today a HarnessController) for the live connection. It implements
|
|
7
9
|
// AgentClient, so the REPL and any caller can prompt it directly.
|
|
8
10
|
//
|
|
9
11
|
// Adapter ownership remains here during the compatibility tranche. The later Agent owner
|
|
@@ -11,14 +13,23 @@
|
|
|
11
13
|
|
|
12
14
|
import { isMissingProviderSessionError } from "./checkpointing/recovery.ts";
|
|
13
15
|
import type { CancelOutcome, CancelReason, OperationLifecycleConfig } from "./operations/contracts.ts";
|
|
16
|
+
import { ConnectionCancelledError, UnsupportedError } from "./errors.ts";
|
|
17
|
+
import type { AgentSessionConfig, AgentSessionOpenConfig } from "./agent-session-config.ts";
|
|
18
|
+
import { withStartupCancellation } from "./conversation-startup.ts";
|
|
19
|
+
export type { AgentSessionConfig, AgentSessionOpenConfig } from "./agent-session-config.ts";
|
|
20
|
+
import { SubscriptionHub } from "./observation/subscription-hub.ts";
|
|
21
|
+
import { validatePermissionConsumerConfig } from "./permissions/consumer-config.ts";
|
|
22
|
+
import { ConversationPermissions } from "./permissions/conversation.ts";
|
|
23
|
+
import { ownPermissions } from "./permissions/policy.ts";
|
|
14
24
|
import { OperationStalledError } from "./operations/errors.ts";
|
|
15
|
-
import { OperationSupervisor } from "./operations/supervisor.ts";
|
|
25
|
+
import { OperationSupervisor, type SupervisedProvider } from "./operations/supervisor.ts";
|
|
26
|
+
import type { HarnessController, AgentControllerConfig, ControllerStartEvent, AgentMode } from "./controller.ts";
|
|
27
|
+
import { normalizeHandoffContinuation, ownHandoffOptions } from "./handoff-options.ts";
|
|
16
28
|
import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
type
|
|
20
|
-
|
|
21
|
-
} from "./controller.ts";
|
|
29
|
+
acpCapabilitiesOf, availableCommandsOf, createController, harnessControllerOf, isDegradedController, listAgentSessions,
|
|
30
|
+
reloadProviderSession, requireFreshContext, requireMember, stallLimitsFor,
|
|
31
|
+
type ConversationCapabilities, type ConversationController,
|
|
32
|
+
} from "./conversation-controller/index.ts";
|
|
22
33
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
23
34
|
import { join } from "node:path";
|
|
24
35
|
import type { ActivitySnapshot, AggregatedRecord } from "./activity.ts";
|
|
@@ -36,7 +47,6 @@ import type {
|
|
|
36
47
|
PersistenceJsonValue,
|
|
37
48
|
} from "./persistence/backend.ts";
|
|
38
49
|
import {
|
|
39
|
-
OwnedPromptPostCommitError,
|
|
40
50
|
type AgentConversationOwnerLifecycle,
|
|
41
51
|
} from "./agent-conversation-owner.ts";
|
|
42
52
|
import {
|
|
@@ -52,11 +62,11 @@ import type { Capabilities } from "./capabilities.ts";
|
|
|
52
62
|
import type { ConfigOption, ConfigOptions } from "./config-options.ts";
|
|
53
63
|
import type { ConnectResult } from "./client.ts";
|
|
54
64
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
55
|
-
import { formatResponseMessages
|
|
56
|
-
import {
|
|
65
|
+
import { formatResponseMessages } from "./response.ts";
|
|
66
|
+
import { recoverNativeClose, withNativeAccounting } from "./metering/native/durability.ts";
|
|
67
|
+
import { MeteringEngine, type CloseOperationInput, type OpenDetachedOperation, type OpenOperation } from "./metering/engine.ts";
|
|
57
68
|
import {
|
|
58
69
|
AgentSessionHandoffError,
|
|
59
|
-
AgentSessionOperationError,
|
|
60
70
|
type AgentSessionMeteringSnapshot,
|
|
61
71
|
type MeteredOperationKind,
|
|
62
72
|
type MeteringConfig,
|
|
@@ -85,16 +95,12 @@ import type {
|
|
|
85
95
|
Attachment,
|
|
86
96
|
PromptHandlers,
|
|
87
97
|
PromptResult,
|
|
88
|
-
PermissionOutcome,
|
|
89
|
-
PermissionRequest,
|
|
90
|
-
ResponseMessage,
|
|
91
98
|
SessionListEntry,
|
|
92
99
|
TokenUsage,
|
|
93
100
|
WireEntry,
|
|
94
101
|
} from "./types.ts";
|
|
95
102
|
import {
|
|
96
103
|
resolveDirectPersistence,
|
|
97
|
-
type AgentSessionPersistenceOptions,
|
|
98
104
|
type ResolvedAgentSessionPersistence,
|
|
99
105
|
} from "./persistence/config.ts";
|
|
100
106
|
import { resolveSessionLogPaths } from "./persistence/paths.ts";
|
|
@@ -111,9 +117,9 @@ import type {
|
|
|
111
117
|
InternalSessionHistoryEntry,
|
|
112
118
|
InternalSessionDescriptor,
|
|
113
119
|
TranscriptHeaderRecord,
|
|
114
|
-
OperationKind,
|
|
115
120
|
} from "./persistence/records.ts";
|
|
116
121
|
import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.ts";
|
|
122
|
+
import { MessageStatusTracker } from "./message-status.ts";
|
|
117
123
|
import {
|
|
118
124
|
RegistryPersistenceRuntime,
|
|
119
125
|
type PersistenceStateRuntime,
|
|
@@ -166,6 +172,8 @@ import type {
|
|
|
166
172
|
TranscriptContinuationBuilder,
|
|
167
173
|
TranscriptContinuationBuilderContext,
|
|
168
174
|
} from "./agent-conversation-contracts.ts";
|
|
175
|
+
import { withdrawBackendInput } from "./conversation-turns/backend-turns.ts";
|
|
176
|
+
import { captureStopFailure, dropClearedOperations } from "./conversation-turns/clear-operations.ts";
|
|
169
177
|
import { AgentConversationQueue } from "./agent-conversation-queue.ts";
|
|
170
178
|
import type { ImportedTurn } from "./agent/adoption/replay.ts";
|
|
171
179
|
import {
|
|
@@ -174,11 +182,9 @@ import {
|
|
|
174
182
|
type PendingMessageId,
|
|
175
183
|
type PromptDelivery,
|
|
176
184
|
type PromptHandle,
|
|
177
|
-
type SteeringPrompt,
|
|
178
185
|
} from "./steering/index.ts";
|
|
179
186
|
import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
|
|
180
187
|
import {
|
|
181
|
-
HANDOFF_SUMMARY_PROMPT,
|
|
182
188
|
buildContinuationPrompt,
|
|
183
189
|
createContinuationReport,
|
|
184
190
|
descriptorFromCheckpoint,
|
|
@@ -186,44 +192,20 @@ import {
|
|
|
186
192
|
normalizeContinuationStrategies,
|
|
187
193
|
stageOpeningContinuation,
|
|
188
194
|
} from "./agent-conversation-continuation.ts";
|
|
189
|
-
import { attachmentParts } from "./media/acp.ts";
|
|
190
195
|
import {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
196
|
+
BackendTurns, checkTurnRun, reportBackendTurn, reportTurnTook, runBackendTurn, runTurn, sendToBackend, settleClearedBackendTurns, steerIntoRunningTurn, turnRunOf, withdrawWaiting,
|
|
197
|
+
type BackendTurnHost, type BackendTurnItem, type PromptQueueItem, type TurnContext, type TurnRunContext,
|
|
198
|
+
} from "./conversation-turns/index.ts";
|
|
199
|
+
import type { TurnCause, TurnEvent, TurnRun } from "./conversation-controller/contracts.ts";
|
|
200
|
+
import {
|
|
201
|
+
copyPromptResult,
|
|
202
|
+
persistenceOperationKind,
|
|
203
|
+
toPersistenceJsonValue,
|
|
204
|
+
snapshotConsumerMetadata,
|
|
205
|
+
} from "./conversation-turns/record-helpers.ts";
|
|
206
|
+
import { promptInputText, promptParts, type MessagePart, type ResolvedPart } from "./media/parts.ts";
|
|
198
207
|
import { redactMedia } from "./media/redact.ts";
|
|
199
208
|
|
|
200
|
-
/** The text of an object-form prompt: its leading text plus its text parts. */
|
|
201
|
-
function promptInputText(input: { readonly text?: string; readonly parts?: readonly MessagePart[] }): string {
|
|
202
|
-
return partsText(promptParts(input) ?? [{ kind: "text", text: input.text ?? "" }]);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** The older JSONL transcript has no media store: a message with parts keeps a line per part. */
|
|
206
|
-
function legacyTranscriptText(
|
|
207
|
-
text: string,
|
|
208
|
-
parts?: readonly MessagePart[],
|
|
209
|
-
attachments?: readonly Attachment[],
|
|
210
|
-
): string {
|
|
211
|
-
if (!parts && !attachments?.length) return text;
|
|
212
|
-
return transcriptParts([...(parts ?? [{ kind: "text", text }]), ...attachmentParts(attachments)]);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/** The older JSONL transcript's view of response messages, with a line per media part. */
|
|
216
|
-
function legacyTranscriptMessages(messages: readonly ResponseMessage[], text: string) {
|
|
217
|
-
const messageText = (message: ResponseMessage) => (message.parts ? transcriptParts(message.parts) : message.text);
|
|
218
|
-
return {
|
|
219
|
-
text: messages.some((message) => message.parts) ? messages.map(messageText).join("\n\n") : text,
|
|
220
|
-
messages: messages.map((message) => ({
|
|
221
|
-
...(message.messageId ? { messageId: message.messageId } : {}),
|
|
222
|
-
text: messageText(message),
|
|
223
|
-
})),
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
|
|
227
209
|
export {
|
|
228
210
|
AdapterMismatchError,
|
|
229
211
|
AgentSessionPromptBlockedError,
|
|
@@ -269,11 +251,6 @@ export type {
|
|
|
269
251
|
TranscriptContinuationBuilderContext,
|
|
270
252
|
} from "./agent-conversation-contracts.ts";
|
|
271
253
|
|
|
272
|
-
interface PromptQueueItem extends SteeringPrompt {
|
|
273
|
-
/** How this operation is classified in its metering record. */
|
|
274
|
-
operationKind: MeteredOperationKind;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
254
|
/** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
|
|
278
255
|
export interface AgentConversationPromptInput {
|
|
279
256
|
readonly text?: string;
|
|
@@ -283,6 +260,8 @@ export interface AgentConversationPromptInput {
|
|
|
283
260
|
readonly attachments?: Attachment[];
|
|
284
261
|
/** How this prompt waits if a turn is running. Defaults to the conversation's `busyDelivery`. */
|
|
285
262
|
readonly delivery?: PromptDelivery;
|
|
263
|
+
/** Awaited before dispatch with this prompt's message ID. A rejection prevents dispatch. */
|
|
264
|
+
readonly beforeDispatch?: (messageId: string) => Promise<void>;
|
|
286
265
|
}
|
|
287
266
|
|
|
288
267
|
export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
|
|
@@ -305,7 +284,7 @@ interface HandoffQueueItem {
|
|
|
305
284
|
* source until the seed confirms the target.
|
|
306
285
|
*/
|
|
307
286
|
interface InternalPromptTarget {
|
|
308
|
-
readonly controller:
|
|
287
|
+
readonly controller: ConversationController;
|
|
309
288
|
readonly metering: MeteringEngine;
|
|
310
289
|
readonly adapterId: string;
|
|
311
290
|
}
|
|
@@ -341,7 +320,7 @@ interface RecoveryResolutionQueueItem {
|
|
|
341
320
|
reject: (error: unknown) => void;
|
|
342
321
|
}
|
|
343
322
|
|
|
344
|
-
type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
|
|
323
|
+
type QueueItem = PromptQueueItem | BackendTurnItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
|
|
345
324
|
|
|
346
325
|
export interface AgentSessionOpenResult {
|
|
347
326
|
readonly session: AgentConversation;
|
|
@@ -352,112 +331,6 @@ export interface AgentSessionOpenResult {
|
|
|
352
331
|
readonly repairs: readonly PersistenceRepair[];
|
|
353
332
|
}
|
|
354
333
|
|
|
355
|
-
export interface AgentSessionConfig {
|
|
356
|
-
/** The resolved adapter this conversation talks to. */
|
|
357
|
-
adapter: Adapter;
|
|
358
|
-
/** Stable adapter id for the catalog/display (e.g. "codex"). */
|
|
359
|
-
adapterId: string;
|
|
360
|
-
/** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
|
|
361
|
-
mode?: AgentMode;
|
|
362
|
-
/** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
|
|
363
|
-
launcher?: AgentControllerConfig["launcher"];
|
|
364
|
-
/** @deprecated Use launcher. */
|
|
365
|
-
execPrefix?: string[];
|
|
366
|
-
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
367
|
-
env?: Record<string, string>;
|
|
368
|
-
cwd?: string;
|
|
369
|
-
/** Additional absolute directories declared to the provider. */
|
|
370
|
-
additionalDirectories?: string[];
|
|
371
|
-
/** Default MCP servers bound at session creation/switch, unless a call overrides them. */
|
|
372
|
-
mcpServers?: schema.McpServer[];
|
|
373
|
-
defaultPermission?: "approve" | "cancel";
|
|
374
|
-
/**
|
|
375
|
-
* How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
|
|
376
|
-
* the turn ends; `steer` delivers it at the next tool boundary. Default `steer`.
|
|
377
|
-
*/
|
|
378
|
-
busyDelivery?: PromptDelivery;
|
|
379
|
-
clientInfo?: { name: string; title?: string; version?: string };
|
|
380
|
-
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
381
|
-
clientCapabilities?: AgentControllerConfig["clientCapabilities"];
|
|
382
|
-
/** Client-side ACP implementations; their presence determines advertisement. */
|
|
383
|
-
clientHandlers?: AgentControllerConfig["clientHandlers"];
|
|
384
|
-
logger?: Logger;
|
|
385
|
-
/** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
|
|
386
|
-
wire?: (entry: WireEntry) => void;
|
|
387
|
-
/** Optional catalog. When present, the session records itself here. */
|
|
388
|
-
sessions?: SessionManager;
|
|
389
|
-
/** New v2 persistence. Direct sessions remain persistence-free when omitted. */
|
|
390
|
-
persistence?: false | AgentSessionPersistenceOptions;
|
|
391
|
-
/** Stable creation transaction/incarnation ID; required by direct v2 persistence. */
|
|
392
|
-
creationId?: string;
|
|
393
|
-
/**
|
|
394
|
-
* Absolute path to an append-only transcript file. This selects history storage only;
|
|
395
|
-
* file existence never selects the provider thread. Omitted means no transcript.
|
|
396
|
-
*/
|
|
397
|
-
transcriptPath?: string;
|
|
398
|
-
/**
|
|
399
|
-
* Directory for `<encoded-agentSessionId>.jsonl`. This selects history storage only;
|
|
400
|
-
* the directory is not a session catalog and is not scanned during creation.
|
|
401
|
-
*/
|
|
402
|
-
transcriptDir?: string;
|
|
403
|
-
/**
|
|
404
|
-
* Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
|
|
405
|
-
* lines. Off by default — it makes transcripts larger, and `readTranscript()` ignores
|
|
406
|
-
* them either way; read them with `readTranscriptLines()`.
|
|
407
|
-
*
|
|
408
|
-
* Lines are SETTLED records, not raw deltas: the session folds the delta stream and
|
|
409
|
-
* writes checkpoints (announced → input → settled), typically 2–3 lines per tool call
|
|
410
|
-
* instead of one per notification. Fold them back with `foldRecords()`, last-wins on
|
|
411
|
-
* `recordId`. `true` selects the defaults below.
|
|
412
|
-
*/
|
|
413
|
-
transcriptActivity?: boolean | TranscriptActivityConfig;
|
|
414
|
-
/** Stable logical identity. Minted if omitted; always available on the created object. */
|
|
415
|
-
agentSessionId?: string;
|
|
416
|
-
/** Provider-thread startup intent. Default `{ kind: "new" }`. */
|
|
417
|
-
providerSession?: ProviderSession;
|
|
418
|
-
/** Stale limits per operation kind (turns, internal inference, recap). */
|
|
419
|
-
operationLifecycle?: OperationLifecycleConfig;
|
|
420
|
-
/**
|
|
421
|
-
* Token/cost metering policy. Optional: omitting it selects best-effort enforcement
|
|
422
|
-
* with the pinned models.dev catalog and no restored state. Metering is not something a
|
|
423
|
-
* consumer must turn on merely to see protocol facts.
|
|
424
|
-
*/
|
|
425
|
-
metering?: MeteringConfig;
|
|
426
|
-
/**
|
|
427
|
-
* @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
|
|
428
|
-
* Retains the historical fallback-to-new behavior for compatibility.
|
|
429
|
-
*/
|
|
430
|
-
internalSessionId?: string;
|
|
431
|
-
title?: string;
|
|
432
|
-
/** Stable conversation identity when this runtime is owned by an Agent. */
|
|
433
|
-
agentConversationId?: AgentConversationId;
|
|
434
|
-
/** Stable owning agent identity. Omitted for detached compatibility conversations. */
|
|
435
|
-
ownerAgentSessionId?: AgentSessionId;
|
|
436
|
-
/** Other sides of this conversation. The owning agent is implied. */
|
|
437
|
-
participants?: readonly ParticipantRef[];
|
|
438
|
-
/** @internal Installed by AgentConversationManager. */
|
|
439
|
-
ownerLifecycle?: AgentConversationOwnerLifecycle;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
/** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
|
|
443
|
-
export interface AgentSessionOpenConfig extends Omit<
|
|
444
|
-
AgentSessionConfig,
|
|
445
|
-
| "agentSessionId"
|
|
446
|
-
| "creationId"
|
|
447
|
-
| "providerSession"
|
|
448
|
-
| "internalSessionId"
|
|
449
|
-
| "mode"
|
|
450
|
-
| "persistence"
|
|
451
|
-
| "sessions"
|
|
452
|
-
> {
|
|
453
|
-
/** Required for directory/default path resolution; exact-file inference is a later slice. */
|
|
454
|
-
agentSessionId: string;
|
|
455
|
-
persistence: AgentSessionPersistenceOptions;
|
|
456
|
-
/** Optional consumer copy must exactly match transcript authority in this first slice. */
|
|
457
|
-
checkpoint?: AgentSessionCheckpoint;
|
|
458
|
-
continuation?: OpenContinuationOptions;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
334
|
interface AgentSessionOpenBootstrap {
|
|
462
335
|
readonly transcript: PersistenceStateRuntime;
|
|
463
336
|
readonly transcriptPath: string;
|
|
@@ -488,13 +361,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
488
361
|
private _adapterId: string;
|
|
489
362
|
private activeAdapter: Adapter;
|
|
490
363
|
|
|
491
|
-
private controller:
|
|
364
|
+
private controller: ConversationController;
|
|
492
365
|
private readonly controllerDefaults: Omit<
|
|
493
366
|
AgentControllerConfig,
|
|
494
367
|
"adapter" | "adapterId" | "mode" | "sessionId" | "sessionLoadFailure"
|
|
495
|
-
>;
|
|
368
|
+
> & Pick<AgentConversationConfig, "native" | "isNativeAdapter" | "answersPermissions" | "permissionTimeoutMs">;
|
|
496
369
|
private detachControllerCommands: (() => void) | null = null;
|
|
497
370
|
private detachControllerUsage: (() => void) | null = null;
|
|
371
|
+
private detachControllerTurns: (() => void) | null = null;
|
|
372
|
+
/**
|
|
373
|
+
* Runs the session sent and whose turn is running or about to (registered before `send`, since
|
|
374
|
+
* a session-scheduled controller reports `turn_started` inside the call). Keyed by turn id.
|
|
375
|
+
*/
|
|
376
|
+
private readonly sentRuns = new Map<string, { readonly run: TurnRun; cause?: TurnCause }>();
|
|
377
|
+
/** Ids of the messages (queued prompts) the session accepted and has not settled yet. */
|
|
378
|
+
private readonly backendTurns = new BackendTurns();
|
|
379
|
+
private readonly messageStatus = new MessageStatusTracker((event) => this.emit(event));
|
|
380
|
+
private readonly acceptedMessages = new Map<string, { readonly order: number; dispatched: boolean }>();
|
|
381
|
+
private acceptedMessageCount = 0;
|
|
498
382
|
private readonly sessions?: SessionManager;
|
|
499
383
|
private readonly _transcriptPath?: string;
|
|
500
384
|
private readonly persistence: false | ResolvedAgentSessionPersistence;
|
|
@@ -509,7 +393,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
509
393
|
private stopPromise: Promise<void> | null = null;
|
|
510
394
|
private phase: AgentSessionPhase = "idle";
|
|
511
395
|
private notificationSeq = 0;
|
|
512
|
-
private readonly listeners = new
|
|
396
|
+
private readonly listeners = new SubscriptionHub<AgentSessionNotification>(({ event, error }) =>
|
|
397
|
+
this.log.warn("agent_session_listener_failed", { kind: event.event.kind, error: String(error) }));
|
|
513
398
|
private lastStateKey = "";
|
|
514
399
|
private _internalSessionId: string | null;
|
|
515
400
|
private providerAttachment: ProviderAttachmentState = Object.freeze({ kind: "absent" });
|
|
@@ -555,6 +440,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
555
440
|
private managedInitializationReported = false;
|
|
556
441
|
private readonly operationLifecycle: OperationLifecycleConfig;
|
|
557
442
|
private reconnecting = false;
|
|
443
|
+
private deferredProviderStart: boolean;
|
|
444
|
+
private connecting = 0;
|
|
445
|
+
private handoffTarget?: ConversationController;
|
|
558
446
|
private detachControllerConnection: (() => void) | null = null;
|
|
559
447
|
private activeSupervisor: OperationSupervisor | null = null;
|
|
560
448
|
/**
|
|
@@ -570,8 +458,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
570
458
|
private providerFailedTurnId: string | null = null;
|
|
571
459
|
private readonly ownerLifecycle?: AgentConversationOwnerLifecycle;
|
|
572
460
|
private _participants: ParticipantRef[];
|
|
461
|
+
private readonly permissions = new ConversationPermissions(event => this.emit(event), () => this.log, this, () => this.controllerDefaults);
|
|
573
462
|
private ownerRecordWrite: Promise<void> = Promise.resolve();
|
|
574
|
-
private readonly defaultPermission: "approve" | "cancel";
|
|
575
463
|
|
|
576
464
|
private constructor(
|
|
577
465
|
config: AgentSessionConfig,
|
|
@@ -622,7 +510,6 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
622
510
|
?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
|
|
623
511
|
this.operationLifecycle = config.operationLifecycle ?? {};
|
|
624
512
|
this.ownerLifecycle = config.ownerLifecycle;
|
|
625
|
-
this.defaultPermission = config.defaultPermission ?? "cancel";
|
|
626
513
|
this.steering = new SteeringController<QueueItem>(
|
|
627
514
|
{
|
|
628
515
|
queue: this.operations,
|
|
@@ -671,10 +558,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
671
558
|
this._cwd = config.cwd;
|
|
672
559
|
this._title = config.title;
|
|
673
560
|
this._internalSessionId = requestedInternalSessionId ?? null;
|
|
561
|
+
this.deferredProviderStart = config.deferProviderStart === true && this.ownerAgentSessionId !== undefined &&
|
|
562
|
+
!config.native && this._mode === "normal" && this.persistence === false;
|
|
674
563
|
this.meteringConfig = Object.freeze({ ...(config.metering ?? {}) });
|
|
675
564
|
this.metering = new MeteringEngine({
|
|
676
565
|
agentSessionId: this.agentSessionId,
|
|
677
566
|
adapterId: config.adapterId,
|
|
567
|
+
native: config.native !== undefined,
|
|
678
568
|
enforcement: config.metering?.enforcement ?? "best_effort",
|
|
679
569
|
// Absence selects the pinned catalog; `false` is how a consumer says "no rating".
|
|
680
570
|
pricing: config.metering?.pricing ?? createModelsDevResolver(),
|
|
@@ -682,22 +572,27 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
682
572
|
...(config.metering?.counterInterpretation
|
|
683
573
|
? { counterInterpretation: config.metering.counterInterpretation }
|
|
684
574
|
: {}),
|
|
685
|
-
...(config.metering?.inferenceSource
|
|
575
|
+
...(config.metering?.inferenceSource && !config.native
|
|
686
576
|
? { inferenceSource: config.metering.inferenceSource }
|
|
687
577
|
: {}),
|
|
688
578
|
// A thread we are about to create has counters starting at zero; one we load does
|
|
689
579
|
// not, and needs restored state to be attributable.
|
|
690
580
|
createdActiveThread: providerSession.kind === "new",
|
|
691
581
|
});
|
|
582
|
+
validatePermissionConsumerConfig(config);
|
|
692
583
|
this.controllerDefaults = {
|
|
584
|
+
answersPermissions: config.answersPermissions, permissionTimeoutMs: config.permissionTimeoutMs,
|
|
693
585
|
operationLifecycle: this.operationLifecycle,
|
|
586
|
+
isNativeAdapter: config.isNativeAdapter,
|
|
587
|
+
...(config.native ? { native: { ...config.native, idleStopWindowMs: config.idleStopWindowMs, onReminderEvent: event => this.emit(event) } } : {}),
|
|
694
588
|
launcher: config.launcher,
|
|
695
589
|
execPrefix: config.execPrefix,
|
|
696
590
|
env: config.env,
|
|
591
|
+
terminalEnv: config.terminalEnv,
|
|
697
592
|
cwd: config.cwd,
|
|
698
593
|
additionalDirectories: config.additionalDirectories,
|
|
699
594
|
mcpServers: config.mcpServers,
|
|
700
|
-
|
|
595
|
+
permissions: ownPermissions(config.permissions), permissionRule: config.permissionRule,
|
|
701
596
|
clientInfo: config.clientInfo,
|
|
702
597
|
clientCapabilities: config.clientCapabilities,
|
|
703
598
|
clientHandlers: config.clientHandlers,
|
|
@@ -714,6 +609,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
714
609
|
if (providerSession.kind === "load") this.sessionLoadFailure = providerSession.onFailure ?? "error";
|
|
715
610
|
this.controller = this.createController(config.adapter, config.adapterId, this._mode, {
|
|
716
611
|
sessionId: requestedInternalSessionId,
|
|
612
|
+
requireStartupSession: this.deferredProviderStart,
|
|
717
613
|
sessionLoadFailure: providerSession.kind === "load"
|
|
718
614
|
? providerSession.onFailure ?? "error"
|
|
719
615
|
: undefined,
|
|
@@ -728,9 +624,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
728
624
|
adapter: Adapter,
|
|
729
625
|
adapterId: string,
|
|
730
626
|
mode: AgentMode,
|
|
731
|
-
startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay"> = {},
|
|
732
|
-
):
|
|
733
|
-
return
|
|
627
|
+
startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay" | "requireStartupSession"> = {},
|
|
628
|
+
): ConversationController {
|
|
629
|
+
return createController({
|
|
734
630
|
...this.controllerDefaults,
|
|
735
631
|
adapter,
|
|
736
632
|
adapterId,
|
|
@@ -739,19 +635,60 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
739
635
|
});
|
|
740
636
|
}
|
|
741
637
|
|
|
742
|
-
private bindController(controller:
|
|
638
|
+
private bindController(controller: ConversationController): void {
|
|
743
639
|
this.detachControllerConnection?.();
|
|
744
640
|
this.detachControllerConnection = controller.subscribeConnection(() => this.emitStateIfChanged());
|
|
745
641
|
this.detachControllerCommands?.();
|
|
746
642
|
this.detachControllerUsage?.();
|
|
747
|
-
this.detachControllerCommands = controller.subscribeAvailableCommands((commands) => {
|
|
643
|
+
this.detachControllerCommands = controller.subscribeAvailableCommands?.((commands) => {
|
|
748
644
|
if (this.controller === controller) {
|
|
749
645
|
this.emit({ kind: "internal_session_commands_changed", commands });
|
|
750
646
|
}
|
|
751
|
-
});
|
|
647
|
+
}) ?? null;
|
|
752
648
|
this.detachControllerUsage = controller.subscribeUsageUpdate((update, sessionId) => {
|
|
753
649
|
if (this.controller === controller) this.applyUsageUpdate(update, sessionId);
|
|
754
650
|
});
|
|
651
|
+
this.detachControllerTurns?.();
|
|
652
|
+
this.detachControllerTurns = controller.subscribeTurns((event) => {
|
|
653
|
+
if (this.controller === controller) this.onControllerTurnEvent(controller, event);
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
private backendTurnHost(): BackendTurnHost {
|
|
658
|
+
const session = this;
|
|
659
|
+
return {
|
|
660
|
+
turns: this.backendTurns,
|
|
661
|
+
log: this.log,
|
|
662
|
+
markSent: (id) => { const message = this.acceptedMessages.get(id); if (message) message.dispatched = true; },
|
|
663
|
+
received: (id) => this.messageStatus.advance(id, "received"),
|
|
664
|
+
get stopped() { return session.stopPromise !== null; }, // `phase` is rewritten by each queue item
|
|
665
|
+
emit: (event) => this.emit(event),
|
|
666
|
+
enqueue: (item) => { this.operations.enqueue(item); this.emitStateIfChanged(); void this.pump(); },
|
|
667
|
+
run: (turn) => this.runPrompt(turn),
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
private onNativeWithdrawal(messageId: string): void {
|
|
672
|
+
if (!this.stopPromise) this.backendTurns.confirmWithdrawal(messageId, messages => this.steering.dropped(messages));
|
|
673
|
+
}
|
|
674
|
+
/** A turn the controller reports. The session announces it; completion stays the session's. */
|
|
675
|
+
private onControllerTurnEvent(controller: ConversationController, event: TurnEvent): void {
|
|
676
|
+
if (event.kind === "input_withdrawn") return this.onNativeWithdrawal(event.messageId);
|
|
677
|
+
if (event.kind === "items_receipt") { if (!this.stopPromise) this.emit(event); return; }
|
|
678
|
+
if (event.kind === "turn_took") {
|
|
679
|
+
const ids = event.cause.messageIds ?? [];
|
|
680
|
+
this.messageStatus.link(event.turnId, ids);
|
|
681
|
+
for (const id of ids) this.messageStatus.advance(id, "taken");
|
|
682
|
+
return reportTurnTook(this.backendTurnHost(), event);
|
|
683
|
+
}
|
|
684
|
+
if (!event.sentBySession) return reportBackendTurn(this.backendTurnHost(), controller, event);
|
|
685
|
+
const sent = this.sentRuns.get(event.turnId);
|
|
686
|
+
if (!sent) {
|
|
687
|
+
this.log.warn("controller_turn_unknown", { turnId: event.turnId });
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
sent.cause = event.cause;
|
|
691
|
+
this.emit({ kind: "turn_started", turnId: event.turnId, cause: event.cause });
|
|
755
692
|
}
|
|
756
693
|
|
|
757
694
|
private queueOwnedRecord(record: NewConversationRecord, parts?: readonly ResolvedPart[]): void {
|
|
@@ -766,14 +703,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
766
703
|
|
|
767
704
|
private async recordOwned(record: NewConversationRecord): Promise<void> {
|
|
768
705
|
if (!this.ownerLifecycle?.record) return;
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
.catch((error) => {
|
|
772
|
-
this.markManagedPersistenceUnhealthy();
|
|
773
|
-
throw error;
|
|
774
|
-
});
|
|
775
|
-
this.ownerRecordWrite = write;
|
|
776
|
-
await write;
|
|
706
|
+
this.queueOwnedRecord(record);
|
|
707
|
+
await this.ownerRecordWrite;
|
|
777
708
|
}
|
|
778
709
|
|
|
779
710
|
private markManagedPersistenceUnhealthy(): void {
|
|
@@ -839,7 +770,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
839
770
|
});
|
|
840
771
|
}
|
|
841
772
|
|
|
842
|
-
private reportManagedControllerProgress(event:
|
|
773
|
+
private reportManagedControllerProgress(event: ControllerStartEvent): void {
|
|
843
774
|
if (!this.managedOpenProgress) return;
|
|
844
775
|
// A continuation policy may restart the same adapter after a failed load. The
|
|
845
776
|
// managed lifecycle reports capability discovery once, while the successful
|
|
@@ -864,7 +795,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
864
795
|
}
|
|
865
796
|
const session = new AgentConversation(config);
|
|
866
797
|
try {
|
|
867
|
-
await session.start();
|
|
798
|
+
await withStartupCancellation(config.signal, () => session.stop(), () => session.start());
|
|
868
799
|
return session;
|
|
869
800
|
} catch (error) {
|
|
870
801
|
await session.stop().catch(() => {});
|
|
@@ -886,7 +817,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
886
817
|
throw error;
|
|
887
818
|
}
|
|
888
819
|
try {
|
|
889
|
-
await session.start();
|
|
820
|
+
await withStartupCancellation(config.signal, () => session.stop(), () => session.start());
|
|
890
821
|
return session;
|
|
891
822
|
} catch (error) {
|
|
892
823
|
await session.stop().catch(() => undefined);
|
|
@@ -954,7 +885,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
954
885
|
session.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
|
|
955
886
|
session.managedAuditLog = audit?.identity ?? null;
|
|
956
887
|
try {
|
|
957
|
-
const result = await session.
|
|
888
|
+
const result = await withStartupCancellation(config.signal, () => session.stop(), () => session.startController());
|
|
958
889
|
if (!result.resumed || !result.sessionId) {
|
|
959
890
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
960
891
|
}
|
|
@@ -1058,22 +989,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1058
989
|
session.managedAuditLog = audit?.identity ?? null;
|
|
1059
990
|
|
|
1060
991
|
try {
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
992
|
+
return await withStartupCancellation(config.signal, () => session.stop(), async () => {
|
|
993
|
+
const continuation = await session.acquireOpeningContinuation(checkpoint, strategies);
|
|
994
|
+
if (continuation.outcome.kind === "unavailable") {
|
|
995
|
+
throw new ContinuationUnavailableError(continuation);
|
|
996
|
+
}
|
|
997
|
+
const configuration = continuation.outcome.kind === "loaded"
|
|
998
|
+
? await session.restoreOpeningConfiguration()
|
|
999
|
+
: session._configurationRestore;
|
|
1000
|
+
session._configurationRestore = configuration;
|
|
1001
|
+
session.emitStateIfChanged();
|
|
1002
|
+
return Object.freeze({
|
|
1003
|
+
session,
|
|
1004
|
+
continuation,
|
|
1005
|
+
recovery: structuredClone(session._recovery),
|
|
1006
|
+
configuration: structuredClone(configuration),
|
|
1007
|
+
promptability: session.promptability,
|
|
1008
|
+
repairs: transcript.openingRepairs,
|
|
1009
|
+
});
|
|
1077
1010
|
});
|
|
1078
1011
|
} catch (error) {
|
|
1079
1012
|
await session.stop().catch(() => undefined);
|
|
@@ -1085,12 +1018,37 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1085
1018
|
}
|
|
1086
1019
|
}
|
|
1087
1020
|
|
|
1021
|
+
private async connectProvider<T>(connect: () => Promise<T>): Promise<T> {
|
|
1022
|
+
this.assertConnectionOpen();
|
|
1023
|
+
this.connecting++;
|
|
1024
|
+
try {
|
|
1025
|
+
const result = await connect();
|
|
1026
|
+
this.assertConnectionOpen();
|
|
1027
|
+
return result;
|
|
1028
|
+
} finally {
|
|
1029
|
+
this.connecting--;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
private assertConnectionOpen(): void {
|
|
1034
|
+
if (this.phase === "stopped") throw new ConnectionCancelledError();
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
private startController(fresh = false): Promise<ConnectResult> {
|
|
1038
|
+
const progress = (event: ControllerStartEvent) => this.reportManagedControllerProgress(event);
|
|
1039
|
+
return this.connectProvider(() => fresh ? this.controller.startFresh(progress) : this.controller.start(progress));
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1088
1042
|
private async start(): Promise<void> {
|
|
1089
1043
|
if (this.persistence !== false) {
|
|
1090
1044
|
await this.startPersistent();
|
|
1091
1045
|
return;
|
|
1092
1046
|
}
|
|
1093
|
-
|
|
1047
|
+
if (this.deferredProviderStart) {
|
|
1048
|
+
if (this._internalSessionId) this.installProviderAttachment(this._internalSessionId, "recorded", false);
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const result = await this.startController();
|
|
1094
1052
|
// A resumed thread's counters did not start at zero, so it needs restored state to
|
|
1095
1053
|
// be attributable.
|
|
1096
1054
|
const internalSessionId = result.sessionId || this._internalSessionId;
|
|
@@ -1123,7 +1081,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1123
1081
|
this.v2Transcript = this.openBootstrap.transcript;
|
|
1124
1082
|
this.v2TranscriptPath = this.openBootstrap.transcriptPath;
|
|
1125
1083
|
this._recovery = this.v2Transcript.recovery;
|
|
1126
|
-
const result = await this.
|
|
1084
|
+
const result = await this.startController();
|
|
1127
1085
|
if (!result.resumed || !result.sessionId) {
|
|
1128
1086
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
1129
1087
|
}
|
|
@@ -1161,7 +1119,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1161
1119
|
}
|
|
1162
1120
|
if (!paths.transcriptPath || persistence.transcript === false) {
|
|
1163
1121
|
try {
|
|
1164
|
-
const result = await this.
|
|
1122
|
+
const result = await this.startController();
|
|
1165
1123
|
this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
|
|
1166
1124
|
if (this.managedCreation) {
|
|
1167
1125
|
const now = new Date().toISOString();
|
|
@@ -1177,7 +1135,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1177
1135
|
policy: persistence.sessionConfiguration,
|
|
1178
1136
|
observedAt: now,
|
|
1179
1137
|
}),
|
|
1180
|
-
protocol: this.controller
|
|
1138
|
+
protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
|
|
1181
1139
|
};
|
|
1182
1140
|
const staged = await this.managedCreation.stageContinuation(observed);
|
|
1183
1141
|
const primary = new RegistryPersistenceRuntime(createAgentSessionCheckpoint({
|
|
@@ -1232,7 +1190,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1232
1190
|
header,
|
|
1233
1191
|
writerLock: this.managedCreation?.transcriptLock,
|
|
1234
1192
|
initializeCheckpoint: async () => {
|
|
1235
|
-
const result = await this.
|
|
1193
|
+
const result = await this.startController();
|
|
1236
1194
|
this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
|
|
1237
1195
|
if (this._internalSessionId) {
|
|
1238
1196
|
this.installProviderAttachment(
|
|
@@ -1255,7 +1213,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1255
1213
|
internalSessionActivatedAt: this._internalSessionId ? now : null,
|
|
1256
1214
|
model: this.model,
|
|
1257
1215
|
sessionConfiguration,
|
|
1258
|
-
protocol: this.controller
|
|
1216
|
+
protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
|
|
1259
1217
|
};
|
|
1260
1218
|
const stagedContinuation = this.managedCreation
|
|
1261
1219
|
? await this.managedCreation.stageContinuation(observedContinuation)
|
|
@@ -1363,14 +1321,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1363
1321
|
continue;
|
|
1364
1322
|
}
|
|
1365
1323
|
try {
|
|
1366
|
-
const loaded = await this.
|
|
1324
|
+
const loaded = await this.startController();
|
|
1367
1325
|
if (!loaded.resumed || !loaded.sessionId) {
|
|
1368
1326
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
1369
1327
|
}
|
|
1370
1328
|
if (loaded.sessionId !== checkpoint.internalSessionId) {
|
|
1371
1329
|
throw new Error("adapter loaded a different internal session than requested");
|
|
1372
1330
|
}
|
|
1373
|
-
this._mode = this.controller.currentMode;
|
|
1331
|
+
this._mode = this.controller.currentMode ?? this._mode;
|
|
1374
1332
|
this.installProviderAttachment(loaded.sessionId, "recorded", false);
|
|
1375
1333
|
await stageOpeningContinuation(
|
|
1376
1334
|
this.openBootstrap.stageContinuation,
|
|
@@ -1385,6 +1343,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1385
1343
|
activeInternalSessionId: loaded.sessionId,
|
|
1386
1344
|
});
|
|
1387
1345
|
} catch (error) {
|
|
1346
|
+
if (error instanceof ConnectionCancelledError) throw error;
|
|
1388
1347
|
recordedThreadAvailability = "unavailable";
|
|
1389
1348
|
attempts.push(Object.freeze({
|
|
1390
1349
|
strategy: strategy.kind,
|
|
@@ -1445,7 +1404,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1445
1404
|
reasonCode: "continuation_reconstruction",
|
|
1446
1405
|
});
|
|
1447
1406
|
try {
|
|
1448
|
-
const created = await this.
|
|
1407
|
+
const created = await this.startController(true);
|
|
1449
1408
|
if (!created.sessionId) throw new Error("harness returned no session id for reconstructed continuation");
|
|
1450
1409
|
if (created.sessionId === checkpoint.internalSessionId && checkpoint.adapterId === this.adapterId) {
|
|
1451
1410
|
throw new Error("harness did not create a replacement internal session");
|
|
@@ -1560,6 +1519,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1560
1519
|
}).catch((persistenceError) => {
|
|
1561
1520
|
this.log.warn("continuation_failure_transcript_failed", { error: String(persistenceError) });
|
|
1562
1521
|
});
|
|
1522
|
+
if (error instanceof ConnectionCancelledError) throw error;
|
|
1563
1523
|
attempts.push(Object.freeze({
|
|
1564
1524
|
strategy: strategy.kind,
|
|
1565
1525
|
status: "failed",
|
|
@@ -1576,13 +1536,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1576
1536
|
// Nothing was ever selected to continue, so there is nothing a reconstruction could
|
|
1577
1537
|
// rebuild from. Starting fresh is the whole continuation, and the new thread stays
|
|
1578
1538
|
// runtime-only until a completed turn earns it a place in the checkpoint.
|
|
1579
|
-
const created = await this.
|
|
1580
|
-
(event) => this.reportManagedControllerProgress(event),
|
|
1581
|
-
);
|
|
1539
|
+
const created = await this.startController(true);
|
|
1582
1540
|
if (!created.sessionId) {
|
|
1583
1541
|
throw new Error("harness returned no session id for an unattached conversation");
|
|
1584
1542
|
}
|
|
1585
|
-
this._mode = this.controller.currentMode;
|
|
1543
|
+
this._mode = this.controller.currentMode ?? this._mode;
|
|
1586
1544
|
this.installProviderAttachment(created.sessionId, "runtime_only", true);
|
|
1587
1545
|
this._configurationRestore = this.snapshotReconstructedConfiguration([]).status;
|
|
1588
1546
|
this.continuationAcquired = true;
|
|
@@ -1890,13 +1848,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1890
1848
|
}
|
|
1891
1849
|
/** Subscribe to future lifecycle changes. The current snapshot is available via state. */
|
|
1892
1850
|
subscribe(listener: AgentSessionListener): () => void {
|
|
1893
|
-
this.listeners.
|
|
1894
|
-
|
|
1851
|
+
return this.listeners.subscribe(listener);
|
|
1852
|
+
}
|
|
1853
|
+
/** Answer an open event-driven permission request. */
|
|
1854
|
+
answerPermission(id: string, optionId: string): Promise<{ accepted: boolean }> {
|
|
1855
|
+
return this.permissions.answer(id, optionId);
|
|
1895
1856
|
}
|
|
1896
1857
|
/** Escape hatch to the live control plane (config, caps, getCommands, login, …). */
|
|
1897
|
-
get connection():
|
|
1858
|
+
get connection(): ConversationController {
|
|
1898
1859
|
return this.controller;
|
|
1899
1860
|
}
|
|
1861
|
+
/** The live controller as a `HarnessController` (an external harness over ACP or a PTY), or null for any other backend. */
|
|
1862
|
+
harnessConnection(): HarnessController | null { return harnessControllerOf(this.controller); }
|
|
1900
1863
|
|
|
1901
1864
|
// --- AgentClient -------------------------------------------------------------
|
|
1902
1865
|
prompt(input: AgentConversationPromptInput): PromptHandle;
|
|
@@ -1914,7 +1877,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1914
1877
|
? this.enqueuePrompt(input, "prompt", handlers, attachments)
|
|
1915
1878
|
: this.enqueuePrompt(
|
|
1916
1879
|
promptInputText(input), "prompt", input.handlers, input.attachments,
|
|
1917
|
-
undefined, input.consumerMetadata, input.delivery, promptParts(input),
|
|
1880
|
+
undefined, input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
|
|
1918
1881
|
);
|
|
1919
1882
|
}
|
|
1920
1883
|
|
|
@@ -1925,7 +1888,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1925
1888
|
|
|
1926
1889
|
/** Take back a message that has not been sent yet. Returns whether it was still pending. */
|
|
1927
1890
|
withdraw(id: PendingMessageId): boolean {
|
|
1928
|
-
return this.steering.withdraw(id)
|
|
1891
|
+
return this.steering.withdraw(id) || (this.controller.withdrawInput !== undefined &&
|
|
1892
|
+
this.backendTurns.withdrawable(id) === "local" && this.backendTurns.confirmWithdrawal(id, messages => this.steering.dropped(messages)));
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
/** Also requests confirmed withdrawal of a native input already submitted. */
|
|
1896
|
+
async withdrawAsync(id: PendingMessageId): Promise<boolean> {
|
|
1897
|
+
return this.withdraw(id) || withdrawBackendInput(this.backendTurns, this.controller, id, messages => this.steering.dropped(messages), () => !this.stopPromise);
|
|
1929
1898
|
}
|
|
1930
1899
|
|
|
1931
1900
|
/** Prompt while attributing the caller to a stable participant identity. */
|
|
@@ -1946,7 +1915,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1946
1915
|
if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
|
|
1947
1916
|
return this.enqueuePrompt(
|
|
1948
1917
|
promptInputText(input), "prompt", input.handlers, input.attachments,
|
|
1949
|
-
input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input),
|
|
1918
|
+
input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
|
|
1950
1919
|
);
|
|
1951
1920
|
}
|
|
1952
1921
|
const participantId = input;
|
|
@@ -1957,7 +1926,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1957
1926
|
private rejectedPrompt(error: Error): PromptHandle {
|
|
1958
1927
|
const id = this.mintTurnId();
|
|
1959
1928
|
const rejected = Promise.reject<AgentSessionPromptResult>(error);
|
|
1960
|
-
return Object.assign(rejected, { id, withdraw: () => false });
|
|
1929
|
+
return Object.assign(rejected, { id, status: "failed" as const, withdraw: () => false, withdrawAsync: async () => false });
|
|
1961
1930
|
}
|
|
1962
1931
|
|
|
1963
1932
|
private enqueuePrompt(
|
|
@@ -1969,6 +1938,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1969
1938
|
consumerMetadata?: PersistenceJsonValue,
|
|
1970
1939
|
delivery?: PromptDelivery,
|
|
1971
1940
|
messageParts?: readonly MessagePart[],
|
|
1941
|
+
beforeDispatch?: AgentConversationPromptInput["beforeDispatch"],
|
|
1972
1942
|
): PromptHandle {
|
|
1973
1943
|
const id = this.mintTurnId();
|
|
1974
1944
|
const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
|
|
@@ -1979,14 +1949,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1979
1949
|
let stableConsumerMetadata: PersistenceJsonValue | undefined;
|
|
1980
1950
|
try {
|
|
1981
1951
|
this.assertPromptable();
|
|
1982
|
-
|
|
1983
|
-
throw new Error("consumerMetadata requires an Agent-owned conversation");
|
|
1984
|
-
}
|
|
1985
|
-
if (consumerMetadata !== undefined) {
|
|
1986
|
-
const serialized = JSON.stringify(consumerMetadata);
|
|
1987
|
-
if (serialized === undefined) throw new Error("consumerMetadata must be a JSON value");
|
|
1988
|
-
stableConsumerMetadata = JSON.parse(serialized) as PersistenceJsonValue;
|
|
1989
|
-
}
|
|
1952
|
+
stableConsumerMetadata = snapshotConsumerMetadata(consumerMetadata, Boolean(this.ownerLifecycle));
|
|
1990
1953
|
} catch (error) {
|
|
1991
1954
|
reject(error);
|
|
1992
1955
|
return;
|
|
@@ -2005,15 +1968,30 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2005
1968
|
handlers,
|
|
2006
1969
|
attachments,
|
|
2007
1970
|
messageParts,
|
|
2008
|
-
|
|
2009
|
-
|
|
1971
|
+
beforeDispatch,
|
|
1972
|
+
resolve: (result) => {
|
|
1973
|
+
this.acceptedMessages.delete(id);
|
|
1974
|
+
// Settled as cancelled before any turn took it: withdrawn (the tracker ignores it once taken).
|
|
1975
|
+
if (result.status === "cancelled") this.messageStatus.end(id, "withdrawn");
|
|
1976
|
+
resolve(result);
|
|
1977
|
+
},
|
|
1978
|
+
reject: (error) => {
|
|
1979
|
+
this.acceptedMessages.delete(id);
|
|
1980
|
+
this.messageStatus.end(id, "failed");
|
|
1981
|
+
reject(error);
|
|
1982
|
+
},
|
|
2010
1983
|
};
|
|
1984
|
+
this.acceptedMessages.set(id, { order: ++this.acceptedMessageCount, dispatched: false });
|
|
1985
|
+
this.messageStatus.accept(id);
|
|
1986
|
+
if (steerIntoRunningTurn(this.backendTurnHost(), this.controller, item)) return;
|
|
2011
1987
|
this.operations.enqueue(item);
|
|
2012
1988
|
this.steering.accepted(item);
|
|
2013
1989
|
this.emitStateIfChanged();
|
|
2014
1990
|
void this.pump();
|
|
2015
1991
|
});
|
|
2016
|
-
|
|
1992
|
+
const handle = Object.assign(promise, { id, withdraw: () => this.withdraw(id) || (!this.controller.withdrawInput && withdrawWaiting(this.backendTurns, id, messages => this.steering.dropped(messages))), withdrawAsync: () => this.withdrawAsync(id) });
|
|
1993
|
+
const statusOf = this.messageStatus;
|
|
1994
|
+
return Object.defineProperty(handle, "status", { get: () => statusOf.statusOf(id) ?? "failed", enumerable: true }) as PromptHandle;
|
|
2017
1995
|
}
|
|
2018
1996
|
|
|
2019
1997
|
/**
|
|
@@ -2254,7 +2232,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2254
2232
|
if (this.operations.isDraining) return;
|
|
2255
2233
|
try {
|
|
2256
2234
|
await this.operations.drain(async (item) => {
|
|
2257
|
-
this.phase = item.kind === "prompt"
|
|
2235
|
+
this.phase = item.kind === "prompt" || item.kind === "backend_turn"
|
|
2258
2236
|
? "prompting"
|
|
2259
2237
|
: item.kind === "handoff"
|
|
2260
2238
|
? "handoff"
|
|
@@ -2264,12 +2242,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2264
2242
|
? "recovering"
|
|
2265
2243
|
: "switching_mode";
|
|
2266
2244
|
this.emitStateIfChanged();
|
|
2267
|
-
this.runningOperationId = item.kind === "prompt" ? item.turnId
|
|
2245
|
+
this.runningOperationId = item.kind === "prompt" || item.kind === "backend_turn" ? item.turnId
|
|
2268
2246
|
: item.kind === "handoff" ? item.handoffId
|
|
2269
2247
|
: item.kind === "set_config" ? item.operationId
|
|
2270
2248
|
: item.kind === "set_mode" ? item.transitionId
|
|
2271
2249
|
: null;
|
|
2272
|
-
if (item.kind === "prompt") {
|
|
2250
|
+
if (item.kind === "prompt" && this.controller.conversationCapabilities.nativeSteering) {
|
|
2251
|
+
// Backend-scheduled: the session never combines or cancels to steer; the message settles with the turn that takes it.
|
|
2252
|
+
const message = this.steering.prepareRun({ ...item, delivery: "queue" }) as PromptQueueItem;
|
|
2253
|
+
this.backendTurnHost().markSent(message.turnId);
|
|
2254
|
+
await sendToBackend(this.backendTurnHost(), this.controller, message);
|
|
2255
|
+
} else if (item.kind === "prompt") {
|
|
2273
2256
|
// A run of steer messages at the head of the queue goes out as one prompt.
|
|
2274
2257
|
let reportDelivery: (() => void) | undefined;
|
|
2275
2258
|
const prompt = this.steering.prepareRun(item, (event) => {
|
|
@@ -2277,12 +2260,46 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2277
2260
|
}) as PromptQueueItem;
|
|
2278
2261
|
this.runningOperationId = prompt.turnId;
|
|
2279
2262
|
this.steering.turnStarted(prompt);
|
|
2280
|
-
|
|
2263
|
+
const run = turnRunOf(prompt);
|
|
2264
|
+
const controller = this.controller;
|
|
2281
2265
|
let stopReason: string | undefined;
|
|
2266
|
+
/** This turn's provider readiness while it is still running (null once settled). */
|
|
2267
|
+
let readiness: Promise<void> | null = null;
|
|
2282
2268
|
try {
|
|
2283
|
-
|
|
2269
|
+
// Checked against the session's own message state, independent of how the run was
|
|
2270
|
+
// built: each id a message it accepted and has not settled, taken out of the queue,
|
|
2271
|
+
// in no other run, in queue (acceptance) order, the turn id being the first.
|
|
2272
|
+
const queued = new Set(this.operations.snapshot().flatMap((queuedItem) =>
|
|
2273
|
+
queuedItem.kind === "prompt" ? [queuedItem.turnId] : []));
|
|
2274
|
+
checkTurnRun(run, (id) => {
|
|
2275
|
+
const message = this.acceptedMessages.get(id);
|
|
2276
|
+
return message && { ...message, queued: queued.has(id) };
|
|
2277
|
+
});
|
|
2278
|
+
for (const id of run.messageIds) this.acceptedMessages.get(id)!.dispatched = true;
|
|
2279
|
+
// Registered before `send`: this controller reports `turn_started` inside the call, and
|
|
2280
|
+
// the session emits it then (with its cause), at the same moment as before.
|
|
2281
|
+
this.sentRuns.set(prompt.turnId, { run });
|
|
2282
|
+
const accepted = controller.send(run);
|
|
2283
|
+
// Observed now so a rejection is never unhandled; it is rethrown below, before dispatch.
|
|
2284
|
+
accepted.catch(() => undefined);
|
|
2285
|
+
let cause = this.sentRuns.get(prompt.turnId)?.cause;
|
|
2286
|
+
if (!cause) {
|
|
2287
|
+
// Not reported inside `send` (a backend-scheduled controller; Brief B2).
|
|
2288
|
+
await accepted;
|
|
2289
|
+
cause = this.sentRuns.get(prompt.turnId)?.cause;
|
|
2290
|
+
}
|
|
2291
|
+
if (!cause) throw new Error(`the controller did not report turn ${prompt.turnId}`);
|
|
2292
|
+
// Provider readiness starts at once after the report, as before the refactor: no
|
|
2293
|
+
// scheduling point between them. The acceptance must still hold before the turn is
|
|
2294
|
+
// dispatched, and a rejection is acted on at once, even while readiness is pending: the
|
|
2295
|
+
// turn fails (abandoned below, no completion). Readiness that is still running then is
|
|
2296
|
+
// waited for after the turn settles (below), so no second reconnect overlaps it.
|
|
2297
|
+
const ready = this.ensureProvider();
|
|
2298
|
+
const settled = ready.then(() => { readiness = null; }, () => { readiness = null; });
|
|
2299
|
+
readiness = settled;
|
|
2300
|
+
await Promise.all([ready, accepted]);
|
|
2284
2301
|
reportDelivery?.();
|
|
2285
|
-
const result = await this.runPrompt(prompt);
|
|
2302
|
+
const result = await this.runPrompt({ turnId: prompt.turnId, cause, messages: prompt });
|
|
2286
2303
|
stopReason = result.stopReason;
|
|
2287
2304
|
this.emit({
|
|
2288
2305
|
kind: "turn_completed",
|
|
@@ -2291,6 +2308,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2291
2308
|
});
|
|
2292
2309
|
prompt.resolve(result);
|
|
2293
2310
|
} catch (err) {
|
|
2311
|
+
// A turn that never reached its prepared turn's `prompt()` is released; for one that did,
|
|
2312
|
+
// this does nothing (abandonTurn is idempotent and never stops provider work).
|
|
2313
|
+
controller.abandonTurn(prompt.turnId, err);
|
|
2294
2314
|
// A prompt that never reached the provider (blocked, rejected, no provider) holds nothing.
|
|
2295
2315
|
const failure = err instanceof OperationStalledError ? "stalled" : "error";
|
|
2296
2316
|
const providerFailed = this.providerFailedTurnId === prompt.turnId;
|
|
@@ -2303,9 +2323,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2303
2323
|
this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
|
|
2304
2324
|
prompt.reject(err);
|
|
2305
2325
|
} finally {
|
|
2326
|
+
this.sentRuns.delete(prompt.turnId);
|
|
2306
2327
|
this.steering.turnEnded(stopReason);
|
|
2307
2328
|
this.providerFailedTurnId = null;
|
|
2308
2329
|
}
|
|
2330
|
+
// A turn that failed while its readiness was still running (a rejected acceptance during
|
|
2331
|
+
// a reconnect) has settled; the queue operation still waits for that readiness, as it
|
|
2332
|
+
// would have without the failure, so the next operation does not start a second one.
|
|
2333
|
+
// Bounded like any reconnect: by the provider answering or the process ending.
|
|
2334
|
+
if (readiness) await readiness;
|
|
2335
|
+
} else if (item.kind === "backend_turn") {
|
|
2336
|
+
await runBackendTurn(this.backendTurnHost(), this.controller, item);
|
|
2309
2337
|
} else if (item.kind === "handoff") {
|
|
2310
2338
|
try {
|
|
2311
2339
|
item.resolve(await this.runHandoff(item));
|
|
@@ -2438,10 +2466,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2438
2466
|
}
|
|
2439
2467
|
|
|
2440
2468
|
private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
|
|
2441
|
-
await this.ensureProvider();
|
|
2442
|
-
const fromInternalSessionId = this._internalSessionId;
|
|
2443
2469
|
const fromAdapterId = this.adapterId;
|
|
2444
2470
|
const targetAdapterId = item.options.target?.adapterId ?? fromAdapterId;
|
|
2471
|
+
const native = this.controllerDefaults.native !== undefined;
|
|
2472
|
+
if (native ? targetAdapterId !== fromAdapterId : this.controllerDefaults.isNativeAdapter?.(targetAdapterId)) {
|
|
2473
|
+
throw new UnsupportedError("switching to or from a native controller is unsupported");
|
|
2474
|
+
}
|
|
2475
|
+
if (targetAdapterId === fromAdapterId) requireFreshContext(this.controller, "a same-adapter handoff");
|
|
2476
|
+
await this.ensureProvider();
|
|
2477
|
+
const fromInternalSessionId = this._internalSessionId;
|
|
2445
2478
|
const targetMode = item.options.target?.mode ?? this._mode;
|
|
2446
2479
|
const continuation = normalizeHandoffContinuation(item.options);
|
|
2447
2480
|
const transitionKind = targetAdapterId === fromAdapterId ? "handoff" as const : "switch" as const;
|
|
@@ -2457,7 +2490,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2457
2490
|
let toDescriptor: InternalSessionDescriptor | undefined;
|
|
2458
2491
|
let summary: string | undefined;
|
|
2459
2492
|
let targetResult: PromptResult | undefined;
|
|
2460
|
-
let targetController:
|
|
2493
|
+
let targetController: ConversationController | null = null;
|
|
2461
2494
|
let resolvedTargetAdapter: Adapter | null = null;
|
|
2462
2495
|
let targetMetering: MeteringEngine | null = null;
|
|
2463
2496
|
let targetActivated = false;
|
|
@@ -2501,7 +2534,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2501
2534
|
}
|
|
2502
2535
|
|
|
2503
2536
|
try {
|
|
2504
|
-
if (continuation.kind !== "none" && this.controller
|
|
2537
|
+
if (continuation.kind !== "none" && isDegradedController(this.controller)) {
|
|
2505
2538
|
throw new Error("handoff continuation requires ACP (normal) mode");
|
|
2506
2539
|
}
|
|
2507
2540
|
|
|
@@ -2509,7 +2542,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2509
2542
|
// A supplied summary removes the generation operation entirely, so no
|
|
2510
2543
|
// `:summary` record is ever minted for it.
|
|
2511
2544
|
summary = continuation.content;
|
|
2512
|
-
} else if (continuation.kind === "generated") {
|
|
2545
|
+
} else if (continuation.kind === "generated" && this.controller.prepareInternalPrompt) {
|
|
2513
2546
|
const generated = await this.meteredInternalPrompt(
|
|
2514
2547
|
`${item.handoffId}:summary`,
|
|
2515
2548
|
"handoff_summary",
|
|
@@ -2543,7 +2576,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2543
2576
|
}
|
|
2544
2577
|
resolvedTargetAdapter = adapter;
|
|
2545
2578
|
targetController = this.createController(adapter, targetAdapterId, targetMode);
|
|
2546
|
-
const
|
|
2579
|
+
const candidate = this.handoffTarget = targetController;
|
|
2580
|
+
const created = await this.connectProvider(() => candidate.startFresh());
|
|
2547
2581
|
if (!created.sessionId) throw new Error("harness returned no session id for handoff");
|
|
2548
2582
|
toInternalSessionId = created.sessionId;
|
|
2549
2583
|
// A target naming the source's thread cannot supersede it: the provider mapping and
|
|
@@ -2681,6 +2715,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2681
2715
|
throw error;
|
|
2682
2716
|
}
|
|
2683
2717
|
|
|
2718
|
+
this.assertConnectionOpen();
|
|
2684
2719
|
const previousController = this.controller;
|
|
2685
2720
|
this.controller = targetController;
|
|
2686
2721
|
this.activeAdapter = resolvedTargetAdapter;
|
|
@@ -2833,6 +2868,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2833
2868
|
});
|
|
2834
2869
|
// A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
|
|
2835
2870
|
// already ran consumed real tokens; their records travel on the error.
|
|
2871
|
+
if (err instanceof ConnectionCancelledError && records.length === 0) throw err;
|
|
2836
2872
|
throw new AgentSessionHandoffError(item.handoffId, records, err, {
|
|
2837
2873
|
fromInternalSessionId,
|
|
2838
2874
|
...(toInternalSessionId ? { toInternalSessionId } : {}),
|
|
@@ -2841,6 +2877,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
2841
2877
|
...(summary !== undefined ? { summary } : {}),
|
|
2842
2878
|
...(targetResult ? { targetResult } : {}),
|
|
2843
2879
|
});
|
|
2880
|
+
} finally {
|
|
2881
|
+
this.handoffTarget = undefined;
|
|
2844
2882
|
}
|
|
2845
2883
|
}
|
|
2846
2884
|
|
|
@@ -3217,10 +3255,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3217
3255
|
|
|
3218
3256
|
private async runSetMode(item: ModeQueueItem): Promise<ConnectResult> {
|
|
3219
3257
|
await this.ensureProvider();
|
|
3220
|
-
if (item.mode === this._mode) return await this.controller
|
|
3258
|
+
if (item.mode === this._mode) return await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
|
|
3221
3259
|
if (!this.v2Transcript) {
|
|
3222
|
-
const result = await this.controller
|
|
3223
|
-
this._mode = this.controller.currentMode;
|
|
3260
|
+
const result = await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
|
|
3261
|
+
this._mode = this.controller.currentMode ?? this._mode;
|
|
3224
3262
|
const nextInternalSessionId = result.sessionId || null;
|
|
3225
3263
|
if (nextInternalSessionId) {
|
|
3226
3264
|
if (
|
|
@@ -3252,8 +3290,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3252
3290
|
reasonCode: "mode_change",
|
|
3253
3291
|
});
|
|
3254
3292
|
try {
|
|
3255
|
-
const result = await this.controller
|
|
3256
|
-
const targetMode = this.controller.currentMode;
|
|
3293
|
+
const result = await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
|
|
3294
|
+
const targetMode = this.controller.currentMode ?? item.mode;
|
|
3257
3295
|
const targetInternalSessionId = result.sessionId || null;
|
|
3258
3296
|
const transitionAt = new Date().toISOString();
|
|
3259
3297
|
to = this.v2Descriptor(targetInternalSessionId, transitionAt, targetMode);
|
|
@@ -3334,457 +3372,68 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3334
3372
|
}
|
|
3335
3373
|
}
|
|
3336
3374
|
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
const owned = this.ownerLifecycle
|
|
3342
|
-
? await this.ownerLifecycle.beforePrompt({
|
|
3343
|
-
operationId: item.turnId,
|
|
3344
|
-
agentSessionId: this.ownerAgentSessionId!,
|
|
3345
|
-
agentConversationId: this.agentConversationId,
|
|
3346
|
-
targetProviderContextId,
|
|
3347
|
-
...(item.participantId ? { participantId: item.participantId } : {}),
|
|
3348
|
-
...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
|
|
3349
|
-
...(item.parts ? { parts: item.parts } : {}),
|
|
3350
|
-
text: item.text,
|
|
3351
|
-
messageParts: item.messageParts,
|
|
3352
|
-
attachments: item.attachments,
|
|
3353
|
-
mediaContext: {
|
|
3354
|
-
cwd: this.controllerDefaults.cwd ?? process.cwd(),
|
|
3355
|
-
...(this.controller.isDegraded
|
|
3356
|
-
? { degraded: true }
|
|
3357
|
-
: { capabilities: this.controller.capabilities.agent.promptCapabilities }),
|
|
3358
|
-
},
|
|
3359
|
-
})
|
|
3360
|
-
: undefined;
|
|
3361
|
-
for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
|
|
3362
|
-
if (!this._participants.some((known) => known.id === participant.id)) {
|
|
3363
|
-
this._participants = [...this._participants, Object.freeze({ ...participant })];
|
|
3364
|
-
}
|
|
3365
|
-
}
|
|
3366
|
-
this.beginTurn(item.turnId);
|
|
3367
|
-
let operation: OpenOperation;
|
|
3368
|
-
if (this.v2Transcript) {
|
|
3369
|
-
let transcriptStarted = false;
|
|
3370
|
-
try {
|
|
3371
|
-
// Metering preflight has no provider side effect. Run it before minting durable
|
|
3372
|
-
// operation evidence so a strict pricing/policy rejection needs no abort record.
|
|
3373
|
-
operation = await this.openMeteredOperation(item);
|
|
3374
|
-
await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
|
|
3375
|
-
transcriptStarted = true;
|
|
3376
|
-
// A combined prompt shows each original message, as it was sent.
|
|
3377
|
-
const userTexts = item.parts
|
|
3378
|
-
? item.parts.map((part) => legacyTranscriptText(part.text, part.messageParts, part.attachments))
|
|
3379
|
-
: [legacyTranscriptText(item.text, item.messageParts, item.attachments)];
|
|
3380
|
-
const userRecords = [];
|
|
3381
|
-
for (const [index, text] of userTexts.entries()) {
|
|
3382
|
-
userRecords.push(await this.v2Transcript.appendPresentationEvent({
|
|
3383
|
-
kind: "message",
|
|
3384
|
-
operationId: item.turnId,
|
|
3385
|
-
role: "user",
|
|
3386
|
-
text,
|
|
3387
|
-
status: "completed",
|
|
3388
|
-
presentation: { id: `message:${item.turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
|
|
3389
|
-
}));
|
|
3390
|
-
}
|
|
3391
|
-
await this.v2Transcript.syncBeforeDispatch();
|
|
3392
|
-
for (const userRecord of userRecords) this.presentation.emitPersistedRecord(userRecord);
|
|
3393
|
-
} catch (error) {
|
|
3394
|
-
this.endTurn(item.turnId, item.handlers);
|
|
3395
|
-
if (transcriptStarted) {
|
|
3396
|
-
await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
|
|
3397
|
-
(abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
|
|
3398
|
-
);
|
|
3399
|
-
}
|
|
3400
|
-
throw error;
|
|
3401
|
-
}
|
|
3402
|
-
} else {
|
|
3403
|
-
await this.appendTranscript({
|
|
3404
|
-
v: 1,
|
|
3405
|
-
t: "msg",
|
|
3406
|
-
role: "user",
|
|
3407
|
-
text: legacyTranscriptText(item.text, item.messageParts, item.attachments),
|
|
3408
|
-
ts: Date.now(),
|
|
3409
|
-
});
|
|
3410
|
-
operation = await this.openMeteredOperation(item);
|
|
3411
|
-
}
|
|
3375
|
+
/** Runs one prompt turn; the turn itself lives in `src/conversation-turns/run-turn.ts`. */
|
|
3376
|
+
private runPrompt(turn: TurnContext): Promise<AgentSessionPromptResult> {
|
|
3377
|
+
return runTurn(this.turnRunContext(), turn);
|
|
3378
|
+
}
|
|
3412
3379
|
|
|
3413
|
-
|
|
3414
|
-
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
id: `message:${item.turnId}:assistant:${assistantOrdinal}`,
|
|
3428
|
-
...(providerMessageId === undefined ? {} : { providerMessageId }),
|
|
3429
|
-
text: "",
|
|
3430
|
-
revision: 0,
|
|
3431
|
-
dirty: false,
|
|
3432
|
-
};
|
|
3433
|
-
return assistantMessage;
|
|
3434
|
-
};
|
|
3435
|
-
// When each message that ended before the turn did received its last text, in order. The
|
|
3436
|
-
// turn's commit records those messages as completed at these times; only the last message
|
|
3437
|
-
// takes the turn's own outcome.
|
|
3438
|
-
const messageEnds: string[] = [];
|
|
3439
|
-
const flushAssistantMessage = (
|
|
3440
|
-
status: "in_progress" | "completed" | "cancelled" | "error",
|
|
3441
|
-
stopReason?: string,
|
|
3442
|
-
force = false,
|
|
3443
|
-
ended = false,
|
|
3444
|
-
) => {
|
|
3445
|
-
if ((!this.v2Transcript && !this.ownerLifecycle) || !assistantMessage
|
|
3446
|
-
|| (!assistantMessage.dirty && !force)) return;
|
|
3447
|
-
assistantMessage.revision++;
|
|
3448
|
-
assistantMessage.dirty = false;
|
|
3449
|
-
const message = assistantMessage;
|
|
3450
|
-
const timestamp = new Date().toISOString();
|
|
3451
|
-
if (ended) messageEnds.push(timestamp);
|
|
3452
|
-
if (this.ownerAgentSessionId && (status === "in_progress" || ended)) {
|
|
3453
|
-
this.queueOwnedRecord({
|
|
3454
|
-
recordId: `${message.id}:snapshot:${message.revision}`,
|
|
3455
|
-
agentSessionId: this.ownerAgentSessionId,
|
|
3456
|
-
agentConversationId: this.agentConversationId,
|
|
3457
|
-
kind: "message",
|
|
3458
|
-
timestamp,
|
|
3459
|
-
operationId: item.turnId,
|
|
3460
|
-
role: "assistant",
|
|
3461
|
-
logicalMessageId: message.id,
|
|
3462
|
-
content: message.text,
|
|
3463
|
-
status: ended ? "completed" : "in_progress",
|
|
3464
|
-
metadata: JSON.stringify({ operationId: item.turnId,
|
|
3465
|
-
...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
|
|
3466
|
-
}, message.parts);
|
|
3467
|
-
}
|
|
3468
|
-
if (this.v2Transcript) this.presentation.queuePresentation({
|
|
3469
|
-
kind: "message",
|
|
3470
|
-
operationId: item.turnId,
|
|
3471
|
-
role: "assistant",
|
|
3472
|
-
text: message.parts ? transcriptParts(message.parts) : message.text,
|
|
3473
|
-
...(message.providerMessageId === undefined ? {} : { providerMessageId: message.providerMessageId }),
|
|
3474
|
-
structured: {
|
|
3475
|
-
version: 1,
|
|
3476
|
-
messages: [message.providerMessageId === undefined
|
|
3477
|
-
? { text: message.text }
|
|
3478
|
-
: { messageId: message.providerMessageId, text: message.text }],
|
|
3479
|
-
},
|
|
3480
|
-
status,
|
|
3481
|
-
...(stopReason === undefined ? {} : { stopReason }),
|
|
3482
|
-
presentation: { id: message.id, revision: message.revision },
|
|
3483
|
-
});
|
|
3484
|
-
};
|
|
3485
|
-
// A message receives no more text once the next message or a tool call begins. Record it
|
|
3486
|
-
// completed then, rather than leaving it open until the turn ends.
|
|
3487
|
-
const endAssistantMessage = () => {
|
|
3488
|
-
flushAssistantMessage("completed", undefined, true, true);
|
|
3489
|
-
assistantMessage = null;
|
|
3490
|
-
};
|
|
3491
|
-
const wrappedHandlers: PromptHandlers = {
|
|
3492
|
-
...item.handlers,
|
|
3493
|
-
// Fired from here, from the one aggregator this session owns — nothing below needs
|
|
3494
|
-
// to know the handler exists, and two places firing it would be two folds.
|
|
3495
|
-
onRecord: undefined,
|
|
3496
|
-
onChunk: (chunk) => {
|
|
3497
|
-
chunks.push(chunk);
|
|
3498
|
-
item.handlers?.onChunk?.(chunk);
|
|
3380
|
+
/** What a turn reads and changes in this session (`TurnRunContext`), read live through getters. */
|
|
3381
|
+
private turnRunContext(): TurnRunContext {
|
|
3382
|
+
const session = this;
|
|
3383
|
+
return {
|
|
3384
|
+
log: this.log,
|
|
3385
|
+
get controller() { return session.controller; },
|
|
3386
|
+
supervisedPrompt: (controller, operationId, kind, provider) =>
|
|
3387
|
+
this.supervisedPrompt(controller, operationId, kind, provider),
|
|
3388
|
+
get supervising() { return session.activeSupervisor !== null; },
|
|
3389
|
+
persistence: {
|
|
3390
|
+
get v2Transcript() { return session.v2Transcript; },
|
|
3391
|
+
appendTranscript: (line) => this.appendTranscript(line),
|
|
3392
|
+
persist: () => this.persist(),
|
|
3393
|
+
finishV2Prompt: (status, record, errorCode) => this.finishV2Prompt(status, record, errorCode),
|
|
3499
3394
|
},
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
response.append(chunk);
|
|
3507
|
-
if (this.v2Transcript || this.ownerLifecycle) {
|
|
3508
|
-
if (chunk.startsMessage) {
|
|
3509
|
-
endAssistantMessage();
|
|
3510
|
-
beginAssistantMessage(chunk.messageId);
|
|
3511
|
-
}
|
|
3512
|
-
const current = assistantMessage ?? beginAssistantMessage(chunk.messageId);
|
|
3513
|
-
if (current.providerMessageId === undefined && chunk.messageId !== undefined) {
|
|
3514
|
-
current.providerMessageId = chunk.messageId;
|
|
3515
|
-
}
|
|
3516
|
-
current.text += chunk.text;
|
|
3517
|
-
current.parts = response.currentParts();
|
|
3518
|
-
current.dirty = true;
|
|
3519
|
-
// Persist the first usable snapshot. Later token chunks remain in memory until
|
|
3520
|
-
// an interleaving item, a new message, or the operation boundary.
|
|
3521
|
-
if (current.revision === 0) flushAssistantMessage("in_progress");
|
|
3522
|
-
}
|
|
3523
|
-
item.handlers?.onResponseChunk?.(chunk);
|
|
3395
|
+
permissions: this.permissions,
|
|
3396
|
+
presentation: this.presentation,
|
|
3397
|
+
metering: {
|
|
3398
|
+
open: (item) => this.openMeteredOperation(item),
|
|
3399
|
+
close: (operation, outcome, reportedCumulative, usageFailureReason, nativeMetering) =>
|
|
3400
|
+
this.closeOperation(operation, outcome, reportedCumulative, usageFailureReason, this.metering, nativeMetering),
|
|
3524
3401
|
},
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
|
|
3528
|
-
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
this.
|
|
3533
|
-
|
|
3534
|
-
item.handlers?.onActivity?.(event);
|
|
3402
|
+
steering: this.steering,
|
|
3403
|
+
owner: {
|
|
3404
|
+
get lifecycle() { return session.ownerLifecycle; },
|
|
3405
|
+
get agentSessionId() { return session.ownerAgentSessionId; },
|
|
3406
|
+
get agentConversationId() { return session.agentConversationId; },
|
|
3407
|
+
contextNonce: () => this.ownerContextNonce ??= crypto.randomUUID(),
|
|
3408
|
+
queueRecord: (record, parts) => this.queueOwnedRecord(record, parts),
|
|
3409
|
+
recordNow: (record) => this.recordOwned(record),
|
|
3410
|
+
get recordWrite() { return session.ownerRecordWrite; },
|
|
3535
3411
|
},
|
|
3536
|
-
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
recordId: `${permissionBase}:requested`,
|
|
3541
|
-
agentSessionId: this.ownerAgentSessionId,
|
|
3542
|
-
agentConversationId: this.agentConversationId,
|
|
3543
|
-
kind: "permission",
|
|
3544
|
-
timestamp: new Date().toISOString(),
|
|
3545
|
-
operationId: item.turnId,
|
|
3546
|
-
permissionId: request.toolCallId,
|
|
3547
|
-
state: "requested",
|
|
3548
|
-
request: toPersistenceJsonValue({
|
|
3549
|
-
toolCallId: request.toolCallId,
|
|
3550
|
-
...(request.title ? { title: request.title } : {}),
|
|
3551
|
-
options: request.options,
|
|
3552
|
-
raw: request.raw,
|
|
3553
|
-
}),
|
|
3554
|
-
});
|
|
3555
|
-
}
|
|
3556
|
-
const outcome = item.handlers?.onPermissionRequest
|
|
3557
|
-
? await permissionWithAbort(() => item.handlers!.onPermissionRequest!(request, signal), signal)
|
|
3558
|
-
: defaultPermissionOutcome(request, this.defaultPermission);
|
|
3559
|
-
if (this.ownerAgentSessionId) {
|
|
3560
|
-
await this.recordOwned({
|
|
3561
|
-
recordId: `${permissionBase}:resolved`,
|
|
3562
|
-
agentSessionId: this.ownerAgentSessionId,
|
|
3563
|
-
agentConversationId: this.agentConversationId,
|
|
3564
|
-
kind: "permission",
|
|
3565
|
-
timestamp: new Date().toISOString(),
|
|
3566
|
-
operationId: item.turnId,
|
|
3567
|
-
permissionId: request.toolCallId,
|
|
3568
|
-
state: "resolved",
|
|
3569
|
-
outcome: permissionRecordOutcome(request, outcome),
|
|
3570
|
-
});
|
|
3571
|
-
}
|
|
3572
|
-
return outcome;
|
|
3412
|
+
turn: {
|
|
3413
|
+
begin: (turnId) => this.beginTurn(turnId),
|
|
3414
|
+
end: (turnId, handlers) => this.endTurn(turnId, handlers),
|
|
3415
|
+
queueActivityRecords: (turnId, records) => this.queueActivityRecords(turnId, records),
|
|
3573
3416
|
},
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
// An owned conversation already resolved the parts and wrapped them with the provider-only
|
|
3585
|
-
// text (identity, out-of-band messages); otherwise the client resolves them.
|
|
3586
|
-
() => this.controller.prompt(owned?.providerParts
|
|
3587
|
-
? { parts: unresolvedParts(owned.providerParts), handlers: wrappedHandlers }
|
|
3588
|
-
: item.messageParts
|
|
3589
|
-
? { parts: item.messageParts, attachments: item.attachments, handlers: wrappedHandlers }
|
|
3590
|
-
: { text: item.text, attachments: item.attachments, handlers: wrappedHandlers }));
|
|
3591
|
-
if (res.cancel === "forced") {
|
|
3592
|
-
const messages = response.snapshot();
|
|
3593
|
-
res = { ...res, messages, text: response.text || chunks.join("") };
|
|
3594
|
-
}
|
|
3595
|
-
providerSettled = true;
|
|
3596
|
-
if (this.v2Transcript) {
|
|
3597
|
-
if (assistantOrdinal === 0) {
|
|
3598
|
-
for (const message of res.messages) {
|
|
3599
|
-
const current = beginAssistantMessage(message.messageId);
|
|
3600
|
-
current.text = message.text;
|
|
3601
|
-
current.dirty = true;
|
|
3602
|
-
flushAssistantMessage(res.status, res.stopReason, true);
|
|
3603
|
-
}
|
|
3604
|
-
} else {
|
|
3605
|
-
flushAssistantMessage(res.status, res.stopReason, true);
|
|
3606
|
-
}
|
|
3607
|
-
}
|
|
3608
|
-
// Before the assistant msg: `msg` delimits a turn, so anything still open has to
|
|
3609
|
-
// land inside those fences.
|
|
3610
|
-
this.endTurn(item.turnId, item.handlers);
|
|
3611
|
-
if (!this._title && item.text.trim()) {
|
|
3612
|
-
this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
|
3613
|
-
}
|
|
3614
|
-
// A session may have been created lazily on first prompt (degraded has none).
|
|
3615
|
-
const observedInternalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
|
|
3616
|
-
if (observedInternalSessionId) {
|
|
3617
|
-
if (
|
|
3618
|
-
this.providerAttachment.kind === "absent"
|
|
3619
|
-
|| this.providerAttachment.descriptor.internalSessionId !== observedInternalSessionId
|
|
3620
|
-
) {
|
|
3621
|
-
this.installProviderAttachment(observedInternalSessionId, "runtime_only", true, {
|
|
3622
|
-
acquiredAt: dispatchedAt,
|
|
3623
|
-
});
|
|
3624
|
-
}
|
|
3625
|
-
} else {
|
|
3626
|
-
this.setInternalSessionId(observedInternalSessionId);
|
|
3627
|
-
}
|
|
3628
|
-
// Metering closes BEFORE local persistence. The provider has already been paid and
|
|
3629
|
-
// has already told us what it charged; letting a transcript or catalog write failure
|
|
3630
|
-
// send us down the catch path would discard usage we are holding and, in a strict
|
|
3631
|
-
// mode, block the session over a local disk problem.
|
|
3632
|
-
//
|
|
3633
|
-
// `closed` then guards the catch path. Closing twice would accrue the operation
|
|
3634
|
-
// twice and emit a second record for it — double-counting tokens and cost, which is
|
|
3635
|
-
// a worse failure than the one closing early prevents.
|
|
3636
|
-
const record = await this.closeOperation(operation, res.status, res.usage);
|
|
3637
|
-
closed = record;
|
|
3638
|
-
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
3639
|
-
// The Agent-owned and transcript paths record the attachment inside their own
|
|
3640
|
-
// commit. A catalog-backed conversation has one mutable row, so the completed turn
|
|
3641
|
-
// is simply what makes the live thread the selected one.
|
|
3642
|
-
const pending = this.providerAttachment;
|
|
3643
|
-
if (res.status === "completed"
|
|
3644
|
-
&& !this.ownerLifecycle
|
|
3645
|
-
&& !this.v2Transcript
|
|
3646
|
-
&& pending.kind === "runtime_only") {
|
|
3647
|
-
this.providerAttachment = recordedProviderAttachment(pending.descriptor);
|
|
3648
|
-
this.lastRecordedInternalSessionId = pending.descriptor.internalSessionId;
|
|
3649
|
-
}
|
|
3650
|
-
await this.persist();
|
|
3651
|
-
if (this.v2Transcript) {
|
|
3652
|
-
await this.presentation.drain();
|
|
3653
|
-
await this.finishV2Prompt(res.status, record);
|
|
3654
|
-
transcriptClosed = true;
|
|
3655
|
-
} else {
|
|
3656
|
-
await this.appendTranscript({
|
|
3657
|
-
v: 1,
|
|
3658
|
-
t: "msg",
|
|
3659
|
-
role: "assistant",
|
|
3660
|
-
...legacyTranscriptMessages(res.messages, res.text),
|
|
3661
|
-
ts: Date.now(),
|
|
3662
|
-
usage: res.usage,
|
|
3663
|
-
stopReason: res.stopReason,
|
|
3664
|
-
status: res.status,
|
|
3665
|
-
});
|
|
3666
|
-
}
|
|
3667
|
-
const result = Object.freeze({
|
|
3668
|
-
...res,
|
|
3669
|
-
operationId: item.turnId,
|
|
3670
|
-
metering: record,
|
|
3671
|
-
...this.steering.resultFields(item.turnId, res.stopReason),
|
|
3672
|
-
});
|
|
3673
|
-
await this.ownerRecordWrite;
|
|
3674
|
-
if (this.ownerLifecycle) {
|
|
3675
|
-
const completed = {
|
|
3676
|
-
operationId: item.turnId,
|
|
3677
|
-
agentSessionId: this.ownerAgentSessionId!,
|
|
3678
|
-
agentConversationId: this.agentConversationId,
|
|
3679
|
-
targetProviderContextId,
|
|
3680
|
-
...(owned?.identityDeliveryReceipt
|
|
3681
|
-
? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
|
|
3682
|
-
: {}),
|
|
3683
|
-
...(item.participantId ? { participantId: item.participantId } : {}),
|
|
3684
|
-
text: item.text,
|
|
3685
|
-
result,
|
|
3686
|
-
messageEnds,
|
|
3687
|
-
providerAttachment: this.providerAttachment,
|
|
3688
|
-
};
|
|
3689
|
-
try {
|
|
3690
|
-
const committed = await this.ownerLifecycle.afterPrompt(completed);
|
|
3691
|
-
if (committed?.providerAttachment) {
|
|
3692
|
-
this.providerAttachment = acknowledgeProviderAttachment(
|
|
3693
|
-
this.providerAttachment,
|
|
3694
|
-
committed.providerAttachment,
|
|
3695
|
-
);
|
|
3417
|
+
session: {
|
|
3418
|
+
get cwd() { return session.controllerDefaults.cwd; },
|
|
3419
|
+
permissionPolicy: this.controllerDefaults,
|
|
3420
|
+
get internalSessionId() { return session._internalSessionId; },
|
|
3421
|
+
setInternalSessionId: (next) => this.setInternalSessionId(next),
|
|
3422
|
+
get title() { return session._title; },
|
|
3423
|
+
set title(value) { session._title = value; },
|
|
3424
|
+
learnParticipant: (participant) => {
|
|
3425
|
+
if (!this._participants.some((known) => known.id === participant.id)) {
|
|
3426
|
+
this._participants = [...this._participants, Object.freeze({ ...participant })];
|
|
3696
3427
|
}
|
|
3697
|
-
}
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
|
|
3705
|
-
|
|
3706
|
-
}
|
|
3707
|
-
throw error;
|
|
3708
|
-
}
|
|
3709
|
-
}
|
|
3710
|
-
await this.ownerRecordWrite;
|
|
3711
|
-
return result;
|
|
3712
|
-
} catch (err) {
|
|
3713
|
-
// Easy to miss, and the whole point of R4: a turn that died mid-tool still records
|
|
3714
|
-
// what it was doing, at its real status.
|
|
3715
|
-
this.endTurn(item.turnId, item.handlers);
|
|
3716
|
-
const structured = response.snapshot();
|
|
3717
|
-
const text = structured.length > 0 ? response.text : chunks.join("");
|
|
3718
|
-
const messages: readonly ResponseMessage[] = structured.length > 0
|
|
3719
|
-
? structured
|
|
3720
|
-
: text
|
|
3721
|
-
? Object.freeze([{ text }])
|
|
3722
|
-
: Object.freeze([]);
|
|
3723
|
-
if (!providerSettled) {
|
|
3724
|
-
await this.ownerRecordWrite.catch((persistenceError) => {
|
|
3725
|
-
this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
|
|
3726
|
-
});
|
|
3727
|
-
await this.ownerLifecycle?.promptFailed({
|
|
3728
|
-
operationId: item.turnId,
|
|
3729
|
-
agentSessionId: this.ownerAgentSessionId!,
|
|
3730
|
-
agentConversationId: this.agentConversationId,
|
|
3731
|
-
...(item.participantId ? { participantId: item.participantId } : {}),
|
|
3732
|
-
text: item.text,
|
|
3733
|
-
messages,
|
|
3734
|
-
messageEnds,
|
|
3735
|
-
error: err,
|
|
3736
|
-
}).catch((persistenceError) => {
|
|
3737
|
-
this.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
|
|
3738
|
-
});
|
|
3739
|
-
}
|
|
3740
|
-
await this.ownerRecordWrite.catch((persistenceError) => {
|
|
3741
|
-
this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
|
|
3742
|
-
});
|
|
3743
|
-
if (this.v2Transcript) {
|
|
3744
|
-
if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
|
|
3745
|
-
for (const message of messages) {
|
|
3746
|
-
const current = beginAssistantMessage(message.messageId);
|
|
3747
|
-
current.text = message.text;
|
|
3748
|
-
current.dirty = true;
|
|
3749
|
-
flushAssistantMessage("error", "error", true);
|
|
3750
|
-
}
|
|
3751
|
-
} else if (!transcriptClosed) {
|
|
3752
|
-
flushAssistantMessage("error", "error", true);
|
|
3753
|
-
}
|
|
3754
|
-
await this.presentation.drain().catch(() => undefined);
|
|
3755
|
-
} else {
|
|
3756
|
-
await this.appendTranscript({
|
|
3757
|
-
v: 1,
|
|
3758
|
-
t: "msg",
|
|
3759
|
-
role: "assistant",
|
|
3760
|
-
...legacyTranscriptMessages(messages, text),
|
|
3761
|
-
ts: Date.now(),
|
|
3762
|
-
stopReason: "error",
|
|
3763
|
-
status: "error",
|
|
3764
|
-
});
|
|
3765
|
-
}
|
|
3766
|
-
// A failed operation may still have consumed tokens, so its record has to survive
|
|
3767
|
-
// the rejection rather than only reaching event subscribers.
|
|
3768
|
-
// Already metered: the failure happened after the operation closed (a transcript or
|
|
3769
|
-
// catalog write), so the record stands and must not be minted a second time.
|
|
3770
|
-
const outcome = err instanceof OperationStalledError ? "cancelled" : "error";
|
|
3771
|
-
const record = closed ?? (await this.closeOperation(operation, outcome, null, String(err)));
|
|
3772
|
-
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
3773
|
-
if (this.v2Transcript && !transcriptClosed) {
|
|
3774
|
-
await this.finishV2Prompt("error", record, "unknown").catch(
|
|
3775
|
-
(persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
|
|
3776
|
-
);
|
|
3777
|
-
}
|
|
3778
|
-
if (err instanceof OperationStalledError) {
|
|
3779
|
-
err.messages = messages;
|
|
3780
|
-
err.metering = record;
|
|
3781
|
-
await this.ownerLifecycle?.operationFailed?.({ operationId: item.turnId, error: err }).catch((error) => {
|
|
3782
|
-
this.log.warn("operation_failure_recording_failed", { error: String(error) });
|
|
3783
|
-
});
|
|
3784
|
-
throw err;
|
|
3785
|
-
}
|
|
3786
|
-
throw new AgentSessionOperationError(item.turnId, record, err);
|
|
3787
|
-
}
|
|
3428
|
+
},
|
|
3429
|
+
get providerAttachment() { return session.providerAttachment; },
|
|
3430
|
+
set providerAttachment(value) { session.providerAttachment = value; },
|
|
3431
|
+
installProviderAttachment: (internalSessionId, kind, created, options) =>
|
|
3432
|
+
this.installProviderAttachment(internalSessionId, kind, created, options),
|
|
3433
|
+
get lastRecordedInternalSessionId() { return session.lastRecordedInternalSessionId; },
|
|
3434
|
+
set lastRecordedInternalSessionId(value) { session.lastRecordedInternalSessionId = value; },
|
|
3435
|
+
},
|
|
3436
|
+
};
|
|
3788
3437
|
}
|
|
3789
3438
|
|
|
3790
3439
|
private openMeteredOperation(item: PromptQueueItem): Promise<OpenOperation> {
|
|
@@ -3794,7 +3443,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3794
3443
|
internalSessionId: this._internalSessionId,
|
|
3795
3444
|
providerId: this.providerId,
|
|
3796
3445
|
model: this.model,
|
|
3797
|
-
|
|
3446
|
+
native: this.controllerDefaults.native,
|
|
3447
|
+
degraded: isDegradedController(this.controller),
|
|
3798
3448
|
});
|
|
3799
3449
|
}
|
|
3800
3450
|
|
|
@@ -3902,12 +3552,20 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3902
3552
|
|
|
3903
3553
|
/** @internal Acquire a fresh leaf for checkpoint recovery without replacing this conversation. */
|
|
3904
3554
|
async restartProviderFresh(): Promise<void> {
|
|
3555
|
+
requireFreshContext(this.controller, "restarting on a fresh provider session");
|
|
3905
3556
|
await this.controller.forceStop();
|
|
3906
|
-
const result = await this.
|
|
3557
|
+
const result = await this.startController(true);
|
|
3907
3558
|
if (!result.sessionId) throw new Error("provider returned no fresh session");
|
|
3908
3559
|
this.installProviderAttachment(result.sessionId, "runtime_only", true);
|
|
3909
3560
|
}
|
|
3910
3561
|
|
|
3562
|
+
/** Observe an existing backend channel without changing its lifecycle. */
|
|
3563
|
+
async attachObservation(): Promise<{ dispose(): void }> {
|
|
3564
|
+
const controller = this.controller;
|
|
3565
|
+
if (!controller.attachObservation) throw new UnsupportedError("The controller does not support observation-only attachment");
|
|
3566
|
+
return controller.attachObservation();
|
|
3567
|
+
}
|
|
3568
|
+
|
|
3911
3569
|
private async ensureProvider(): Promise<void> {
|
|
3912
3570
|
if (this.controller.isConnected) return;
|
|
3913
3571
|
if (this.phase === "stopped") throw new Error("conversation is stopped");
|
|
@@ -3919,20 +3577,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3919
3577
|
let via: "loaded" | "recovered" | "fresh" = "loaded";
|
|
3920
3578
|
try {
|
|
3921
3579
|
try {
|
|
3922
|
-
if (sessionId) await this.
|
|
3923
|
-
else await this.
|
|
3580
|
+
if (!sessionId) await this.startController(true);
|
|
3581
|
+
else await this.connectProvider(() => reloadProviderSession(this.controller, sessionId)); // no reconnect: recovery decides
|
|
3924
3582
|
} catch (error) {
|
|
3925
|
-
if (!sessionId) throw error;
|
|
3583
|
+
if (!sessionId || error instanceof ConnectionCancelledError) throw error;
|
|
3926
3584
|
via = await this.continueWithoutProviderSession(sessionId, error);
|
|
3927
3585
|
}
|
|
3928
3586
|
if (this.state.phase === "stopped") {
|
|
3929
3587
|
await this.controller.forceStop();
|
|
3930
|
-
throw new
|
|
3588
|
+
throw new ConnectionCancelledError();
|
|
3931
3589
|
}
|
|
3932
3590
|
const loadedId = this.controller.currentSessionId;
|
|
3933
3591
|
if (via === "loaded" && loadedId && loadedId !== this._internalSessionId) {
|
|
3934
3592
|
this.installProviderAttachment(loadedId, "runtime_only", !sessionId);
|
|
3935
3593
|
}
|
|
3594
|
+
if (this.deferredProviderStart && !sessionId) via = "fresh";
|
|
3595
|
+
this.deferredProviderStart = false;
|
|
3936
3596
|
this.emit({ kind: "provider_reconnected", via, internalSessionId: this._internalSessionId! });
|
|
3937
3597
|
} catch (error) {
|
|
3938
3598
|
await this.controller.forceStop().catch(() => {});
|
|
@@ -3989,7 +3649,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3989
3649
|
return "recovered";
|
|
3990
3650
|
}
|
|
3991
3651
|
if (this.sessionLoadFailure === "error") unavailable(loadFailed("provider_session_missing"));
|
|
3992
|
-
const created = await this.
|
|
3652
|
+
const created = await this.startController(true);
|
|
3993
3653
|
if (!created.sessionId) throw new Error("harness returned no session id for a replacement session");
|
|
3994
3654
|
this.installProviderAttachment(created.sessionId, "runtime_only", true);
|
|
3995
3655
|
return "fresh";
|
|
@@ -4034,26 +3694,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4034
3694
|
|
|
4035
3695
|
/** Run one provider request under its own supervisor: stage, stale conditions, cancel escalation. */
|
|
4036
3696
|
private async supervisedPrompt(
|
|
4037
|
-
controller:
|
|
3697
|
+
controller: ConversationController,
|
|
4038
3698
|
operationId: string,
|
|
4039
3699
|
kind: "turn" | "internal_inference" | "recap",
|
|
4040
|
-
|
|
3700
|
+
provider: SupervisedProvider,
|
|
4041
3701
|
): Promise<PromptResult> {
|
|
4042
3702
|
const limits = kind === "turn"
|
|
4043
3703
|
? this.operationLifecycle.turns
|
|
4044
3704
|
: kind === "recap" ? this.operationLifecycle.recap : this.operationLifecycle.internalInference;
|
|
4045
|
-
const supervisor = new OperationSupervisor({
|
|
4046
|
-
prompt,
|
|
4047
|
-
subscribeOutput: (listener) => controller.subscribeOutput(listener),
|
|
4048
|
-
cancel: () => controller.cancel(),
|
|
4049
|
-
forceStop: () => controller.forceStop(),
|
|
4050
|
-
}, {
|
|
3705
|
+
const supervisor = new OperationSupervisor(provider, {
|
|
4051
3706
|
operationId,
|
|
4052
3707
|
kind,
|
|
4053
3708
|
sessionId: controller.currentSessionId,
|
|
4054
3709
|
cancelGraceMs: controller.cancelGraceMs,
|
|
4055
3710
|
// A screen-scraped harness cannot report tools or permissions, so silence explains nothing.
|
|
4056
|
-
limits: controller
|
|
3711
|
+
limits: stallLimitsFor(controller, limits),
|
|
3712
|
+
isReplaying: () => (provider as { live?: boolean }).live === false,
|
|
4057
3713
|
onStageChanged: (activity) => {
|
|
4058
3714
|
this.emit({ kind: "operation_stage_changed", activity });
|
|
4059
3715
|
this.emitStateIfChanged();
|
|
@@ -4092,6 +3748,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4092
3748
|
target?: InternalPromptTarget,
|
|
4093
3749
|
): Promise<PromptResult> {
|
|
4094
3750
|
const controller = target?.controller ?? this.controller;
|
|
3751
|
+
const prepareInternalPrompt = requireMember(controller, "prepareInternalPrompt", "internal prompts"); // before any operation is opened
|
|
4095
3752
|
if (!target && !this.reconnecting) await this.ensureProvider();
|
|
4096
3753
|
const metering = target?.metering ?? this.metering;
|
|
4097
3754
|
const advertised = target ? activeModel(target.controller.configOptions) : this.advertisedModel;
|
|
@@ -4102,7 +3759,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4102
3759
|
internalSessionId: target ? controller.currentSessionId : this._internalSessionId,
|
|
4103
3760
|
providerId: target ? reference?.providerId ?? null : this.providerId,
|
|
4104
3761
|
model: target ? reference?.modelId ?? advertised : this.model,
|
|
4105
|
-
degraded: controller
|
|
3762
|
+
degraded: isDegradedController(controller),
|
|
4106
3763
|
});
|
|
4107
3764
|
let transcriptStarted = false;
|
|
4108
3765
|
if (this.v2Transcript) {
|
|
@@ -4131,7 +3788,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4131
3788
|
this.runningOperationId = operationId;
|
|
4132
3789
|
try {
|
|
4133
3790
|
const kind = operationKind === "conversation_checkpoint" ? "recap" : "internal_inference";
|
|
4134
|
-
const result = await this.supervisedPrompt(controller, operationId, kind,
|
|
3791
|
+
const result = await this.supervisedPrompt(controller, operationId, kind,
|
|
3792
|
+
prepareInternalPrompt({ input: { text }, handlers: this.permissions.internalHandler(operationId, this.controllerDefaults) }));
|
|
4135
3793
|
const record = await this.closeOperation(
|
|
4136
3794
|
operation,
|
|
4137
3795
|
result.status,
|
|
@@ -4188,6 +3846,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4188
3846
|
}
|
|
4189
3847
|
throw err;
|
|
4190
3848
|
} finally {
|
|
3849
|
+
this.permissions.end(operationId);
|
|
4191
3850
|
this.runningOperationId = enclosingOperationId;
|
|
4192
3851
|
}
|
|
4193
3852
|
}
|
|
@@ -4220,38 +3879,32 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4220
3879
|
: internalSessionId
|
|
4221
3880
|
? observedAt
|
|
4222
3881
|
: null,
|
|
4223
|
-
protocol: this.controller
|
|
3882
|
+
protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
|
|
4224
3883
|
};
|
|
4225
3884
|
}
|
|
4226
3885
|
|
|
4227
|
-
/**
|
|
4228
|
-
* Close a rating unit, emit its record, and surface a strict-mode block.
|
|
4229
|
-
*
|
|
4230
|
-
* `contextAfter`/`providerCostAfter` are the latest observations seen by completion.
|
|
4231
|
-
* ACP gives no ordering guarantee, so neither is asserted to describe THIS operation.
|
|
4232
|
-
*/
|
|
4233
3886
|
private async closeOperation(
|
|
4234
3887
|
operation: OpenOperation,
|
|
4235
3888
|
outcome: "completed" | "cancelled" | "error",
|
|
4236
3889
|
reportedCumulative: TokenUsage | null,
|
|
4237
3890
|
usageFailureReason?: string,
|
|
4238
3891
|
engine: MeteringEngine = this.metering,
|
|
3892
|
+
nativeMetering?: CloseOperationInput["nativeMetering"],
|
|
4239
3893
|
): Promise<OperationMeteringRecord> {
|
|
4240
|
-
const wasBlocked = engine.blocked;
|
|
4241
|
-
const
|
|
3894
|
+
const wasBlocked = engine.blocked, live = engine === this.metering;
|
|
3895
|
+
const recovery = this.ownerLifecycle?.nativeMetering;
|
|
3896
|
+
const replay = operation.nativeChannel ? await recoverNativeClose(recovery, engine, operation) : null;
|
|
3897
|
+
if (replay) return replay;
|
|
4242
3898
|
const record = await engine.close(operation, {
|
|
4243
3899
|
outcome,
|
|
4244
3900
|
reportedCumulative,
|
|
3901
|
+
nativeMetering: withNativeAccounting(nativeMetering, recovery),
|
|
4245
3902
|
...(usageFailureReason ? { usageFailureReason } : {}),
|
|
4246
|
-
// Context and provider cost describe the live thread. An unconfirmed transition
|
|
4247
|
-
// target has neither yet, and borrowing the source's would misreport it.
|
|
4248
3903
|
contextAfter: live ? this._contextWindow : null,
|
|
4249
3904
|
providerCostAfter: live ? this._providerCost : null,
|
|
4250
3905
|
});
|
|
4251
3906
|
this.emit({ kind: "metering_recorded", record });
|
|
4252
|
-
if (!wasBlocked && engine.blocked) {
|
|
4253
|
-
this.emit({ kind: "metering_blocked", reason: engine.blockedReason ?? "unknown" });
|
|
4254
|
-
}
|
|
3907
|
+
if (!wasBlocked && engine.blocked) this.emit({ kind: "metering_blocked", reason: engine.blockedReason ?? "unknown" });
|
|
4255
3908
|
return record;
|
|
4256
3909
|
}
|
|
4257
3910
|
|
|
@@ -4275,6 +3928,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4275
3928
|
}
|
|
4276
3929
|
|
|
4277
3930
|
private endTurn(turnId: string, handlers?: PromptHandlers): void {
|
|
3931
|
+
this.permissions.end(turnId);
|
|
4278
3932
|
this.queueActivityRecords(turnId, this.presentation.endTurn(handlers));
|
|
4279
3933
|
}
|
|
4280
3934
|
|
|
@@ -4304,21 +3958,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4304
3958
|
// A stop closes the connection, so its turn fails and `endedBy` is never reported for it.
|
|
4305
3959
|
this.steering.interrupted();
|
|
4306
3960
|
if (options?.clearQueue) {
|
|
4307
|
-
const
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
this.
|
|
4311
|
-
|
|
4312
|
-
if (item.kind === "prompt") continue;
|
|
4313
|
-
const label = item.kind === "handoff"
|
|
4314
|
-
? "handoff"
|
|
4315
|
-
: item.kind === "set_config" || item.kind === "resolve_config"
|
|
4316
|
-
? "configuration change"
|
|
4317
|
-
: item.kind === "resolve_recovery"
|
|
4318
|
-
? "recovery resolution"
|
|
4319
|
-
: "mode change";
|
|
4320
|
-
item.reject(new Error(`${label} cancelled before it started`));
|
|
4321
|
-
}
|
|
3961
|
+
const cancellation = reason === "stop" && (this.reconnecting || this.connecting > 0)
|
|
3962
|
+
? new ConnectionCancelledError() : undefined;
|
|
3963
|
+
const dropped = settleClearedBackendTurns(this.operations.clear(), reason === "stop", (turn) => { this.operations.enqueue(turn); void this.pump(); });
|
|
3964
|
+
const backend = this.backendTurns.clear(reason === "stop", Boolean(this.controller.withdrawInput));
|
|
3965
|
+
dropClearedOperations(dropped, backend, (messages, error) => this.steering.dropped(messages, error), cancellation, reason === "stop" && Boolean(this.controller.withdrawInput));
|
|
4322
3966
|
this.emitStateIfChanged();
|
|
4323
3967
|
}
|
|
4324
3968
|
this.cancelOperation(reason);
|
|
@@ -4326,19 +3970,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4326
3970
|
|
|
4327
3971
|
stop(): Promise<void> {
|
|
4328
3972
|
if (this.stopPromise) return this.stopPromise;
|
|
4329
|
-
// Publish the terminal state synchronously
|
|
4330
|
-
// completion promise, including callers arriving while teardown is in progress.
|
|
3973
|
+
// Publish the terminal state synchronously and share teardown with later callers.
|
|
4331
3974
|
this.phase = "stopped";
|
|
4332
3975
|
const failures: unknown[] = [];
|
|
3976
|
+
const cancel = captureStopFailure(() => this.cancelRunning("stop", { clearQueue: true }), failures);
|
|
3977
|
+
const native = this.controller.withdrawInput !== undefined;
|
|
4333
3978
|
const completion = Promise.resolve().then(async () => {
|
|
4334
|
-
|
|
4335
|
-
await this.
|
|
4336
|
-
|
|
4337
|
-
|
|
3979
|
+
if (native) {
|
|
3980
|
+
await this.backendTurns.withdrawBeforeStop(this.controller);
|
|
3981
|
+
cancel();
|
|
3982
|
+
}
|
|
3983
|
+
const controllers = new Set([this.controller, this.handoffTarget]);
|
|
3984
|
+
for (const result of await Promise.allSettled([...controllers].map(async controller => controller?.stop()))) {
|
|
3985
|
+
if (result.status === "rejected") failures.push(result.reason);
|
|
4338
3986
|
}
|
|
4339
|
-
//
|
|
4340
|
-
// enqueue final message and metering writes, so the pre-stop write tail is not
|
|
4341
|
-
// sufficient evidence that persistence is quiescent.
|
|
3987
|
+
// Wait for the provider rejection and its finalization writes before draining persistence.
|
|
4342
3988
|
try {
|
|
4343
3989
|
await this.operations.waitForIdle();
|
|
4344
3990
|
} catch (error) {
|
|
@@ -4368,11 +4014,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4368
4014
|
if (failures.length > 1) throw new AggregateError(failures, "AgentSession shutdown failed");
|
|
4369
4015
|
});
|
|
4370
4016
|
this.stopPromise = completion;
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
} catch (error) {
|
|
4374
|
-
failures.push(error);
|
|
4375
|
-
}
|
|
4017
|
+
this.permissions.stop();
|
|
4018
|
+
if (!native) cancel();
|
|
4376
4019
|
this.emitStateIfChanged();
|
|
4377
4020
|
return completion;
|
|
4378
4021
|
}
|
|
@@ -4381,6 +4024,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4381
4024
|
async setMode(mode: AgentMode): Promise<ConnectResult> {
|
|
4382
4025
|
if (this.phase === "stopped") throw new Error("AgentSession is stopped");
|
|
4383
4026
|
this.assertPromptable();
|
|
4027
|
+
requireMember(this.controller, "setMode", "switching modes"); // refused before anything is queued
|
|
4384
4028
|
return await new Promise<ConnectResult>((resolve, reject) => {
|
|
4385
4029
|
this.operations.enqueue({
|
|
4386
4030
|
kind: "set_mode",
|
|
@@ -4394,9 +4038,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4394
4038
|
});
|
|
4395
4039
|
}
|
|
4396
4040
|
|
|
4397
|
-
// --- thin proxies to the live connection -------------------------------------
|
|
4398
4041
|
get capabilities(): Capabilities {
|
|
4399
|
-
return this.controller
|
|
4042
|
+
return acpCapabilitiesOf(this.controller);
|
|
4043
|
+
}
|
|
4044
|
+
/** What the backend offers, in neutral terms; safe to read before connecting and in PTY mode. */
|
|
4045
|
+
get conversationCapabilities(): ConversationCapabilities { return this.controller.conversationCapabilities; }
|
|
4046
|
+
get reminders() {
|
|
4047
|
+
const service = this.ownerLifecycle?.reminders;
|
|
4048
|
+
if (!service) throw new ReminderError(this.conversationCapabilities.reminders ? "reminders_unavailable" : "reminders_unsupported", "Reminders require an owning Agent and a native conversation");
|
|
4049
|
+
return service.conversation(this.agentConversationId, this.conversationCapabilities.reminders === true, event => this.emit(event));
|
|
4400
4050
|
}
|
|
4401
4051
|
get configOptions(): ConfigOptions {
|
|
4402
4052
|
return this.controller.configOptions;
|
|
@@ -4483,19 +4133,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4483
4133
|
}
|
|
4484
4134
|
/** Immutable snapshot of commands advertised by the active ACP harness. */
|
|
4485
4135
|
get internalSessionCommands(): readonly InternalSessionCommand[] {
|
|
4486
|
-
return this.controller
|
|
4136
|
+
return availableCommandsOf(this.controller);
|
|
4487
4137
|
}
|
|
4488
4138
|
get isDegraded(): boolean {
|
|
4489
|
-
return this.controller
|
|
4139
|
+
return isDegradedController(this.controller);
|
|
4490
4140
|
}
|
|
4491
4141
|
bridge(options?: BridgeOptions): Promise<void> {
|
|
4492
|
-
return this.controller
|
|
4142
|
+
return requireMember(this.controller, "bridge", "a terminal bridge")(options);
|
|
4493
4143
|
}
|
|
4494
4144
|
authenticate(
|
|
4495
4145
|
methodId: string,
|
|
4496
4146
|
handlers?: { onOutput?: (line: string) => void },
|
|
4497
4147
|
): Promise<unknown> {
|
|
4498
|
-
return this.controller
|
|
4148
|
+
return requireMember(this.controller, "authenticate", "authentication")(methodId, handlers);
|
|
4499
4149
|
}
|
|
4500
4150
|
|
|
4501
4151
|
// --- sessions (merged catalog + live) ----------------------------------------
|
|
@@ -4510,13 +4160,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4510
4160
|
* their owners.
|
|
4511
4161
|
*/
|
|
4512
4162
|
async listSessions(): Promise<MergedSession[]> {
|
|
4513
|
-
|
|
4514
|
-
if (
|
|
4515
|
-
!this.controller.isDegraded &&
|
|
4516
|
-
this.controller.capabilities.agent.sessionCapabilities.list
|
|
4517
|
-
) {
|
|
4518
|
-
agentEntries = (await this.controller.listSessions()).sessions;
|
|
4519
|
-
}
|
|
4163
|
+
const agentEntries = await listAgentSessions(this.controller);
|
|
4520
4164
|
if (this.sessions) return this.sessions.listMerged(agentEntries, this.adapterId);
|
|
4521
4165
|
return agentEntries.map((e) => ({
|
|
4522
4166
|
agentSessionId: e.sessionId,
|
|
@@ -4706,15 +4350,26 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4706
4350
|
agentSessionId: this.agentSessionId,
|
|
4707
4351
|
event: Object.freeze(event),
|
|
4708
4352
|
});
|
|
4709
|
-
|
|
4710
|
-
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4353
|
+
this.listeners.emit(notification);
|
|
4354
|
+
this.observeMessageStatus(event);
|
|
4355
|
+
}
|
|
4356
|
+
|
|
4357
|
+
/**
|
|
4358
|
+
* Advances message statuses from the events the session already emits. Native conversations
|
|
4359
|
+
* (backend-supervised) report real milestones; ACP ones are approximated: sent means taken and
|
|
4360
|
+
* delivered, the provider's first output means seen.
|
|
4361
|
+
*/
|
|
4362
|
+
private observeMessageStatus(event: AgentSessionEvent): void {
|
|
4363
|
+
const native = this.controller?.conversationCapabilities?.supervision === "backend";
|
|
4364
|
+
if (event.kind === "turn_started") {
|
|
4365
|
+
const ids = event.cause.messageIds ?? [];
|
|
4366
|
+
this.messageStatus.link(event.turnId, ids);
|
|
4367
|
+
for (const id of ids) this.messageStatus.advance(id, native ? "taken" : "delivered");
|
|
4368
|
+
} else if (event.kind === "items_receipt") {
|
|
4369
|
+
this.messageStatus.link(event.turnId, event.itemIds);
|
|
4370
|
+
for (const id of event.itemIds) this.messageStatus.advance(id, event.milestone);
|
|
4371
|
+
} else if (event.kind === "operation_stage_changed" && !native && event.activity.lastOutputAt !== null) {
|
|
4372
|
+
for (const id of this.messageStatus.idsOfTurn(event.activity.operationId)) this.messageStatus.advance(id, "seen");
|
|
4718
4373
|
}
|
|
4719
4374
|
}
|
|
4720
4375
|
}
|
|
@@ -4731,94 +4386,6 @@ export type AgentConversationOpenResult = AgentSessionOpenResult;
|
|
|
4731
4386
|
export type ManagedAgentConversationCreationBootstrap = ManagedAgentSessionCreationBootstrap;
|
|
4732
4387
|
export type ManagedAgentConversationPersistenceSnapshot = ManagedAgentSessionPersistenceSnapshot;
|
|
4733
4388
|
|
|
4734
|
-
function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
|
|
4735
|
-
if (kind === "internal_command") return "internal_session_command";
|
|
4736
|
-
if (
|
|
4737
|
-
kind === "conversation_checkpoint"
|
|
4738
|
-
|| kind === "conversation_recovery"
|
|
4739
|
-
|| kind === "identity_update"
|
|
4740
|
-
) return "other";
|
|
4741
|
-
return kind;
|
|
4742
|
-
}
|
|
4743
|
-
|
|
4744
|
-
function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
|
|
4745
|
-
return Object.freeze({
|
|
4746
|
-
...(options.summary === undefined ? {} : { summary: options.summary }),
|
|
4747
|
-
...(options.target === undefined
|
|
4748
|
-
? {}
|
|
4749
|
-
: {
|
|
4750
|
-
target: Object.freeze({
|
|
4751
|
-
adapterId: options.target.adapterId,
|
|
4752
|
-
...(options.target.mode === undefined ? {} : { mode: options.target.mode }),
|
|
4753
|
-
...(options.target.adapter === undefined
|
|
4754
|
-
? {}
|
|
4755
|
-
: {
|
|
4756
|
-
adapter: Object.freeze({
|
|
4757
|
-
...(options.target.adapter.cancelGraceMs === undefined
|
|
4758
|
-
? {}
|
|
4759
|
-
: { cancelGraceMs: options.target.adapter.cancelGraceMs }),
|
|
4760
|
-
...options.target.adapter,
|
|
4761
|
-
command: Object.freeze([...options.target.adapter.command]) as unknown as string[],
|
|
4762
|
-
...(options.target.adapter.ptyCommand
|
|
4763
|
-
? {
|
|
4764
|
-
ptyCommand: Object.freeze([
|
|
4765
|
-
...options.target.adapter.ptyCommand,
|
|
4766
|
-
]) as unknown as string[],
|
|
4767
|
-
}
|
|
4768
|
-
: {}),
|
|
4769
|
-
}),
|
|
4770
|
-
}),
|
|
4771
|
-
...(options.target.config === undefined
|
|
4772
|
-
? {}
|
|
4773
|
-
: { config: Object.freeze({ ...options.target.config }) }),
|
|
4774
|
-
}),
|
|
4775
|
-
}),
|
|
4776
|
-
...(options.continuation === undefined
|
|
4777
|
-
? {}
|
|
4778
|
-
: { continuation: Object.freeze({ ...options.continuation }) }),
|
|
4779
|
-
...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
|
|
4780
|
-
});
|
|
4781
|
-
}
|
|
4782
|
-
|
|
4783
|
-
function normalizeHandoffContinuation(options: HandoffOptions):
|
|
4784
|
-
| { readonly kind: "generated"; readonly summaryPrompt: string }
|
|
4785
|
-
| { readonly kind: "provided"; readonly content: string }
|
|
4786
|
-
| { readonly kind: "none" } {
|
|
4787
|
-
if (options.summary !== undefined && options.continuation !== undefined) {
|
|
4788
|
-
throw new Error("handoff cannot combine deprecated summary with continuation");
|
|
4789
|
-
}
|
|
4790
|
-
if (options.target && !options.target.adapterId.trim()) {
|
|
4791
|
-
throw new Error("handoff target adapter id cannot be blank");
|
|
4792
|
-
}
|
|
4793
|
-
if (options.targetPrompt !== undefined && !options.targetPrompt.trim()) {
|
|
4794
|
-
throw new Error("handoff target prompt cannot be blank");
|
|
4795
|
-
}
|
|
4796
|
-
if (options.summary !== undefined) {
|
|
4797
|
-
if (!options.summary.trim()) throw new Error("handoff summary cannot be blank");
|
|
4798
|
-
return Object.freeze({ kind: "provided", content: options.summary });
|
|
4799
|
-
}
|
|
4800
|
-
const continuation = options.continuation ?? { kind: "generated" as const };
|
|
4801
|
-
if (continuation.kind === "provided") {
|
|
4802
|
-
if (!continuation.content.trim()) throw new Error("handoff continuation cannot be blank");
|
|
4803
|
-
return Object.freeze({ kind: "provided", content: continuation.content });
|
|
4804
|
-
}
|
|
4805
|
-
if (continuation.kind === "none") return Object.freeze({ kind: "none" });
|
|
4806
|
-
if (continuation.summaryPrompt !== undefined && continuation.summaryInstructions !== undefined) {
|
|
4807
|
-
throw new Error("handoff generated continuation cannot combine summaryPrompt and summaryInstructions");
|
|
4808
|
-
}
|
|
4809
|
-
if (continuation.summaryPrompt !== undefined && !continuation.summaryPrompt.trim()) {
|
|
4810
|
-
throw new Error("handoff summary prompt cannot be blank");
|
|
4811
|
-
}
|
|
4812
|
-
if (continuation.summaryInstructions !== undefined && !continuation.summaryInstructions.trim()) {
|
|
4813
|
-
throw new Error("handoff summary instructions cannot be blank");
|
|
4814
|
-
}
|
|
4815
|
-
const base = continuation.summaryPrompt ?? HANDOFF_SUMMARY_PROMPT;
|
|
4816
|
-
const summaryPrompt = continuation.summaryInstructions === undefined
|
|
4817
|
-
? base
|
|
4818
|
-
: `${base}\n\nAdditional summary instructions:\n${continuation.summaryInstructions}`;
|
|
4819
|
-
return Object.freeze({ kind: "generated", summaryPrompt });
|
|
4820
|
-
}
|
|
4821
|
-
|
|
4822
4389
|
function configurationTargetIssue(
|
|
4823
4390
|
option: ConfigOption | undefined,
|
|
4824
4391
|
target: PersistedSessionConfigSelection,
|
|
@@ -4929,6 +4496,8 @@ function runtimeRecordFromActivity(
|
|
|
4929
4496
|
case "plan":
|
|
4930
4497
|
case "plan_update":
|
|
4931
4498
|
case "plan_removed":
|
|
4499
|
+
// A provider's warning, retry or failure: kept so a consumer can show it apart from messages.
|
|
4500
|
+
case "provider_notice":
|
|
4932
4501
|
return {
|
|
4933
4502
|
recordId,
|
|
4934
4503
|
agentSessionId,
|
|
@@ -4957,66 +4526,3 @@ function runtimeRecordFromActivity(
|
|
|
4957
4526
|
return null;
|
|
4958
4527
|
}
|
|
4959
4528
|
}
|
|
4960
|
-
|
|
4961
|
-
function protocolMethod(message: PersistenceJsonValue): string | undefined {
|
|
4962
|
-
if (message === null || Array.isArray(message) || typeof message !== "object") return undefined;
|
|
4963
|
-
const method = (message as { readonly method?: unknown }).method;
|
|
4964
|
-
return typeof method === "string" ? method : undefined;
|
|
4965
|
-
}
|
|
4966
|
-
|
|
4967
|
-
function toPersistenceJsonValue(value: unknown): PersistenceJsonValue {
|
|
4968
|
-
if (value === undefined) return null;
|
|
4969
|
-
const serialized = JSON.stringify(value);
|
|
4970
|
-
return serialized === undefined ? String(value) : JSON.parse(serialized) as PersistenceJsonValue;
|
|
4971
|
-
}
|
|
4972
|
-
|
|
4973
|
-
function defaultPermissionOutcome(
|
|
4974
|
-
request: PermissionRequest,
|
|
4975
|
-
policy: "approve" | "cancel",
|
|
4976
|
-
): PermissionOutcome {
|
|
4977
|
-
if (policy === "cancel") return { outcome: "cancelled" };
|
|
4978
|
-
const allow = request.options.find((option) => option.kind === "allow_once")
|
|
4979
|
-
?? request.options.find((option) => option.kind === "allow_always");
|
|
4980
|
-
return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
|
|
4981
|
-
}
|
|
4982
|
-
|
|
4983
|
-
function permissionRecordOutcome(
|
|
4984
|
-
request: PermissionRequest,
|
|
4985
|
-
outcome: PermissionOutcome,
|
|
4986
|
-
): "approved" | "denied" | "cancelled" {
|
|
4987
|
-
if (outcome.outcome === "cancelled") return "cancelled";
|
|
4988
|
-
const selected = request.options.find((option) => option.optionId === outcome.optionId);
|
|
4989
|
-
return selected?.kind === "allow_once" || selected?.kind === "allow_always"
|
|
4990
|
-
? "approved"
|
|
4991
|
-
: "denied";
|
|
4992
|
-
}
|
|
4993
|
-
|
|
4994
|
-
/** Do not let one notification observer mutate the PromptResult another observer sees. */
|
|
4995
|
-
function copyPromptResult(result: PromptResult): PromptResult {
|
|
4996
|
-
const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
|
|
4997
|
-
return Object.freeze({
|
|
4998
|
-
...result,
|
|
4999
|
-
messages: Object.freeze(
|
|
5000
|
-
messages.map((message) => Object.freeze({ ...message })),
|
|
5001
|
-
),
|
|
5002
|
-
usage: result.usage ? Object.freeze({ ...result.usage }) : null,
|
|
5003
|
-
});
|
|
5004
|
-
}
|
|
5005
|
-
|
|
5006
|
-
/** Settle our wrapper too, so cancelled permission decisions are durably recorded. */
|
|
5007
|
-
async function permissionWithAbort(
|
|
5008
|
-
handler: () => PermissionOutcome | Promise<PermissionOutcome>,
|
|
5009
|
-
signal?: AbortSignal,
|
|
5010
|
-
): Promise<PermissionOutcome> {
|
|
5011
|
-
if (signal?.aborted) return { outcome: "cancelled" };
|
|
5012
|
-
let abort!: () => void;
|
|
5013
|
-
const cancelled = new Promise<PermissionOutcome>((resolve) => {
|
|
5014
|
-
abort = () => resolve({ outcome: "cancelled" });
|
|
5015
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
5016
|
-
});
|
|
5017
|
-
try {
|
|
5018
|
-
return await Promise.race([Promise.resolve().then(handler), cancelled]);
|
|
5019
|
-
} finally {
|
|
5020
|
-
signal?.removeEventListener("abort", abort);
|
|
5021
|
-
}
|
|
5022
|
-
}
|