@qlairoslabs/acp-client 0.7.4 → 0.8.0

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 (53) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +452 -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 +55 -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 +973 -673
  14. package/src/agent.ts +1175 -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 +125 -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.ts +62 -0
  30. package/src/index.ts +117 -0
  31. package/src/internal-inference/config.ts +68 -0
  32. package/src/internal-inference/contracts.ts +218 -0
  33. package/src/internal-inference/coordination/handles.ts +133 -0
  34. package/src/internal-inference/coordination/manager.ts +487 -0
  35. package/src/internal-inference/ids.ts +10 -0
  36. package/src/internal-inference/index.ts +10 -0
  37. package/src/internal-inference/persistence/records.ts +132 -0
  38. package/src/internal-inference/persistence/repository.ts +35 -0
  39. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  40. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  41. package/src/internal-inference/strategy/registry.ts +42 -0
  42. package/src/metering/engine.ts +47 -0
  43. package/src/metering/record.ts +4 -1
  44. package/src/observation/contracts.ts +10 -0
  45. package/src/observation/index.ts +8 -0
  46. package/src/observation/subscription-hub.ts +43 -0
  47. package/src/persistence/activity-projection.ts +26 -12
  48. package/src/persistence/backend.ts +774 -0
  49. package/src/persistence/index.ts +99 -0
  50. package/src/persistence/sqlite-backend.ts +1927 -0
  51. package/src/persistence/sqlite-conversation-records.ts +425 -0
  52. package/src/persistence/sqlite-owner-lock.ts +106 -0
  53. package/src/persistence/sqlite-schema.ts +561 -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,6 +209,7 @@ interface PromptQueueItem {
118
209
  /** How this operation is classified in its metering record. */
119
210
  operationKind: MeteredOperationKind;
120
211
  text: string;
212
+ participantId?: string;
121
213
  handlers?: PromptHandlers;
122
214
  attachments?: Attachment[];
123
215
  resolve: (r: AgentSessionPromptResult) => void;
@@ -165,108 +257,8 @@ interface RecoveryResolutionQueueItem {
165
257
 
166
258
  type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
167
259
 
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
260
  export interface AgentSessionOpenResult {
269
- readonly session: AgentSession;
261
+ readonly session: AgentConversation;
270
262
  readonly continuation: ContinuationReport;
271
263
  readonly recovery: SessionRecoveryStatus;
272
264
  readonly configuration: ConfigurationRestoreStatus;
@@ -274,227 +266,6 @@ export interface AgentSessionOpenResult {
274
266
  readonly repairs: readonly PersistenceRepair[];
275
267
  }
276
268
 
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
269
  export interface AgentSessionConfig {
499
270
  /** The resolved adapter this conversation talks to. */
500
271
  adapter: Adapter;
@@ -563,6 +334,14 @@ export interface AgentSessionConfig {
563
334
  */
564
335
  internalSessionId?: string;
565
336
  title?: string;
337
+ /** Stable conversation identity when this runtime is owned by an Agent. */
338
+ agentConversationId?: AgentConversationId;
339
+ /** Stable owning agent identity. Omitted for detached compatibility conversations. */
340
+ ownerAgentSessionId?: AgentSessionId;
341
+ /** Other sides of this conversation. The owning agent is implied. */
342
+ participants?: readonly ParticipantRef[];
343
+ /** @internal Installed by AgentConversationManager. */
344
+ ownerLifecycle?: AgentConversationOwnerLifecycle;
566
345
  }
567
346
 
568
347
  /** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
@@ -606,41 +385,38 @@ export interface ManagedAgentSessionPersistenceSnapshot {
606
385
  readonly auditLog: AuditLogIdentity | null;
607
386
  }
608
387
 
609
- export class AgentSession implements AgentClient, Bridgeable {
610
- /** Our stable AgentSession id — decoupled from the ACP/harness session id. */
388
+ export class AgentConversation implements AgentClient, Bridgeable {
389
+ /** Compatibility logical id — decoupled from the ACP/harness session id. */
611
390
  readonly agentSessionId: string;
612
- readonly adapterId: string;
613
-
614
- private readonly controller: AgentController;
391
+ readonly agentConversationId: AgentConversationId;
392
+ readonly ownerAgentSessionId: AgentSessionId | null;
393
+ private _adapterId: string;
394
+ private activeAdapter: Adapter;
395
+
396
+ private controller: AgentController;
397
+ private readonly controllerDefaults: Omit<
398
+ AgentControllerConfig,
399
+ "adapter" | "adapterId" | "mode" | "sessionId" | "sessionLoadFailure"
400
+ >;
401
+ private detachControllerCommands: (() => void) | null = null;
402
+ private detachControllerUsage: (() => void) | null = null;
615
403
  private readonly sessions?: SessionManager;
616
404
  private readonly _transcriptPath?: string;
617
405
  private readonly persistence: false | ResolvedAgentSessionPersistence;
618
406
  private readonly creationId: string;
619
407
  private v2Transcript: PersistenceStateRuntime | null = null;
620
408
  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;
409
+ private readonly presentation: AgentConversationPresentation;
634
410
  private readonly log: Logger;
635
411
  private transcriptWrite: Promise<void> = Promise.resolve();
636
- private queue: QueueItem[] = [];
637
- private pumping = false;
412
+ private readonly operations = new AgentConversationQueue<QueueItem>();
638
413
  private phase: AgentSessionPhase = "idle";
639
414
  private notificationSeq = 0;
640
415
  private readonly listeners = new Set<AgentSessionListener>();
641
416
  private lastStateKey = "";
642
417
  private _internalSessionId: string | null;
643
- private readonly metering: MeteringEngine;
418
+ private metering: MeteringEngine;
419
+ private readonly meteringConfig: MeteringConfig;
644
420
  private _contextWindow: ContextWindowStatus | null = null;
645
421
  private _providerCost: ProviderCostSnapshot | null = null;
646
422
  /**
@@ -663,6 +439,10 @@ export class AgentSession implements AgentClient, Bridgeable {
663
439
  private managedAuditLog: AuditLogIdentity | null = null;
664
440
  private readonly managedOpenProgress?: ManagedOpenProgressReporter;
665
441
  private managedInitializationReported = false;
442
+ private readonly ownerLifecycle?: AgentConversationOwnerLifecycle;
443
+ private _participants: ParticipantRef[];
444
+ private ownerRecordWrite: Promise<void> = Promise.resolve();
445
+ private readonly defaultPermission: "approve" | "cancel";
666
446
 
667
447
  private constructor(
668
448
  config: AgentSessionConfig,
@@ -699,7 +479,23 @@ export class AgentSession implements AgentClient, Bridgeable {
699
479
  // IDs are opaque provider/consumer values. Validate blankness above, but never
700
480
  // normalize a nonblank identifier and accidentally select a different session.
701
481
  this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
702
- this.adapterId = config.adapterId;
482
+ if (config.agentConversationId !== undefined && !isAgentConversationId(config.agentConversationId)) {
483
+ throw new Error(`invalid agent conversation id: ${config.agentConversationId}`);
484
+ }
485
+ if (config.ownerAgentSessionId !== undefined && !isAgentSessionId(config.ownerAgentSessionId)) {
486
+ throw new Error(`invalid owner agent session id: ${config.ownerAgentSessionId}`);
487
+ }
488
+ if (config.ownerAgentSessionId !== undefined && config.agentSessionId !== config.ownerAgentSessionId) {
489
+ throw new Error("owned AgentConversation agentSessionId must equal ownerAgentSessionId");
490
+ }
491
+ this.agentConversationId = config.agentConversationId ?? createAgentConversationId();
492
+ this.ownerAgentSessionId = config.ownerAgentSessionId
493
+ ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
494
+ this.ownerLifecycle = config.ownerLifecycle;
495
+ this.defaultPermission = config.defaultPermission ?? "cancel";
496
+ this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
497
+ this._adapterId = config.adapterId;
498
+ this.activeAdapter = config.adapter;
703
499
  this.sessions = config.sessions;
704
500
  this.persistence = resolveDirectPersistence(config.persistence);
705
501
  if (this.persistence !== false && config.sessions) {
@@ -722,19 +518,21 @@ export class AgentSession implements AgentClient, Bridgeable {
722
518
  (config.transcriptDir
723
519
  ? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
724
520
  : 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
521
  this.log = config.logger ?? noopLogger;
522
+ this.presentation = new AgentConversationPresentation({
523
+ activity: config.transcriptActivity,
524
+ logger: this.log,
525
+ persistence: () => this.v2Transcript,
526
+ ...(this._transcriptPath
527
+ ? { appendLegacyActivity: (line) => this.appendTranscript(line) }
528
+ : {}),
529
+ onPresentation: (item) => this.emit({ kind: "presentation_recorded", item }),
530
+ });
734
531
  this._mode = config.mode ?? "normal";
735
532
  this._cwd = config.cwd;
736
533
  this._title = config.title;
737
534
  this._internalSessionId = requestedInternalSessionId ?? null;
535
+ this.meteringConfig = Object.freeze({ ...(config.metering ?? {}) });
738
536
  this.metering = new MeteringEngine({
739
537
  agentSessionId: this.agentSessionId,
740
538
  adapterId: config.adapterId,
@@ -752,31 +550,143 @@ export class AgentSession implements AgentClient, Bridgeable {
752
550
  // not, and needs restored state to be attributable.
753
551
  createdActiveThread: providerSession.kind === "new",
754
552
  });
755
- this.controller = new AgentController({
756
- adapter: config.adapter,
757
- adapterId: config.adapterId,
758
- mode: this._mode,
553
+ this.controllerDefaults = {
759
554
  launcher: config.launcher,
760
555
  execPrefix: config.execPrefix,
761
556
  env: config.env,
762
557
  cwd: config.cwd,
763
- sessionId: requestedInternalSessionId,
764
- sessionLoadFailure: providerSession.kind === "load"
765
- ? providerSession.onFailure ?? "error"
766
- : undefined,
767
558
  mcpServers: config.mcpServers,
768
559
  defaultPermission: config.defaultPermission,
769
560
  clientInfo: config.clientInfo,
770
561
  clientCapabilities: config.clientCapabilities,
771
562
  clientHandlers: config.clientHandlers,
772
563
  logger: config.logger,
773
- wire: config.wire,
564
+ ...(config.wire || this.ownerLifecycle
565
+ ? {
566
+ wire: (entry: WireEntry) => {
567
+ config.wire?.(entry);
568
+ this.queueProtocolRecord(entry);
569
+ },
570
+ }
571
+ : {}),
572
+ };
573
+ this.controller = this.createController(config.adapter, config.adapterId, this._mode, {
574
+ sessionId: requestedInternalSessionId,
575
+ sessionLoadFailure: providerSession.kind === "load"
576
+ ? providerSession.onFailure ?? "error"
577
+ : undefined,
578
+ });
579
+ this.bindController(this.controller);
580
+ }
581
+
582
+ private createController(
583
+ adapter: Adapter,
584
+ adapterId: string,
585
+ mode: AgentMode,
586
+ startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure"> = {},
587
+ ): AgentController {
588
+ return new AgentController({
589
+ ...this.controllerDefaults,
590
+ adapter,
591
+ adapterId,
592
+ mode,
593
+ ...startup,
594
+ });
595
+ }
596
+
597
+ private bindController(controller: AgentController): void {
598
+ this.detachControllerCommands?.();
599
+ this.detachControllerUsage?.();
600
+ this.detachControllerCommands = controller.subscribeAvailableCommands((commands) => {
601
+ if (this.controller === controller) {
602
+ this.emit({ kind: "internal_session_commands_changed", commands });
603
+ }
774
604
  });
775
- this.controller.subscribeAvailableCommands((commands) => {
776
- this.emit({ kind: "internal_session_commands_changed", commands });
605
+ this.detachControllerUsage = controller.subscribeUsageUpdate((update, sessionId) => {
606
+ if (this.controller === controller) this.applyUsageUpdate(update, sessionId);
777
607
  });
778
- this.controller.subscribeUsageUpdate((update, sessionId) => {
779
- this.applyUsageUpdate(update, sessionId);
608
+ }
609
+
610
+ private queueOwnedRecord(record: NewConversationRecord): void {
611
+ if (!this.ownerLifecycle?.record) return;
612
+ this.ownerRecordWrite = this.ownerRecordWrite
613
+ .then(() => this.ownerLifecycle!.record!(record))
614
+ .catch((error) => {
615
+ this.markManagedPersistenceUnhealthy();
616
+ throw error;
617
+ });
618
+ }
619
+
620
+ private async recordOwned(record: NewConversationRecord): Promise<void> {
621
+ if (!this.ownerLifecycle?.record) return;
622
+ const write = this.ownerRecordWrite
623
+ .then(() => this.ownerLifecycle!.record!(record))
624
+ .catch((error) => {
625
+ this.markManagedPersistenceUnhealthy();
626
+ throw error;
627
+ });
628
+ this.ownerRecordWrite = write;
629
+ await write;
630
+ }
631
+
632
+ private markManagedPersistenceUnhealthy(): void {
633
+ if (!this.managedPersistenceHealthy) return;
634
+ this.managedPersistenceHealthy = false;
635
+ this.emitStateIfChanged();
636
+ }
637
+
638
+ private queueProtocolRecord(entry: WireEntry): void {
639
+ if (!this.ownerAgentSessionId || !this.ownerLifecycle?.record) return;
640
+ let message: PersistenceJsonValue;
641
+ try {
642
+ message = JSON.parse(entry.line) as PersistenceJsonValue;
643
+ } catch {
644
+ message = entry.line;
645
+ }
646
+ this.queueOwnedRecord({
647
+ recordId: `protocol-${crypto.randomUUID()}`,
648
+ agentSessionId: this.ownerAgentSessionId,
649
+ agentConversationId: this.agentConversationId,
650
+ kind: "protocol",
651
+ timestamp: new Date(entry.ts).toISOString(),
652
+ direction: entry.dir === "err" ? "error" : entry.dir,
653
+ ...(protocolMethod(message) ? { method: protocolMethod(message)! } : {}),
654
+ message,
655
+ });
656
+ }
657
+
658
+ private queueActivityRecords(turnId: string, records: readonly AggregatedRecord[]): void {
659
+ if (!this.ownerAgentSessionId) return;
660
+ for (const record of records) {
661
+ const runtimeRecord = runtimeRecordFromActivity(
662
+ this.ownerAgentSessionId,
663
+ this.agentConversationId,
664
+ turnId,
665
+ record,
666
+ );
667
+ if (runtimeRecord) this.queueOwnedRecord(runtimeRecord);
668
+ }
669
+ }
670
+
671
+ private async recordNativeAction(
672
+ transitionId: string,
673
+ action: string,
674
+ state: "started" | "checkpoint" | "completed" | "failed",
675
+ details: { readonly input?: unknown; readonly output?: unknown; readonly error?: string } = {},
676
+ ): Promise<void> {
677
+ if (!this.ownerAgentSessionId) return;
678
+ await this.recordOwned({
679
+ recordId: `${transitionId}:native:${state}:${crypto.randomUUID()}`,
680
+ agentSessionId: this.ownerAgentSessionId,
681
+ agentConversationId: this.agentConversationId,
682
+ kind: "native_action",
683
+ timestamp: new Date().toISOString(),
684
+ action,
685
+ transitionId,
686
+ state,
687
+ ...(details.input === undefined ? {} : { input: toPersistenceJsonValue(details.input) }),
688
+ ...(details.output === undefined ? {} : { output: toPersistenceJsonValue(details.output) }),
689
+ ...(details.error === undefined ? {} : { error: details.error }),
780
690
  });
781
691
  }
782
692
 
@@ -798,12 +708,12 @@ export class AgentSession implements AgentClient, Bridgeable {
798
708
  * options independently select history storage. No catalog or transcript is read
799
709
  * implicitly. Consumers compose a catalog record back into this method when reopening.
800
710
  */
801
- static async create(config: AgentSessionConfig): Promise<AgentSession> {
711
+ static async create(config: AgentSessionConfig): Promise<AgentConversation> {
802
712
  const directPersistence = resolveDirectPersistence(config.persistence);
803
713
  if (directPersistence !== false && directPersistence.auditLog !== false) {
804
714
  throw new DirectAuditPersistenceUnsupportedError();
805
715
  }
806
- const session = new AgentSession(config);
716
+ const session = new AgentConversation(config);
807
717
  try {
808
718
  await session.start();
809
719
  return session;
@@ -817,10 +727,10 @@ export class AgentSession implements AgentClient, Bridgeable {
817
727
  static async createManaged(
818
728
  config: AgentSessionConfig,
819
729
  bootstrap: ManagedAgentSessionCreationBootstrap,
820
- ): Promise<AgentSession> {
821
- let session: AgentSession;
730
+ ): Promise<AgentConversation> {
731
+ let session: AgentConversation;
822
732
  try {
823
- session = new AgentSession(config, null, bootstrap);
733
+ session = new AgentConversation(config, null, bootstrap);
824
734
  } catch (error) {
825
735
  await bootstrap.transcriptLock?.release().catch(() => undefined);
826
736
  await bootstrap.auditLogLock?.release().catch(() => undefined);
@@ -839,7 +749,7 @@ export class AgentSession implements AgentClient, Bridgeable {
839
749
 
840
750
  /** Restore one logical session by loading the exact provider thread in transcript authority. */
841
751
  static async open(config: AgentSessionOpenConfig): Promise<AgentSessionOpenResult> {
842
- return await AgentSession.openWithLock(config);
752
+ return await AgentConversation.openWithLock(config);
843
753
  }
844
754
 
845
755
  /** @internal Managed open after maintenance acquired the artifact lock. */
@@ -850,7 +760,7 @@ export class AgentSession implements AgentClient, Bridgeable {
850
760
  stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
851
761
  onOpenProgress?: ManagedOpenProgressReporter,
852
762
  ): Promise<AgentSessionOpenResult> {
853
- return await AgentSession.openWithLock(
763
+ return await AgentConversation.openWithLock(
854
764
  config,
855
765
  transcriptLock,
856
766
  audit,
@@ -879,7 +789,7 @@ export class AgentSession implements AgentClient, Bridgeable {
879
789
  throw new Error("registry-managed open has no recorded internal session id");
880
790
  }
881
791
  const { checkpoint: _checkpoint, continuation: _continuation, ...runtime } = config;
882
- const session = new AgentSession({
792
+ const session = new AgentConversation({
883
793
  ...runtime,
884
794
  agentSessionId: checkpoint.agentSessionId,
885
795
  creationId: checkpoint.incarnationId,
@@ -905,7 +815,7 @@ export class AgentSession implements AgentClient, Bridgeable {
905
815
  strategy: "load_internal_session",
906
816
  status: "succeeded",
907
817
  });
908
- const continuation = continuationReport(
818
+ const continuation = createContinuationReport(
909
819
  checkpoint, config.adapterId, session.v2Transcript, "available", [attempt],
910
820
  { kind: "loaded", activeInternalSessionId: result.sessionId },
911
821
  );
@@ -974,7 +884,7 @@ export class AgentSession implements AgentClient, Bridgeable {
974
884
  throw new AdapterMismatchError(checkpoint.adapterId, config.adapterId);
975
885
  }
976
886
  const { checkpoint: _suppliedCheckpoint, continuation: _continuation, ...runtimeConfig } = config;
977
- const session = new AgentSession({
887
+ const session = new AgentConversation({
978
888
  ...runtimeConfig,
979
889
  agentSessionId: checkpoint.agentSessionId,
980
890
  creationId: checkpoint.incarnationId,
@@ -1275,7 +1185,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1275
1185
  this.continuationAcquired = true;
1276
1186
  recordedThreadAvailability = "available";
1277
1187
  attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1278
- return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1188
+ return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1279
1189
  kind: "loaded",
1280
1190
  activeInternalSessionId: loaded.sessionId,
1281
1191
  });
@@ -1414,7 +1324,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1414
1324
  const seeded = await this.meteredInternalPrompt(
1415
1325
  `${transitionId}:seed`,
1416
1326
  "switch_seed",
1417
- continuationPrompt(continuation.trim()),
1327
+ buildContinuationPrompt(continuation.trim()),
1418
1328
  records,
1419
1329
  );
1420
1330
  if (seeded.status !== "completed") {
@@ -1432,7 +1342,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1432
1342
  });
1433
1343
  this.continuationAcquired = true;
1434
1344
  attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
1435
- return continuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1345
+ return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
1436
1346
  kind: "reconstructed",
1437
1347
  source,
1438
1348
  activeInternalSessionId: created.sessionId,
@@ -1464,7 +1374,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1464
1374
  }
1465
1375
  }
1466
1376
 
1467
- return continuationReport(
1377
+ return createContinuationReport(
1468
1378
  checkpoint,
1469
1379
  this.adapterId,
1470
1380
  this.v2Transcript,
@@ -1535,6 +1445,25 @@ export class AgentSession implements AgentClient, Bridgeable {
1535
1445
  return this._internalSessionId;
1536
1446
  }
1537
1447
 
1448
+ /** Active adapter route. It changes only after a durable switch activation. */
1449
+ get adapterId(): string {
1450
+ return this._adapterId;
1451
+ }
1452
+
1453
+ /** Canonical `agc-` identity. */
1454
+ get id(): AgentConversationId {
1455
+ return this.agentConversationId;
1456
+ }
1457
+
1458
+ /** Owning `ags-` identity, or null for a detached compatibility conversation. */
1459
+ get ownerId(): AgentSessionId | null {
1460
+ return this.ownerAgentSessionId;
1461
+ }
1462
+
1463
+ get participants(): readonly ParticipantRef[] {
1464
+ return Object.freeze(this._participants.map((participant) => Object.freeze({ ...participant })));
1465
+ }
1466
+
1538
1467
  /**
1539
1468
  * Latest context-window observation for the ACTIVE provider thread, or null.
1540
1469
  *
@@ -1587,6 +1516,37 @@ export class AgentSession implements AgentClient, Bridgeable {
1587
1516
  });
1588
1517
  }
1589
1518
 
1519
+ /** @internal Meter disposable provider work without replacing this conversation's baseline. */
1520
+ beginDetachedMetering(input: {
1521
+ operationId: string;
1522
+ operationKind: MeteredOperationKind;
1523
+ internalSessionId: string;
1524
+ model: string | null;
1525
+ }): Promise<OpenDetachedOperation> {
1526
+ return this.metering.openDetached({
1527
+ ...input,
1528
+ providerId: this.providerId,
1529
+ });
1530
+ }
1531
+
1532
+ /** @internal Completes a detached rating unit; the owner persists its returned record. */
1533
+ async closeDetachedMetering(
1534
+ operation: OpenDetachedOperation,
1535
+ input: {
1536
+ outcome: "completed" | "cancelled" | "error";
1537
+ usage: TokenUsage | null;
1538
+ usageFailureReason?: string;
1539
+ },
1540
+ ): Promise<OperationMeteringRecord> {
1541
+ return await this.metering.closeDetached(operation, {
1542
+ outcome: input.outcome,
1543
+ reportedCumulative: input.usage,
1544
+ ...(input.usageFailureReason ? { usageFailureReason: input.usageFailureReason } : {}),
1545
+ contextAfter: this._contextWindow,
1546
+ providerCostAfter: this._providerCost,
1547
+ });
1548
+ }
1549
+
1590
1550
  get contextWindow(): ContextWindowStatus | null {
1591
1551
  return this._contextWindow;
1592
1552
  }
@@ -1686,7 +1646,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1686
1646
  return this.phase !== "idle" && this.phase !== "stopped";
1687
1647
  }
1688
1648
  get queuedOperationCount(): number {
1689
- return this.queue.length;
1649
+ return this.operations.queuedCount;
1690
1650
  }
1691
1651
  /** Subscribe to future lifecycle changes. The current snapshot is available via state. */
1692
1652
  subscribe(listener: AgentSessionListener): () => void {
@@ -1707,11 +1667,23 @@ export class AgentSession implements AgentClient, Bridgeable {
1707
1667
  return this.enqueuePrompt(text, "prompt", handlers, attachments);
1708
1668
  }
1709
1669
 
1670
+ /** Prompt while attributing the caller to a stable participant identity. */
1671
+ promptFrom(
1672
+ participantId: string,
1673
+ text: string,
1674
+ handlers?: PromptHandlers,
1675
+ attachments?: Attachment[],
1676
+ ): Promise<AgentSessionPromptResult> {
1677
+ if (!participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1678
+ return this.enqueuePrompt(text, "prompt", handlers, attachments, participantId.trim());
1679
+ }
1680
+
1710
1681
  private enqueuePrompt(
1711
1682
  text: string,
1712
1683
  operationKind: MeteredOperationKind,
1713
1684
  handlers?: PromptHandlers,
1714
1685
  attachments?: Attachment[],
1686
+ participantId?: string,
1715
1687
  ): Promise<AgentSessionPromptResult> {
1716
1688
  return new Promise<AgentSessionPromptResult>((resolve, reject) => {
1717
1689
  if (this.phase === "stopped") {
@@ -1724,11 +1696,12 @@ export class AgentSession implements AgentClient, Bridgeable {
1724
1696
  reject(error);
1725
1697
  return;
1726
1698
  }
1727
- this.queue.push({
1699
+ this.operations.enqueue({
1728
1700
  kind: "prompt",
1729
1701
  turnId: this.mintTurnId(),
1730
1702
  operationKind,
1731
1703
  text,
1704
+ ...(participantId ? { participantId } : {}),
1732
1705
  handlers,
1733
1706
  attachments,
1734
1707
  resolve,
@@ -1778,12 +1751,12 @@ export class AgentSession implements AgentClient, Bridgeable {
1778
1751
  reject(error);
1779
1752
  return;
1780
1753
  }
1781
- this.queue.push({
1754
+ this.operations.enqueue({
1782
1755
  kind: "handoff",
1783
1756
  handoffId: this.mintOperationId(),
1784
1757
  // A queued operation owns its arguments. Do not let a caller mutate the object
1785
1758
  // while it waits behind an active prompt and silently change the handoff.
1786
- options: Object.freeze({ ...options }),
1759
+ options: ownHandoffOptions(options),
1787
1760
  resolve,
1788
1761
  reject,
1789
1762
  });
@@ -1792,12 +1765,80 @@ export class AgentSession implements AgentClient, Bridgeable {
1792
1765
  });
1793
1766
  }
1794
1767
 
1768
+ /** Cross-adapter handoff. The owning Agent resolves `targetAdapterId` in its registry. */
1769
+ switch(
1770
+ targetAdapterId: string,
1771
+ options: Omit<HandoffOptions, "target" | "summary"> & {
1772
+ readonly mode?: AgentMode;
1773
+ readonly config?: Readonly<Record<string, unknown>>;
1774
+ } = {},
1775
+ ): Promise<HandoffResult> {
1776
+ if (!targetAdapterId.trim()) return Promise.reject(new Error("target adapter id cannot be blank"));
1777
+ return this.handoff({
1778
+ continuation: options.continuation,
1779
+ targetPrompt: options.targetPrompt,
1780
+ target: {
1781
+ adapterId: targetAdapterId.trim(),
1782
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
1783
+ ...(options.config === undefined ? {} : { config: options.config }),
1784
+ },
1785
+ });
1786
+ }
1787
+
1788
+ /** @internal Seed a newly created provider thread from a durable recovery checkpoint. */
1789
+ async seedRecoveryContext(text: string): Promise<PromptResult> {
1790
+ if (!text.trim()) throw new Error("recovery context cannot be blank");
1791
+ const recoveryId = `recovery-${crypto.randomUUID()}`;
1792
+ const records: OperationMeteringRecord[] = [];
1793
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "started");
1794
+ try {
1795
+ const result = await this.meteredInternalPrompt(
1796
+ recoveryId,
1797
+ "conversation_recovery",
1798
+ text,
1799
+ records,
1800
+ );
1801
+ if (result.status !== "completed") {
1802
+ throw new Error(`conversation recovery seed ${result.status}`);
1803
+ }
1804
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "completed", {
1805
+ output: { internalSessionId: this._internalSessionId },
1806
+ });
1807
+ return result;
1808
+ } catch (error) {
1809
+ await this.recordNativeAction(recoveryId, "conversation_recovery", "failed", {
1810
+ error: error instanceof Error ? error.message : String(error),
1811
+ }).catch(() => undefined);
1812
+ throw error;
1813
+ }
1814
+ }
1815
+
1816
+ /** Start a blank provider thread without generating or installing continuation context. */
1817
+ reset(options: {
1818
+ readonly targetAdapterId?: string;
1819
+ readonly mode?: AgentMode;
1820
+ readonly config?: Readonly<Record<string, unknown>>;
1821
+ readonly targetPrompt?: string;
1822
+ } = {}): Promise<HandoffResult> {
1823
+ return this.handoff({
1824
+ continuation: { kind: "none" },
1825
+ ...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
1826
+ ...((options.targetAdapterId ?? options.mode ?? options.config) === undefined
1827
+ ? {}
1828
+ : {
1829
+ target: {
1830
+ adapterId: options.targetAdapterId ?? this.adapterId,
1831
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
1832
+ ...(options.config === undefined ? {} : { config: options.config }),
1833
+ },
1834
+ }),
1835
+ });
1836
+ }
1837
+
1795
1838
  private async pump(): Promise<void> {
1796
- if (this.pumping) return;
1797
- this.pumping = true;
1839
+ if (this.operations.isDraining) return;
1798
1840
  try {
1799
- while (this.queue.length > 0) {
1800
- const item = this.queue.shift()!;
1841
+ await this.operations.drain(async (item) => {
1801
1842
  this.phase = item.kind === "prompt"
1802
1843
  ? "prompting"
1803
1844
  : item.kind === "handoff"
@@ -1831,10 +1872,52 @@ export class AgentSession implements AgentClient, Bridgeable {
1831
1872
  } else if (item.kind === "set_config") {
1832
1873
  this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
1833
1874
  try {
1875
+ if (this.ownerAgentSessionId) {
1876
+ await this.recordOwned({
1877
+ recordId: `${item.operationId}:configuration:started`,
1878
+ agentSessionId: this.ownerAgentSessionId,
1879
+ agentConversationId: this.agentConversationId,
1880
+ kind: "configuration",
1881
+ timestamp: new Date().toISOString(),
1882
+ operation: "set",
1883
+ configId: item.configId,
1884
+ value: toPersistenceJsonValue(item.value),
1885
+ status: "started",
1886
+ });
1887
+ }
1834
1888
  await this.runSetConfig(item);
1889
+ if (this.ownerAgentSessionId) {
1890
+ await this.recordOwned({
1891
+ recordId: `${item.operationId}:configuration:completed`,
1892
+ agentSessionId: this.ownerAgentSessionId,
1893
+ agentConversationId: this.agentConversationId,
1894
+ kind: "configuration",
1895
+ timestamp: new Date().toISOString(),
1896
+ operation: "set",
1897
+ configId: item.configId,
1898
+ value: toPersistenceJsonValue(item.value),
1899
+ status: "completed",
1900
+ });
1901
+ }
1835
1902
  this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
1836
1903
  item.resolve();
1837
1904
  } catch (err) {
1905
+ if (this.ownerAgentSessionId) {
1906
+ await this.recordOwned({
1907
+ recordId: `${item.operationId}:configuration:failed`,
1908
+ agentSessionId: this.ownerAgentSessionId,
1909
+ agentConversationId: this.agentConversationId,
1910
+ kind: "configuration",
1911
+ timestamp: new Date().toISOString(),
1912
+ operation: "set",
1913
+ configId: item.configId,
1914
+ value: toPersistenceJsonValue(item.value),
1915
+ status: "failed",
1916
+ error: String(err),
1917
+ }).catch((persistenceError) => this.log.warn("configuration_failure_persistence_failed", {
1918
+ error: String(persistenceError),
1919
+ }));
1920
+ }
1838
1921
  this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
1839
1922
  item.reject(err);
1840
1923
  }
@@ -1860,28 +1943,60 @@ export class AgentSession implements AgentClient, Bridgeable {
1860
1943
  const from = this._mode;
1861
1944
  this.emit({ kind: "mode_change_started", transitionId: item.transitionId, from, to: item.mode });
1862
1945
  try {
1946
+ await this.recordNativeAction(item.transitionId, "mode_change", "started", {
1947
+ input: { from, to: item.mode },
1948
+ });
1863
1949
  const result = await this.runSetMode(item);
1950
+ await this.recordNativeAction(item.transitionId, "mode_change", "completed", {
1951
+ output: { mode: item.mode, internalSessionId: result.sessionId || null },
1952
+ });
1864
1953
  this.emit({ kind: "mode_change_completed", transitionId: item.transitionId, from, to: item.mode });
1865
1954
  item.resolve(result);
1866
1955
  } catch (err) {
1956
+ await this.recordNativeAction(item.transitionId, "mode_change", "failed", {
1957
+ error: String(err),
1958
+ }).catch(() => undefined);
1867
1959
  this.emit({ kind: "mode_change_failed", transitionId: item.transitionId, from, to: item.mode, error: String(err) });
1868
1960
  item.reject(err);
1869
1961
  }
1870
1962
  }
1871
- }
1963
+ // Promise consumers must observe the settled public state. The old in-class
1964
+ // loop reached its `finally` synchronously after resolving the last item;
1965
+ // crossing the extracted queue's async callback adds a microtask boundary.
1966
+ // Settle here only when no next item exists, preserving both that ordering and
1967
+ // the no-idle-gap guarantee between queued operations.
1968
+ this.settleIdleIfDrained();
1969
+ });
1872
1970
  } finally {
1873
- this.pumping = false;
1874
1971
  if (this.phase !== "stopped") this.phase = "idle";
1875
1972
  this.emitStateIfChanged();
1876
1973
  }
1877
1974
  }
1878
1975
 
1976
+ private settleIdleIfDrained(): void {
1977
+ if (this.operations.queuedCount !== 0 || this.phase === "stopped") return;
1978
+ this.phase = "idle";
1979
+ this.emitStateIfChanged();
1980
+ }
1981
+
1879
1982
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
1880
1983
  const fromInternalSessionId = this._internalSessionId;
1984
+ const fromAdapterId = this.adapterId;
1985
+ const targetAdapterId = item.options.target?.adapterId ?? fromAdapterId;
1986
+ const targetMode = item.options.target?.mode ?? this._mode;
1987
+ const continuation = normalizeHandoffContinuation(item.options);
1988
+ const transitionKind = targetAdapterId === fromAdapterId ? "handoff" as const : "switch" as const;
1989
+ const action = continuation.kind === "none" && transitionKind === "handoff"
1990
+ ? "reset"
1991
+ : transitionKind;
1881
1992
  const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
1882
1993
  let toInternalSessionId: string | undefined;
1883
1994
  let toDescriptor: InternalSessionDescriptor | undefined;
1884
1995
  let summary: string | undefined;
1996
+ let targetResult: PromptResult | undefined;
1997
+ let targetController: AgentController | null = null;
1998
+ let resolvedTargetAdapter: Adapter | null = null;
1999
+ let targetActivated = false;
1885
2000
  let failedAfter: "start" | "target_created" | "target_activated" = "start";
1886
2001
  // Records accumulate as they complete, so a handoff that fails partway still reports
1887
2002
  // the operations it already paid for.
@@ -1891,14 +2006,22 @@ export class AgentSession implements AgentClient, Bridgeable {
1891
2006
  handoffId: item.handoffId,
1892
2007
  fromInternalSessionId,
1893
2008
  });
2009
+ await this.recordNativeAction(item.handoffId, action, "started", {
2010
+ input: {
2011
+ fromAdapterId,
2012
+ targetAdapterId,
2013
+ targetMode,
2014
+ continuation: continuation.kind,
2015
+ },
2016
+ });
1894
2017
  if (this.v2Transcript) {
1895
2018
  await this.v2Transcript.appendTransitionEvent({
1896
2019
  kind: "transition",
1897
2020
  transitionId: item.handoffId,
1898
- transitionKind: "handoff",
2021
+ transitionKind,
1899
2022
  event: "started",
1900
2023
  from: fromDescriptor,
1901
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
2024
+ ...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
1902
2025
  });
1903
2026
  } else {
1904
2027
  await this.appendTranscript({
@@ -1908,25 +2031,24 @@ export class AgentSession implements AgentClient, Bridgeable {
1908
2031
  ts: Date.now(),
1909
2032
  handoffId: item.handoffId,
1910
2033
  fromInternalSessionId,
1911
- ...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
2034
+ ...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
1912
2035
  });
1913
2036
  }
1914
2037
 
1915
2038
  try {
1916
- if (this.controller.isDegraded) {
1917
- throw new Error("handoff requires ACP (normal) mode");
2039
+ if (continuation.kind !== "none" && this.controller.isDegraded) {
2040
+ throw new Error("handoff continuation requires ACP (normal) mode");
1918
2041
  }
1919
2042
 
1920
- if (item.options.summary !== undefined) {
1921
- if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
2043
+ if (continuation.kind === "provided") {
1922
2044
  // A supplied summary removes the generation operation entirely, so no
1923
2045
  // `:summary` record is ever minted for it.
1924
- summary = item.options.summary;
1925
- } else {
2046
+ summary = continuation.content;
2047
+ } else if (continuation.kind === "generated") {
1926
2048
  const generated = await this.meteredInternalPrompt(
1927
2049
  `${item.handoffId}:summary`,
1928
2050
  "handoff_summary",
1929
- HANDOFF_SUMMARY_PROMPT,
2051
+ continuation.summaryPrompt,
1930
2052
  records,
1931
2053
  );
1932
2054
  if (generated.status !== "completed" || !generated.text.trim()) {
@@ -1935,22 +2057,51 @@ export class AgentSession implements AgentClient, Bridgeable {
1935
2057
  // Handoff requires one seed string, so this internal boundary policy is explicit;
1936
2058
  // it is not treated as the canonical shape of the provider response.
1937
2059
  summary = formatResponseMessages(generated.messages, "\n\n").trim();
2060
+ } else {
2061
+ summary = "";
1938
2062
  }
1939
2063
 
1940
- const created = await this.controller.newSession();
2064
+ const replacingController = targetAdapterId !== fromAdapterId || targetMode !== this._mode;
2065
+ let created: ConnectResult;
2066
+ if (replacingController) {
2067
+ const adapter = item.options.target?.adapter ?? (targetAdapterId === fromAdapterId
2068
+ ? this.activeAdapter
2069
+ : this.ownerLifecycle?.resolveAdapter?.(targetAdapterId));
2070
+ if (!adapter) {
2071
+ throw new Error(
2072
+ `cannot resolve adapter ${targetAdapterId}; cross-adapter switch requires an Agent-owned conversation`,
2073
+ );
2074
+ }
2075
+ resolvedTargetAdapter = adapter;
2076
+ targetController = this.createController(adapter, targetAdapterId, targetMode);
2077
+ created = await targetController.startFresh();
2078
+ } else {
2079
+ if (this.controller.isDegraded) {
2080
+ throw new Error("starting a fresh provider thread requires ACP (normal) mode");
2081
+ }
2082
+ targetController = this.controller;
2083
+ created = await targetController.newSession();
2084
+ }
1941
2085
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
1942
2086
  toInternalSessionId = created.sessionId;
1943
- if (toInternalSessionId === fromInternalSessionId) {
2087
+ if (!replacingController && toInternalSessionId === fromInternalSessionId) {
1944
2088
  throw new Error("harness did not replace the internal session during handoff");
1945
2089
  }
1946
2090
 
2091
+ for (const [configId, value] of Object.entries(item.options.target?.config ?? {})) {
2092
+ await targetController.setConfig(configId, value);
2093
+ }
2094
+ await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2095
+ output: { stage: "target_created", internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2096
+ });
2097
+
1947
2098
  if (this.v2Transcript) {
1948
2099
  const transitionAt = new Date().toISOString();
1949
2100
  toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
1950
2101
  await this.v2Transcript.appendTransitionEvent({
1951
2102
  kind: "transition",
1952
2103
  transitionId: item.handoffId,
1953
- transitionKind: "handoff",
2104
+ transitionKind,
1954
2105
  event: "target_created",
1955
2106
  from: fromDescriptor,
1956
2107
  to: toDescriptor,
@@ -1960,7 +2111,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1960
2111
  await this.v2Transcript.activateTransition({
1961
2112
  kind: "transition",
1962
2113
  transitionId: item.handoffId,
1963
- transitionKind: "handoff",
2114
+ transitionKind,
1964
2115
  event: "target_activated",
1965
2116
  from: fromDescriptor,
1966
2117
  to: toDescriptor,
@@ -1974,7 +2125,7 @@ export class AgentSession implements AgentClient, Bridgeable {
1974
2125
  protocol: fromDescriptor.protocol,
1975
2126
  activatedAt: fromDescriptor.activatedAt!,
1976
2127
  deactivatedAt: transitionAt,
1977
- transition: { kind: "handoff", transitionId: item.handoffId },
2128
+ transition: { kind: transitionKind, transitionId: item.handoffId },
1978
2129
  },
1979
2130
  }
1980
2131
  : {}),
@@ -1987,18 +2138,77 @@ export class AgentSession implements AgentClient, Bridgeable {
1987
2138
  });
1988
2139
  failedAfter = "target_activated";
1989
2140
  }
2141
+ const activatedAt = new Date().toISOString();
2142
+ try {
2143
+ await this.ownerLifecycle?.transitionActivated?.({
2144
+ transitionId: item.handoffId,
2145
+ agentConversationId: this.agentConversationId,
2146
+ internalSessionId: toInternalSessionId,
2147
+ adapterId: targetAdapterId,
2148
+ mode: targetMode,
2149
+ ...(activeModel(targetController.configOptions)
2150
+ ? { model: activeModel(targetController.configOptions)! }
2151
+ : {}),
2152
+ activatedAt,
2153
+ });
2154
+ } catch (error) {
2155
+ this.markManagedPersistenceUnhealthy();
2156
+ throw error;
2157
+ }
2158
+
2159
+ const previousController = this.controller;
2160
+ if (targetController !== previousController) {
2161
+ this.controller = targetController;
2162
+ this.activeAdapter = resolvedTargetAdapter!;
2163
+ this._adapterId = targetAdapterId;
2164
+ this._mode = targetMode;
2165
+ this.metering = new MeteringEngine({
2166
+ ...this.meteringConfig,
2167
+ agentSessionId: this.agentSessionId,
2168
+ adapterId: targetAdapterId,
2169
+ initialState: this.metering.currentState,
2170
+ createdActiveThread: true,
2171
+ pricing: this.meteringConfig.pricing ?? createModelsDevResolver(),
2172
+ enforcement: this.meteringConfig.enforcement ?? "best_effort",
2173
+ });
2174
+ this.bindController(targetController);
2175
+ }
2176
+ targetActivated = true;
1990
2177
  this.setInternalSessionId(toInternalSessionId);
2178
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
1991
2179
  this.emitStateIfChanged();
1992
2180
  await this.persist();
2181
+ await this.recordNativeAction(item.handoffId, action, "checkpoint", {
2182
+ output: { stage: "target_activated", internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2183
+ });
2184
+ if (targetController !== previousController) {
2185
+ await previousController.stop().catch((error) => {
2186
+ this.log.warn("handoff_previous_controller_stop_failed", { error: String(error) });
2187
+ });
2188
+ }
1993
2189
 
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}`);
2190
+ if (continuation.kind !== "none") {
2191
+ const seeded = await this.meteredInternalPrompt(
2192
+ `${item.handoffId}:seed`,
2193
+ transitionKind === "switch" ? "switch_seed" : "handoff_seed",
2194
+ buildContinuationPrompt(summary),
2195
+ records,
2196
+ );
2197
+ if (seeded.status !== "completed") {
2198
+ throw new Error(`handoff continuation seeding ${seeded.status}`);
2199
+ }
2200
+ }
2201
+ if (item.options.targetPrompt !== undefined) {
2202
+ const prompted = await this.meteredInternalPrompt(
2203
+ `${item.handoffId}:target`,
2204
+ "internal_command",
2205
+ item.options.targetPrompt,
2206
+ records,
2207
+ );
2208
+ if (prompted.status !== "completed") {
2209
+ throw new Error(`handoff target prompt ${prompted.status}`);
2210
+ }
2211
+ targetResult = copyPromptResult(prompted);
2002
2212
  }
2003
2213
 
2004
2214
  const result: HandoffResult = Object.freeze({
@@ -2006,14 +2216,16 @@ export class AgentSession implements AgentClient, Bridgeable {
2006
2216
  agentSessionId: this.agentSessionId,
2007
2217
  fromInternalSessionId,
2008
2218
  toInternalSessionId,
2219
+ ...(transitionKind === "switch" ? { fromAdapterId, toAdapterId: targetAdapterId } : {}),
2009
2220
  summary,
2221
+ ...(targetResult ? { targetResult } : {}),
2010
2222
  meteringRecords: Object.freeze([...records]),
2011
2223
  });
2012
2224
  if (this.v2Transcript) {
2013
2225
  await this.v2Transcript.appendTransitionEvent({
2014
2226
  kind: "transition",
2015
2227
  transitionId: item.handoffId,
2016
- transitionKind: "handoff",
2228
+ transitionKind,
2017
2229
  event: "completed",
2018
2230
  from: fromDescriptor,
2019
2231
  to: toDescriptor,
@@ -2031,6 +2243,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2031
2243
  summary,
2032
2244
  });
2033
2245
  }
2246
+ await this.recordNativeAction(item.handoffId, action, "completed", {
2247
+ output: { internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
2248
+ });
2034
2249
  this.emit({ kind: "handoff_completed", result });
2035
2250
  return result;
2036
2251
  } catch (err) {
@@ -2042,6 +2257,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2042
2257
  toInternalSessionId = actualSessionId;
2043
2258
  this.emitStateIfChanged();
2044
2259
  try {
2260
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2045
2261
  await this.persist();
2046
2262
  } catch (persistError) {
2047
2263
  this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
@@ -2052,7 +2268,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2052
2268
  await this.v2Transcript.appendTransitionEvent({
2053
2269
  kind: "transition",
2054
2270
  transitionId: item.handoffId,
2055
- transitionKind: "handoff",
2271
+ transitionKind,
2056
2272
  event: "failed",
2057
2273
  from: fromDescriptor,
2058
2274
  ...(toDescriptor ? { to: toDescriptor } : {}),
@@ -2075,6 +2291,14 @@ export class AgentSession implements AgentClient, Bridgeable {
2075
2291
  error,
2076
2292
  });
2077
2293
  }
2294
+ if (!targetActivated && targetController && targetController !== this.controller) {
2295
+ await targetController.stop().catch(() => undefined);
2296
+ }
2297
+ await this.recordNativeAction(item.handoffId, action, "failed", { error }).catch(
2298
+ (persistenceError) => this.log.warn("native_action_failure_persistence_failed", {
2299
+ error: String(persistenceError),
2300
+ }),
2301
+ );
2078
2302
  this.emit({
2079
2303
  kind: "handoff_failed",
2080
2304
  handoffId: item.handoffId,
@@ -2449,6 +2673,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2449
2673
  const result = await this.controller.setMode(item.mode);
2450
2674
  this._mode = this.controller.currentMode;
2451
2675
  this.setInternalSessionId(result.sessionId || null);
2676
+ await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
2452
2677
  await this.persist();
2453
2678
  return result;
2454
2679
  }
@@ -2548,6 +2773,19 @@ export class AgentSession implements AgentClient, Bridgeable {
2548
2773
  }
2549
2774
 
2550
2775
  private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
2776
+ const owned = this.ownerLifecycle
2777
+ ? await this.ownerLifecycle.beforePrompt({
2778
+ operationId: item.turnId,
2779
+ agentSessionId: this.ownerAgentSessionId!,
2780
+ agentConversationId: this.agentConversationId,
2781
+ ...(item.participantId ? { participantId: item.participantId } : {}),
2782
+ text: item.text,
2783
+ })
2784
+ : undefined;
2785
+ if (owned?.participant && !this._participants.some((participant) => participant.id === owned.participant!.id)) {
2786
+ this._participants = [...this._participants, Object.freeze({ ...owned.participant })];
2787
+ }
2788
+ const providerText = owned?.providerText ?? item.text;
2551
2789
  this.beginTurn(item.turnId);
2552
2790
  let operation: OpenOperation;
2553
2791
  if (this.v2Transcript) {
@@ -2567,9 +2805,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2567
2805
  presentation: { id: `message:${item.turnId}:user`, revision: 1 },
2568
2806
  });
2569
2807
  await this.v2Transcript.syncBeforeDispatch();
2570
- this.emitPresentationRecord(userRecord);
2808
+ this.presentation.emitPersistedRecord(userRecord);
2571
2809
  } catch (error) {
2572
- this.endTurn(item.handlers);
2810
+ this.endTurn(item.turnId, item.handlers);
2573
2811
  if (transcriptStarted) {
2574
2812
  await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
2575
2813
  (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
@@ -2618,7 +2856,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2618
2856
  assistantMessage.revision++;
2619
2857
  assistantMessage.dirty = false;
2620
2858
  const message = assistantMessage;
2621
- this.queueV2Presentation({
2859
+ this.presentation.queuePresentation({
2622
2860
  kind: "message",
2623
2861
  operationId: item.turnId,
2624
2862
  role: "assistant",
@@ -2645,9 +2883,9 @@ export class AgentSession implements AgentClient, Bridgeable {
2645
2883
  item.handlers?.onChunk?.(chunk);
2646
2884
  },
2647
2885
  onResponseChunk: (chunk) => {
2648
- const settledReasoning = this.aggregator.closeReasoningBoundary();
2886
+ const settledReasoning = this.presentation.closeReasoningBoundary();
2649
2887
  if (settledReasoning) {
2650
- if (this.transcriptActivity || this.v2Transcript) this.writeActivity(settledReasoning);
2888
+ this.queueActivityRecords(item.turnId, [settledReasoning]);
2651
2889
  item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
2652
2890
  }
2653
2891
  response.append(chunk);
@@ -2672,19 +2910,55 @@ export class AgentSession implements AgentClient, Bridgeable {
2672
2910
  // The message snapshot must enter the shared queue before an activity first seen
2673
2911
  // after it. Later activity revisions keep their original presentation position.
2674
2912
  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
- }
2913
+ const result = this.presentation.applyActivity(event);
2914
+ this.queueActivityRecords(item.turnId, result.emitted);
2679
2915
  item.handlers?.onRecord?.(result);
2680
2916
  item.handlers?.onActivity?.(event);
2681
2917
  },
2918
+ onPermissionRequest: async (request) => {
2919
+ const permissionBase = `${item.turnId}:permission:${request.toolCallId}`;
2920
+ if (this.ownerAgentSessionId) {
2921
+ await this.recordOwned({
2922
+ recordId: `${permissionBase}:requested`,
2923
+ agentSessionId: this.ownerAgentSessionId,
2924
+ agentConversationId: this.agentConversationId,
2925
+ kind: "permission",
2926
+ timestamp: new Date().toISOString(),
2927
+ permissionId: request.toolCallId,
2928
+ state: "requested",
2929
+ request: toPersistenceJsonValue({
2930
+ toolCallId: request.toolCallId,
2931
+ ...(request.title ? { title: request.title } : {}),
2932
+ options: request.options,
2933
+ raw: request.raw,
2934
+ }),
2935
+ });
2936
+ }
2937
+ const outcome = item.handlers?.onPermissionRequest
2938
+ ? await item.handlers.onPermissionRequest(request)
2939
+ : defaultPermissionOutcome(request, this.defaultPermission);
2940
+ if (this.ownerAgentSessionId) {
2941
+ await this.recordOwned({
2942
+ recordId: `${permissionBase}:resolved`,
2943
+ agentSessionId: this.ownerAgentSessionId,
2944
+ agentConversationId: this.agentConversationId,
2945
+ kind: "permission",
2946
+ timestamp: new Date().toISOString(),
2947
+ permissionId: request.toolCallId,
2948
+ state: "resolved",
2949
+ outcome: permissionRecordOutcome(request, outcome),
2950
+ });
2951
+ }
2952
+ return outcome;
2953
+ },
2682
2954
  };
2683
2955
 
2684
2956
  let closed: OperationMeteringRecord | null = null;
2685
2957
  let transcriptClosed = false;
2958
+ let providerSettled = false;
2686
2959
  try {
2687
- const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
2960
+ const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
2961
+ providerSettled = true;
2688
2962
  if (this.v2Transcript) {
2689
2963
  if (assistantOrdinal === 0) {
2690
2964
  for (const message of res.messages) {
@@ -2699,7 +2973,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2699
2973
  }
2700
2974
  // Before the assistant msg: `msg` delimits a turn, so anything still open has to
2701
2975
  // land inside those fences.
2702
- this.endTurn(item.handlers);
2976
+ this.endTurn(item.turnId, item.handlers);
2703
2977
  if (!this._title && item.text.trim()) {
2704
2978
  this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
2705
2979
  }
@@ -2715,9 +2989,10 @@ export class AgentSession implements AgentClient, Bridgeable {
2715
2989
  // a worse failure than the one closing early prevents.
2716
2990
  const record = await this.closeOperation(operation, res.status, res.usage);
2717
2991
  closed = record;
2992
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2718
2993
  await this.persist();
2719
2994
  if (this.v2Transcript) {
2720
- await this.drainV2Presentation();
2995
+ await this.presentation.drain();
2721
2996
  await this.finishV2Prompt(res.status, record);
2722
2997
  transcriptClosed = true;
2723
2998
  } else {
@@ -2733,11 +3008,21 @@ export class AgentSession implements AgentClient, Bridgeable {
2733
3008
  status: res.status,
2734
3009
  });
2735
3010
  }
2736
- return Object.freeze({ ...res, operationId: item.turnId, metering: record });
3011
+ const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3012
+ await this.ownerLifecycle?.afterPrompt({
3013
+ operationId: item.turnId,
3014
+ agentSessionId: this.ownerAgentSessionId!,
3015
+ agentConversationId: this.agentConversationId,
3016
+ ...(item.participantId ? { participantId: item.participantId } : {}),
3017
+ text: item.text,
3018
+ result,
3019
+ });
3020
+ await this.ownerRecordWrite;
3021
+ return result;
2737
3022
  } catch (err) {
2738
3023
  // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
2739
3024
  // what it was doing, at its real status.
2740
- this.endTurn(item.handlers);
3025
+ this.endTurn(item.turnId, item.handlers);
2741
3026
  const structured = response.snapshot();
2742
3027
  const text = structured.length > 0 ? response.text : chunks.join("");
2743
3028
  const messages: readonly ResponseMessage[] = structured.length > 0
@@ -2745,6 +3030,22 @@ export class AgentSession implements AgentClient, Bridgeable {
2745
3030
  : text
2746
3031
  ? Object.freeze([{ text }])
2747
3032
  : Object.freeze([]);
3033
+ if (!providerSettled) {
3034
+ await this.ownerLifecycle?.promptFailed({
3035
+ operationId: item.turnId,
3036
+ agentSessionId: this.ownerAgentSessionId!,
3037
+ agentConversationId: this.agentConversationId,
3038
+ ...(item.participantId ? { participantId: item.participantId } : {}),
3039
+ text: item.text,
3040
+ messages,
3041
+ error: err,
3042
+ }).catch((persistenceError) => {
3043
+ this.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
3044
+ });
3045
+ }
3046
+ await this.ownerRecordWrite.catch((persistenceError) => {
3047
+ this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3048
+ });
2748
3049
  if (this.v2Transcript) {
2749
3050
  if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
2750
3051
  for (const message of messages) {
@@ -2756,7 +3057,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2756
3057
  } else if (!transcriptClosed) {
2757
3058
  flushAssistantMessage("error", "error", true);
2758
3059
  }
2759
- await this.drainV2Presentation().catch(() => undefined);
3060
+ await this.presentation.drain().catch(() => undefined);
2760
3061
  } else {
2761
3062
  await this.appendTranscript({
2762
3063
  v: 1,
@@ -2774,6 +3075,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2774
3075
  // Already metered: the failure happened after the operation closed (a transcript or
2775
3076
  // catalog write), so the record stands and must not be minted a second time.
2776
3077
  const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
3078
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2777
3079
  if (this.v2Transcript && !transcriptClosed) {
2778
3080
  await this.finishV2Prompt("error", record, "unknown").catch(
2779
3081
  (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
@@ -2836,7 +3138,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2836
3138
  before: AgentSessionMeteringState;
2837
3139
  after: AgentSessionMeteringState;
2838
3140
  }> {
2839
- if (this.isBusy || this.queue.length > 0) {
3141
+ if (this.isBusy || this.operations.queuedCount > 0) {
2840
3142
  throw new Error("reconcileMetering requires an idle session with no queued operations");
2841
3143
  }
2842
3144
  if (!reconciliation.reason?.trim()) {
@@ -2859,6 +3161,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2859
3161
  // Validated first: state is replaced atomically or not at all.
2860
3162
  const { before } = this.metering.reconcile(restoration.state);
2861
3163
  const after = this.metering.currentState;
3164
+ await this.ownerLifecycle?.meteringStateChanged?.(after);
2862
3165
  this.emit({
2863
3166
  kind: "metering_reconciled",
2864
3167
  before,
@@ -2923,6 +3226,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2923
3226
  const record = await this.closeOperation(operation, result.status, result.usage);
2924
3227
  records.push(record);
2925
3228
  closed = true;
3229
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2926
3230
  if (this.v2Transcript) {
2927
3231
  await this.v2Transcript.appendEvent({
2928
3232
  kind: "message",
@@ -2942,6 +3246,7 @@ export class AgentSession implements AgentClient, Bridgeable {
2942
3246
  const record = await this.closeOperation(operation, "error", null, String(err));
2943
3247
  records.push(record);
2944
3248
  closed = true;
3249
+ await this.ownerLifecycle?.meteringRecorded?.(record);
2945
3250
  }
2946
3251
  if (this.v2Transcript && !transcriptClosed) {
2947
3252
  const record = records[records.length - 1]!;
@@ -3033,26 +3338,15 @@ export class AgentSession implements AgentClient, Bridgeable {
3033
3338
  * activity in its log before the messages around it had loaded.
3034
3339
  */
3035
3340
  activitySnapshot(): ActivitySnapshot {
3036
- return this.aggregator.snapshot();
3341
+ return this.presentation.snapshot();
3037
3342
  }
3038
3343
 
3039
3344
  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
- }
3345
+ this.presentation.beginTurn(turnId);
3047
3346
  }
3048
3347
 
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 });
3348
+ private endTurn(turnId: string, handlers?: PromptHandlers): void {
3349
+ this.queueActivityRecords(turnId, this.presentation.endTurn(handlers));
3056
3350
  }
3057
3351
 
3058
3352
  /**
@@ -3072,80 +3366,9 @@ export class AgentSession implements AgentClient, Bridgeable {
3072
3366
  return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
3073
3367
  }
3074
3368
 
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
3369
  interrupt(options?: InterruptOptions): void {
3147
3370
  if (options?.clearQueue) {
3148
- const dropped = this.queue.splice(0);
3371
+ const dropped = this.operations.clear();
3149
3372
  for (const item of dropped) {
3150
3373
  if (item.kind === "prompt") {
3151
3374
  // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
@@ -3184,7 +3407,10 @@ export class AgentSession implements AgentClient, Bridgeable {
3184
3407
  this.phase = "stopped";
3185
3408
  this.emitStateIfChanged();
3186
3409
  await this.controller.stop();
3187
- await this.drainV2Presentation().catch(() => undefined);
3410
+ await this.ownerRecordWrite.catch((error) => {
3411
+ this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3412
+ });
3413
+ await this.presentation.drain().catch(() => undefined);
3188
3414
  await this.v2Transcript?.close();
3189
3415
  }
3190
3416
 
@@ -3193,7 +3419,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3193
3419
  if (this.phase === "stopped") throw new Error("AgentSession is stopped");
3194
3420
  this.assertPromptable();
3195
3421
  return await new Promise<ConnectResult>((resolve, reject) => {
3196
- this.queue.push({
3422
+ this.operations.enqueue({
3197
3423
  kind: "set_mode",
3198
3424
  transitionId: this.mintOperationId(),
3199
3425
  mode,
@@ -3232,7 +3458,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3232
3458
  return Promise.reject(new Error(`configuration value cannot be cloned: ${String(error)}`));
3233
3459
  }
3234
3460
  return new Promise<void>((resolve, reject) => {
3235
- this.queue.push({
3461
+ this.operations.enqueue({
3236
3462
  kind: "set_config",
3237
3463
  operationId: this.mintOperationId(),
3238
3464
  configId,
@@ -3263,7 +3489,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3263
3489
  return Promise.reject(new Error(`configuration resolution cannot be cloned: ${String(error)}`));
3264
3490
  }
3265
3491
  return new Promise((resolve, reject) => {
3266
- this.queue.push({ kind: "resolve_config", resolution: owned, resolve, reject });
3492
+ this.operations.enqueue({ kind: "resolve_config", resolution: owned, resolve, reject });
3267
3493
  this.emitStateIfChanged();
3268
3494
  void this.pump();
3269
3495
  });
@@ -3287,7 +3513,7 @@ export class AgentSession implements AgentClient, Bridgeable {
3287
3513
  ...(resolution.continuation === undefined ? {} : { continuation: resolution.continuation }),
3288
3514
  });
3289
3515
  return new Promise((resolve, reject) => {
3290
- this.queue.push({ kind: "resolve_recovery", resolution: owned, resolve, reject });
3516
+ this.operations.enqueue({ kind: "resolve_recovery", resolution: owned, resolve, reject });
3291
3517
  this.emitStateIfChanged();
3292
3518
  void this.pump();
3293
3519
  });
@@ -3479,96 +3705,101 @@ export class AgentSession implements AgentClient, Bridgeable {
3479
3705
  }
3480
3706
  }
3481
3707
 
3708
+ /**
3709
+ * @deprecated `AgentSession` is the compatibility name for one conversation. New code
3710
+ * should use `AgentConversation`; the forthcoming `Agent` object owns conversations.
3711
+ */
3712
+ export { AgentConversation as AgentSession };
3713
+
3714
+ export type AgentConversationConfig = AgentSessionConfig;
3715
+ export type AgentConversationOpenConfig = AgentSessionOpenConfig;
3716
+ export type AgentConversationOpenResult = AgentSessionOpenResult;
3717
+ export type ManagedAgentConversationCreationBootstrap = ManagedAgentSessionCreationBootstrap;
3718
+ export type ManagedAgentConversationPersistenceSnapshot = ManagedAgentSessionPersistenceSnapshot;
3719
+
3482
3720
  function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
3483
- return kind === "internal_command" ? "internal_session_command" : kind;
3721
+ if (kind === "internal_command") return "internal_session_command";
3722
+ if (
3723
+ kind === "conversation_checkpoint"
3724
+ || kind === "conversation_recovery"
3725
+ || kind === "identity_update"
3726
+ ) return "other";
3727
+ return kind;
3484
3728
  }
3485
3729
 
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 {
3730
+ function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
3494
3731
  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 }),
3732
+ ...(options.summary === undefined ? {} : { summary: options.summary }),
3733
+ ...(options.target === undefined
3734
+ ? {}
3735
+ : {
3736
+ target: Object.freeze({
3737
+ adapterId: options.target.adapterId,
3738
+ ...(options.target.mode === undefined ? {} : { mode: options.target.mode }),
3739
+ ...(options.target.adapter === undefined
3740
+ ? {}
3741
+ : {
3742
+ adapter: Object.freeze({
3743
+ ...options.target.adapter,
3744
+ command: Object.freeze([...options.target.adapter.command]) as unknown as string[],
3745
+ ...(options.target.adapter.ptyCommand
3746
+ ? {
3747
+ ptyCommand: Object.freeze([
3748
+ ...options.target.adapter.ptyCommand,
3749
+ ]) as unknown as string[],
3750
+ }
3751
+ : {}),
3752
+ }),
3753
+ }),
3754
+ ...(options.target.config === undefined
3755
+ ? {}
3756
+ : { config: Object.freeze({ ...options.target.config }) }),
3757
+ }),
3758
+ }),
3759
+ ...(options.continuation === undefined
3760
+ ? {}
3761
+ : { continuation: Object.freeze({ ...options.continuation }) }),
3762
+ ...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
3502
3763
  });
3503
3764
  }
3504
3765
 
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");
3766
+ function normalizeHandoffContinuation(options: HandoffOptions):
3767
+ | { readonly kind: "generated"; readonly summaryPrompt: string }
3768
+ | { readonly kind: "provided"; readonly content: string }
3769
+ | { readonly kind: "none" } {
3770
+ if (options.summary !== undefined && options.continuation !== undefined) {
3771
+ throw new Error("handoff cannot combine deprecated summary with continuation");
3772
+ }
3773
+ if (options.target && !options.target.adapterId.trim()) {
3774
+ throw new Error("handoff target adapter id cannot be blank");
3775
+ }
3776
+ if (options.targetPrompt !== undefined && !options.targetPrompt.trim()) {
3777
+ throw new Error("handoff target prompt cannot be blank");
3778
+ }
3779
+ if (options.summary !== undefined) {
3780
+ if (!options.summary.trim()) throw new Error("handoff summary cannot be blank");
3781
+ return Object.freeze({ kind: "provided", content: options.summary });
3782
+ }
3783
+ const continuation = options.continuation ?? { kind: "generated" as const };
3784
+ if (continuation.kind === "provided") {
3785
+ if (!continuation.content.trim()) throw new Error("handoff continuation cannot be blank");
3786
+ return Object.freeze({ kind: "provided", content: continuation.content });
3787
+ }
3788
+ if (continuation.kind === "none") return Object.freeze({ kind: "none" });
3789
+ if (continuation.summaryPrompt !== undefined && continuation.summaryInstructions !== undefined) {
3790
+ throw new Error("handoff generated continuation cannot combine summaryPrompt and summaryInstructions");
3571
3791
  }
3792
+ if (continuation.summaryPrompt !== undefined && !continuation.summaryPrompt.trim()) {
3793
+ throw new Error("handoff summary prompt cannot be blank");
3794
+ }
3795
+ if (continuation.summaryInstructions !== undefined && !continuation.summaryInstructions.trim()) {
3796
+ throw new Error("handoff summary instructions cannot be blank");
3797
+ }
3798
+ const base = continuation.summaryPrompt ?? HANDOFF_SUMMARY_PROMPT;
3799
+ const summaryPrompt = continuation.summaryInstructions === undefined
3800
+ ? base
3801
+ : `${base}\n\nAdditional summary instructions:\n${continuation.summaryInstructions}`;
3802
+ return Object.freeze({ kind: "generated", summaryPrompt });
3572
3803
  }
3573
3804
 
3574
3805
  function configurationTargetIssue(
@@ -3619,6 +3850,130 @@ function sameJsonValue(left: unknown, right: JsonValue): boolean {
3619
3850
  }
3620
3851
  }
3621
3852
 
3853
+ function runtimeRecordFromActivity(
3854
+ agentSessionId: AgentSessionId,
3855
+ agentConversationId: AgentConversationId,
3856
+ turnId: string,
3857
+ record: AggregatedRecord,
3858
+ ): NewConversationRecord | null {
3859
+ const timestamp = new Date().toISOString();
3860
+ const recordId = `${turnId}:runtime:${record.recordId}:${record.seq}`;
3861
+ const event = record.event;
3862
+ if (event.kind === "thinking") {
3863
+ return {
3864
+ recordId,
3865
+ agentSessionId,
3866
+ agentConversationId,
3867
+ kind: "thinking",
3868
+ timestamp,
3869
+ thinkingId: record.recordId,
3870
+ state: record.reason === "settled" || record.reason === "flushed" ? "completed" : "in_progress",
3871
+ content: event.text,
3872
+ ...(event.messageId ? { metadata: JSON.stringify({ providerMessageId: event.messageId }) } : {}),
3873
+ };
3874
+ }
3875
+ if (event.kind === "tool") {
3876
+ const terminal = event.status === "completed" || event.status === "failed";
3877
+ const state = event.status === "failed"
3878
+ ? "failed" as const
3879
+ : terminal
3880
+ ? "completed" as const
3881
+ : record.reason === "input"
3882
+ ? "input" as const
3883
+ : record.reason === "flushed"
3884
+ ? "failed" as const
3885
+ : "announced" as const;
3886
+ const output = event.rawOutput !== undefined || event.content !== undefined
3887
+ ? [{
3888
+ type: "json" as const,
3889
+ value: toPersistenceJsonValue({
3890
+ ...(event.rawOutput === undefined ? {} : { rawOutput: event.rawOutput }),
3891
+ ...(event.content === undefined ? {} : { content: event.content }),
3892
+ ...(event.locations === undefined ? {} : { locations: event.locations }),
3893
+ }),
3894
+ }]
3895
+ : undefined;
3896
+ return {
3897
+ recordId,
3898
+ agentSessionId,
3899
+ agentConversationId,
3900
+ kind: "tool_call",
3901
+ timestamp,
3902
+ toolCallId: event.toolCallId,
3903
+ state,
3904
+ ...(event.title || event.toolKind ? { name: event.title ?? event.toolKind } : {}),
3905
+ ...(event.rawInput === undefined ? {} : { input: toPersistenceJsonValue(event.rawInput) }),
3906
+ ...(output === undefined ? {} : { output }),
3907
+ ...(state === "failed" ? { error: `tool call ended with status ${event.status}` } : {}),
3908
+ metadata: JSON.stringify({ providerStatus: event.status, toolKind: event.toolKind }),
3909
+ };
3910
+ }
3911
+ switch (event.kind) {
3912
+ case "plan":
3913
+ case "plan_update":
3914
+ case "plan_removed":
3915
+ return {
3916
+ recordId,
3917
+ agentSessionId,
3918
+ agentConversationId,
3919
+ kind: "activity",
3920
+ timestamp,
3921
+ activityId: record.recordId,
3922
+ activityType: event.kind,
3923
+ state: "completed",
3924
+ data: toPersistenceJsonValue(event),
3925
+ };
3926
+ case "user_message":
3927
+ case "commands":
3928
+ case "mode":
3929
+ case "usage":
3930
+ case "session_info":
3931
+ case "config":
3932
+ case "unknown":
3933
+ // These are conversation echo, session state, or diagnostic protocol updates.
3934
+ // Their semantic state is persisted by messages/configuration/metering/checkpoints;
3935
+ // exact frames are independently available through raw protocol capture.
3936
+ return null;
3937
+ case "tool_update":
3938
+ // Folded updates return above as tool records. An unfurled tool_update is not a
3939
+ // self-contained model activity, so it must not be persisted independently.
3940
+ return null;
3941
+ }
3942
+ }
3943
+
3944
+ function protocolMethod(message: PersistenceJsonValue): string | undefined {
3945
+ if (message === null || Array.isArray(message) || typeof message !== "object") return undefined;
3946
+ const method = (message as { readonly method?: unknown }).method;
3947
+ return typeof method === "string" ? method : undefined;
3948
+ }
3949
+
3950
+ function toPersistenceJsonValue(value: unknown): PersistenceJsonValue {
3951
+ if (value === undefined) return null;
3952
+ const serialized = JSON.stringify(value);
3953
+ return serialized === undefined ? String(value) : JSON.parse(serialized) as PersistenceJsonValue;
3954
+ }
3955
+
3956
+ function defaultPermissionOutcome(
3957
+ request: PermissionRequest,
3958
+ policy: "approve" | "cancel",
3959
+ ): PermissionOutcome {
3960
+ if (policy === "cancel") return { outcome: "cancelled" };
3961
+ const allow = request.options.find((option) => option.kind === "allow_once")
3962
+ ?? request.options.find((option) => option.kind === "allow_always");
3963
+ return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
3964
+ }
3965
+
3966
+ function permissionRecordOutcome(
3967
+ request: PermissionRequest,
3968
+ outcome: PermissionOutcome,
3969
+ ): "approved" | "denied" | "cancelled" {
3970
+ if (outcome.outcome === "cancelled") return "cancelled";
3971
+ const selected = request.options.find((option) => option.optionId === outcome.optionId);
3972
+ return selected?.kind === "allow_once" || selected?.kind === "allow_always"
3973
+ ? "approved"
3974
+ : "denied";
3975
+ }
3976
+
3622
3977
  /** Do not let one notification observer mutate the PromptResult another observer sees. */
3623
3978
  function copyPromptResult(result: PromptResult): PromptResult {
3624
3979
  const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
@@ -3630,58 +3985,3 @@ function copyPromptResult(result: PromptResult): PromptResult {
3630
3985
  usage: result.usage ? Object.freeze({ ...result.usage }) : null,
3631
3986
  });
3632
3987
  }
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
- }