@qlairoslabs/acp-client 0.7.4 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +571 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +60 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +1032 -674
  14. package/src/agent.ts +1223 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +127 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/identity/checkpoint-backed.ts +248 -0
  30. package/src/identity.ts +76 -0
  31. package/src/index.ts +132 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +839 -0
  50. package/src/persistence/index.ts +113 -0
  51. package/src/persistence/sqlite-backend.ts +2192 -0
  52. package/src/persistence/sqlite-conversation-records.ts +430 -0
  53. package/src/persistence/sqlite-owner-lock.ts +106 -0
  54. package/src/persistence/sqlite-schema.ts +589 -0
  55. package/src/persistence/timeline-reconcile.ts +72 -0
@@ -1,13 +1,13 @@
1
- // AgentSession — the durable conversation and the library's FRONT FACE. This is what a
2
- // consumer (the orchestration hub, the CLI) holds: a conversation with a stable identity
3
- // that persists across reconnects/mode-swaps, backed by a SessionManager catalog.
1
+ // AgentConversation — one durable conversation and the library's compatibility front
2
+ // face. Existing consumers still import this constructor as `AgentSession`; both names
3
+ // refer to the same class while the new agent-level owner is introduced.
4
4
  //
5
5
  // It owns identity (our `agentSessionId`, adapter, mode, internalSessionId, title) and persistence, and
6
6
  // HOLDS an AgentController for the live connection (the control plane). It implements
7
7
  // AgentClient, so the REPL and any caller can prompt it directly.
8
8
  //
9
- // Adapter lives HERE, not on the controller: switching adapter = a new AgentSession (the
10
- // agent dies on switch). Mode-swap (degrade/upgrade) stays within one AgentSession.
9
+ // Adapter ownership remains here during the compatibility tranche. The later Agent owner
10
+ // supplies the adapter registry used by cross-adapter conversation transitions.
11
11
 
