@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
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { requireNativeMeteringCapability } from "../metering/native/requirements.ts";
|
|
2
|
+
import { defersProvider, resolveProviderStart } from "../conversation-startup.ts";
|
|
3
|
+
import { appendAssistantMessage } from "./append-assistant-message.ts";
|
|
4
|
+
import { inheritPermissionConfig, validateConversationPermissionConfig, type ConversationPermissionConfig } from "../permissions/policy.ts";
|
|
1
5
|
import { writeConversationError } from "./error-record-writer.ts";
|
|
2
6
|
import { randomUUID } from "node:crypto";
|
|
3
7
|
import {
|
|
@@ -24,10 +28,9 @@ import {
|
|
|
24
28
|
type ParticipantRef,
|
|
25
29
|
} from "../persistence/backend.ts";
|
|
26
30
|
import { ProviderSessionError, ProviderSessionInUseError } from "../agent-conversation-errors.ts";
|
|
27
|
-
import {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
} from "../out-of-band-messages.ts";
|
|
31
|
+
import { ConnectionCancelledError, UnsupportedError } from "../errors.ts";
|
|
32
|
+
import { recordAdoptedProviderSession } from "./adoption/provider-attachment.ts";
|
|
33
|
+
import type { AppendAssistantMessageInput } from "../out-of-band-messages.ts";
|
|
31
34
|
import type {
|
|
32
35
|
ProviderAttachmentCommitAcknowledgement,
|
|
33
36
|
} from "../persistence/provider-attachment.ts";
|
|
@@ -40,9 +43,7 @@ import {
|
|
|
40
43
|
|
|
41
44
|
import type { ManagerSettings } from "./manager-settings.ts";
|
|
42
45
|
import {
|
|
43
|
-
updateConversationIdentity,
|
|
44
46
|
persistConversationObservations,
|
|
45
|
-
persistObservationsInTransaction,
|
|
46
47
|
normalizeParticipants,
|
|
47
48
|
internalInferenceMeteringKind,
|
|
48
49
|
appendCanonicalRecord,
|
|
@@ -85,14 +86,14 @@ import {
|
|
|
85
86
|
type ProviderSessionSummary,
|
|
86
87
|
} from "./adoption/index.ts";
|
|
87
88
|
import { NoopAgentIdentityRuntime } from "../identity.ts";
|
|
88
|
-
import
|
|
89
|
-
import { forgetPendingParts
|
|
90
|
-
import {
|
|
91
|
-
import { persistParts } from "../media/content.ts";
|
|
92
|
-
import { isMediaPart, promptParts, partsText } from "../media/parts.ts";
|
|
89
|
+
import { conversationPersistenceContext } from "./persistence-policy/context.ts";
|
|
90
|
+
import { forgetPendingParts } from "../media/pending.ts";
|
|
91
|
+
import { createConversationWithChannel, deleteConversationWithChannel, initialChannelDesire } from "./native-channel-lifecycle.ts";
|
|
93
92
|
|
|
94
93
|
export class DefaultAgentConversationManager implements AgentConversationManager {
|
|
95
94
|
private readonly live = new Map<AgentConversationId, AgentConversation>();
|
|
95
|
+
private readonly shutdownStarts = new AbortController();
|
|
96
|
+
private readonly creating = new Set<Promise<AgentConversation>>();
|
|
96
97
|
private readonly openings = new Map<AgentConversationId, Promise<OpenOwnedAgentConversationResult>>();
|
|
97
98
|
private readonly meteringSetupLocks = new Map<AgentConversationId, Promise<void>>();
|
|
98
99
|
private readonly detachedMeteringBarriers = new Map<AgentConversationId, Promise<void>>();
|
|
@@ -106,16 +107,6 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
106
107
|
this.policies = new ConversationSettingsResolver(settings, settings.conversationPersistence);
|
|
107
108
|
}
|
|
108
109
|
|
|
109
|
-
private contextOf(summary: AgentConversationSummary): ConversationPersistenceContext {
|
|
110
|
-
return {
|
|
111
|
-
agentConversationId: summary.agentConversationId,
|
|
112
|
-
participants: summary.participants,
|
|
113
|
-
...(summary.title !== undefined && summary.title !== null ? { title: summary.title } : {}),
|
|
114
|
-
...(summary.metadata !== undefined && summary.metadata !== null ? { metadata: summary.metadata } : {}),
|
|
115
|
-
adopted: summary.adopted === true,
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
|
|
119
110
|
/**
|
|
120
111
|
* What a conversation persists, for the writes an internal inference makes about it (a checkpoint's
|
|
121
112
|
* `native_action` record, the detailed metering record). Resolved from the stored conversation, or the live
|
|
@@ -141,23 +132,31 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
141
132
|
/** Settings for a write about a conversation: the live conversation's own, or what the resolver says now. */
|
|
142
133
|
private writeSettings(summary: AgentConversationSummary): ManagerSettings {
|
|
143
134
|
return (this.live.has(summary.agentConversationId) && this.liveSettings.get(summary.agentConversationId))
|
|
144
|
-
|| this.policies.settingsFor(
|
|
135
|
+
|| this.policies.settingsFor(conversationPersistenceContext(summary));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
|
|
139
|
+
const creating = this.createOnce(config).finally(() => { this.creating.delete(creating); });
|
|
140
|
+
this.creating.add(creating);
|
|
141
|
+
return creating;
|
|
145
142
|
}
|
|
146
143
|
|
|
147
|
-
async
|
|
144
|
+
private async createOnce(config: CreateAgentConversationConfig): Promise<AgentConversation> {
|
|
145
|
+
this.shutdownStarts.signal.throwIfAborted();
|
|
148
146
|
const id = config.id ?? createAgentConversationId();
|
|
149
147
|
const participants = normalizeParticipants(config.participants);
|
|
150
|
-
|
|
151
|
-
// returns something invalid leaves no row, no error record and no provider session behind.
|
|
148
|
+
if (config.role === "worker" && config.adopt) throw new UnsupportedError("workers cannot adopt provider sessions");
|
|
152
149
|
const adoption = config.adopt
|
|
153
150
|
? normalizeAdoption(config.adopt, { recap: !(this.agent.identity instanceof NoopAgentIdentityRuntime) })
|
|
154
151
|
: undefined;
|
|
152
|
+
// Resolve persistence before writes so invalid policy leaves no row, error record, or provider session.
|
|
155
153
|
const settings = this.policies.settingsFor({
|
|
156
154
|
agentConversationId: id,
|
|
157
155
|
participants,
|
|
158
156
|
...(config.title !== undefined ? { title: config.title } : {}),
|
|
159
157
|
...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
|
|
160
158
|
adopted: adoption !== undefined,
|
|
159
|
+
...(config.role ? { role: config.role } : {}),
|
|
161
160
|
});
|
|
162
161
|
if (adoption) {
|
|
163
162
|
// An adopted conversation joins the Agent's memory, which is built from stored messages; one that
|
|
@@ -167,25 +166,29 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
167
166
|
throw new Error(`adopting a provider session requires message capture "content" or "raw", not "${level}"`);
|
|
168
167
|
}
|
|
169
168
|
}
|
|
170
|
-
// Validate
|
|
171
|
-
|
|
172
|
-
this.
|
|
169
|
+
// Validate before the durable row so caller errors neither orphan a conversation nor look like provider failures.
|
|
170
|
+
const adapterId = this.prepareStart({ ...config, providerSession: adoption ? "load" : "new" });
|
|
171
|
+
if (config.role === "worker" && this.agent.adapters.native(adapterId)) throw new UnsupportedError("workers require an ACP adapter");
|
|
173
172
|
if (adoption) return await this.createAdopting(id, participants, config, adoption, settings);
|
|
174
|
-
await this.agent
|
|
173
|
+
const channelIntentCommitted = await createConversationWithChannel(this.agent, {
|
|
175
174
|
agentSessionId: this.agent.id,
|
|
176
175
|
agentConversationId: id,
|
|
177
176
|
participants,
|
|
178
177
|
...(config.title !== undefined ? { title: config.title } : {}),
|
|
179
178
|
...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
|
|
180
|
-
|
|
179
|
+
...(config.role ? { role: config.role } : {}),
|
|
180
|
+
}, this.agent.adapters.native(adapterId));
|
|
181
181
|
const attemptId = `provider-create-${randomUUID()}`;
|
|
182
182
|
try {
|
|
183
183
|
return await this.start(id, participants, {
|
|
184
184
|
...config,
|
|
185
185
|
providerSession: "new",
|
|
186
|
+
channelIntentCommitted,
|
|
187
|
+
deferProviderStart: defersProvider(config, this.settings.defaults, this.agent.adapters.native(adapterId) !== null),
|
|
186
188
|
settings,
|
|
187
189
|
});
|
|
188
190
|
} catch (error) {
|
|
191
|
+
if (error instanceof ConnectionCancelledError) throw error;
|
|
189
192
|
return await this.throwCreateFailure(id, attemptId, error, settings);
|
|
190
193
|
}
|
|
191
194
|
}
|
|
@@ -218,6 +221,7 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
218
221
|
...(config.title !== undefined ? { title: config.title } : {}),
|
|
219
222
|
...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
|
|
220
223
|
adoptProviderSessionId: adoption.providerSessionId,
|
|
224
|
+
controllerKind: this.agent.adapters.native(this.resolveAdapterId(config.adapterId)) ? "native" : "acp",
|
|
221
225
|
});
|
|
222
226
|
});
|
|
223
227
|
const attemptId = `provider-load-${randomUUID()}`;
|
|
@@ -232,10 +236,11 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
232
236
|
...(adoption.importHistory ? { onReplay: (notification: unknown) => replay.push(notification) } : {}),
|
|
233
237
|
});
|
|
234
238
|
} catch (error) {
|
|
239
|
+
if (error instanceof ConnectionCancelledError) throw error;
|
|
235
240
|
throw await this.loadFailure(id, attemptId, adoption.providerSessionId, error, settings);
|
|
236
241
|
}
|
|
237
242
|
try {
|
|
238
|
-
await this.
|
|
243
|
+
await recordAdoptedProviderSession(this.agent.persistence, conversation.providerAttachmentState, id, attemptId);
|
|
239
244
|
const recap = adoption.recap ? await this.recap(conversation, id, attemptId, settings) : undefined;
|
|
240
245
|
if (adoption.importHistory) {
|
|
241
246
|
const turns = selectTail(withoutRecapTurns(turnsFromReplay(replay)), adoption.importHistory.last);
|
|
@@ -351,39 +356,11 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
351
356
|
});
|
|
352
357
|
}
|
|
353
358
|
|
|
354
|
-
/**
|
|
355
|
-
* Write the provider-session row of a loaded session that no conversation had recorded yet (an adoption). A
|
|
356
|
-
* loaded thread is "recorded" in memory already, so this is the one write that makes it durable; the
|
|
357
|
-
* identity delivery cursors restart, as for any new provider context.
|
|
358
|
-
*/
|
|
359
|
-
private async recordAdoptedProviderSession(
|
|
360
|
-
conversation: AgentConversation,
|
|
361
|
-
id: AgentConversationId,
|
|
362
|
-
transitionId: string,
|
|
363
|
-
): Promise<void> {
|
|
364
|
-
const attachment = conversation.providerAttachmentState;
|
|
365
|
-
if (attachment.kind === "absent") throw new Error("the adopted provider session is not attached");
|
|
366
|
-
const descriptor = attachment.descriptor;
|
|
367
|
-
await this.agent.persistence.transaction(async (persistence) => {
|
|
368
|
-
await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
|
|
369
|
-
await persistence.providerSessions.append({
|
|
370
|
-
providerSessionRecordId: `provider-${randomUUID()}`,
|
|
371
|
-
agentConversationId: id,
|
|
372
|
-
internalSessionId: descriptor.internalSessionId,
|
|
373
|
-
adapterId: descriptor.adapterId,
|
|
374
|
-
mode: descriptor.mode,
|
|
375
|
-
...(descriptor.model ? { model: descriptor.model } : {}),
|
|
376
|
-
activatedAt: descriptor.acquiredAt,
|
|
377
|
-
transitionId,
|
|
378
|
-
metadata: JSON.stringify({ adopted: true }),
|
|
379
|
-
});
|
|
380
|
-
});
|
|
381
|
-
}
|
|
382
|
-
|
|
383
359
|
async open(
|
|
384
360
|
id: AgentConversationId,
|
|
385
361
|
config: OpenAgentConversationConfig = {},
|
|
386
362
|
): Promise<OpenOwnedAgentConversationResult> {
|
|
363
|
+
this.shutdownStarts.signal.throwIfAborted();
|
|
387
364
|
const existing = this.live.get(id);
|
|
388
365
|
if (existing && existing.state.phase !== "stopped") {
|
|
389
366
|
return Object.freeze({ conversation: existing, providerSession: "already_open" });
|
|
@@ -420,9 +397,8 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
420
397
|
`conversation ${id} is active on ${active.adapterId}; use a conversation switch instead of loading it with ${config.adapterId}`,
|
|
421
398
|
);
|
|
422
399
|
}
|
|
423
|
-
//
|
|
424
|
-
|
|
425
|
-
const settings = this.policies.settingsFor(this.contextOf(summary));
|
|
400
|
+
// Resolve once before writes so the load-failure records, recovery records, and recovered thread share this policy.
|
|
401
|
+
const settings = this.policies.settingsFor(conversationPersistenceContext(summary));
|
|
426
402
|
const startConfig = {
|
|
427
403
|
...config,
|
|
428
404
|
runtime: {
|
|
@@ -433,18 +409,23 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
433
409
|
};
|
|
434
410
|
// Validate caller input before the recorded region so a configuration mistake is not
|
|
435
411
|
// persisted as a provider-session failure.
|
|
436
|
-
this.prepareStart({ ...startConfig, providerSession: active ? "load" : "new" });
|
|
412
|
+
const adapterId = this.prepareStart({ ...startConfig, providerSession: active ? "load" : "new" });
|
|
413
|
+
if (summary.controllerKind && summary.controllerKind !== (this.agent.adapters.native(adapterId) ? "native" : "acp")) {
|
|
414
|
+
throw new UnsupportedError("opening with a different conversation controller kind is unsupported");
|
|
415
|
+
}
|
|
416
|
+
const deferProviderStart = !summary.adopted && defersProvider(startConfig, this.settings.defaults, this.agent.adapters.native(adapterId) !== null);
|
|
437
417
|
const attemptId = active ? `provider-load-${randomUUID()}` : `provider-create-${randomUUID()}`;
|
|
438
418
|
try {
|
|
439
419
|
const conversation = await this.start(id, summary.participants, {
|
|
440
420
|
...startConfig,
|
|
441
421
|
providerSession: active ? "load" : "new",
|
|
442
422
|
internalSessionId: active?.internalSessionId,
|
|
423
|
+
deferProviderStart,
|
|
443
424
|
settings,
|
|
444
425
|
});
|
|
445
426
|
if (pendingAdoption) {
|
|
446
427
|
try {
|
|
447
|
-
await this.
|
|
428
|
+
await recordAdoptedProviderSession(this.agent.persistence, conversation.providerAttachmentState, id, attemptId);
|
|
448
429
|
} catch (recordError) {
|
|
449
430
|
this.live.delete(id);
|
|
450
431
|
await conversation.stop().catch(() => undefined);
|
|
@@ -453,9 +434,10 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
453
434
|
}
|
|
454
435
|
return Object.freeze({
|
|
455
436
|
conversation,
|
|
456
|
-
providerSession: active ? "loaded" : "new",
|
|
437
|
+
providerSession: deferProviderStart ? "deferred" : active ? "loaded" : "new",
|
|
457
438
|
});
|
|
458
439
|
} catch (error) {
|
|
440
|
+
if (error instanceof ConnectionCancelledError) throw error;
|
|
459
441
|
// No recorded mapping means this open was creating a thread, not loading one.
|
|
460
442
|
if (!active) return await this.throwCreateFailure(id, attemptId, error, settings);
|
|
461
443
|
return await this.recoverAfterLoadFailure(id, active.internalSessionId, error, settings, config,
|
|
@@ -545,6 +527,7 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
545
527
|
config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
|
|
546
528
|
return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
|
|
547
529
|
} catch (recoveryError) {
|
|
530
|
+
if (recoveryError instanceof ConnectionCancelledError) throw recoveryError;
|
|
548
531
|
// A recovery failure is a distinct root cause from the load failure already
|
|
549
532
|
// recorded above; it prevents the logical conversation from reopening.
|
|
550
533
|
const recoveryRecorded = await this.recordConversationError({
|
|
@@ -574,6 +557,11 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
574
557
|
}
|
|
575
558
|
}
|
|
576
559
|
|
|
560
|
+
/** @internal Resolve a live permission destination without opening its provider. */
|
|
561
|
+
liveConversation(id: AgentConversationId): AgentConversation | undefined {
|
|
562
|
+
return this.live.get(id);
|
|
563
|
+
}
|
|
564
|
+
|
|
577
565
|
async get(id: AgentConversationId): Promise<AgentConversationSummary | null> {
|
|
578
566
|
return await this.agent.persistence.conversations.get(id);
|
|
579
567
|
}
|
|
@@ -589,6 +577,7 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
589
577
|
...(defaults.launcher ? { launcher: defaults.launcher } : {}),
|
|
590
578
|
...(defaults.execPrefix ? { execPrefix: defaults.execPrefix } : {}),
|
|
591
579
|
...(defaults.env ? { env: defaults.env } : {}),
|
|
580
|
+
...(defaults.terminalEnv ? { terminalEnv: defaults.terminalEnv } : {}),
|
|
592
581
|
...(defaults.cwd ? { cwd: defaults.cwd } : {}),
|
|
593
582
|
...(defaults.clientInfo ? { clientInfo: defaults.clientInfo } : {}),
|
|
594
583
|
...(defaults.logger ? { logger: defaults.logger } : {}),
|
|
@@ -618,19 +607,12 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
618
607
|
id: AgentConversationId,
|
|
619
608
|
options: string | DeleteConversationOptions = {},
|
|
620
609
|
): Promise<DeleteConversationResult> {
|
|
621
|
-
const { deletedAt, providerSession = "no", checkpoints = false }: DeleteConversationOptions =
|
|
622
|
-
typeof options === "string" ? { deletedAt: options } : options;
|
|
623
|
-
// Read what the provider side needs before the conversation is gone from view.
|
|
624
|
-
const active = providerSession === "best-effort"
|
|
625
|
-
? await this.agent.persistence.providerSessions.active(id)
|
|
626
|
-
: null;
|
|
627
610
|
const live = this.live.get(id);
|
|
628
611
|
if (live) await live.stop();
|
|
629
612
|
this.live.delete(id);
|
|
630
|
-
const checkpointsDeleted =
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
await this.agent.persistence.conversations.delete(id, deletedAt);
|
|
613
|
+
const { active, checkpointsDeleted } = await deleteConversationWithChannel(
|
|
614
|
+
this.agent, id, typeof options === "string" ? { deletedAt: options } : options, live?.adapterId,
|
|
615
|
+
);
|
|
634
616
|
// A deleted conversation runs no next turn, so its waiting out-of-band parts would never leave.
|
|
635
617
|
forgetPendingParts(this.agent, id);
|
|
636
618
|
let providerDeleted: boolean | "unsupported" = false;
|
|
@@ -670,77 +652,18 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
670
652
|
return result;
|
|
671
653
|
}
|
|
672
654
|
|
|
673
|
-
|
|
674
|
-
id
|
|
675
|
-
|
|
676
|
-
): Promise<MessageRecord> {
|
|
677
|
-
const parts = promptParts(input) ?? [{ kind: "text" as const, text: input.text ?? "" }];
|
|
678
|
-
const hasMedia = parts.some((part) => part.kind !== "text" && part.kind !== "pasted");
|
|
679
|
-
if (!partsText(parts).trim() && !hasMedia) {
|
|
680
|
-
throw new Error("assistant message text cannot be blank");
|
|
681
|
-
}
|
|
682
|
-
const summary = await this.agent.persistence.conversations.get(id);
|
|
683
|
-
if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
|
|
684
|
-
const settings = this.writeSettings(summary);
|
|
685
|
-
const level = settings.capture.message;
|
|
686
|
-
if (!hasMedia && level !== "content" && level !== "raw") {
|
|
687
|
-
throw new Error(
|
|
688
|
-
`appending an assistant message requires message capture "content" or "raw", not "${level}"`,
|
|
689
|
-
);
|
|
690
|
-
}
|
|
691
|
-
// No agent reads the parts yet: every kind is accepted now, and delivery names what the agent of
|
|
692
|
-
// the next turn cannot take.
|
|
693
|
-
const resolved = await resolveParts(parts, {
|
|
694
|
-
cwd: this.live.get(id)?.cwd ?? this.settings.defaults.cwd ?? process.cwd(),
|
|
695
|
-
capabilities: { image: true, audio: true, embeddedContext: true },
|
|
696
|
-
thresholds: this.agent.media.thresholds,
|
|
697
|
-
owner: id,
|
|
698
|
-
store: this.agent.media.store ?? this.agent.persistence.media,
|
|
699
|
-
});
|
|
700
|
-
const appendId = `append-${randomUUID()}`;
|
|
701
|
-
const persisted: ConversationRecord[] = [];
|
|
702
|
-
const recordId = `${appendId}:assistant`;
|
|
703
|
-
await this.agent.persistence.transaction(async (scope) => {
|
|
704
|
-
const content = await persistParts(resolved, id, this.agent.media.store ?? scope.media, settings.capture.media);
|
|
705
|
-
await persistObservationsInTransaction(settings, scope, [{
|
|
706
|
-
recordId,
|
|
707
|
-
agentSessionId: this.agent.id,
|
|
708
|
-
agentConversationId: id,
|
|
709
|
-
kind: "message",
|
|
710
|
-
timestamp: new Date().toISOString(),
|
|
711
|
-
// A standalone message at its observed sequence, without a provider operation.
|
|
712
|
-
role: "assistant",
|
|
713
|
-
logicalMessageId: `message:${appendId}:assistant`,
|
|
714
|
-
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
715
|
-
content,
|
|
716
|
-
status: "completed",
|
|
717
|
-
metadata: JSON.stringify({ origin: OUT_OF_BAND_MESSAGE_ORIGIN, appendId }),
|
|
718
|
-
}], true, persisted);
|
|
719
|
-
});
|
|
720
|
-
const record = persisted[0];
|
|
721
|
-
if (record?.kind !== "message") throw new Error("assistant message was not persisted");
|
|
722
|
-
// The next turn delivers the message from its record. When the record cannot restore it (a part
|
|
723
|
-
// not recorded, media left out by capture, a copy not kept, text not captured), its parts wait in
|
|
724
|
-
// memory instead.
|
|
725
|
-
const blocks = Array.isArray(record.content) ? record.content : [];
|
|
726
|
-
const media = resolved.filter(isMediaPart);
|
|
727
|
-
const restorable = (level === "content" || level === "raw")
|
|
728
|
-
&& resolved.every((part) => part.record !== false)
|
|
729
|
-
&& blocks.filter((block) => block.type === "media").length === media.length
|
|
730
|
-
&& blocks.filter((block) => block.type === "media" && block.ref).length
|
|
731
|
-
=== media.filter((part) => part.mode === "copy").length;
|
|
732
|
-
if (!restorable) pendingOutOfBandParts(this.agent).set(recordId, { owner: id, parts: resolved });
|
|
733
|
-
this.agent.publishCommittedRecords(persisted);
|
|
734
|
-
if (settings.auditLog) this.agent.audit?.notifyPending();
|
|
735
|
-
await updateConversationIdentity(this.agent, settings, id, [record]);
|
|
736
|
-
return record;
|
|
655
|
+
appendAssistantMessage(id: AgentConversationId, input: AppendAssistantMessageInput, stableId?: string): Promise<MessageRecord> {
|
|
656
|
+
return appendAssistantMessage(this.agent, id, input, this.live.get(id)?.cwd ?? this.settings.defaults.cwd ?? process.cwd(),
|
|
657
|
+
summary => this.writeSettings(summary), stableId);
|
|
737
658
|
}
|
|
738
659
|
|
|
660
|
+
cancelStarts(): void { this.shutdownStarts.abort(new ConnectionCancelledError()); }
|
|
661
|
+
|
|
739
662
|
async stopAll(): Promise<void> {
|
|
740
|
-
|
|
741
|
-
const
|
|
663
|
+
this.cancelStarts();
|
|
664
|
+
const stopping = [...this.live.values()].map(conversation => conversation.stop());
|
|
665
|
+
await Promise.allSettled([...this.creating, ...this.openings.values(), ...stopping]);
|
|
742
666
|
this.live.clear();
|
|
743
|
-
await Promise.allSettled(conversations.map((conversation) => conversation.stop()));
|
|
744
667
|
}
|
|
745
668
|
|
|
746
669
|
async beginInternalInferenceMetering(
|
|
@@ -856,6 +779,8 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
856
779
|
participants: readonly ParticipantRef[],
|
|
857
780
|
config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
|
|
858
781
|
readonly providerSession: "new" | "load";
|
|
782
|
+
readonly channelIntentCommitted?: boolean;
|
|
783
|
+
readonly deferProviderStart?: boolean;
|
|
859
784
|
readonly internalSessionId?: string;
|
|
860
785
|
/** What this conversation persists, resolved before it started. */
|
|
861
786
|
readonly settings: ManagerSettings;
|
|
@@ -868,9 +793,15 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
868
793
|
try {
|
|
869
794
|
const adapterId = this.resolveAdapterId(config.adapterId);
|
|
870
795
|
const adapter = this.agent.adapters.require(adapterId);
|
|
871
|
-
const runtime = { ...this.settings.defaults, ...config.runtime };
|
|
796
|
+
const runtime = { ...this.settings.defaults, ...config.runtime, ...inheritPermissionConfig(this.settings.defaults, config, config.runtime) };
|
|
797
|
+
const nativeAdapter = this.agent.adapters.native(adapterId);
|
|
798
|
+
const nativeHost = nativeAdapter ? this.agent.nativeHarness : null;
|
|
799
|
+
if (nativeAdapter && !nativeHost) throw new Error("a native adapter requires AgentConfig.harness");
|
|
800
|
+
if (nativeHost && config.providerSession !== "load" && !config.channelIntentCommitted) {
|
|
801
|
+
const desire = initialChannelDesire(nativeAdapter!, "title" in config ? config.title : undefined);
|
|
802
|
+
if (desire) await nativeHost.changeChannel(id, desire);
|
|
803
|
+
}
|
|
872
804
|
await this.detachedMeteringBarriers.get(id);
|
|
873
|
-
const persistedMetering = await this.agent.persistence.metering.state(id);
|
|
874
805
|
const lifecycle = new PersistedConversationLifecycle(
|
|
875
806
|
this.agent,
|
|
876
807
|
id,
|
|
@@ -878,7 +809,8 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
878
809
|
config.settings,
|
|
879
810
|
async (loadError) => {
|
|
880
811
|
const current = conversation!;
|
|
881
|
-
await this.recoverAfterLoadFailure(id, current.internalSessionId!, loadError, config.settings,
|
|
812
|
+
await this.recoverAfterLoadFailure(id, current.internalSessionId!, loadError, config.settings,
|
|
813
|
+
"onRecoveryProgress" in config ? config : {},
|
|
882
814
|
async () => {
|
|
883
815
|
await current.restartProviderFresh();
|
|
884
816
|
return current;
|
|
@@ -888,15 +820,20 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
888
820
|
});
|
|
889
821
|
},
|
|
890
822
|
);
|
|
823
|
+
const meteringState = nativeHost ? await lifecycle.nativeMetering.restore()
|
|
824
|
+
: (await this.agent.persistence.metering.state(id))?.state;
|
|
825
|
+
this.shutdownStarts.signal.throwIfAborted();
|
|
891
826
|
this.liveSettings.set(id, config.settings);
|
|
892
827
|
conversation = await AgentConversation.create({
|
|
828
|
+
signal: this.shutdownStarts.signal,
|
|
829
|
+
deferProviderStart: config.deferProviderStart,
|
|
893
830
|
...runtime,
|
|
894
|
-
...(
|
|
895
|
-
? { metering: { ...runtime.metering, initialState: persistedMetering.state } }
|
|
896
|
-
: {}),
|
|
831
|
+
...(meteringState ? { metering: { ...runtime.metering, initialState: meteringState } } : {}),
|
|
897
832
|
...("title" in config && config.title !== undefined ? { title: config.title } : {}),
|
|
898
833
|
adapter,
|
|
899
834
|
adapterId,
|
|
835
|
+
isNativeAdapter: (id) => this.agent.adapters.native(id) !== null,
|
|
836
|
+
...(nativeHost ? { native: { host: nativeHost, channelId: id } } : {}),
|
|
900
837
|
agentSessionId: this.agent.id,
|
|
901
838
|
ownerAgentSessionId: this.agent.id,
|
|
902
839
|
agentConversationId: id,
|
|
@@ -914,6 +851,7 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
914
851
|
: { kind: "new" },
|
|
915
852
|
persistence: false,
|
|
916
853
|
});
|
|
854
|
+
this.shutdownStarts.signal.throwIfAborted();
|
|
917
855
|
const openedConversation = conversation;
|
|
918
856
|
this.live.set(id, openedConversation);
|
|
919
857
|
openedConversation.subscribe((notification) => {
|
|
@@ -986,26 +924,25 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
986
924
|
return writeConversationError(this.agent, this.settings, input);
|
|
987
925
|
}
|
|
988
926
|
|
|
989
|
-
/**
|
|
990
|
-
* Validate caller-supplied start configuration before any durable write or recorded
|
|
991
|
-
* region.
|
|
992
|
-
*
|
|
993
|
-
* Adapter resolution and mode/provider-thread compatibility are caller mistakes, not
|
|
994
|
-
* conversation failures. Persisting them as provider-session errors would violate the
|
|
995
|
-
* spec and mislead a UI (for example, `retryable` for an adapter that can never resolve).
|
|
996
|
-
*/
|
|
927
|
+
/** Reject invalid caller configuration before any durable row or provider-session failure record. */
|
|
997
928
|
private prepareStart(config: {
|
|
998
929
|
readonly adapterId?: string;
|
|
999
930
|
readonly mode?: AgentMode;
|
|
1000
931
|
readonly runtime?: AgentConversationRuntimeDefaults;
|
|
1001
932
|
readonly providerSession: "new" | "load";
|
|
1002
|
-
}):
|
|
933
|
+
} & ConversationPermissionConfig): string {
|
|
934
|
+
validateConversationPermissionConfig(config);
|
|
935
|
+
validateConversationPermissionConfig(config.runtime);
|
|
936
|
+
resolveProviderStart(config.runtime?.providerStart);
|
|
1003
937
|
const adapterId = this.resolveAdapterId(config.adapterId);
|
|
1004
938
|
this.agent.adapters.require(adapterId);
|
|
939
|
+
if (this.agent.adapters.native(adapterId)) requireNativeMeteringCapability(
|
|
940
|
+
(config.runtime?.metering ?? this.settings.defaults.metering)?.enforcement);
|
|
1005
941
|
const mode = config.mode ?? config.runtime?.mode ?? this.settings.defaults.mode;
|
|
1006
942
|
if (mode === "degraded" && config.providerSession === "load") {
|
|
1007
943
|
throw new Error("providerSession.kind=load requires ACP (normal) mode");
|
|
1008
944
|
}
|
|
945
|
+
return adapterId;
|
|
1009
946
|
}
|
|
1010
947
|
|
|
1011
948
|
/**
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
import type { ConversationPersistenceResolver } from "./persistence-policy/types.ts";
|
|
25
25
|
|
|
26
26
|
export interface ManagerSettings {
|
|
27
|
+
readonly role?: "worker";
|
|
27
28
|
readonly defaultAdapterId?: string;
|
|
28
29
|
readonly identityConsistency: IdentityConsistency;
|
|
29
30
|
readonly identityTimeoutMs?: number;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { NativeAdapter } from "../adapters.ts";
|
|
2
|
+
import type { Agent } from "../agent.ts";
|
|
3
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
4
|
+
import type { DeleteConversationOptions } from "./config.ts";
|
|
5
|
+
import type { CreateAgentConversationInput, PersistenceBackend, PersistenceScope } from "../persistence/backend.ts";
|
|
6
|
+
import type { ChannelDesire, ChannelPersistence } from "../persistence/channels.ts";
|
|
7
|
+
|
|
8
|
+
/** Enforce channel lifecycle precedence in the same transaction as a declarative change. */
|
|
9
|
+
export function protectPendingRetirement(
|
|
10
|
+
persistence: PersistenceBackend,
|
|
11
|
+
channels: ChannelPersistence,
|
|
12
|
+
): ChannelPersistence {
|
|
13
|
+
return {
|
|
14
|
+
desire(channel, desire) {
|
|
15
|
+
if (desire.lifecycle === undefined) return channels.desire(channel, desire);
|
|
16
|
+
const change = { ...desire };
|
|
17
|
+
return persistence.transaction(async ({ channels: scoped, reminders }) => {
|
|
18
|
+
const pending = await scoped!.pendingChange(channel);
|
|
19
|
+
if (pending?.desire.lifecycle === "retired" && change.lifecycle !== "retired") return pending;
|
|
20
|
+
const result = await scoped!.desire(channel, change);
|
|
21
|
+
await reminders?.setConversationSuspended(channel, change.lifecycle !== "open");
|
|
22
|
+
return result;
|
|
23
|
+
});
|
|
24
|
+
},
|
|
25
|
+
pendingChange: channels.pendingChange.bind(channels),
|
|
26
|
+
pendingChanges: channels.pendingChanges.bind(channels),
|
|
27
|
+
confirmChange(channel, version) {
|
|
28
|
+
return persistence.transaction(async ({ channels: scoped, reminders }) => {
|
|
29
|
+
const pending = await scoped!.pendingChange(channel);
|
|
30
|
+
const confirmed = await scoped!.confirmChange(channel, version);
|
|
31
|
+
if (confirmed && pending?.version === version && pending.desire.lifecycle !== undefined) {
|
|
32
|
+
await reminders?.setConversationSuspended(channel, pending.desire.lifecycle !== "open");
|
|
33
|
+
}
|
|
34
|
+
return confirmed;
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function initialChannelDesire(adapter: NativeAdapter, title?: string): ChannelDesire | undefined {
|
|
41
|
+
if (title === undefined && adapter.defaultPolicy === undefined) return undefined;
|
|
42
|
+
return {
|
|
43
|
+
...(title !== undefined ? { displayName: title } : {}),
|
|
44
|
+
...(adapter.defaultPolicy !== undefined ? { policy: adapter.defaultPolicy } : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Stores the initial settings alongside the conversation row when the backend supports channel intents. */
|
|
49
|
+
export async function createConversationWithChannel(
|
|
50
|
+
agent: Agent,
|
|
51
|
+
input: CreateAgentConversationInput,
|
|
52
|
+
adapter: NativeAdapter | null,
|
|
53
|
+
): Promise<boolean> {
|
|
54
|
+
const { persistence, nativeHarness } = agent;
|
|
55
|
+
input = { ...input, controllerKind: adapter ? "native" : "acp" };
|
|
56
|
+
const desire = adapter && initialChannelDesire(adapter, input.title);
|
|
57
|
+
if (!nativeHarness || !persistence.capabilities.channels || !desire) {
|
|
58
|
+
await persistence.conversations.create(input);
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
const committed = persistence.transaction(async (scope) => {
|
|
62
|
+
await scope.conversations.create(input);
|
|
63
|
+
await scope.channels!.desire(input.agentConversationId, desire);
|
|
64
|
+
});
|
|
65
|
+
await nativeHarness.deliverCommittedChannelChange(input.agentConversationId, committed);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function deleteConversationWithChannel(
|
|
70
|
+
agent: Agent,
|
|
71
|
+
id: AgentConversationId,
|
|
72
|
+
{ checkpoints, deletedAt, providerSession }: DeleteConversationOptions,
|
|
73
|
+
liveAdapterId?: string,
|
|
74
|
+
) {
|
|
75
|
+
const { persistence, nativeHarness } = agent;
|
|
76
|
+
const classify = async (scope: PersistenceScope) => {
|
|
77
|
+
const kind = (await scope.conversations.get(id))?.controllerKind;
|
|
78
|
+
const descriptor = kind !== "native" && (kind === undefined || providerSession === "best-effort")
|
|
79
|
+
? await scope.providerSessions.active(id)
|
|
80
|
+
: null;
|
|
81
|
+
const adapterId = descriptor?.adapterId ?? liveAdapterId;
|
|
82
|
+
const retired = kind === "native" || (kind === undefined && !!adapterId && agent.adapters.native(adapterId) !== null);
|
|
83
|
+
return { retired, active: !retired && providerSession === "best-effort" ? descriptor : null };
|
|
84
|
+
};
|
|
85
|
+
const remove = async (scope: PersistenceScope) => {
|
|
86
|
+
const count = checkpoints ? (await scope.recoveryCheckpoints?.deleteForConversation?.(id)) ?? 0 : 0;
|
|
87
|
+
await scope.reminders?.deleteConversation(id);
|
|
88
|
+
await scope.conversations.delete(id, deletedAt);
|
|
89
|
+
return count;
|
|
90
|
+
};
|
|
91
|
+
if (persistence.capabilities.channels) {
|
|
92
|
+
const committed = persistence.transaction(async (scope) => {
|
|
93
|
+
const disposition = await classify(scope);
|
|
94
|
+
if (disposition.retired) await scope.channels!.desire(id, { lifecycle: "retired" });
|
|
95
|
+
return { ...disposition, checkpointsDeleted: await remove(scope) };
|
|
96
|
+
});
|
|
97
|
+
return nativeHarness ? nativeHarness.deliverCommittedChannelChange(id, committed, ({ retired }) => retired) : committed;
|
|
98
|
+
}
|
|
99
|
+
const disposition = await classify(persistence);
|
|
100
|
+
if (disposition.retired) await nativeHarness?.changeChannel(id, { lifecycle: "retired" });
|
|
101
|
+
const checkpointsDeleted = persistence.reminders ? await persistence.transaction(remove) : await remove(persistence);
|
|
102
|
+
return { ...disposition, checkpointsDeleted };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function protectedChannels(persistence: PersistenceBackend): ChannelPersistence | undefined {
|
|
106
|
+
if (!persistence.capabilities.channels) return undefined;
|
|
107
|
+
if (!persistence.channels) {
|
|
108
|
+
throw new Error("The persistence backend advertises channel intents but provides no channels repository");
|
|
109
|
+
}
|
|
110
|
+
return protectPendingRetirement(persistence, persistence.channels);
|
|
111
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
|
+
import type { ChannelChangeOutcome } from "../native/channel-changes.ts";
|
|
3
|
+
import type { AgentHarnessConfig } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
export const channelSettingsLive = {
|
|
6
|
+
channel: ["displayName", "policy", "lifecycle"],
|
|
7
|
+
channelOperations: ["create", "edit", "suspend", "resume", "delete"],
|
|
8
|
+
sessionTools: ["enable", "remove", "revoke", "restore"],
|
|
9
|
+
restartRequired: ["policies", "defaultPolicy", "model", "system", "toolCatalog", "participants"],
|
|
10
|
+
} as const;
|
|
11
|
+
export type NativeToolSetting = typeof channelSettingsLive.sessionTools[number];
|
|
12
|
+
export type NativeChannelSettings = Readonly<Record<string, unknown>> & {
|
|
13
|
+
readonly displayName?: string | null;
|
|
14
|
+
readonly policy?: string | null;
|
|
15
|
+
readonly lifecycle?: "open" | "suspended" | "retired";
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type NativeChannelSettingsResult = ChannelChangeOutcome
|
|
19
|
+
| { readonly state: "unsupported"; readonly code: "channel_settings_not_live"; readonly fields: readonly string[] }
|
|
20
|
+
| { readonly state: "unsupported"; readonly code: "invalid_channel_settings" | "not_native_conversation" };
|
|
21
|
+
|
|
22
|
+
export interface NativeRestartOptions {
|
|
23
|
+
readonly when?: "idle" | "now";
|
|
24
|
+
readonly signal?: AbortSignal;
|
|
25
|
+
readonly config?: AgentHarnessConfig["config"];
|
|
26
|
+
readonly functions?: AgentHarnessConfig["functions"] | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface NativeRestartPreview {
|
|
30
|
+
readonly conversationCount: number;
|
|
31
|
+
readonly conversationIds: readonly AgentConversationId[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type NativeRestartResult = NativeRestartPreview & {
|
|
35
|
+
readonly kind: "restarted" | "restart_failed";
|
|
36
|
+
readonly interruptedTurns: readonly { channel: string; turnId: string }[];
|
|
37
|
+
readonly conversations: readonly { id: AgentConversationId; outcome: "reconnected" | "deferred" | "failed" }[];
|
|
38
|
+
readonly error?: unknown;
|
|
39
|
+
};
|