12
12
  import {
13
13
  AgentController,
@@ -17,15 +17,28 @@ import {
17
17
  } from "./controller.ts";
18
18
  import type * as schema from "@agentclientprotocol/sdk";
19
19
  import { join } from "node:path";
20
- import { ActivityAggregator, type ActivitySnapshot, type AggregatedRecord } from "./activity.ts";
20
+ import type { ActivitySnapshot, AggregatedRecord } from "./activity.ts";
21
21
  import type { Adapter } from "./adapters.ts";
22
+ import {
23
+ createAgentConversationId,
24
+ isAgentConversationId,
25
+ isAgentSessionId,
26
+ type AgentConversationId,
27
+ type AgentSessionId,
28
+ } from "./agent-ids.ts";
29
+ import type {
30
+ NewConversationRecord,
31
+ ParticipantRef,
32
+ PersistenceJsonValue,
33
+ } from "./persistence/backend.ts";
34
+ import type { AgentConversationOwnerLifecycle } from "./agent-conversation-owner.ts";
22
35
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
23
36
  import type { Capabilities } from "./capabilities.ts";
24
37
  import type { ConfigOption, ConfigOptions } from "./config-options.ts";
25
38
  import type { ConnectResult } from "./client.ts";
26
39
  import { noopLogger, type Logger } from "./logger.ts";
27
40
  import { formatResponseMessages, ResponseAccumulator } from "./response.ts";
28
- import { MeteringEngine, type OpenOperation } from "./metering/engine.ts";
41
+ import { MeteringEngine, type OpenDetachedOperation, type OpenOperation } from "./metering/engine.ts";
29
42
  import {
30
43
  AgentSessionHandoffError,
31
44
  AgentSessionOperationError,
@@ -49,7 +62,6 @@ import {
49
62
  import type { SessionManager, MergedSession } from "./session-manager.ts";
50
63
  import {
51
64
  appendTranscriptLine,
52
- type TranscriptActivityLine,
53
65
  type TranscriptLine,
54
66
  } from "./transcript.ts";
55
67
  import type {
@@ -58,6 +70,8 @@ import type {
58
70
  Attachment,
59
71
  PromptHandlers,
60
72
  PromptResult,
73
+ PermissionOutcome,
74
+ PermissionRequest,
61
75
  ResponseMessage,
62
76
  SessionListEntry,
63
77
  TokenUsage,
@@ -88,20 +102,14 @@ import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.t
88
102
  import {
89
103
  RegistryPersistenceRuntime,
90
104
  type PersistenceStateRuntime,
91
- type PresentationPersistenceEvent,
92
105
  } from "./persistence/state-runtime.ts";
93
106
  import { AuditPersistenceRuntime, AuditedPersistenceRuntime, type AuditLogIdentity } from "./persistence/audit-runtime.ts";
94
107
  import { TranscriptReader } from "./persistence/transcript-reader.ts";
95
- import {
96
- presentationItemFromRecord,
97
- type TranscriptPresentationItem,
98
- } from "./persistence/presentation.ts";
99
108
  import {
100
109
  snapshotSessionConfiguration,
101
110
  snapshotSessionConfigurationAfterSelection,
102
111
  snapshotAcceptedEffectiveConfiguration,
103
112
  } from "./persistence/configuration-state.ts";
104
- import { persistenceEventFromActivity } from "./persistence/activity-projection.ts";
105
113
  import {
106
114
  canonicalizeJson,
107
115
  sha256CanonicalJson,
@@ -111,6 +119,89 @@ import type { PersistenceRepair, SessionRecoveryStatus } from "./persistence/red
111
119
  import type { StagedContinuationState } from "./persistence/registry.ts";
112
120
  import type { SessionLogWriterLock } from "./persistence/session-log-writer.ts";
113
121
  import type { ManagedOpenProgressReporter } from "./persistence/managed-open-progress.ts";
122
+ import {
123
+ AdapterMismatchError,
124
+ AgentSessionPromptBlockedError,
125
+ ContinuationUnavailableError,
126
+ DirectAuditPersistenceUnsupportedError,
127
+ } from "./agent-conversation-errors.ts";
128
+ import type {
129
+ AgentSessionEvent,
130
+ AgentSessionListener,
131
+ AgentSessionNotification,
132
+ AgentSessionPhase,
133
+ AgentSessionPromptResult,
134
+ AgentSessionPromptability,
135
+ AgentSessionRecoveryResolution,
136
+ AgentSessionRecoveryResolutionResult,
137
+ AgentSessionState,
138
+ ConfigurationMismatchResolution,
139
+ ConfigurationMismatchResolutionResult,
140
+ ConfigurationRestoreStatus,
141
+ ContinuationAttempt,
142
+ ContinuationReport,
143
+ ContinuationStrategy,
144
+ HandoffOptions,
145
+ HandoffResult,
146
+ OpenContinuationOptions,
147
+ PromptBlocker,
148
+ ProviderSession,
149
+ TranscriptActivityConfig,
150
+ TranscriptContinuationBuilder,
151
+ TranscriptContinuationBuilderContext,
152
+ } from "./agent-conversation-contracts.ts";
153
+ import { AgentConversationQueue } from "./agent-conversation-queue.ts";
154
+ import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
155
+ import {
156
+ HANDOFF_SUMMARY_PROMPT,
157
+ buildContinuationPrompt,
158
+ createContinuationReport,
159
+ descriptorFromCheckpoint,
160
+ isReconstructionStrategy,
161
+ normalizeContinuationStrategies,
162
+ stageOpeningContinuation,
163
+ } from "./agent-conversation-continuation.ts";
164
+
165
+ export {
166
+ AdapterMismatchError,
167
+ AgentSessionPromptBlockedError,
168
+ ContinuationUnavailableError,
169
+ DirectAuditPersistenceUnsupportedError,
170
+ } from "./agent-conversation-errors.ts";
171
+ export type {
172
+ AgentConversationEvent,
173
+ AgentConversationListener,
174
+ AgentConversationNotification,
175
+ AgentConversationPhase,
176
+ AgentConversationPromptResult,
177
+ AgentConversationPromptability,
178
+ AgentConversationRecoveryResolution,
179
+ AgentConversationRecoveryResolutionResult,
180
+ AgentConversationState,
181
+ AgentSessionEvent,
182
+ AgentSessionListener,
183
+ AgentSessionNotification,
184
+ AgentSessionPhase,
185
+ AgentSessionPromptResult,
186
+ AgentSessionPromptability,
187
+ AgentSessionRecoveryResolution,
188
+ AgentSessionRecoveryResolutionResult,
189
+ AgentSessionState,
190
+ ConfigurationMismatchResolution,
191
+ ConfigurationMismatchResolutionResult,
192
+ ConfigurationRestoreStatus,
193
+ ContinuationAttempt,
194
+ ContinuationReport,
195
+ ContinuationStrategy,
196
+ HandoffOptions,
197
+ HandoffResult,
198
+ OpenContinuationOptions,
199
+ PromptBlocker,
200
+ ProviderSession,
201
+ TranscriptActivityConfig,
202
+ TranscriptContinuationBuilder,
203
+ TranscriptContinuationBuilderContext,
204
+ } from "./agent-conversation-contracts.ts";
114
205
 
115
206
  interface PromptQueueItem {
116
207
  kind: "prompt";
@@ -118,12 +209,26 @@ interface PromptQueueItem {
118
209
  /** How this operation is classified in its metering record. */
119
210
  operationKind: MeteredOperationKind;
120
211
  text: string;
212
+ participantId?: string;
213
+ consumerMetadata?: PersistenceJsonValue;
121
214
  handlers?: PromptHandlers;
122
215
  attachments?: Attachment[];
123
216
  resolve: (r: AgentSessionPromptResult) => void;
124
217
  reject: (e: unknown) => void;
125
218
  }
126
219
 
220
+ /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
221
+ export interface AgentConversationPromptInput {
222
+ readonly text: string;
223
+ readonly consumerMetadata?: PersistenceJsonValue;
224
+ readonly handlers?: PromptHandlers;
225
+ readonly attachments?: Attachment[];
226
+ }
227
+
228
+ export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
229
+ readonly participantId: string;
230
+ }
231
+
127
232
  interface HandoffQueueItem {
128
233
  kind: "handoff";
129
234
  handoffId: string;
@@ -165,108 +270,8 @@ interface RecoveryResolutionQueueItem {
165
270
 
166
271
  type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
167
272
 
168
- /** What the stable logical session is doing right now. */
169
- export type AgentSessionPhase =
170
- | "idle"
171
- | "prompting"
172
- | "handoff"
173
- | "configuring"
174
- | "recovering"
175
- | "switching_mode"
176
- | "stopped";
177
-
178
- /** Authoritative, immutable point-in-time state for orchestration consumers. */
179
- export interface AgentSessionState {
180
- readonly phase: AgentSessionPhase;
181
- /** True only while an operation is executing; queued work is reported separately. */
182
- readonly isBusy: boolean;
183
- /** Operations waiting behind the active one. Does not count the active operation. */
184
- readonly queuedOperationCount: number;
185
- readonly agentSessionId: string;
186
- readonly internalSessionId: string | null;
187
- readonly adapterId: string;
188
- readonly mode: AgentMode;
189
- readonly promptability: AgentSessionPromptability;
190
- }
191
-
192
- export type ConfigurationRestoreStatus =
193
- | { readonly kind: "matched" }
194
- | { readonly kind: "partial"; readonly omittedConfigIds: readonly string[] }
195
- | {
196
- readonly kind: "mismatch";
197
- readonly configIds: readonly string[];
198
- readonly reasons: readonly string[];
199
- };
200
-
201
- export type PromptBlocker =
202
- | "continuation_unavailable"
203
- | "recovery_required"
204
- | "configuration_mismatch"
205
- | "persistence_unhealthy"
206
- | "maintenance_pending"
207
- | "session_stopped";
208
-
209
- export type AgentSessionPromptability =
210
- | { readonly promptable: true; readonly blockers: readonly [] }
211
- | { readonly promptable: false; readonly blockers: readonly PromptBlocker[] };
212
-
213
- export interface ContinuationAttempt {
214
- readonly strategy: ContinuationStrategy["kind"];
215
- readonly status: "succeeded" | "failed" | "skipped";
216
- readonly errorCode?: PersistedMachineCode;
217
- readonly reason?: string;
218
- }
219
-
220
- export interface ContinuationReport {
221
- readonly recordedAdapterId: string;
222
- readonly recordedInternalSessionId: string | null;
223
- readonly requestedAdapterId: string;
224
- readonly recordedConversationAvailability: "available" | "partial" | "not_captured";
225
- readonly recordedThreadAvailability: "available" | "unavailable" | "not_checked";
226
- readonly attempts: readonly ContinuationAttempt[];
227
- readonly outcome:
228
- | { readonly kind: "loaded"; readonly activeInternalSessionId: string }
229
- | {
230
- readonly kind: "reconstructed";
231
- readonly source: "transcript" | "consumer";
232
- readonly activeInternalSessionId: string;
233
- readonly transitionId: string;
234
- }
235
- | { readonly kind: "unavailable" };
236
- }
237
-
238
- export interface TranscriptContinuationBuilderContext {
239
- readonly agentSessionId: string;
240
- readonly checkpoint: AgentSessionCheckpoint;
241
- /** Snapshot-bound access to captured history; the builder decides how much to read. */
242
- readonly transcript: TranscriptReader;
243
- readonly targetAdapterId: string;
244
- }
245
-
246
- export type TranscriptContinuationBuilder = (
247
- context: TranscriptContinuationBuilderContext,
248
- ) => Promise<{ readonly continuation: string; readonly metadata?: Readonly<Record<string, JsonValue>> }>;
249
-
250
- export type ContinuationStrategy =
251
- | { readonly kind: "load_internal_session" }
252
- | {
253
- readonly kind: "new_from_transcript";
254
- readonly strategyId: string;
255
- readonly buildContinuation: TranscriptContinuationBuilder;
256
- }
257
- | {
258
- readonly kind: "new_from_consumer_continuation";
259
- readonly continuationId: string;
260
- readonly continuation: string;
261
- };
262
-
263
- export interface OpenContinuationOptions {
264
- /** Defaults to only `load_internal_session`; an empty array is invalid. */
265
- readonly strategies?: readonly ContinuationStrategy[];
266
- }
267
-
268
273
  export interface AgentSessionOpenResult {
269
- readonly session: AgentSession;
274
+ readonly session: AgentConversation;
270
275
  readonly continuation: ContinuationReport;
271
276
  readonly recovery: SessionRecoveryStatus;
272
277
  readonly configuration: ConfigurationRestoreStatus;
@@ -274,227 +279,6 @@ export interface AgentSessionOpenResult {
274
279
  readonly repairs: readonly PersistenceRepair[];
275
280
  }
276
281
 
277
- export type ConfigurationMismatchResolution =
278
- | { readonly strategy: "accept_effective" }
279
- | {
280
- readonly strategy: "replace_restoration_targets";
281
- readonly selections: readonly { readonly configId: string; readonly value: JsonValue }[];
282
- };
283
-
284
- export interface ConfigurationMismatchResolutionResult {
285
- readonly configuration: ConfigurationRestoreStatus;
286
- readonly appliedConfigIds: readonly string[];
287
- }
288
-
289
- export type AgentSessionRecoveryResolution =
290
- | { readonly strategy: "accept_harness_state" }
291
- | {
292
- readonly strategy: "start_new_internal_session";
293
- /** When omitted, the currently loaded harness thread generates portable context. */
294
- readonly continuation?: string;
295
- };
296
-
297
- export interface AgentSessionRecoveryResolutionResult {
298
- readonly previous: Extract<SessionRecoveryStatus, { readonly kind: "uncertain" }>;
299
- readonly recovery: Extract<SessionRecoveryStatus, { readonly kind: "clean" }>;
300
- /** Present when resolution deliberately replaced the provider thread. */
301
- readonly handoff?: HandoffResult;
302
- }
303
-
304
- export class AgentSessionPromptBlockedError extends Error {
305
- constructor(readonly blockers: readonly PromptBlocker[]) {
306
- super(`AgentSession cannot mutate while blocked: ${blockers.join(", ")}`);
307
- this.name = "AgentSessionPromptBlockedError";
308
- }
309
- }
310
-
311
- export class ContinuationUnavailableError extends Error {
312
- constructor(readonly continuation: ContinuationReport, options?: ErrorOptions) {
313
- super("recorded internal session could not be loaded", options);
314
- this.name = "ContinuationUnavailableError";
315
- }
316
- }
317
-
318
- export class AdapterMismatchError extends Error {
319
- constructor(readonly recordedAdapterId: string, readonly requestedAdapterId: string) {
320
- super(`adapter mismatch: transcript requires ${recordedAdapterId}, received ${requestedAdapterId}`);
321
- this.name = "AdapterMismatchError";
322
- }
323
- }
324
-
325
- /** Direct V2 audit creation is deferred until it has the same crash transaction as managed creation. */
326
- export class DirectAuditPersistenceUnsupportedError extends Error {
327
- constructor() {
328
- super("direct V2 audit persistence is not supported; use SessionManager.createAgentSession()");
329
- this.name = "DirectAuditPersistenceUnsupportedError";
330
- }
331
- }
332
-
333
- export interface HandoffOptions {
334
- /** Portable continuation context. When omitted, the current thread generates it. */
335
- readonly summary?: string;
336
- }
337
-
338
- export interface HandoffResult {
339
- readonly handoffId: string;
340
- readonly agentSessionId: string;
341
- readonly fromInternalSessionId: string | null;
342
- readonly toInternalSessionId: string;
343
- readonly summary: string;
344
- /** One record per token-consuming operation the handoff performed, in order. */
345
- readonly meteringRecords: readonly OperationMeteringRecord[];
346
- }
347
-
348
- /** Session-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
349
- export type AgentSessionEvent =
350
- | { kind: "state_changed"; state: AgentSessionState }
351
- | { kind: "turn_started"; turnId: string }
352
- | { kind: "turn_completed"; turnId: string; result: PromptResult }
353
- | { kind: "turn_failed"; turnId: string; error: string }
354
- /** A display item revision was appended to the transcript and can be joined to reloads by id. */
355
- | { kind: "presentation_recorded"; item: TranscriptPresentationItem }
356
- /** The active ACP harness changed the slash commands it advertises. */
357
- | { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
358
- | {
359
- kind: "handoff_started";
360
- handoffId: string;
361
- fromInternalSessionId: string | null;
362
- }
363
- | { kind: "handoff_completed"; result: HandoffResult }
364
- | {
365
- kind: "handoff_failed";
366
- handoffId: string;
367
- fromInternalSessionId: string | null;
368
- toInternalSessionId?: string;
369
- error: string;
370
- /** Records produced before and during the failure. */
371
- meteringRecords: readonly OperationMeteringRecord[];
372
- }
373
- | { kind: "configuration_started"; operationId: string; configId: string }
374
- | { kind: "configuration_completed"; operationId: string; configId: string }
375
- | { kind: "configuration_failed"; operationId: string; configId: string; error: string }
376
- | { kind: "mode_change_started"; transitionId: string; from: AgentMode; to: AgentMode }
377
- | { kind: "mode_change_completed"; transitionId: string; from: AgentMode; to: AgentMode }
378
- | { kind: "mode_change_failed"; transitionId: string; from: AgentMode; to: AgentMode; error: string }
379
- | {
380
- kind: "configuration_mismatch_resolved";
381
- configuration: ConfigurationRestoreStatus;
382
- appliedConfigIds: readonly string[];
383
- }
384
- | {
385
- kind: "recovery_resolved";
386
- strategy: AgentSessionRecoveryResolution["strategy"];
387
- previous: Extract<SessionRecoveryStatus, { kind: "uncertain" }>;
388
- recovery: Extract<SessionRecoveryStatus, { kind: "clean" }>;
389
- }
390
- /** Latest context-window observation for the ACTIVE provider thread, or null. */
391
- | { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
392
- /** Latest cumulative provider-reported cost. Telemetry, never asserted to be an invoice. */
393
- | { kind: "provider_cost_changed"; providerCost: ProviderCostSnapshot | null }
394
- /** One immutable record per observed operation, emitted before its turn completes. */
395
- | { kind: "metering_recorded"; record: OperationMeteringRecord }
396
- /** A strict mode detected a metering failure; later token-consuming work will reject. */
397
- | { kind: "metering_blocked"; reason: string }
398
- | { kind: "metering_unblocked" }
399
- | {
400
- kind: "metering_reconciled";
401
- before: AgentSessionMeteringState;
402
- after: AgentSessionMeteringState;
403
- reason: string;
404
- reference?: string;
405
- reconciledAt: number;
406
- };
407
-
408
- /** A prompt result enriched with the operation's metering record. */
409
- export interface AgentSessionPromptResult extends PromptResult {
410
- readonly operationId: string;
411
- /**
412
- * The operation's record, or null when the operation never reached the provider.
413
- *
414
- * Null happens only for a queued prompt cancelled before dispatch (§16). Such an
415
- * operation consumed nothing, and minting a record for it would put a fabricated
416
- * entry in the consumer's ledger — so the field is honestly empty instead.
417
- */
418
- readonly metering: OperationMeteringRecord | null;
419
- }
420
-
421
- /** Ordered envelope delivered to every AgentSession subscriber. */
422
- export interface AgentSessionNotification {
423
- readonly seq: number;
424
- readonly ts: number;
425
- readonly agentSessionId: string;
426
- readonly event: AgentSessionEvent;
427
- }
428
-
429
- export type AgentSessionListener = (notification: AgentSessionNotification) => void;
430
-
431
- /** What to record when `transcriptActivity` is on. */
432
- export interface TranscriptActivityConfig {
433
- /**
434
- * Which record kinds to persist. Default: `tool`, `thinking`, `plan`, `plan_update`,
435
- * `plan_removed`, `usage`, `mode`, `unknown` — everything except client state
436
- * (`commands`, `config`, `session_info`) and `user_message`, which duplicates `t:"msg"`.
437
- */
438
- kinds?: Array<ActivityEvent["kind"]>;
439
- /**
440
- * Write an extra line the first time a tool call learns its arguments. Default true —
441
- * agents routinely announce a call long before they know what it will run, so without
442
- * this a turn that dies mid-call leaves a record naming the tool but not the command.
443
- *
444
- * This is an aggregator-level knob, so it also shapes `onRecord`'s `emitted` when no
445
- * transcript is configured.
446
- */
447
- checkpointOnInput?: boolean;
448
- /**
449
- * Persist `rawOutput`. Default false: in practice it is a byte-identical duplicate of
450
- * `content` (measured on live Kimi), so it doubles the largest field on the line.
451
- */
452
- rawOutput?: boolean;
453
- /**
454
- * Cap each individual string field (terminal output, text content, a stringified
455
- * `rawInput`) at this many bytes, appending `… [truncated N bytes]` and marking the
456
- * line `truncated: true`. Default off. Per-field on purpose — capping the serialized
457
- * line would emit unparseable JSON.
458
- */
459
- maxBytes?: number;
460
- }
461
-
462
- const DEFAULT_ACTIVITY_KINDS: Array<ActivityEvent["kind"]> = [
463
- "tool",
464
- "thinking",
465
- "plan",
466
- "plan_update",
467
- "plan_removed",
468
- "usage",
469
- "mode",
470
- "unknown",
471
- ];
472
-
473
- const HANDOFF_SUMMARY_PROMPT = [
474
- "Create portable continuation context for a new agent thread.",
475
- "Summarize the objective, decisions, completed work, current state, important files or identifiers,",
476
- "and concrete next steps. Preserve unresolved risks and constraints. Return only the continuation context.",
477
- ].join(" ");
478
-
479
- function continuationPrompt(summary: string): string {
480
- return [
481
- "Continue this conversation using the following portable continuation context.",
482
- "Treat it as prior context, not as a new user request. Confirm internally and continue from this state.",
483
- "",
484
- summary,
485
- ].join("\n");
486
- }
487
-
488
- /** Explicit selection of the provider thread backing a newly opened AgentSession. */
489
- export type ProviderSession =
490
- | { readonly kind: "new" }
491
- | {
492
- readonly kind: "load";
493
- readonly internalSessionId: string;
494
- /** Default "error": never silently replace a requested thread. */
495
- readonly onFailure?: "error" | "new";
496
- };
497
-
498
282
  export interface AgentSessionConfig {
499
283
  /** The resolved adapter this conversation talks to. */
500
284
  adapter: Adapter;
@@ -563,6 +347,14 @@ export interface AgentSessionConfig {
563
347
  */
564
348
  internalSessionId?: string;
565
349
  title?: string;
350
+ /** Stable conversation identity when this runtime is owned by an Agent. */
351
+ agentConversationId?: AgentConversationId;
352
+ /** Stable owning agent identity. Omitted for detached compatibility conversations. */
353
+ ownerAgentSessionId?: AgentSessionId;
354
+ /** Other sides of this conversation. The owning agent is implied. */
355
+ participants?: readonly ParticipantRef[];
356
+ /** @internal Installed by AgentConversationManager. */
357
+ ownerLifecycle?: AgentConversationOwnerLifecycle;
566
358
  }
567
359
 
568
360
  /** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
@@ -606,41 +398,39 @@ export interface ManagedAgentSessionPersistenceSnapshot {
606
398
  readonly auditLog: AuditLogIdentity | null;
607
399
  }
608
400
 
609
- export class AgentSession implements AgentClient, Bridgeable {
610
- /** Our stable AgentSession id — decoupled from the ACP/harness session id. */
401
+ export class AgentConversation implements AgentClient, Bridgeable {
402
+ /** Compatibility logical id — decoupled from the ACP/harness session id. */
611
403
  readonly agentSessionId: string;
612
- readonly adapterId: string;
613
-
614
- private readonly controller: AgentController;
404
+ readonly agentConversationId: AgentConversationId;
405
+ readonly ownerAgentSessionId: AgentSessionId | null;
406
+ private _adapterId: string;
407
+ private activeAdapter: Adapter;
408
+
409
+ private controller: AgentController;
410
+ private readonly controllerDefaults: Omit<
411
+ AgentControllerConfig,
412
+ "adapter" | "adapterId" | "mode" | "sessionId" | "sessionLoadFailure"
413
+ >;
414
+ private detachControllerCommands: (() => void) | null = null;
415
+ private detachControllerUsage: (() => void) | null = null;
615
416
  private readonly sessions?: SessionManager;
616
417
  private readonly _transcriptPath?: string;
617
418
  private readonly persistence: false | ResolvedAgentSessionPersistence;
618
419
  private readonly creationId: string;
619
420
  private v2Transcript: PersistenceStateRuntime | null = null;
620
421
  private v2TranscriptPath: string | null = null;
621
- /** One display queue preserves the live message/activity interleaving seen by consumers. */
622
- private v2PresentationWrite: Promise<void> = Promise.resolve();
623
- private readonly transcriptActivity: boolean;
624
- private readonly activityKinds: Set<string>;
625
- private readonly activityRawOutput: boolean;
626
- private readonly activityMaxBytes: number | null;
627
- /**
628
- * THE aggregator — one per session for its whole life, never one per turn: `seq` has to
629
- * keep counting across turns or a subscriber's discard threshold goes stale (see
630
- * `activitySnapshot`). Runs unconditionally, so a snapshot is truthful and `onRecord`
631
- * works whether or not a transcript is configured.
632
- */
633
- private readonly aggregator: ActivityAggregator;
422
+ private readonly presentation: AgentConversationPresentation;
634
423
  private readonly log: Logger;
635
424
  private transcriptWrite: Promise<void> = Promise.resolve();
636
- private queue: QueueItem[] = [];
637
- private pumping = false;
425
+ private readonly operations = new AgentConversationQueue<QueueItem>();
638
426
  private phase: AgentSessionPhase = "idle";
639
427
  private notificationSeq = 0;
640
428
  private readonly listeners = new Set<AgentSessionListener>();
641
429
  private lastStateKey = "";
642
430
  private _internalSessionId: string | null;
643
- private readonly metering: MeteringEngine;
431
+ private ownerContextNonce: string | null = null;
432
+ private metering: MeteringEngine;
433
+ private readonly meteringConfig: MeteringConfig;
644
434
  private _contextWindow: ContextWindowStatus | null = null;
645
435
  private _providerCost: ProviderCostSnapshot | null = null;
646
436
  /**
@@ -663,6 +453,10 @@ export class AgentSession implements AgentClient, Bridgeable {
663
453
  private managedAuditLog: AuditLogIdentity | null = null;
664
454
  private readonly managedOpenProgress?: ManagedOpenProgressReporter;
665
455
  private managedInitializationReported = false;
456
+ private readonly ownerLifecycle?: AgentConversationOwnerLifecycle;
457
+ private _participants: ParticipantRef[];
458
+ private ownerRecordWrite: Promise<void> = Promise.resolve();
459
+ private readonly defaultPermission: "approve" | "cancel";
666
460
 
667
461
  private constructor(
668
462
  config: AgentSessionConfig,
@@ -699,7 +493,23 @@ export class AgentSession implements AgentClient, Bridgeable {
699
493
  // IDs are opaque provider/consumer values. Validate blankness above, but never
700
494
  // normalize a nonblank identifier and accidentally select a different session.
701
495
  this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
702
- this.adapterId = config.adapterId;
496
+ if (config.agentConversationId !== undefined && !isAgentConversationId(config.agentConversationId)) {
497
+ throw new Error(`invalid agent conversation id: ${config.agentConversationId}`);
498
+ }
499
+ if (config.ownerAgentSessionId !== undefined && !isAgentSessionId(config.ownerAgentSessionId)) {
500
+ throw new Error(`invalid owner agent session id: ${config.ownerAgentSessionId}`);
501
+ }
502
+ if (config.ownerAgentSessionId !== undefined && config.agentSessionId !== config.ownerAgentSessionId) {
503
+ throw new Error("owned AgentConversation agentSessionId must equal ownerAgentSessionId");
504
+ }
505
+ this.agentConversationId = config.agentConversationId ?? createAgentConversationId();
506
+ this.ownerAgentSessionId = config.ownerAgentSessionId
507
+ ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
508
+ this.ownerLifecycle = config.ownerLifecycle;
509
+ this.defaultPermission = config.defaultPermission ?? "cancel";
510
+ this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
511
+ this._adapterId = config.adapterId;
512
+ this.activeAdapter = config.adapter;
703
513
  this.sessions = config.sessions;
704
514
  this.persistence = resolveDirectPersistence(config.persistence);
705
515
  if (this.persistence !== false && config.sessions) {
@@ -722,19 +532,21 @@ export class AgentSession implements AgentClient, Bridgeable {
722
532
  (config.transcriptDir
723
533
  ? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
724
534
  : undefined);
725
- const activity: TranscriptActivityConfig | null =
726
- config.transcriptActivity === true ? {} : config.transcriptActivity || null;
727
- this.transcriptActivity = activity !== null;
728
- this.activityKinds = new Set(activity?.kinds ?? DEFAULT_ACTIVITY_KINDS);
729
- this.activityRawOutput = activity?.rawOutput === true;
730
- this.activityMaxBytes =
731
- activity?.maxBytes != null && activity.maxBytes > 0 ? activity.maxBytes : null;
732
- this.aggregator = new ActivityAggregator({ checkpointOnInput: activity?.checkpointOnInput });
733
535
  this.log = config.logger ?? noopLogger;
536
+ this.presentation = new AgentConversationPresentation({
537
+ activity: config.transcriptActivity,
538
+ logger: this.log,
539
+ persistence: () => this.v2Transcript,
540
+ ...(this._transcriptPath
541
+ ? { appendLegacyActivity: (line) => this.appendTranscript(line) }
542
+ : {}),
543
+ onPresentation: (item) => this.emit({ kind: "presentation_recorded", item }),
544
+ });
734
545
  this._mode = config.mode ?? "normal";
735
546
  this._cwd = config.cwd;
736
547
  this._title = config.title;
737
548
  this._internalSessionId = requestedInternalSessionId ?? null;
549
+ this.meteringConfig = Object.freeze({ ...(config.metering ?? {}) });
738
550
  this.metering = new MeteringEngine({
739
551
  agentSessionId: this.agentSessionId,
740
552
  adapterId: config.adapterId,
@@ -752,31 +564,143 @@ export class AgentSession implements AgentClient, Bridgeable {
752
564
  // not, and needs restored state to be attributable.
753
565
  createdActiveThread: providerSession.kind === "new",
754
566
  });
755
- this.controller = new AgentController({
756
- adapter: config.adapter,
757
- adapterId: config.adapterId,
758
- mode: this._mode,
567
+ this.controllerDefaults = {
759
568
  launcher: config.launcher,
760
569
  execPrefix: config.execPrefix,
761
570
  env: config.env,
762
571
  cwd: config.cwd,
763
- sessionId: requestedInternalSessionId,
764
- sessionLoadFailure: providerSession.kind === "load"
765
- ? providerSession.onFailure ?? "error"
766
- : undefined,
767
572
  mcpServers: config.mcpServers,
768
573
  defaultPermission: config.defaultPermission,
769
574
  clientInfo: config.clientInfo,
770
575
  clientCapabilities: config.clientCapabilities,
771
576
  clientHandlers: config.clientHandlers,
772
577
  logger: config.logger,
773
- wire: config.wire,
578
+ ...(config.wire || this.ownerLifecycle
579
+ ? {
580
+ wire: (entry: WireEntry) => {
581
+ config.wire?.(entry);
582
+ this.queueProtocolRecord(entry);
583
+ },
584
+ }
585
+ : {}),
586
+ };
587
+ this.controller = this.createController(config.adapter, config.adapterId, this._mode, {
588
+ sessionId: requestedInternalSessionId,
589
+ sessionLoadFailure: providerSession.kind === "load"
590
+ ? providerSession.onFailure ?? "error"
591
+ : undefined,
774
592
  });
775
- this.controller.subscribeAvailableCommands((commands) => {
776
- this.emit({ kind: "internal_session_commands_changed", commands });
593
+ this.bindController(this.controller);
594
+ }
595
+
596
+ private createController(
597
+ adapter: Adapter,
598
+ adapterId: string,
599
+ mode: AgentMode,
600
+ startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure"> = {},
601
+ ): AgentController {
602
+ return new AgentController({
603
+ ...this.controllerDefaults,
604
+ adapter,
605
+ adapterId,
606
+ mode,
607
+ ...startup,
777
608
  });
778
- this.controller.subscribeUsageUpdate((update, sessionId) => {
779
- this.applyUsageUpdate(update, sessionId);
609
+ }
610
+
611
+ private bindController(controller: AgentController): void {
612
+ this.detachControllerCommands?.();
613
+ this.detachControllerUsage?.();
614
+ this.detachControllerCommands = controller.subscribeAvailableCommands((commands) => {
615
+ if (this.controller === controller) {
616
+ this.emit({ kind: "internal_session_commands_changed", commands });
617
+ }
618
+ });
619
+ this.detachControllerUsage = controller.subscribeUsageUpdate((update, sessionId) => {
620
+ if (this.controller === controller) this.applyUsageUpdate(update, sessionId);
621
+ });
622
+ }
623
+
624
+ private queueOwnedRecord(record: NewConversationRecord): void {
625
+ if (!this.ownerLifecycle?.record) return;
626
+ this.ownerRecordWrite = this.ownerRecordWrite
627
+ .then(() => this.ownerLifecycle!.record!(record))
628
+ .catch((error) => {
629
+ this.markManagedPersistenceUnhealthy();
630
+ throw error;
631
+ });
632
+ }
633
+
634
+ private async recordOwned(record: NewConversationRecord): Promise<void> {
635
+ if (!this.ownerLifecycle?.record) return;
636
+ const write = this.ownerRecordWrite
637
+ .then(() => this.ownerLifecycle!.record!(record))
638
+ .catch((error) => {
639
+ this.markManagedPersistenceUnhealthy();
640
+ throw error;
641
+ });
642
+ this.ownerRecordWrite = write;
643
+ await write;
644
+ }
645
+
646
+ private markManagedPersistenceUnhealthy(): void {
647
+ if (!this.managedPersistenceHealthy) return;
648
+ this.managedPersistenceHealthy = false;
649
+ this.emitStateIfChanged();
650
+ }
651
+
652
+ private queueProtocolRecord(entry: WireEntry): void {
653
+ if (!this.ownerAgentSessionId || !this.ownerLifecycle?.record) return;
654
+ let message: PersistenceJsonValue;
655
+ try {
656
+ message = JSON.parse(entry.line) as PersistenceJsonValue;
657
+ } catch {
658
+ message = entry.line;
659
+ }
660
+ this.queueOwnedRecord({
661
+ recordId: `protocol-${crypto.randomUUID()}`,
662
+ agentSessionId: this.ownerAgentSessionId,
663
+ agentConversationId: this.agentConversationId,
664
+ kind: "protocol",
665
+ timestamp: new Date(entry.ts).toISOString(),
666
+ direction: entry.dir === "err" ? "error" : entry.dir,
667
+ ...(protocolMethod(message) ? { method: protocolMethod(message)! } : {}),
668
+ message,
669
+ });
670
+ }
671
+
672
+ private queueActivityRecords(turnId: string, records: readonly AggregatedRecord[]): void {
673
+ if (!this.ownerAgentSessionId) return;
674
+ for (const record of records) {
675
+ const runtimeRecord = runtimeRecordFromActivity(
676
+ this.ownerAgentSessionId,
677
+ this.agentConversationId,
678
+ turnId,
679
+ record,
680
+ );
681
+ if (runtimeRecord) this.queueOwnedRecord(runtimeRecord);
682
+ }
683
+ }
684
+
685
+ private async recordNativeAction(
686
+ transitionId: string,
687
+ action: string,
688
+ state: "started" | "checkpoint" | "completed" | "failed",
689
+ details: { readonly input?: unknown; readonly output?: unknown; readonly error?: string } = {},
690
+ ): Promise<void> {
691
+ if (!this.ownerAgentSessionId) return;
692
+ await this.recordOwned({
693
+ recordId: `${transitionId}:native:${state}:${crypto.randomUUID()}`,
694
+ agentSessionId: this.ownerAgentSessionId,
695
+ agentConversationId: this.agentConversationId,
696
+ kind: "native_action",
697
+ timestamp: new Date().toISOString(),
698
+ action,
699
+ transitionId,
700
+ state,
701
+ ...(details.input === undefined ? {} : { input: toPersistenceJsonValue(details.input) }),
702
+ ...(details.output === undefined ? {} : { output: toPersistenceJsonValue(details.output) }),
703
+ ...(details.error === undefined ? {} : { error: details.error }),
780
704
  });
781
705
  }
782
706
 
@@ -798,12 +722,12 @@ export class AgentSession implements AgentClient, Bridgeable {
798
722
  * options independently select history storage. No catalog or transcript is read
799
723
  * implicitly. Consumers compose a catalog record back into this method when reopening.
800
724
  */
801
- static async create(config: AgentSessionConfig): Promise<AgentSession> {
725
+ static async create(config: AgentSessionConfig): Promise<AgentConversation> {
802
726
  const directPersistence = resolveDirectPersistence(config.persistence);
803
727
  if (directPersistence !== false && directPersistence.auditLog !== false) {
804
728
  throw new DirectAuditPersistenceUnsupportedError();
805
729
  }
806
- const session = new AgentSession(config);
730
+ const session = new AgentConversation(config);
807
731
  try {
808
732
  await session.start();
809
733
  return session;
@@ -817,10 +741,10 @@ export class AgentSession implements AgentClient, Bridgeable {
817
741
  static async createManaged(
818
742
  config: AgentSessionConfig,
819
743
  bootstrap: ManagedAgentSessionCreationBootstrap,
820
- ): Promise<AgentSession> {
821
- let session: AgentSession;
744
+ ): Promise<AgentConversation> {
745
+ let session: AgentConversation;
822
746
  try {
823
- session = new AgentSession(config, null, bootstrap);
747
+ session = new AgentConversation(config, null, bootstrap);
824
748
  } catch (error) {
825
749
  await bootstrap.transcriptLock?.release().catch(() => undefined);
826
750
  await bootstrap.auditLogLock?.release().catch(() => undefined);
@@ -839,7 +763,7 @@ export class AgentSession implements AgentClient, Bridgeable {
839
763
 
840
764
  /** Restore one logical session by loading the exact provider thread in transcript authority. */
841
765
  static async open(config: AgentSessionOpenConfig): Promise<AgentSessionOpenResult> {
842
- return await AgentSession.openWithLock(config);
766
+ return await AgentConversation.openWithLock(config);
843
767
  }
844
768
 
845
769
  /** @internal Managed open after maintenance acquired the artifact lock. */
@@ -850,7 +774,7 @@ export class AgentSession implements AgentClient, Bridgeable {
850
774
  stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
851
775
  onOpenProgress?: ManagedOpenProgressReporter,
852
776
  ): Promise<AgentSessionOpenResult> {
853
- return await AgentSession.openWithLock(
777
+ return await AgentConversation.openWithLock(
854
778
  config,
855
779
  transcriptLock,
856
780
  audit,
@@ -879,7 +803,7 @@ export class AgentSession implements AgentClient, Bridgeable {
879
803
  throw new Error("registry-managed open has no recorded internal session id");
880
804
  }
881
805
  const { checkpoint: _checkpoint, continuation: _continuation, ...runtime } = config;
882
- const session = new AgentSession({
806
+ const session = new AgentConversation({
883
807
  ...runtime,
884
808
  agentSessionId: checkpoint.agentSessionId,
885
809
  creationId: checkpoint.incarnationId,
@@ -905,7 +829,7 @@ export class AgentSession implements AgentClient, Bridgeable {
905
829
  strategy: "load_internal_session",
906
830
  status: "succeeded",
907
831
  });
908
- const continuation = continuationReport(
832
+ const continuation = createContinuationReport(
909
833
  checkpoint, config.adapterId, session.v2Transcript, "available", [attempt],
910
834
  { kind: "loaded", activeInternalSessionId: result.sessionId },
911
835
  );
@@ -974,7 +898,7 @@ export class AgentSession implements AgentClient, Bridgeable {
974
898
  throw new AdapterMismatchError(checkpoint.adapterId, config.adapterId);
975
899
  }
976
900
  const { checkpoint: _suppliedCheckpoint, continuation: _continuation, ...runtimeConfig } = config;
977
- const session = new AgentSession({
901
+ const session = new AgentConversation({
978
902
  ...runtimeConfig,
979
903
  agentSessionId: checkpoint.agentSessionId,
980
904
  creationId: checkpoint.incarnationId,
@@ -1275,7 +1199,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1275
1199
  this.continuationAcquired = true;
1276
1200
  recordedThreadAvailability = "available";
1277
1201
  attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1278
- return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1202
+ return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1279
1203
  kind: "loaded",
1280
1204
  activeInternalSessionId: loaded.sessionId,
1281
1205
  });
@@ -1414,7 +1338,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1414
1338
  const seeded = await this.meteredInternalPrompt(
1415
1339
  `${transitionId}:seed`,
1416
1340
  "switch_seed",
1417
- continuationPrompt(continuation.trim()),
1341
+ buildContinuationPrompt(continuation.trim()),
1418
1342
  records,
1419
1343
  );
1420
1344
  if (seeded.status !== "completed") {
@@ -1432,7 +1356,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1432
1356
  });
1433
1357
  this.continuationAcquired = true;
1434
1358
  attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1435
- return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1359
+ return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1436
1360
  kind: "reconstructed",
1437
1361
  source,
1438
1362
  activeInternalSessionId: created.sessionId,
@@ -1464,7 +1388,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1464
1388
  }
1465
1389
  }
1466
1390
 
1467
- return continuationReport(
1391
+ return createContinuationReport(
1468
1392
  checkpoint,
1469
1393
  this.adapterId,
1470
1394
  this.v2Transcript,
@@ -1535,6 +1459,25 @@ export class AgentSession implements AgentClient, Bridgeable {
1535
1459
  return this._internalSessionId;
1536
1460
  }
1537
1461
 
1462
+ /** Active adapter route. It changes only after a durable switch activation. */
1463
+ get adapterId(): string {
1464
+ return this._adapterId;
1465
+ }
1466
+
1467
+ /** Canonical `agc-` identity. */
1468
+ get id(): AgentConversationId {
1469
+ return this.agentConversationId;
1470
+ }
1471
+
1472
+ /** Owning `ags-` identity, or null for a detached compatibility conversation. */
1473
+ get ownerId(): AgentSessionId | null {
1474
+ return this.ownerAgentSessionId;
1475
+ }
1476
+
1477
+ get participants(): readonly ParticipantRef[] {
1478
+ return Object.freeze(this._participants.map((participant) => Object.freeze({ ...participant })));
1479
+ }
1480
+
1538
1481
  /**
1539
1482
  * Latest context-window observation for the ACTIVE provider thread, or null.
1540
1483
  *
@@ -1587,6 +1530,37 @@ export class AgentSession implements AgentClient, Bridgeable {
1587
1530
  });
1588
1531
  }
1589
1532
 
1533
+ /** @internal Meter disposable provider work without replacing this conversation's baseline. */
1534
+ beginDetachedMetering(input: {
1535
+ operationId: string;
1536
+ operationKind: MeteredOperationKind;
1537
+ internalSessionId: string;
1538
+ model: string | null;
1539
+ }): Promise<OpenDetachedOperation> {
1540
+ return this.metering.openDetached({
1541
+ ...input,
1542
+ providerId: this.providerId,
1543
+ });
1544
+ }
1545
+
1546
+ /** @internal Completes a detached rating unit; the owner persists its returned record. */
1547
+ async closeDetachedMetering(
1548
+ operation: OpenDetachedOperation,
1549
+ input: {
1550
+ outcome: "completed" | "cancelled" | "error";
1551
+ usage: TokenUsage | null;
1552
+ usageFailureReason?: string;
1553
+ },
1554
+ ): Promise<OperationMeteringRecord> {
1555
+ return await this.metering.closeDetached(operation, {
1556
+ outcome: input.outcome,
1557
+ reportedCumulative: input.usage,
1558
+ ...(input.usageFailureReason ? { usageFailureReason: input.usageFailureReason } : {}),
1559
+ contextAfter: this._contextWindow,
1560
+ providerCostAfter: this._providerCost,
1561
+ });
1562
+ }
1563
+
1590
1564
  get contextWindow(): ContextWindowStatus | null {
1591
1565
  return this._contextWindow;
1592
1566
  }
@@ -1686,7 +1660,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1686
1660
  return this.phase !== "idle" && this.phase !== "stopped";
1687
1661
  }
1688
1662
  get queuedOperationCount(): number {
1689
- return this.queue.length;
1663
+ return this.operations.queuedCount;
1690
1664
  }
1691
1665
  /** Subscribe to future lifecycle changes. The current snapshot is available via state. */
1692
1666
  subscribe(listener: AgentSessionListener): () => void {
@@ -1699,12 +1673,46 @@ export class AgentSession implements AgentClient, Bridgeable {
1699
1673
  }
1700
1674
 
1701
1675
  // --- AgentClient -------------------------------------------------------------
1676
+ prompt(input: AgentConversationPromptInput): Promise<AgentSessionPromptResult>;
1677
+ prompt(
1678
+ text: string,
1679
+ handlers?: PromptHandlers,
1680
+ attachments?: Attachment[],
1681
+ ): Promise<AgentSessionPromptResult>;
1702
1682
  async prompt(
1683
+ input: string | AgentConversationPromptInput,
1684
+ handlers?: PromptHandlers,
1685
+ attachments?: Attachment[],
1686
+ ): Promise<AgentSessionPromptResult> {
1687
+ return typeof input === "string"
1688
+ ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1689
+ : this.enqueuePrompt(input.text, "prompt", input.handlers, input.attachments, undefined, input.consumerMetadata);
1690
+ }
1691
+
1692
+ /** Prompt while attributing the caller to a stable participant identity. */
1693
+ promptFrom(input: AgentConversationAttributedPromptInput): Promise<AgentSessionPromptResult>;
1694
+ promptFrom(
1695
+ participantId: string,
1703
1696
  text: string,
1704
1697
  handlers?: PromptHandlers,
1705
1698
  attachments?: Attachment[],
1699
+ ): Promise<AgentSessionPromptResult>;
1700
+ promptFrom(
1701
+ input: string | AgentConversationAttributedPromptInput,
1702
+ text?: string,
1703
+ handlers?: PromptHandlers,
1704
+ attachments?: Attachment[],
1706
1705
  ): Promise<AgentSessionPromptResult> {
1707
- return this.enqueuePrompt(text, "prompt", handlers, attachments);
1706
+ if (typeof input !== "string") {
1707
+ if (!input.participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1708
+ return this.enqueuePrompt(
1709
+ input.text, "prompt", input.handlers, input.attachments,
1710
+ input.participantId.trim(), input.consumerMetadata,
1711
+ );
1712
+ }
1713
+ const participantId = input;
1714
+ if (!participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1715
+ return this.enqueuePrompt(text!, "prompt", handlers, attachments, participantId.trim());
1708
1716
  }
1709
1717
 
1710
1718
  private enqueuePrompt(
@@ -1712,23 +1720,36 @@ export class AgentSession implements AgentClient, Bridgeable {
1712
1720
  operationKind: MeteredOperationKind,
1713
1721
  handlers?: PromptHandlers,
1714
1722
  attachments?: Attachment[],
1723
+ participantId?: string,
1724
+ consumerMetadata?: PersistenceJsonValue,
1715
1725
  ): Promise<AgentSessionPromptResult> {
1716
1726
  return new Promise<AgentSessionPromptResult>((resolve, reject) => {
1717
1727
  if (this.phase === "stopped") {
1718
1728
  reject(new Error("AgentSession is stopped"));
1719
1729
  return;
1720
1730
  }
1731
+ let stableConsumerMetadata: PersistenceJsonValue | undefined;
1721
1732
  try {
1722
1733
  this.assertPromptable();
1734
+ if (consumerMetadata !== undefined && !this.ownerLifecycle) {
1735
+ throw new Error("consumerMetadata requires an Agent-owned conversation");
1736
+ }
1737
+ if (consumerMetadata !== undefined) {
1738
+ const serialized = JSON.stringify(consumerMetadata);
1739
+ if (serialized === undefined) throw new Error("consumerMetadata must be a JSON value");
1740
+ stableConsumerMetadata = JSON.parse(serialized) as PersistenceJsonValue;
1741
+ }
1723
1742
  } catch (error) {
1724
1743
  reject(error);
1725
1744
  return;
1726
1745
  }
1727
- this.queue.push({
1746
+ this.operations.enqueue({
1728
1747
  kind: "prompt",
1729
1748
  turnId: this.mintTurnId(),
1730
1749
  operationKind,
1731
1750
  text,
1751
+ ...(participantId ? { participantId } : {}),
1752
+ ...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
1732
1753
  handlers,
1733
1754
  attachments,
1734
1755
  resolve,
@@ -1778,12 +1799,12 @@ export class AgentSession implements AgentClient, Bridgeable {
1778
1799
  reject(error);
1779
1800
  return;
1780
1801
  }
1781
- this.queue.push({
1802
+ this.operations.enqueue({
1782
1803
  kind: "handoff",
1783
1804
  handoffId: this.mintOperationId(),
1784
1805
  // A queued operation owns its arguments. Do not let a caller mutate the object
1785
1806
  // while it waits behind an active prompt and silently change the handoff.
1786
- options: Object.freeze({ ...options }),
1807
+ options: ownHandoffOptions(options),
1787
1808
  resolve,
1788
1809
  reject,
1789
1810
  });
@@ -1792,12 +1813,80 @@ export class AgentSession implements AgentClient, Bridgeable {
1792
1813
  });
1793
1814
  }
1794
1815
 
1816
+ /** Cross-adapter handoff. The owning Agent resolves `targetAdapterId` in its registry. */
1817
+ switch(
1818
+ targetAdapterId: string,
1819
+ options: Omit<HandoffOptions, "target" | "summary"> & {
1820
+ readonly mode?: AgentMode;
1821
+ readonly config?: Readonly<Record<string, unknown>>;
1822
+ } = {},
1823
+ ): Promise<HandoffResult> {
1824
+ if (!targetAdapterId.trim()) return Promise.reject(new Error("target adapter id cannot be blank"));
1825
+ return this.handoff({
1826
+ continuation: options.continuation,
1827
+ targetPrompt: options.targetPrompt,
1828
+ target: {
1829
+ adapterId: targetAdapterId.trim(),
1830
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
1831
+ ...(options.config === undefined ? {} : { config: options.config }),
1832
+ },
1833
+ });
1834
+ }
1835
+
1836
+ /** @internal Seed a newly created provider thread from a durable recovery checkpoint. */
1837
+ async seedRecoveryContext(text: string): Promise<PromptResult> {
1838
+ if (!text.trim()) throw new Error("recovery context cannot be blank");
1839
+ const recoveryId = `recovery-${crypto.randomUUID()}`;
1840
+ const records: OperationMeteringRecord[] = [];
1841
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "started");
1842
+ try {
1843
+ const result = await this.meteredInternalPrompt(
1844
+ recoveryId,
1845
+ "conversation_recovery",
1846
+ text,
1847
+ records,
1848
+ );
1849
+ if (result.status !== "completed") {
1850
+ throw new Error(`conversation recovery seed ${result.status}`);
1851
+ }
1852
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "completed", {
1853
+ output: { internalSessionId: this._internalSessionId },
1854
+ });
1855
+ return result;
1856
+ } catch (error) {
1857
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "failed", {
1858
+ error: error instanceof Error ? error.message : String(error),
1859
+ }).catch(() => undefined);
1860
+ throw error;
1861
+ }
1862
+ }
1863
+
1864
+ /** Start a blank provider thread without generating or installing continuation context. */
1865
+ reset(options: {
1866
+ readonly targetAdapterId?: string;
1867
+ readonly mode?: AgentMode;
1868
+ readonly config?: Readonly<Record<string, unknown>>;
1869
+ readonly targetPrompt?: string;
1870
+ } = {}): Promise<HandoffResult> {
1871
+ return this.handoff({
1872
+ continuation: { kind: "none" },
1873
+ ...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
1874
+ ...((options.targetAdapterId ?? options.mode ?? options.config) === undefined
1875
+ ? {}
1876
+ : {
1877
+ target: {
1878
+ adapterId: options.targetAdapterId ?? this.adapterId,
1879
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
1880
+ ...(options.config === undefined ? {} : { config: options.config }),
1881
+ },
1882
+ }),
1883
+ });
1884
+ }
1885
+
1795
1886
  private async pump(): Promise<void> {
1796
- if (this.pumping) return;
1797
- this.pumping = true;
1887
+ if (this.operations.isDraining) return;
1798
1888
  try {
1799
- while (this.queue.length > 0) {
1800
- const item = this.queue.shift()!;
1889
+ await this.operations.drain(async (item) => {
1801
1890
  this.phase = item.kind === "prompt"
1802
1891
  ? "prompting"
1803
1892
  : item.kind === "handoff"
@@ -1831,10 +1920,52 @@ export class AgentSession implements AgentClient, Bridgeable {
1831
1920
  } else if (item.kind === "set_config") {
1832
1921
  this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
1833
1922
  try {
1923
+ if (this.ownerAgentSessionId) {
1924
+ await this.recordOwned({
1925
+ recordId: `${item.operationId}:configuration:started`,
1926
+ agentSessionId: this.ownerAgentSessionId,
1927
+ agentConversationId: this.agentConversationId,
1928
+ kind: "configuration",
1929
+ timestamp: new Date().toISOString(),
1930
+ operation: "set",
1931
+ configId: item.configId,
1932
+ value: toPersistenceJsonValue(item.value),
1933
+ status: "started",
1934
+ });
1935
+ }
1834
1936
  await this.runSetConfig(item);
1937
+ if (this.ownerAgentSessionId) {
1938
+ await this.recordOwned({
1939
+ recordId: `${item.operationId}:configuration:completed`,
1940
+ agentSessionId: this.ownerAgentSessionId,
1941
+ agentConversationId: this.agentConversationId,
1942
+ kind: "configuration",
1943
+ timestamp: new Date().toISOString(),
1944
+ operation: "set",
1945
+ configId: item.configId,
1946
+ value: toPersistenceJsonValue(item.value),
1947
+ status: "completed",
1948
+ });
1949
+ }
1835
1950
  this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
1836
1951
  item.resolve();
1837
1952
  } catch (err) {
1953
+ if (this.ownerAgentSessionId) {
1954
+ await this.recordOwned({
1955
+ recordId: `${item.operationId}:configuration:failed`,
1956
+ agentSessionId: this.ownerAgentSessionId,
1957
+ agentConversationId: this.agentConversationId,
1958
+ kind: "configuration",
1959
+ timestamp: new Date().toISOString(),
1960
+ operation: "set",
1961
+ configId: item.configId,
1962
+ value: toPersistenceJsonValue(item.value),
1963
+ status: "failed",
1964
+ error: String(err),
1965
+ }).catch((persistenceError) => this.log.warn("configuration_failure_persistence_failed", {
1966
+ error: String(persistenceError),
1967
+ }));
1968
+ }
1838
1969
  this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
1839
1970
  item.reject(err);
1840
1971
  }
@@ -1860,28 +1991,60 @@ export class AgentSession implements AgentClient, Bridgeable {
1860
1991
  const from = this._mode;
1861
1992
  this.emit({ kind: "mode_change_started", transitionId: item.transitionId, from, to: item.mode });
1862
1993
  try {
1994
+ await this.recordNativeAction(item.transitionId, "mode_change", "started", {
1995
+ input: { from, to: item.mode },
1996
+ });
1863
1997
  const result = await this.runSetMode(item);
1998
+ await this.recordNativeAction(item.transitionId, "mode_change", "completed", {
1999
+ output: { mode: item.mode, internalSessionId: result.sessionId || null },
2000
+ });
1864
2001
  this.emit({ kind: "mode_change_completed", transitionId: item.transitionId, from, to: item.mode });
1865
2002
  item.resolve(result);
1866
2003
  } catch (err) {
2004
+ await this.recordNativeAction(item.transitionId, "mode_change", "failed", {
2005
+ error: String(err),
2006
+ }).catch(() => undefined);
1867
2007
  this.emit({ kind: "mode_change_failed", transitionId: item.transitionId, from, to: item.mode, error: String(err) });
1868
2008
  item.reject(err);
1869
2009
  }
1870
2010
  }
1871
- }
2011
+ // Promise consumers must observe the settled public state. The old in-class
2012
+ // loop reached its `finally` synchronously after resolving the last item;
2013
+ // crossing the extracted queue's async callback adds a microtask boundary.
2014
+ // Settle here only when no next item exists, preserving both that ordering and
2015
+ // the no-idle-gap guarantee between queued operations.
2016
+ this.settleIdleIfDrained();
2017
+ });
1872
2018
  } finally {
1873
- this.pumping = false;
1874
2019
  if (this.phase !== "stopped") this.phase = "idle";
1875
2020
  this.emitStateIfChanged();
1876
2021
  }
1877
2022
  }
1878
2023
 
2024
+ private settleIdleIfDrained(): void {
2025
+ if (this.operations.queuedCount !== 0 || this.phase === "stopped") return;
2026
+ this.phase = "idle";
2027
+ this.emitStateIfChanged();
2028
+ }
2029
+
1879
2030
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
1880
2031
  const fromInternalSessionId = this._internalSessionId;
2032
+ const fromAdapterId = this.adapterId;
2033
+ const targetAdapterId = item.options.target?.adapterId ?? fromAdapterId;
2034
+ const targetMode = item.options.target?.mode ?? this._mode;
2035
+ const continuation = normalizeHandoffContinuation(item.options);
2036
+ const transitionKind = targetAdapterId === fromAdapterId ? "handoff" as const : "switch" as const;
2037
+ const action = continuation.kind === "none" && transitionKind === "handoff"
2038
+ ? "reset"
2039
+ : transitionKind;
1881
2040
  const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
1882
2041
  let toInternalSessionId: string | undefined;
1883
2042
  let toDescriptor: InternalSessionDescriptor | undefined;
1884
2043
  let summary: string | undefined;
2044
+ let targetResult: PromptResult | undefined;
2045
+ let targetController: AgentController | null = null;
2046
+ let resolvedTargetAdapter: Adapter | null = null;
2047
+ let targetActivated = false;
1885
2048
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
1886
2049
  // Records accumulate as they complete, so a handoff that fails partway still reports
1887
2050
  // the operations it already paid for.
@@ -1891,14 +2054,22 @@ export class AgentSession implements AgentClient, Bridgeable {
1891
2054
  handoffId: item.handoffId,
1892
2055
  fromInternalSessionId,
1893
2056
  });
2057
+ await this.recordNativeAction(item.handoffId, action, "started", {
2058
+ input: {
2059
+ fromAdapterId,
2060
+ targetAdapterId,
2061
+ targetMode,
2062
+ continuation: continuation.kind,
2063
+ },
2064
+ });
1894
2065
  if (this.v2Transcript) {
1895
2066
  await this.v2Transcript.appendTransitionEvent({
1896
2067
  kind: "transition",
1897
2068
  transitionId: item.handoffId,
1898
- transitionKind: "handoff",
2069
+ transitionKind,
1899
2070
  event: "started",
1900
2071
  from: fromDescriptor,
1901
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
2072
+ ...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
1902
2073
  });
1903
2074
  } else {
1904
2075
  await this.appendTranscript({
@@ -1908,25 +2079,24 @@ export class AgentSession implements AgentClient, Bridgeable {
1908
2079
  ts: Date.now(),
1909
2080
  handoffId: item.handoffId,
1910
2081
  fromInternalSessionId,
1911
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
2082
+ ...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
1912
2083
  });
1913
2084
  }
1914
2085
 
1915
2086
  try {
1916
- if (this.controller.isDegraded) {
1917
- throw new Error("handoff requires ACP (normal) mode");
2087
+ if (continuation.kind !== "none" && this.controller.isDegraded) {
2088
+ throw new Error("handoff continuation requires ACP (normal) mode");
1918
2089
  }
1919
2090
 
1920
- if (item.options.summary !== undefined) {
1921
- if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
2091
+ if (continuation.kind === "provided") {
1922
2092
  // A supplied summary removes the generation operation entirely, so no
1923
2093
  // `:summary` record is ever minted for it.
1924
- summary = item.options.summary;
1925
- } else {
2094
+ summary = continuation.content;
2095
+ } else if (continuation.kind === "generated") {
1926
2096
  const generated = await this.meteredInternalPrompt(
1927
2097
  `${item.handoffId}:summary`,
1928
2098
  "handoff_summary",
1929
- HANDOFF_SUMMARY_PROMPT,
2099
+ continuation.summaryPrompt,
1930
2100
  records,
1931
2101
  );
1932
2102
  if (generated.status !== "completed" || !generated.text.trim()) {
@@ -1935,22 +2105,51 @@ export class AgentSession implements AgentClient, Bridgeable {
1935
2105
  // Handoff requires one seed string, so this internal boundary policy is explicit;
1936
2106
  // it is not treated as the canonical shape of the provider response.
1937
2107
  summary = formatResponseMessages(generated.messages, "\n\n").trim();
2108
+ } else {
2109
+ summary = "";
1938
2110
  }
1939
2111
 
1940
- const created = await this.controller.newSession();
2112
+ const replacingController = targetAdapterId !== fromAdapterId || targetMode !== this._mode;
2113
+ let created: ConnectResult;
2114
+ if (replacingController) {
2115
+ const adapter = item.options.target?.adapter ?? (targetAdapterId === fromAdapterId
2116
+ ? this.activeAdapter
2117
+ : this.ownerLifecycle?.resolveAdapter?.(targetAdapterId));
2118
+ if (!adapter) {
2119
+ throw new Error(
2120
+ `cannot resolve adapter ${targetAdapterId}; cross-adapter switch requires an Agent-owned conversation`,
2121
+ );
2122
+ }
2123
+ resolvedTargetAdapter = adapter;
2124
+ targetController = this.createController(adapter, targetAdapterId, targetMode);
2125
+ created = await targetController.startFresh();
2126
+ } else {
2127
+ if (this.controller.isDegraded) {
2128
+ throw new Error("starting a fresh provider thread requires ACP (normal) mode");
2129
+ }
2130
+ targetController = this.controller;
2131
+ created = await targetController.newSession();
2132
+ }
1941
2133
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
1942
2134
  toInternalSessionId = created.sessionId;
1943
- if (toInternalSessionId === fromInternalSessionId) {
2135
+ if (!replacingController && toInternalSessionId === fromInternalSessionId) {
1944
2136
  throw new Error("harness did not replace the internal session during handoff");
1945
2137
  }
1946
2138
 
2139
+ for (const [configId, value] of Object.entries(item.options.target?.config ?? {})) {
2140
+ await targetController.setConfig(configId, value);
2141
+ }
2142
+ await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2143
+ output: { stage: "target_created", internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2144
+ });
2145
+
1947
2146
  if (this.v2Transcript) {
1948
2147
  const transitionAt = new Date().toISOString();
1949
2148
  toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
1950
2149
  await this.v2Transcript.appendTransitionEvent({
1951
2150
  kind: "transition",
1952
2151
  transitionId: item.handoffId,
1953
- transitionKind: "handoff",
2152
+ transitionKind,
1954
2153
  event: "target_created",
1955
2154
  from: fromDescriptor,
1956
2155
  to: toDescriptor,
@@ -1960,7 +2159,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1960
2159
  await this.v2Transcript.activateTransition({
1961
2160
  kind: "transition",
1962
2161
  transitionId: item.handoffId,
1963
- transitionKind: "handoff",
2162
+ transitionKind,
1964
2163
  event: "target_activated",
1965
2164
  from: fromDescriptor,
1966
2165
  to: toDescriptor,
@@ -1974,7 +2173,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1974
2173
  protocol: fromDescriptor.protocol,
1975
2174
  activatedAt: fromDescriptor.activatedAt!,
1976
2175
  deactivatedAt: transitionAt,
1977
- transition: { kind: "handoff", transitionId: item.handoffId },
2176
+ transition: { kind: transitionKind, transitionId: item.handoffId },
1978
2177
  },
1979
2178
  }
1980
2179
  : {}),
@@ -1987,18 +2186,77 @@ export class AgentSession implements AgentClient, Bridgeable {
1987
2186
  });
1988
2187
  failedAfter = "target_activated";
1989
2188
  }
2189
+ const activatedAt = new Date().toISOString();
2190
+ try {
2191
+ await this.ownerLifecycle?.transitionActivated?.({
2192
+ transitionId: item.handoffId,
2193
+ agentConversationId: this.agentConversationId,
2194
+ internalSessionId: toInternalSessionId,
2195
+ adapterId: targetAdapterId,
2196
+ mode: targetMode,
2197
+ ...(activeModel(targetController.configOptions)
2198
+ ? { model: activeModel(targetController.configOptions)! }
2199
+ : {}),
2200
+ activatedAt,
2201
+ });
2202
+ } catch (error) {
2203
+ this.markManagedPersistenceUnhealthy();
2204
+ throw error;
2205
+ }
2206
+
2207
+ const previousController = this.controller;
2208
+ if (targetController !== previousController) {
2209
+ this.controller = targetController;
2210
+ this.activeAdapter = resolvedTargetAdapter!;
2211
+ this._adapterId = targetAdapterId;
2212
+ this._mode = targetMode;
2213
+ this.metering = new MeteringEngine({
2214
+ ...this.meteringConfig,
2215
+ agentSessionId: this.agentSessionId,
2216
+ adapterId: targetAdapterId,
2217
+ initialState: this.metering.currentState,
2218
+ createdActiveThread: true,
2219
+ pricing: this.meteringConfig.pricing ?? createModelsDevResolver(),
2220
+ enforcement: this.meteringConfig.enforcement ?? "best_effort",
2221
+ });
2222
+ this.bindController(targetController);
2223
+ }
2224
+ targetActivated = true;
1990
2225
  this.setInternalSessionId(toInternalSessionId);
2226
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
1991
2227
  this.emitStateIfChanged();
1992
2228
  await this.persist();
2229
+ await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2230
+ output: { stage: "target_activated", internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2231
+ });
2232
+ if (targetController !== previousController) {
2233
+ await previousController.stop().catch((error) => {
2234
+ this.log.warn("handoff_previous_controller_stop_failed", { error: String(error) });
2235
+ });
2236
+ }
1993
2237
 
1994
- const seeded = await this.meteredInternalPrompt(
1995
- `${item.handoffId}:seed`,
1996
- "handoff_seed",
1997
- continuationPrompt(summary),
1998
- records,
1999
- );
2000
- if (seeded.status !== "completed") {
2001
- throw new Error(`handoff continuation seeding ${seeded.status}`);
2238
+ if (continuation.kind !== "none") {
2239
+ const seeded = await this.meteredInternalPrompt(
2240
+ `${item.handoffId}:seed`,
2241
+ transitionKind === "switch" ? "switch_seed" : "handoff_seed",
2242
+ buildContinuationPrompt(summary),
2243
+ records,
2244
+ );
2245
+ if (seeded.status !== "completed") {
2246
+ throw new Error(`handoff continuation seeding ${seeded.status}`);
2247
+ }
2248
+ }
2249
+ if (item.options.targetPrompt !== undefined) {
2250
+ const prompted = await this.meteredInternalPrompt(
2251
+ `${item.handoffId}:target`,
2252
+ "internal_command",
2253
+ item.options.targetPrompt,
2254
+ records,
2255
+ );
2256
+ if (prompted.status !== "completed") {
2257
+ throw new Error(`handoff target prompt ${prompted.status}`);
2258
+ }
2259
+ targetResult = copyPromptResult(prompted);
2002
2260
  }
2003
2261
 
2004
2262
  const result: HandoffResult = Object.freeze({
@@ -2006,14 +2264,16 @@ export class AgentSession implements AgentClient, Bridgeable {
2006
2264
  agentSessionId: this.agentSessionId,
2007
2265
  fromInternalSessionId,
2008
2266
  toInternalSessionId,
2267
+ ...(transitionKind === "switch" ? { fromAdapterId, toAdapterId: targetAdapterId } : {}),
2009
2268
  summary,
2269
+ ...(targetResult ? { targetResult } : {}),
2010
2270
  meteringRecords: Object.freeze([...records]),
2011
2271
  });
2012
2272
  if (this.v2Transcript) {
2013
2273
  await this.v2Transcript.appendTransitionEvent({
2014
2274
  kind: "transition",
2015
2275
  transitionId: item.handoffId,
2016
- transitionKind: "handoff",
2276
+ transitionKind,
2017
2277
  event: "completed",
2018
2278
  from: fromDescriptor,
2019
2279
  to: toDescriptor,
@@ -2031,6 +2291,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2031
2291
  summary,
2032
2292
  });
2033
2293
  }
2294
+ await this.recordNativeAction(item.handoffId, action, "completed", {
2295
+ output: { internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2296
+ });
2034
2297
  this.emit({ kind: "handoff_completed", result });
2035
2298
  return result;
2036
2299
  } catch (err) {
@@ -2042,6 +2305,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2042
2305
  toInternalSessionId = actualSessionId;
2043
2306
  this.emitStateIfChanged();
2044
2307
  try {
2308
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2045
2309
  await this.persist();
2046
2310
  } catch (persistError) {
2047
2311
  this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
@@ -2052,7 +2316,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2052
2316
  await this.v2Transcript.appendTransitionEvent({
2053
2317
  kind: "transition",
2054
2318
  transitionId: item.handoffId,
2055
- transitionKind: "handoff",
2319
+ transitionKind,
2056
2320
  event: "failed",
2057
2321
  from: fromDescriptor,
2058
2322
  ...(toDescriptor ? { to: toDescriptor } : {}),
@@ -2075,6 +2339,14 @@ export class AgentSession implements AgentClient, Bridgeable {
2075
2339
  error,
2076
2340
  });
2077
2341
  }
2342
+ if (!targetActivated && targetController && targetController !== this.controller) {
2343
+ await targetController.stop().catch(() => undefined);
2344
+ }
2345
+ await this.recordNativeAction(item.handoffId, action, "failed", { error }).catch(
2346
+ (persistenceError) => this.log.warn("native_action_failure_persistence_failed", {
2347
+ error: String(persistenceError),
2348
+ }),
2349
+ );
2078
2350
  this.emit({
2079
2351
  kind: "handoff_failed",
2080
2352
  handoffId: item.handoffId,
@@ -2449,6 +2721,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2449
2721
  const result = await this.controller.setMode(item.mode);
2450
2722
  this._mode = this.controller.currentMode;
2451
2723
  this.setInternalSessionId(result.sessionId || null);
2724
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2452
2725
  await this.persist();
2453
2726
  return result;
2454
2727
  }
@@ -2548,6 +2821,24 @@ export class AgentSession implements AgentClient, Bridgeable {
2548
2821
  }
2549
2822
 
2550
2823
  private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
2824
+ const targetProviderContextId = this.ownerLifecycle
2825
+ ? this._internalSessionId ?? `runtime:${this.ownerContextNonce ??= crypto.randomUUID()}`
2826
+ : undefined;
2827
+ const owned = this.ownerLifecycle
2828
+ ? await this.ownerLifecycle.beforePrompt({
2829
+ operationId: item.turnId,
2830
+ agentSessionId: this.ownerAgentSessionId!,
2831
+ agentConversationId: this.agentConversationId,
2832
+ targetProviderContextId,
2833
+ ...(item.participantId ? { participantId: item.participantId } : {}),
2834
+ ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
2835
+ text: item.text,
2836
+ })
2837
+ : undefined;
2838
+ if (owned?.participant && !this._participants.some((participant) => participant.id === owned.participant!.id)) {
2839
+ this._participants = [...this._participants, Object.freeze({ ...owned.participant })];
2840
+ }
2841
+ const providerText = owned?.providerText ?? item.text;
2551
2842
  this.beginTurn(item.turnId);
2552
2843
  let operation: OpenOperation;
2553
2844
  if (this.v2Transcript) {
@@ -2567,9 +2858,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2567
2858
  presentation: { id: `message:${item.turnId}:user`, revision: 1 },
2568
2859
  });
2569
2860
  await this.v2Transcript.syncBeforeDispatch();
2570
- this.emitPresentationRecord(userRecord);
2861
+ this.presentation.emitPersistedRecord(userRecord);
2571
2862
  } catch (error) {
2572
- this.endTurn(item.handlers);
2863
+ this.endTurn(item.turnId, item.handlers);
2573
2864
  if (transcriptStarted) {
2574
2865
  await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
2575
2866
  (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
@@ -2618,7 +2909,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2618
2909
  assistantMessage.revision++;
2619
2910
  assistantMessage.dirty = false;
2620
2911
  const message = assistantMessage;
2621
- this.queueV2Presentation({
2912
+ this.presentation.queuePresentation({
2622
2913
  kind: "message",
2623
2914
  operationId: item.turnId,
2624
2915
  role: "assistant",
@@ -2645,9 +2936,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2645
2936
  item.handlers?.onChunk?.(chunk);
2646
2937
  },
2647
2938
  onResponseChunk: (chunk) => {
2648
- const settledReasoning = this.aggregator.closeReasoningBoundary();
2939
+ const settledReasoning = this.presentation.closeReasoningBoundary();
2649
2940
  if (settledReasoning) {
2650
- if (this.transcriptActivity || this.v2Transcript) this.writeActivity(settledReasoning);
2941
+ this.queueActivityRecords(item.turnId, [settledReasoning]);
2651
2942
  item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
2652
2943
  }
2653
2944
  response.append(chunk);
@@ -2672,19 +2963,55 @@ export class AgentSession implements AgentClient, Bridgeable {
2672
2963
  // The message snapshot must enter the shared queue before an activity first seen
2673
2964
  // after it. Later activity revisions keep their original presentation position.
2674
2965
  flushAssistantMessage("in_progress");
2675
- const result = this.aggregator.apply(event);
2676
- if (this.transcriptActivity || this.v2Transcript) {
2677
- for (const record of result.emitted) this.writeActivity(record);
2678
- }
2966
+ const result = this.presentation.applyActivity(event);
2967
+ this.queueActivityRecords(item.turnId, result.emitted);
2679
2968
  item.handlers?.onRecord?.(result);
2680
2969
  item.handlers?.onActivity?.(event);
2681
2970
  },
2971
+ onPermissionRequest: async (request) => {
2972
+ const permissionBase = `${item.turnId}:permission:${request.toolCallId}`;
2973
+ if (this.ownerAgentSessionId) {
2974
+ await this.recordOwned({
2975
+ recordId: `${permissionBase}:requested`,
2976
+ agentSessionId: this.ownerAgentSessionId,
2977
+ agentConversationId: this.agentConversationId,
2978
+ kind: "permission",
2979
+ timestamp: new Date().toISOString(),
2980
+ permissionId: request.toolCallId,
2981
+ state: "requested",
2982
+ request: toPersistenceJsonValue({
2983
+ toolCallId: request.toolCallId,
2984
+ ...(request.title ? { title: request.title } : {}),
2985
+ options: request.options,
2986
+ raw: request.raw,
2987
+ }),
2988
+ });
2989
+ }
2990
+ const outcome = item.handlers?.onPermissionRequest
2991
+ ? await item.handlers.onPermissionRequest(request)
2992
+ : defaultPermissionOutcome(request, this.defaultPermission);
2993
+ if (this.ownerAgentSessionId) {
2994
+ await this.recordOwned({
2995
+ recordId: `${permissionBase}:resolved`,
2996
+ agentSessionId: this.ownerAgentSessionId,
2997
+ agentConversationId: this.agentConversationId,
2998
+ kind: "permission",
2999
+ timestamp: new Date().toISOString(),
3000
+ permissionId: request.toolCallId,
3001
+ state: "resolved",
3002
+ outcome: permissionRecordOutcome(request, outcome),
3003
+ });
3004
+ }
3005
+ return outcome;
3006
+ },
2682
3007
  };
2683
3008
 
2684
3009
  let closed: OperationMeteringRecord | null = null;
2685
3010
  let transcriptClosed = false;
3011
+ let providerSettled = false;
2686
3012
  try {
2687
- const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
3013
+ const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
3014
+ providerSettled = true;
2688
3015
  if (this.v2Transcript) {
2689
3016
  if (assistantOrdinal === 0) {
2690
3017
  for (const message of res.messages) {
@@ -2699,7 +3026,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2699
3026
  }
2700
3027
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
2701
3028
  // land inside those fences.
2702
- this.endTurn(item.handlers);
3029
+ this.endTurn(item.turnId, item.handlers);
2703
3030
  if (!this._title && item.text.trim()) {
2704
3031
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
2705
3032
  }
@@ -2715,9 +3042,10 @@ export class AgentSession implements AgentClient, Bridgeable {
2715
3042
  // a worse failure than the one closing early prevents.
2716
3043
  const record = await this.closeOperation(operation, res.status, res.usage);
2717
3044
  closed = record;
3045
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2718
3046
  await this.persist();
2719
3047
  if (this.v2Transcript) {
2720
- await this.drainV2Presentation();
3048
+ await this.presentation.drain();
2721
3049
  await this.finishV2Prompt(res.status, record);
2722
3050
  transcriptClosed = true;
2723
3051
  } else {
@@ -2733,11 +3061,25 @@ export class AgentSession implements AgentClient, Bridgeable {
2733
3061
  status: res.status,
2734
3062
  });
2735
3063
  }
2736
- return Object.freeze({ ...res, operationId: item.turnId, metering: record });
3064
+ const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3065
+ await this.ownerLifecycle?.afterPrompt({
3066
+ operationId: item.turnId,
3067
+ agentSessionId: this.ownerAgentSessionId!,
3068
+ agentConversationId: this.agentConversationId,
3069
+ targetProviderContextId,
3070
+ ...(owned?.identityDeliveryReceipt
3071
+ ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3072
+ : {}),
3073
+ ...(item.participantId ? { participantId: item.participantId } : {}),
3074
+ text: item.text,
3075
+ result,
3076
+ });
3077
+ await this.ownerRecordWrite;
3078
+ return result;
2737
3079
  } catch (err) {
2738
3080
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
2739
3081
  // what it was doing, at its real status.
2740
- this.endTurn(item.handlers);
3082
+ this.endTurn(item.turnId, item.handlers);
2741
3083
  const structured = response.snapshot();
2742
3084
  const text = structured.length > 0 ? response.text : chunks.join("");
2743
3085
  const messages: readonly ResponseMessage[] = structured.length > 0
@@ -2745,6 +3087,22 @@ export class AgentSession implements AgentClient, Bridgeable {
2745
3087
  : text
2746
3088
  ? Object.freeze([{ text }])
2747
3089
  : Object.freeze([]);
3090
+ if (!providerSettled) {
3091
+ await this.ownerLifecycle?.promptFailed({
3092
+ operationId: item.turnId,
3093
+ agentSessionId: this.ownerAgentSessionId!,
3094
+ agentConversationId: this.agentConversationId,
3095
+ ...(item.participantId ? { participantId: item.participantId } : {}),
3096
+ text: item.text,
3097
+ messages,
3098
+ error: err,
3099
+ }).catch((persistenceError) => {
3100
+ this.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
3101
+ });
3102
+ }
3103
+ await this.ownerRecordWrite.catch((persistenceError) => {
3104
+ this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3105
+ });
2748
3106
  if (this.v2Transcript) {
2749
3107
  if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
2750
3108
  for (const message of messages) {
@@ -2756,7 +3114,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2756
3114
  } else if (!transcriptClosed) {
2757
3115
  flushAssistantMessage("error", "error", true);
2758
3116
  }
2759
- await this.drainV2Presentation().catch(() => undefined);
3117
+ await this.presentation.drain().catch(() => undefined);
2760
3118
  } else {
2761
3119
  await this.appendTranscript({
2762
3120
  v: 1,
@@ -2774,6 +3132,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2774
3132
  // Already metered: the failure happened after the operation closed (a transcript or
2775
3133
  // catalog write), so the record stands and must not be minted a second time.
2776
3134
  const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
3135
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2777
3136
  if (this.v2Transcript && !transcriptClosed) {
2778
3137
  await this.finishV2Prompt("error", record, "unknown").catch(
2779
3138
  (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
@@ -2836,7 +3195,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2836
3195
  before: AgentSessionMeteringState;
2837
3196
  after: AgentSessionMeteringState;
2838
3197
  }> {
2839
- if (this.isBusy || this.queue.length > 0) {
3198
+ if (this.isBusy || this.operations.queuedCount > 0) {
2840
3199
  throw new Error("reconcileMetering requires an idle session with no queued operations");
2841
3200
  }
2842
3201
  if (!reconciliation.reason?.trim()) {
@@ -2859,6 +3218,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2859
3218
  // Validated first: state is replaced atomically or not at all.
2860
3219
  const { before } = this.metering.reconcile(restoration.state);
2861
3220
  const after = this.metering.currentState;
3221
+ await this.ownerLifecycle?.meteringStateChanged?.(after);
2862
3222
  this.emit({
2863
3223
  kind: "metering_reconciled",
2864
3224
  before,
@@ -2923,6 +3283,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2923
3283
  const record = await this.closeOperation(operation, result.status, result.usage);
2924
3284
  records.push(record);
2925
3285
  closed = true;
3286
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2926
3287
  if (this.v2Transcript) {
2927
3288
  await this.v2Transcript.appendEvent({
2928
3289
  kind: "message",
@@ -2942,6 +3303,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2942
3303
  const record = await this.closeOperation(operation, "error", null, String(err));
2943
3304
  records.push(record);
2944
3305
  closed = true;
3306
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2945
3307
  }
2946
3308
  if (this.v2Transcript && !transcriptClosed) {
2947
3309
  const record = records[records.length - 1]!;
@@ -3033,26 +3395,15 @@ export class AgentSession implements AgentClient, Bridgeable {
3033
3395
  * activity in its log before the messages around it had loaded.
3034
3396
  */
3035
3397
  activitySnapshot(): ActivitySnapshot {
3036
- return this.aggregator.snapshot();
3398
+ return this.presentation.snapshot();
3037
3399
  }
3038
3400
 
3039
3401
  private beginTurn(turnId: string): void {
3040
- // A correct caller always gets an empty array back — both exit paths flush. If one
3041
- // ever doesn't, keeping the records (loudly) beats dropping them.
3042
- const leftover = this.aggregator.startTurn(turnId);
3043
- if (leftover.length > 0) {
3044
- this.log.warn("activity_turn_not_flushed", { records: leftover.length });
3045
- if (this.transcriptActivity || this.v2Transcript) for (const record of leftover) this.writeActivity(record);
3046
- }
3402
+ this.presentation.beginTurn(turnId);
3047
3403
  }
3048
3404
 
3049
- private endTurn(handlers?: PromptHandlers): void {
3050
- const emitted = this.aggregator.flush();
3051
- if (emitted.length === 0) return;
3052
- if (this.transcriptActivity || this.v2Transcript) for (const record of emitted) this.writeActivity(record);
3053
- // Live subscribers need these too: without them, a tool call on a turn that was
3054
- // cancelled or crashed spins forever in the UI. `wireFrames()` handles this shape.
3055
- handlers?.onRecord?.({ current: null, delta: null, emitted });
3405
+ private endTurn(turnId: string, handlers?: PromptHandlers): void {
3406
+ this.queueActivityRecords(turnId, this.presentation.endTurn(handlers));
3056
3407
  }
3057
3408
 
3058
3409
  /**
@@ -3072,80 +3423,9 @@ export class AgentSession implements AgentClient, Bridgeable {
3072
3423
  return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
3073
3424
  }
3074
3425
 
3075
- /**
3076
- * Persist one settled record. Filtering lives here, not in the aggregator: the
3077
- * aggregator owns semantics, the writer owns policy.
3078
- *
3079
- * Fire and forget — `appendTranscript` serializes writes in call order, so ordering
3080
- * holds without blocking the agent's update stream on disk.
3081
- */
3082
- private writeActivity(record: AggregatedRecord): void {
3083
- if (this.v2Transcript) {
3084
- const operationId = this.v2Transcript.checkpoint.boundary.status === "in_flight"
3085
- ? this.v2Transcript.checkpoint.boundary.interruptedOperationId
3086
- : record.recordId.split(":", 1)[0] ?? record.recordId;
3087
- const projected = persistenceEventFromActivity(record, operationId);
3088
- this.queueV2Presentation({
3089
- ...projected,
3090
- presentation: {
3091
- id: `${projected.kind}:${operationId}:${record.recordId}`,
3092
- revision: record.seq,
3093
- },
3094
- });
3095
- return;
3096
- }
3097
- if (!this._transcriptPath) return;
3098
- if (!this.activityKinds.has(record.event.kind)) return;
3099
- void this.appendTranscript(this.toActivityLine(record));
3100
- }
3101
-
3102
- private queueV2Presentation(event: PresentationPersistenceEvent): void {
3103
- this.v2PresentationWrite = this.v2PresentationWrite.then(async () => {
3104
- if (!this.v2Transcript) return;
3105
- const record = await this.v2Transcript.appendPresentationEvent(event);
3106
- this.emitPresentationRecord(record);
3107
- });
3108
- }
3109
-
3110
- private emitPresentationRecord(
3111
- record: Awaited<ReturnType<PersistenceStateRuntime["appendPresentationEvent"]>>,
3112
- ): void {
3113
- if (!record) return;
3114
- const item = presentationItemFromRecord(record);
3115
- if (item) this.emit({ kind: "presentation_recorded", item });
3116
- }
3117
-
3118
- private async drainV2Presentation(): Promise<void> {
3119
- await this.v2PresentationWrite;
3120
- }
3121
-
3122
- private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
3123
- let fields: Record<string, unknown> = { ...record.event };
3124
- if (!this.activityRawOutput) delete fields.rawOutput;
3125
-
3126
- let truncated = false;
3127
- if (this.activityMaxBytes != null) {
3128
- const capped = capActivityStrings(fields, this.activityMaxBytes);
3129
- fields = capped.fields;
3130
- truncated = capped.truncated;
3131
- }
3132
-
3133
- const line: TranscriptActivityLine = {
3134
- ...fields,
3135
- v: 1,
3136
- t: "activity",
3137
- ts: Date.now(),
3138
- recordId: record.recordId,
3139
- reason: record.reason,
3140
- kind: record.event.kind,
3141
- };
3142
- if (truncated) line.truncated = true;
3143
- return line;
3144
- }
3145
-
3146
3426
  interrupt(options?: InterruptOptions): void {
3147
3427
  if (options?.clearQueue) {
3148
- const dropped = this.queue.splice(0);
3428
+ const dropped = this.operations.clear();
3149
3429
  for (const item of dropped) {
3150
3430
  if (item.kind === "prompt") {
3151
3431
  // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
@@ -3184,7 +3464,10 @@ export class AgentSession implements AgentClient, Bridgeable {
3184
3464
  this.phase = "stopped";
3185
3465
  this.emitStateIfChanged();
3186
3466
  await this.controller.stop();
3187
- await this.drainV2Presentation().catch(() => undefined);
3467
+ await this.ownerRecordWrite.catch((error) => {
3468
+ this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3469
+ });
3470
+ await this.presentation.drain().catch(() => undefined);
3188
3471
  await this.v2Transcript?.close();
3189
3472
  }
3190
3473
 
@@ -3193,7 +3476,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3193
3476
  if (this.phase === "stopped") throw new Error("AgentSession is stopped");
3194
3477
  this.assertPromptable();
3195
3478
  return await new Promise<ConnectResult>((resolve, reject) => {
3196
- this.queue.push({
3479
+ this.operations.enqueue({
3197
3480
  kind: "set_mode",
3198
3481
  transitionId: this.mintOperationId(),
3199
3482
  mode,
@@ -3232,7 +3515,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3232
3515
  return Promise.reject(new Error(`configuration value cannot be cloned: ${String(error)}`));
3233
3516
  }
3234
3517
  return new Promise<void>((resolve, reject) => {
3235
- this.queue.push({
3518
+ this.operations.enqueue({
3236
3519
  kind: "set_config",
3237
3520
  operationId: this.mintOperationId(),
3238
3521
  configId,
@@ -3263,7 +3546,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3263
3546
  return Promise.reject(new Error(`configuration resolution cannot be cloned: ${String(error)}`));
3264
3547
  }
3265
3548
  return new Promise((resolve, reject) => {
3266
- this.queue.push({ kind: "resolve_config", resolution: owned, resolve, reject });
3549
+ this.operations.enqueue({ kind: "resolve_config", resolution: owned, resolve, reject });
3267
3550
  this.emitStateIfChanged();
3268
3551
  void this.pump();
3269
3552
  });
@@ -3287,7 +3570,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3287
3570
  ...(resolution.continuation === undefined ? {} : { continuation: resolution.continuation }),
3288
3571
  });
3289
3572
  return new Promise((resolve, reject) => {
3290
- this.queue.push({ kind: "resolve_recovery", resolution: owned, resolve, reject });
3573
+ this.operations.enqueue({ kind: "resolve_recovery", resolution: owned, resolve, reject });
3291
3574
  this.emitStateIfChanged();
3292
3575
  void this.pump();
3293
3576
  });
@@ -3376,6 +3659,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3376
3659
  private setInternalSessionId(next: string | null, created = true): void {
3377
3660
  if (next === this._internalSessionId) return;
3378
3661
  this._internalSessionId = next;
3662
+ if (this.ownerLifecycle) this.ownerContextNonce = null;
3379
3663
  // The new thread's counters restart, so the old baseline no longer describes them.
3380
3664
  this.metering.onThreadReplaced(next, created);
3381
3665
  if (this._contextWindow !== null) {
@@ -3479,96 +3763,101 @@ export class AgentSession implements AgentClient, Bridgeable {
3479
3763
  }
3480
3764
  }
3481
3765
 
3766
+ /**
3767
+ * @deprecated `AgentSession` is the compatibility name for one conversation. New code
3768
+ * should use `AgentConversation`; the forthcoming `Agent` object owns conversations.
3769
+ */
3770
+ export { AgentConversation as AgentSession };
3771
+
3772
+ export type AgentConversationConfig = AgentSessionConfig;
3773
+ export type AgentConversationOpenConfig = AgentSessionOpenConfig;
3774
+ export type AgentConversationOpenResult = AgentSessionOpenResult;
3775
+ export type ManagedAgentConversationCreationBootstrap = ManagedAgentSessionCreationBootstrap;
3776
+ export type ManagedAgentConversationPersistenceSnapshot = ManagedAgentSessionPersistenceSnapshot;
3777
+
3482
3778
  function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
3483
- return kind === "internal_command" ? "internal_session_command" : kind;
3779
+ if (kind === "internal_command") return "internal_session_command";
3780
+ if (
3781
+ kind === "conversation_checkpoint"
3782
+ || kind === "conversation_recovery"
3783
+ || kind === "identity_update"
3784
+ ) return "other";
3785
+ return kind;
3484
3786
  }
3485
3787
 
3486
- function continuationReport(
3487
- checkpoint: AgentSessionCheckpoint,
3488
- requestedAdapterId: string,
3489
- transcript: PersistenceStateRuntime,
3490
- recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"],
3491
- attempts: readonly ContinuationAttempt[],
3492
- outcome: ContinuationReport["outcome"],
3493
- ): ContinuationReport {
3788
+ function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
3494
3789
  return Object.freeze({
3495
- recordedAdapterId: checkpoint.adapterId,
3496
- recordedInternalSessionId: checkpoint.internalSessionId,
3497
- requestedAdapterId,
3498
- recordedConversationAvailability: transcript.conversationAvailability,
3499
- recordedThreadAvailability,
3500
- attempts: Object.freeze(attempts.map((attempt) => Object.freeze({ ...attempt }))),
3501
- outcome: Object.freeze({ ...outcome }),
3790
+ ...(options.summary === undefined ? {} : { summary: options.summary }),
3791
+ ...(options.target === undefined
3792
+ ? {}
3793
+ : {
3794
+ target: Object.freeze({
3795
+ adapterId: options.target.adapterId,
3796
+ ...(options.target.mode === undefined ? {} : { mode: options.target.mode }),
3797
+ ...(options.target.adapter === undefined
3798
+ ? {}
3799
+ : {
3800
+ adapter: Object.freeze({
3801
+ ...options.target.adapter,
3802
+ command: Object.freeze([...options.target.adapter.command]) as unknown as string[],
3803
+ ...(options.target.adapter.ptyCommand
3804
+ ? {
3805
+ ptyCommand: Object.freeze([
3806
+ ...options.target.adapter.ptyCommand,
3807
+ ]) as unknown as string[],
3808
+ }
3809
+ : {}),
3810
+ }),
3811
+ }),
3812
+ ...(options.target.config === undefined
3813
+ ? {}
3814
+ : { config: Object.freeze({ ...options.target.config }) }),
3815
+ }),
3816
+ }),
3817
+ ...(options.continuation === undefined
3818
+ ? {}
3819
+ : { continuation: Object.freeze({ ...options.continuation }) }),
3820
+ ...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
3502
3821
  });
3503
3822
  }
3504
3823
 
3505
- function descriptorFromCheckpoint(checkpoint: AgentSessionCheckpoint): InternalSessionDescriptor {
3506
- return {
3507
- internalSessionId: checkpoint.internalSessionId,
3508
- adapterId: checkpoint.adapterId,
3509
- mode: checkpoint.mode,
3510
- model: checkpoint.model,
3511
- sessionConfiguration: checkpoint.sessionConfiguration,
3512
- activatedAt: checkpoint.internalSessionActivatedAt,
3513
- protocol: checkpoint.protocol,
3514
- };
3515
- }
3516
-
3517
- function isReconstructionStrategy(strategy: ContinuationStrategy): boolean {
3518
- return strategy.kind === "new_from_transcript" || strategy.kind === "new_from_consumer_continuation";
3519
- }
3520
-
3521
- function normalizeContinuationStrategies(
3522
- options: OpenContinuationOptions | undefined,
3523
- ): readonly ContinuationStrategy[] {
3524
- const strategies = options?.strategies ?? [{ kind: "load_internal_session" as const }];
3525
- if (strategies.length === 0) throw new Error("continuation.strategies cannot be empty");
3526
- return Object.freeze(strategies.map((strategy): ContinuationStrategy => {
3527
- if (strategy.kind === "load_internal_session") {
3528
- return Object.freeze({ kind: strategy.kind });
3529
- }
3530
- if (strategy.kind === "new_from_transcript") {
3531
- if (!strategy.strategyId.trim()) throw new Error("transcript continuation strategyId cannot be blank");
3532
- if (typeof strategy.buildContinuation !== "function") {
3533
- throw new Error("transcript continuation strategy requires buildContinuation");
3534
- }
3535
- return Object.freeze({
3536
- kind: strategy.kind,
3537
- strategyId: strategy.strategyId,
3538
- buildContinuation: strategy.buildContinuation,
3539
- });
3540
- }
3541
- if (!strategy.continuationId.trim()) throw new Error("consumer continuationId cannot be blank");
3542
- if (!strategy.continuation.trim()) throw new Error("consumer continuation cannot be blank");
3543
- return Object.freeze({
3544
- kind: strategy.kind,
3545
- continuationId: strategy.continuationId,
3546
- continuation: strategy.continuation,
3547
- });
3548
- }));
3549
- }
3550
-
3551
- async function stageOpeningContinuation(
3552
- stage: ((state: StagedContinuationState) => Promise<StagedContinuationState>) | undefined,
3553
- checkpoint: AgentSessionCheckpoint,
3554
- internalSessionId: string,
3555
- ): Promise<void> {
3556
- if (!stage) return;
3557
- const observed: StagedContinuationState = {
3558
- adapterId: checkpoint.adapterId,
3559
- mode: checkpoint.mode,
3560
- internalSessionId,
3561
- internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
3562
- model: checkpoint.model,
3563
- sessionConfiguration: checkpoint.sessionConfiguration,
3564
- protocol: checkpoint.protocol,
3565
- };
3566
- const persisted = await stage(observed);
3567
- if (persisted.adapterId !== observed.adapterId
3568
- || persisted.mode !== observed.mode
3569
- || persisted.internalSessionId !== observed.internalSessionId) {
3570
- throw new Error("staged continuation disagrees with the loaded provider identity");
3824
+ function normalizeHandoffContinuation(options: HandoffOptions):
3825
+ | { readonly kind: "generated"; readonly summaryPrompt: string }
3826
+ | { readonly kind: "provided"; readonly content: string }
3827
+ | { readonly kind: "none" } {
3828
+ if (options.summary !== undefined && options.continuation !== undefined) {
3829
+ throw new Error("handoff cannot combine deprecated summary with continuation");
3830
+ }
3831
+ if (options.target && !options.target.adapterId.trim()) {
3832
+ throw new Error("handoff target adapter id cannot be blank");
3833
+ }
3834
+ if (options.targetPrompt !== undefined && !options.targetPrompt.trim()) {
3835
+ throw new Error("handoff target prompt cannot be blank");
3836
+ }
3837
+ if (options.summary !== undefined) {
3838
+ if (!options.summary.trim()) throw new Error("handoff summary cannot be blank");
3839
+ return Object.freeze({ kind: "provided", content: options.summary });
3840
+ }
3841
+ const continuation = options.continuation ?? { kind: "generated" as const };
3842
+ if (continuation.kind === "provided") {
3843
+ if (!continuation.content.trim()) throw new Error("handoff continuation cannot be blank");
3844
+ return Object.freeze({ kind: "provided", content: continuation.content });
3571
3845
  }
3846
+ if (continuation.kind === "none") return Object.freeze({ kind: "none" });
3847
+ if (continuation.summaryPrompt !== undefined && continuation.summaryInstructions !== undefined) {
3848
+ throw new Error("handoff generated continuation cannot combine summaryPrompt and summaryInstructions");
3849
+ }
3850
+ if (continuation.summaryPrompt !== undefined && !continuation.summaryPrompt.trim()) {
3851
+ throw new Error("handoff summary prompt cannot be blank");
3852
+ }
3853
+ if (continuation.summaryInstructions !== undefined && !continuation.summaryInstructions.trim()) {
3854
+ throw new Error("handoff summary instructions cannot be blank");
3855
+ }
3856
+ const base = continuation.summaryPrompt ?? HANDOFF_SUMMARY_PROMPT;
3857
+ const summaryPrompt = continuation.summaryInstructions === undefined
3858
+ ? base
3859
+ : `${base}\n\nAdditional summary instructions:\n${continuation.summaryInstructions}`;
3860
+ return Object.freeze({ kind: "generated", summaryPrompt });
3572
3861
  }
3573
3862
 
3574
3863
  function configurationTargetIssue(
@@ -3619,6 +3908,130 @@ function sameJsonValue(left: unknown, right: JsonValue): boolean {
3619
3908
  }
3620
3909
  }
3621
3910
 
3911
+ function runtimeRecordFromActivity(
3912
+ agentSessionId: AgentSessionId,
3913
+ agentConversationId: AgentConversationId,
3914
+ turnId: string,
3915
+ record: AggregatedRecord,
3916
+ ): NewConversationRecord | null {
3917
+ const timestamp = new Date().toISOString();
3918
+ const recordId = `${turnId}:runtime:${record.recordId}:${record.seq}`;
3919
+ const event = record.event;
3920
+ if (event.kind === "thinking") {
3921
+ return {
3922
+ recordId,
3923
+ agentSessionId,
3924
+ agentConversationId,
3925
+ kind: "thinking",
3926
+ timestamp,
3927
+ thinkingId: record.recordId,
3928
+ state: record.reason === "settled" || record.reason === "flushed" ? "completed" : "in_progress",
3929
+ content: event.text,
3930
+ ...(event.messageId ? { metadata: JSON.stringify({ providerMessageId: event.messageId }) } : {}),
3931
+ };
3932
+ }
3933
+ if (event.kind === "tool") {
3934
+ const terminal = event.status === "completed" || event.status === "failed";
3935
+ const state = event.status === "failed"
3936
+ ? "failed" as const
3937
+ : terminal
3938
+ ? "completed" as const
3939
+ : record.reason === "input"
3940
+ ? "input" as const
3941
+ : record.reason === "flushed"
3942
+ ? "failed" as const
3943
+ : "announced" as const;
3944
+ const output = event.rawOutput !== undefined || event.content !== undefined
3945
+ ? [{
3946
+ type: "json" as const,
3947
+ value: toPersistenceJsonValue({
3948
+ ...(event.rawOutput === undefined ? {} : { rawOutput: event.rawOutput }),
3949
+ ...(event.content === undefined ? {} : { content: event.content }),
3950
+ ...(event.locations === undefined ? {} : { locations: event.locations }),
3951
+ }),
3952
+ }]
3953
+ : undefined;
3954
+ return {
3955
+ recordId,
3956
+ agentSessionId,
3957
+ agentConversationId,
3958
+ kind: "tool_call",
3959
+ timestamp,
3960
+ toolCallId: event.toolCallId,
3961
+ state,
3962
+ ...(event.title || event.toolKind ? { name: event.title ?? event.toolKind } : {}),
3963
+ ...(event.rawInput === undefined ? {} : { input: toPersistenceJsonValue(event.rawInput) }),
3964
+ ...(output === undefined ? {} : { output }),
3965
+ ...(state === "failed" ? { error: `tool call ended with status ${event.status}` } : {}),
3966
+ metadata: JSON.stringify({ providerStatus: event.status, toolKind: event.toolKind }),
3967
+ };
3968
+ }
3969
+ switch (event.kind) {
3970
+ case "plan":
3971
+ case "plan_update":
3972
+ case "plan_removed":
3973
+ return {
3974
+ recordId,
3975
+ agentSessionId,
3976
+ agentConversationId,
3977
+ kind: "activity",
3978
+ timestamp,
3979
+ activityId: record.recordId,
3980
+ activityType: event.kind,
3981
+ state: "completed",
3982
+ data: toPersistenceJsonValue(event),
3983
+ };
3984
+ case "user_message":
3985
+ case "commands":
3986
+ case "mode":
3987
+ case "usage":
3988
+ case "session_info":
3989
+ case "config":
3990
+ case "unknown":
3991
+ // These are conversation echo, session state, or diagnostic protocol updates.
3992
+ // Their semantic state is persisted by messages/configuration/metering/checkpoints;
3993
+ // exact frames are independently available through raw protocol capture.
3994
+ return null;
3995
+ case "tool_update":
3996
+ // Folded updates return above as tool records. An unfurled tool_update is not a
3997
+ // self-contained model activity, so it must not be persisted independently.
3998
+ return null;
3999
+ }
4000
+ }
4001
+
4002
+ function protocolMethod(message: PersistenceJsonValue): string | undefined {
4003
+ if (message === null || Array.isArray(message) || typeof message !== "object") return undefined;
4004
+ const method = (message as { readonly method?: unknown }).method;
4005
+ return typeof method === "string" ? method : undefined;
4006
+ }
4007
+
4008
+ function toPersistenceJsonValue(value: unknown): PersistenceJsonValue {
4009
+ if (value === undefined) return null;
4010
+ const serialized = JSON.stringify(value);
4011
+ return serialized === undefined ? String(value) : JSON.parse(serialized) as PersistenceJsonValue;
4012
+ }
4013
+
4014
+ function defaultPermissionOutcome(
4015
+ request: PermissionRequest,
4016
+ policy: "approve" | "cancel",
4017
+ ): PermissionOutcome {
4018
+ if (policy === "cancel") return { outcome: "cancelled" };
4019
+ const allow = request.options.find((option) => option.kind === "allow_once")
4020
+ ?? request.options.find((option) => option.kind === "allow_always");
4021
+ return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
4022
+ }
4023
+
4024
+ function permissionRecordOutcome(
4025
+ request: PermissionRequest,
4026
+ outcome: PermissionOutcome,
4027
+ ): "approved" | "denied" | "cancelled" {
4028
+ if (outcome.outcome === "cancelled") return "cancelled";
4029
+ const selected = request.options.find((option) => option.optionId === outcome.optionId);
4030
+ return selected?.kind === "allow_once" || selected?.kind === "allow_always"
4031
+ ? "approved"
4032
+ : "denied";
4033
+ }
4034
+
3622
4035
  /** Do not let one notification observer mutate the PromptResult another observer sees. */
3623
4036
  function copyPromptResult(result: PromptResult): PromptResult {
3624
4037
  const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
@@ -3630,58 +4043,3 @@ function copyPromptResult(result: PromptResult): PromptResult {
3630
4043
  usage: result.usage ? Object.freeze({ ...result.usage }) : null,
3631
4044
  });
3632
4045
  }
3633
-
3634
- const encoder = new TextEncoder();
3635
- const decoder = new TextDecoder();
3636
-
3637
- /**
3638
- * Cap the fields that can realistically reach megabytes — terminal output, text content,
3639
- * diffs, and a stringified `rawInput` — one field at a time so the JSON structure survives.
3640
- * An oversized `rawInput` object becomes its truncated serialization, which is lossy by
3641
- * design; `truncated: true` on the line says so.
3642
- */
3643
- function capActivityStrings(
3644
- fields: Record<string, unknown>,
3645
- maxBytes: number,
3646
- ): { fields: Record<string, unknown>; truncated: boolean } {
3647
- let truncated = false;
3648
- const cap = (text: string): string => {
3649
- const bytes = encoder.encode(text);
3650
- if (bytes.length <= maxBytes) return text;
3651
- // Back up off a continuation byte (0b10xxxxxx) so a multi-byte character is never
3652
- // split — decoding a partial sequence would yield U+FFFD.
3653
- let end = maxBytes;
3654
- while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
3655
- truncated = true;
3656
- return `${decoder.decode(bytes.subarray(0, end))}… [truncated ${bytes.length - end} bytes]`;
3657
- };
3658
- const capUnknown = (value: unknown): unknown => {
3659
- if (typeof value === "string") return cap(value);
3660
- const text = JSON.stringify(value) ?? "";
3661
- const capped = cap(text);
3662
- return capped === text ? value : capped;
3663
- };
3664
-
3665
- const out = { ...fields };
3666
- if (out.rawInput !== undefined) out.rawInput = capUnknown(out.rawInput);
3667
- if (out.rawOutput !== undefined) out.rawOutput = capUnknown(out.rawOutput);
3668
- if (typeof out.text === "string") out.text = cap(out.text);
3669
- if (Array.isArray(out.content)) {
3670
- out.content = (out.content as unknown[]).map((entry) => {
3671
- if (entry === null || typeof entry !== "object") return entry;
3672
- const item = { ...(entry as Record<string, unknown>) };
3673
- if (typeof item.text === "string") item.text = cap(item.text);
3674
- if (typeof item.output === "string") item.output = cap(item.output);
3675
- if (typeof item.oldText === "string") item.oldText = cap(item.oldText);
3676
- if (typeof item.newText === "string") item.newText = cap(item.newText);
3677
- // `text` on a content entry is our convenience copy; the block itself still holds it.
3678
- if (item.content !== null && typeof item.content === "object") {
3679
- const block = { ...(item.content as Record<string, unknown>) };
3680
- if (typeof block.text === "string") block.text = cap(block.text);
3681
- item.content = block;
3682
- }
3683
- return item;
3684
- });
3685
- }
3686
- return { fields: out, truncated };
3687
- }