@qlairoslabs/acp-client 0.7.3 → 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.
- package/CHANGELOG-audit.md +58 -0
- package/CONSUMER_GUIDE.md +474 -19
- package/package.json +6 -1
- package/src/agent-adapter-registry.ts +66 -0
- package/src/agent-conversation-continuation.ts +121 -0
- package/src/agent-conversation-contracts.ts +279 -0
- package/src/agent-conversation-errors.ts +31 -0
- package/src/agent-conversation-owner.ts +55 -0
- package/src/agent-conversation-presentation.ts +217 -0
- package/src/agent-conversation-queue.ts +44 -0
- package/src/agent-conversation.ts +41 -0
- package/src/agent-ids.ts +50 -0
- package/src/agent-session.ts +1022 -682
- package/src/agent.ts +1175 -0
- package/src/audit/config.ts +186 -0
- package/src/audit/contracts.ts +59 -0
- package/src/audit/index.ts +50 -0
- package/src/audit/projection.ts +125 -0
- package/src/audit/reader.ts +371 -0
- package/src/audit/runtime.ts +1060 -0
- package/src/checkpointing/config.ts +91 -0
- package/src/checkpointing/contracts.ts +45 -0
- package/src/checkpointing/coordinator.ts +100 -0
- package/src/checkpointing/ids.ts +5 -0
- package/src/checkpointing/index.ts +6 -0
- package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
- package/src/checkpointing/recovery.ts +114 -0
- package/src/checkpointing/strategy.ts +139 -0
- package/src/controller.ts +37 -5
- package/src/identity.ts +62 -0
- package/src/index.ts +121 -0
- package/src/internal-inference/config.ts +68 -0
- package/src/internal-inference/contracts.ts +218 -0
- package/src/internal-inference/coordination/handles.ts +133 -0
- package/src/internal-inference/coordination/manager.ts +487 -0
- package/src/internal-inference/ids.ts +10 -0
- package/src/internal-inference/index.ts +10 -0
- package/src/internal-inference/persistence/records.ts +132 -0
- package/src/internal-inference/persistence/repository.ts +35 -0
- package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
- package/src/internal-inference/runtime/harness-runtime.ts +78 -0
- package/src/internal-inference/strategy/registry.ts +42 -0
- package/src/metering/engine.ts +47 -0
- package/src/metering/record.ts +4 -1
- package/src/observation/contracts.ts +10 -0
- package/src/observation/index.ts +8 -0
- package/src/observation/subscription-hub.ts +43 -0
- package/src/persistence/activity-projection.ts +26 -12
- package/src/persistence/backend.ts +774 -0
- package/src/persistence/index.ts +99 -0
- package/src/persistence/managed-creation.ts +18 -2
- package/src/persistence/managed-load.ts +19 -5
- package/src/persistence/managed-open-progress.ts +54 -0
- package/src/persistence/presentation.ts +3 -0
- package/src/persistence/sqlite-backend.ts +1927 -0
- package/src/persistence/sqlite-conversation-records.ts +425 -0
- package/src/persistence/sqlite-owner-lock.ts +106 -0
- package/src/persistence/sqlite-schema.ts +561 -0
package/src/agent-session.ts
CHANGED
|
@@ -1,26 +1,44 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
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
|
|
10
|
-
//
|
|
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
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
AgentController,
|
|
14
|
+
type AgentControllerConfig,
|
|
15
|
+
type AgentControllerStartEvent,
|
|
16
|
+
type AgentMode,
|
|
17
|
+
} from "./controller.ts";
|
|
13
18
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
14
19
|
import { join } from "node:path";
|
|
15
|
-
import {
|
|
20
|
+
import type { ActivitySnapshot, AggregatedRecord } from "./activity.ts";
|
|
16
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";
|
|
17
35
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
|
|
18
36
|
import type { Capabilities } from "./capabilities.ts";
|
|
19
37
|
import type { ConfigOption, ConfigOptions } from "./config-options.ts";
|
|
20
38
|
import type { ConnectResult } from "./client.ts";
|
|
21
39
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
22
40
|
import { formatResponseMessages, ResponseAccumulator } from "./response.ts";
|
|
23
|
-
import { MeteringEngine, type OpenOperation } from "./metering/engine.ts";
|
|
41
|
+
import { MeteringEngine, type OpenDetachedOperation, type OpenOperation } from "./metering/engine.ts";
|
|
24
42
|
import {
|
|
25
43
|
AgentSessionHandoffError,
|
|
26
44
|
AgentSessionOperationError,
|
|
@@ -44,7 +62,6 @@ import {
|
|
|
44
62
|
import type { SessionManager, MergedSession } from "./session-manager.ts";
|
|
45
63
|
import {
|
|
46
64
|
appendTranscriptLine,
|
|
47
|
-
type TranscriptActivityLine,
|
|
48
65
|
type TranscriptLine,
|
|
49
66
|
} from "./transcript.ts";
|
|
50
67
|
import type {
|
|
@@ -53,6 +70,8 @@ import type {
|
|
|
53
70
|
Attachment,
|
|
54
71
|
PromptHandlers,
|
|
55
72
|
PromptResult,
|
|
73
|
+
PermissionOutcome,
|
|
74
|
+
PermissionRequest,
|
|
56
75
|
ResponseMessage,
|
|
57
76
|
SessionListEntry,
|
|
58
77
|
TokenUsage,
|
|
@@ -83,20 +102,14 @@ import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.t
|
|
|
83
102
|
import {
|
|
84
103
|
RegistryPersistenceRuntime,
|
|
85
104
|
type PersistenceStateRuntime,
|
|
86
|
-
type PresentationPersistenceEvent,
|
|
87
105
|
} from "./persistence/state-runtime.ts";
|
|
88
106
|
import { AuditPersistenceRuntime, AuditedPersistenceRuntime, type AuditLogIdentity } from "./persistence/audit-runtime.ts";
|
|
89
107
|
import { TranscriptReader } from "./persistence/transcript-reader.ts";
|
|
90
|
-
import {
|
|
91
|
-
presentationItemFromRecord,
|
|
92
|
-
type TranscriptPresentationItem,
|
|
93
|
-
} from "./persistence/presentation.ts";
|
|
94
108
|
import {
|
|
95
109
|
snapshotSessionConfiguration,
|
|
96
110
|
snapshotSessionConfigurationAfterSelection,
|
|
97
111
|
snapshotAcceptedEffectiveConfiguration,
|
|
98
112
|
} from "./persistence/configuration-state.ts";
|
|
99
|
-
import { persistenceEventFromActivity } from "./persistence/activity-projection.ts";
|
|
100
113
|
import {
|
|
101
114
|
canonicalizeJson,
|
|
102
115
|
sha256CanonicalJson,
|
|
@@ -105,6 +118,90 @@ import {
|
|
|
105
118
|
import type { PersistenceRepair, SessionRecoveryStatus } from "./persistence/reducer.ts";
|
|
106
119
|
import type { StagedContinuationState } from "./persistence/registry.ts";
|
|
107
120
|
import type { SessionLogWriterLock } from "./persistence/session-log-writer.ts";
|
|
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";
|
|
108
205
|
|
|
109
206
|
interface PromptQueueItem {
|
|
110
207
|
kind: "prompt";
|
|
@@ -112,6 +209,7 @@ interface PromptQueueItem {
|
|
|
112
209
|
/** How this operation is classified in its metering record. */
|
|
113
210
|
operationKind: MeteredOperationKind;
|
|
114
211
|
text: string;
|
|
212
|
+
participantId?: string;
|
|
115
213
|
handlers?: PromptHandlers;
|
|
116
214
|
attachments?: Attachment[];
|
|
117
215
|
resolve: (r: AgentSessionPromptResult) => void;
|
|
@@ -159,108 +257,8 @@ interface RecoveryResolutionQueueItem {
|
|
|
159
257
|
|
|
160
258
|
type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
|
|
161
259
|
|
|
162
|
-
/** What the stable logical session is doing right now. */
|
|
163
|
-
export type AgentSessionPhase =
|
|
164
|
-
| "idle"
|
|
165
|
-
| "prompting"
|
|
166
|
-
| "handoff"
|
|
167
|
-
| "configuring"
|
|
168
|
-
| "recovering"
|
|
169
|
-
| "switching_mode"
|
|
170
|
-
| "stopped";
|
|
171
|
-
|
|
172
|
-
/** Authoritative, immutable point-in-time state for orchestration consumers. */
|
|
173
|
-
export interface AgentSessionState {
|
|
174
|
-
readonly phase: AgentSessionPhase;
|
|
175
|
-
/** True only while an operation is executing; queued work is reported separately. */
|
|
176
|
-
readonly isBusy: boolean;
|
|
177
|
-
/** Operations waiting behind the active one. Does not count the active operation. */
|
|
178
|
-
readonly queuedOperationCount: number;
|
|
179
|
-
readonly agentSessionId: string;
|
|
180
|
-
readonly internalSessionId: string | null;
|
|
181
|
-
readonly adapterId: string;
|
|
182
|
-
readonly mode: AgentMode;
|
|
183
|
-
readonly promptability: AgentSessionPromptability;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export type ConfigurationRestoreStatus =
|
|
187
|
-
| { readonly kind: "matched" }
|
|
188
|
-
| { readonly kind: "partial"; readonly omittedConfigIds: readonly string[] }
|
|
189
|
-
| {
|
|
190
|
-
readonly kind: "mismatch";
|
|
191
|
-
readonly configIds: readonly string[];
|
|
192
|
-
readonly reasons: readonly string[];
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
export type PromptBlocker =
|
|
196
|
-
| "continuation_unavailable"
|
|
197
|
-
| "recovery_required"
|
|
198
|
-
| "configuration_mismatch"
|
|
199
|
-
| "persistence_unhealthy"
|
|
200
|
-
| "maintenance_pending"
|
|
201
|
-
| "session_stopped";
|
|
202
|
-
|
|
203
|
-
export type AgentSessionPromptability =
|
|
204
|
-
| { readonly promptable: true; readonly blockers: readonly [] }
|
|
205
|
-
| { readonly promptable: false; readonly blockers: readonly PromptBlocker[] };
|
|
206
|
-
|
|
207
|
-
export interface ContinuationAttempt {
|
|
208
|
-
readonly strategy: ContinuationStrategy["kind"];
|
|
209
|
-
readonly status: "succeeded" | "failed" | "skipped";
|
|
210
|
-
readonly errorCode?: PersistedMachineCode;
|
|
211
|
-
readonly reason?: string;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
export interface ContinuationReport {
|
|
215
|
-
readonly recordedAdapterId: string;
|
|
216
|
-
readonly recordedInternalSessionId: string | null;
|
|
217
|
-
readonly requestedAdapterId: string;
|
|
218
|
-
readonly recordedConversationAvailability: "available" | "partial" | "not_captured";
|
|
219
|
-
readonly recordedThreadAvailability: "available" | "unavailable" | "not_checked";
|
|
220
|
-
readonly attempts: readonly ContinuationAttempt[];
|
|
221
|
-
readonly outcome:
|
|
222
|
-
| { readonly kind: "loaded"; readonly activeInternalSessionId: string }
|
|
223
|
-
| {
|
|
224
|
-
readonly kind: "reconstructed";
|
|
225
|
-
readonly source: "transcript" | "consumer";
|
|
226
|
-
readonly activeInternalSessionId: string;
|
|
227
|
-
readonly transitionId: string;
|
|
228
|
-
}
|
|
229
|
-
| { readonly kind: "unavailable" };
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
export interface TranscriptContinuationBuilderContext {
|
|
233
|
-
readonly agentSessionId: string;
|
|
234
|
-
readonly checkpoint: AgentSessionCheckpoint;
|
|
235
|
-
/** Snapshot-bound access to captured history; the builder decides how much to read. */
|
|
236
|
-
readonly transcript: TranscriptReader;
|
|
237
|
-
readonly targetAdapterId: string;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
export type TranscriptContinuationBuilder = (
|
|
241
|
-
context: TranscriptContinuationBuilderContext,
|
|
242
|
-
) => Promise<{ readonly continuation: string; readonly metadata?: Readonly<Record<string, JsonValue>> }>;
|
|
243
|
-
|
|
244
|
-
export type ContinuationStrategy =
|
|
245
|
-
| { readonly kind: "load_internal_session" }
|
|
246
|
-
| {
|
|
247
|
-
readonly kind: "new_from_transcript";
|
|
248
|
-
readonly strategyId: string;
|
|
249
|
-
readonly buildContinuation: TranscriptContinuationBuilder;
|
|
250
|
-
}
|
|
251
|
-
| {
|
|
252
|
-
readonly kind: "new_from_consumer_continuation";
|
|
253
|
-
readonly continuationId: string;
|
|
254
|
-
readonly continuation: string;
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
export interface OpenContinuationOptions {
|
|
258
|
-
/** Defaults to only `load_internal_session`; an empty array is invalid. */
|
|
259
|
-
readonly strategies?: readonly ContinuationStrategy[];
|
|
260
|
-
}
|
|
261
|
-
|
|
262
260
|
export interface AgentSessionOpenResult {
|
|
263
|
-
readonly session:
|
|
261
|
+
readonly session: AgentConversation;
|
|
264
262
|
readonly continuation: ContinuationReport;
|
|
265
263
|
readonly recovery: SessionRecoveryStatus;
|
|
266
264
|
readonly configuration: ConfigurationRestoreStatus;
|
|
@@ -268,227 +266,6 @@ export interface AgentSessionOpenResult {
|
|
|
268
266
|
readonly repairs: readonly PersistenceRepair[];
|
|
269
267
|
}
|
|
270
268
|
|
|
271
|
-
export type ConfigurationMismatchResolution =
|
|
272
|
-
| { readonly strategy: "accept_effective" }
|
|
273
|
-
| {
|
|
274
|
-
readonly strategy: "replace_restoration_targets";
|
|
275
|
-
readonly selections: readonly { readonly configId: string; readonly value: JsonValue }[];
|
|
276
|
-
};
|
|
277
|
-
|
|
278
|
-
export interface ConfigurationMismatchResolutionResult {
|
|
279
|
-
readonly configuration: ConfigurationRestoreStatus;
|
|
280
|
-
readonly appliedConfigIds: readonly string[];
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
export type AgentSessionRecoveryResolution =
|
|
284
|
-
| { readonly strategy: "accept_harness_state" }
|
|
285
|
-
| {
|
|
286
|
-
readonly strategy: "start_new_internal_session";
|
|
287
|
-
/** When omitted, the currently loaded harness thread generates portable context. */
|
|
288
|
-
readonly continuation?: string;
|
|
289
|
-
};
|
|
290
|
-
|
|
291
|
-
export interface AgentSessionRecoveryResolutionResult {
|
|
292
|
-
readonly previous: Extract<SessionRecoveryStatus, { readonly kind: "uncertain" }>;
|
|
293
|
-
readonly recovery: Extract<SessionRecoveryStatus, { readonly kind: "clean" }>;
|
|
294
|
-
/** Present when resolution deliberately replaced the provider thread. */
|
|
295
|
-
readonly handoff?: HandoffResult;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
export class AgentSessionPromptBlockedError extends Error {
|
|
299
|
-
constructor(readonly blockers: readonly PromptBlocker[]) {
|
|
300
|
-
super(`AgentSession cannot mutate while blocked: ${blockers.join(", ")}`);
|
|
301
|
-
this.name = "AgentSessionPromptBlockedError";
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
export class ContinuationUnavailableError extends Error {
|
|
306
|
-
constructor(readonly continuation: ContinuationReport, options?: ErrorOptions) {
|
|
307
|
-
super("recorded internal session could not be loaded", options);
|
|
308
|
-
this.name = "ContinuationUnavailableError";
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
export class AdapterMismatchError extends Error {
|
|
313
|
-
constructor(readonly recordedAdapterId: string, readonly requestedAdapterId: string) {
|
|
314
|
-
super(`adapter mismatch: transcript requires ${recordedAdapterId}, received ${requestedAdapterId}`);
|
|
315
|
-
this.name = "AdapterMismatchError";
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/** Direct V2 audit creation is deferred until it has the same crash transaction as managed creation. */
|
|
320
|
-
export class DirectAuditPersistenceUnsupportedError extends Error {
|
|
321
|
-
constructor() {
|
|
322
|
-
super("direct V2 audit persistence is not supported; use SessionManager.createAgentSession()");
|
|
323
|
-
this.name = "DirectAuditPersistenceUnsupportedError";
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
export interface HandoffOptions {
|
|
328
|
-
/** Portable continuation context. When omitted, the current thread generates it. */
|
|
329
|
-
readonly summary?: string;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
export interface HandoffResult {
|
|
333
|
-
readonly handoffId: string;
|
|
334
|
-
readonly agentSessionId: string;
|
|
335
|
-
readonly fromInternalSessionId: string | null;
|
|
336
|
-
readonly toInternalSessionId: string;
|
|
337
|
-
readonly summary: string;
|
|
338
|
-
/** One record per token-consuming operation the handoff performed, in order. */
|
|
339
|
-
readonly meteringRecords: readonly OperationMeteringRecord[];
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
/** Session-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
|
|
343
|
-
export type AgentSessionEvent =
|
|
344
|
-
| { kind: "state_changed"; state: AgentSessionState }
|
|
345
|
-
| { kind: "turn_started"; turnId: string }
|
|
346
|
-
| { kind: "turn_completed"; turnId: string; result: PromptResult }
|
|
347
|
-
| { kind: "turn_failed"; turnId: string; error: string }
|
|
348
|
-
/** A display item revision was appended to the transcript and can be joined to reloads by id. */
|
|
349
|
-
| { kind: "presentation_recorded"; item: TranscriptPresentationItem }
|
|
350
|
-
/** The active ACP harness changed the slash commands it advertises. */
|
|
351
|
-
| { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
|
|
352
|
-
| {
|
|
353
|
-
kind: "handoff_started";
|
|
354
|
-
handoffId: string;
|
|
355
|
-
fromInternalSessionId: string | null;
|
|
356
|
-
}
|
|
357
|
-
| { kind: "handoff_completed"; result: HandoffResult }
|
|
358
|
-
| {
|
|
359
|
-
kind: "handoff_failed";
|
|
360
|
-
handoffId: string;
|
|
361
|
-
fromInternalSessionId: string | null;
|
|
362
|
-
toInternalSessionId?: string;
|
|
363
|
-
error: string;
|
|
364
|
-
/** Records produced before and during the failure. */
|
|
365
|
-
meteringRecords: readonly OperationMeteringRecord[];
|
|
366
|
-
}
|
|
367
|
-
| { kind: "configuration_started"; operationId: string; configId: string }
|
|
368
|
-
| { kind: "configuration_completed"; operationId: string; configId: string }
|
|
369
|
-
| { kind: "configuration_failed"; operationId: string; configId: string; error: string }
|
|
370
|
-
| { kind: "mode_change_started"; transitionId: string; from: AgentMode; to: AgentMode }
|
|
371
|
-
| { kind: "mode_change_completed"; transitionId: string; from: AgentMode; to: AgentMode }
|
|
372
|
-
| { kind: "mode_change_failed"; transitionId: string; from: AgentMode; to: AgentMode; error: string }
|
|
373
|
-
| {
|
|
374
|
-
kind: "configuration_mismatch_resolved";
|
|
375
|
-
configuration: ConfigurationRestoreStatus;
|
|
376
|
-
appliedConfigIds: readonly string[];
|
|
377
|
-
}
|
|
378
|
-
| {
|
|
379
|
-
kind: "recovery_resolved";
|
|
380
|
-
strategy: AgentSessionRecoveryResolution["strategy"];
|
|
381
|
-
previous: Extract<SessionRecoveryStatus, { kind: "uncertain" }>;
|
|
382
|
-
recovery: Extract<SessionRecoveryStatus, { kind: "clean" }>;
|
|
383
|
-
}
|
|
384
|
-
/** Latest context-window observation for the ACTIVE provider thread, or null. */
|
|
385
|
-
| { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
|
|
386
|
-
/** Latest cumulative provider-reported cost. Telemetry, never asserted to be an invoice. */
|
|
387
|
-
| { kind: "provider_cost_changed"; providerCost: ProviderCostSnapshot | null }
|
|
388
|
-
/** One immutable record per observed operation, emitted before its turn completes. */
|
|
389
|
-
| { kind: "metering_recorded"; record: OperationMeteringRecord }
|
|
390
|
-
/** A strict mode detected a metering failure; later token-consuming work will reject. */
|
|
391
|
-
| { kind: "metering_blocked"; reason: string }
|
|
392
|
-
| { kind: "metering_unblocked" }
|
|
393
|
-
| {
|
|
394
|
-
kind: "metering_reconciled";
|
|
395
|
-
before: AgentSessionMeteringState;
|
|
396
|
-
after: AgentSessionMeteringState;
|
|
397
|
-
reason: string;
|
|
398
|
-
reference?: string;
|
|
399
|
-
reconciledAt: number;
|
|
400
|
-
};
|
|
401
|
-
|
|
402
|
-
/** A prompt result enriched with the operation's metering record. */
|
|
403
|
-
export interface AgentSessionPromptResult extends PromptResult {
|
|
404
|
-
readonly operationId: string;
|
|
405
|
-
/**
|
|
406
|
-
* The operation's record, or null when the operation never reached the provider.
|
|
407
|
-
*
|
|
408
|
-
* Null happens only for a queued prompt cancelled before dispatch (§16). Such an
|
|
409
|
-
* operation consumed nothing, and minting a record for it would put a fabricated
|
|
410
|
-
* entry in the consumer's ledger — so the field is honestly empty instead.
|
|
411
|
-
*/
|
|
412
|
-
readonly metering: OperationMeteringRecord | null;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/** Ordered envelope delivered to every AgentSession subscriber. */
|
|
416
|
-
export interface AgentSessionNotification {
|
|
417
|
-
readonly seq: number;
|
|
418
|
-
readonly ts: number;
|
|
419
|
-
readonly agentSessionId: string;
|
|
420
|
-
readonly event: AgentSessionEvent;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
export type AgentSessionListener = (notification: AgentSessionNotification) => void;
|
|
424
|
-
|
|
425
|
-
/** What to record when `transcriptActivity` is on. */
|
|
426
|
-
export interface TranscriptActivityConfig {
|
|
427
|
-
/**
|
|
428
|
-
* Which record kinds to persist. Default: `tool`, `thinking`, `plan`, `plan_update`,
|
|
429
|
-
* `plan_removed`, `usage`, `mode`, `unknown` — everything except client state
|
|
430
|
-
* (`commands`, `config`, `session_info`) and `user_message`, which duplicates `t:"msg"`.
|
|
431
|
-
*/
|
|
432
|
-
kinds?: Array<ActivityEvent["kind"]>;
|
|
433
|
-
/**
|
|
434
|
-
* Write an extra line the first time a tool call learns its arguments. Default true —
|
|
435
|
-
* agents routinely announce a call long before they know what it will run, so without
|
|
436
|
-
* this a turn that dies mid-call leaves a record naming the tool but not the command.
|
|
437
|
-
*
|
|
438
|
-
* This is an aggregator-level knob, so it also shapes `onRecord`'s `emitted` when no
|
|
439
|
-
* transcript is configured.
|
|
440
|
-
*/
|
|
441
|
-
checkpointOnInput?: boolean;
|
|
442
|
-
/**
|
|
443
|
-
* Persist `rawOutput`. Default false: in practice it is a byte-identical duplicate of
|
|
444
|
-
* `content` (measured on live Kimi), so it doubles the largest field on the line.
|
|
445
|
-
*/
|
|
446
|
-
rawOutput?: boolean;
|
|
447
|
-
/**
|
|
448
|
-
* Cap each individual string field (terminal output, text content, a stringified
|
|
449
|
-
* `rawInput`) at this many bytes, appending `… [truncated N bytes]` and marking the
|
|
450
|
-
* line `truncated: true`. Default off. Per-field on purpose — capping the serialized
|
|
451
|
-
* line would emit unparseable JSON.
|
|
452
|
-
*/
|
|
453
|
-
maxBytes?: number;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
const DEFAULT_ACTIVITY_KINDS: Array<ActivityEvent["kind"]> = [
|
|
457
|
-
"tool",
|
|
458
|
-
"thinking",
|
|
459
|
-
"plan",
|
|
460
|
-
"plan_update",
|
|
461
|
-
"plan_removed",
|
|
462
|
-
"usage",
|
|
463
|
-
"mode",
|
|
464
|
-
"unknown",
|
|
465
|
-
];
|
|
466
|
-
|
|
467
|
-
const HANDOFF_SUMMARY_PROMPT = [
|
|
468
|
-
"Create portable continuation context for a new agent thread.",
|
|
469
|
-
"Summarize the objective, decisions, completed work, current state, important files or identifiers,",
|
|
470
|
-
"and concrete next steps. Preserve unresolved risks and constraints. Return only the continuation context.",
|
|
471
|
-
].join(" ");
|
|
472
|
-
|
|
473
|
-
function continuationPrompt(summary: string): string {
|
|
474
|
-
return [
|
|
475
|
-
"Continue this conversation using the following portable continuation context.",
|
|
476
|
-
"Treat it as prior context, not as a new user request. Confirm internally and continue from this state.",
|
|
477
|
-
"",
|
|
478
|
-
summary,
|
|
479
|
-
].join("\n");
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
/** Explicit selection of the provider thread backing a newly opened AgentSession. */
|
|
483
|
-
export type ProviderSession =
|
|
484
|
-
| { readonly kind: "new" }
|
|
485
|
-
| {
|
|
486
|
-
readonly kind: "load";
|
|
487
|
-
readonly internalSessionId: string;
|
|
488
|
-
/** Default "error": never silently replace a requested thread. */
|
|
489
|
-
readonly onFailure?: "error" | "new";
|
|
490
|
-
};
|
|
491
|
-
|
|
492
269
|
export interface AgentSessionConfig {
|
|
493
270
|
/** The resolved adapter this conversation talks to. */
|
|
494
271
|
adapter: Adapter;
|
|
@@ -557,6 +334,14 @@ export interface AgentSessionConfig {
|
|
|
557
334
|
*/
|
|
558
335
|
internalSessionId?: string;
|
|
559
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;
|
|
560
345
|
}
|
|
561
346
|
|
|
562
347
|
/** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
|
|
@@ -582,6 +367,7 @@ interface AgentSessionOpenBootstrap {
|
|
|
582
367
|
readonly transcript: PersistenceStateRuntime;
|
|
583
368
|
readonly transcriptPath: string;
|
|
584
369
|
readonly stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>;
|
|
370
|
+
readonly onOpenProgress?: ManagedOpenProgressReporter;
|
|
585
371
|
}
|
|
586
372
|
|
|
587
373
|
/** @internal Transaction hooks supplied only by SessionManager managed creation. */
|
|
@@ -590,6 +376,7 @@ export interface ManagedAgentSessionCreationBootstrap {
|
|
|
590
376
|
readonly transcriptLock?: SessionLogWriterLock;
|
|
591
377
|
readonly auditLogLock?: SessionLogWriterLock;
|
|
592
378
|
readonly stageContinuation: (state: StagedContinuationState) => Promise<StagedContinuationState>;
|
|
379
|
+
readonly onOpenProgress?: ManagedOpenProgressReporter;
|
|
593
380
|
}
|
|
594
381
|
|
|
595
382
|
export interface ManagedAgentSessionPersistenceSnapshot {
|
|
@@ -598,41 +385,38 @@ export interface ManagedAgentSessionPersistenceSnapshot {
|
|
|
598
385
|
readonly auditLog: AuditLogIdentity | null;
|
|
599
386
|
}
|
|
600
387
|
|
|
601
|
-
export class
|
|
602
|
-
/**
|
|
388
|
+
export class AgentConversation implements AgentClient, Bridgeable {
|
|
389
|
+
/** Compatibility logical id — decoupled from the ACP/harness session id. */
|
|
603
390
|
readonly agentSessionId: string;
|
|
604
|
-
readonly
|
|
605
|
-
|
|
606
|
-
private
|
|
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;
|
|
607
403
|
private readonly sessions?: SessionManager;
|
|
608
404
|
private readonly _transcriptPath?: string;
|
|
609
405
|
private readonly persistence: false | ResolvedAgentSessionPersistence;
|
|
610
406
|
private readonly creationId: string;
|
|
611
407
|
private v2Transcript: PersistenceStateRuntime | null = null;
|
|
612
408
|
private v2TranscriptPath: string | null = null;
|
|
613
|
-
|
|
614
|
-
private v2PresentationWrite: Promise<void> = Promise.resolve();
|
|
615
|
-
private readonly transcriptActivity: boolean;
|
|
616
|
-
private readonly activityKinds: Set<string>;
|
|
617
|
-
private readonly activityRawOutput: boolean;
|
|
618
|
-
private readonly activityMaxBytes: number | null;
|
|
619
|
-
/**
|
|
620
|
-
* THE aggregator — one per session for its whole life, never one per turn: `seq` has to
|
|
621
|
-
* keep counting across turns or a subscriber's discard threshold goes stale (see
|
|
622
|
-
* `activitySnapshot`). Runs unconditionally, so a snapshot is truthful and `onRecord`
|
|
623
|
-
* works whether or not a transcript is configured.
|
|
624
|
-
*/
|
|
625
|
-
private readonly aggregator: ActivityAggregator;
|
|
409
|
+
private readonly presentation: AgentConversationPresentation;
|
|
626
410
|
private readonly log: Logger;
|
|
627
411
|
private transcriptWrite: Promise<void> = Promise.resolve();
|
|
628
|
-
private
|
|
629
|
-
private pumping = false;
|
|
412
|
+
private readonly operations = new AgentConversationQueue<QueueItem>();
|
|
630
413
|
private phase: AgentSessionPhase = "idle";
|
|
631
414
|
private notificationSeq = 0;
|
|
632
415
|
private readonly listeners = new Set<AgentSessionListener>();
|
|
633
416
|
private lastStateKey = "";
|
|
634
417
|
private _internalSessionId: string | null;
|
|
635
|
-
private
|
|
418
|
+
private metering: MeteringEngine;
|
|
419
|
+
private readonly meteringConfig: MeteringConfig;
|
|
636
420
|
private _contextWindow: ContextWindowStatus | null = null;
|
|
637
421
|
private _providerCost: ProviderCostSnapshot | null = null;
|
|
638
422
|
/**
|
|
@@ -653,11 +437,18 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
653
437
|
private readonly managedCreation: ManagedAgentSessionCreationBootstrap | null;
|
|
654
438
|
private managedPersistenceHealthy = true;
|
|
655
439
|
private managedAuditLog: AuditLogIdentity | null = null;
|
|
440
|
+
private readonly managedOpenProgress?: ManagedOpenProgressReporter;
|
|
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";
|
|
656
446
|
|
|
657
447
|
private constructor(
|
|
658
448
|
config: AgentSessionConfig,
|
|
659
449
|
openBootstrap: AgentSessionOpenBootstrap | null = null,
|
|
660
450
|
managedCreation: ManagedAgentSessionCreationBootstrap | null = null,
|
|
451
|
+
managedOpenProgress?: ManagedOpenProgressReporter,
|
|
661
452
|
) {
|
|
662
453
|
if (config.transcriptPath && config.transcriptDir) {
|
|
663
454
|
throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
|
|
@@ -688,7 +479,23 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
688
479
|
// IDs are opaque provider/consumer values. Validate blankness above, but never
|
|
689
480
|
// normalize a nonblank identifier and accidentally select a different session.
|
|
690
481
|
this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
|
|
691
|
-
|
|
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;
|
|
692
499
|
this.sessions = config.sessions;
|
|
693
500
|
this.persistence = resolveDirectPersistence(config.persistence);
|
|
694
501
|
if (this.persistence !== false && config.sessions) {
|
|
@@ -703,24 +510,29 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
703
510
|
this.creationId = config.creationId ?? crypto.randomUUID();
|
|
704
511
|
this.openBootstrap = openBootstrap;
|
|
705
512
|
this.managedCreation = managedCreation;
|
|
513
|
+
this.managedOpenProgress = managedOpenProgress
|
|
514
|
+
?? managedCreation?.onOpenProgress
|
|
515
|
+
?? openBootstrap?.onOpenProgress;
|
|
706
516
|
this._transcriptPath =
|
|
707
517
|
config.transcriptPath ??
|
|
708
518
|
(config.transcriptDir
|
|
709
519
|
? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
|
|
710
520
|
: undefined);
|
|
711
|
-
const activity: TranscriptActivityConfig | null =
|
|
712
|
-
config.transcriptActivity === true ? {} : config.transcriptActivity || null;
|
|
713
|
-
this.transcriptActivity = activity !== null;
|
|
714
|
-
this.activityKinds = new Set(activity?.kinds ?? DEFAULT_ACTIVITY_KINDS);
|
|
715
|
-
this.activityRawOutput = activity?.rawOutput === true;
|
|
716
|
-
this.activityMaxBytes =
|
|
717
|
-
activity?.maxBytes != null && activity.maxBytes > 0 ? activity.maxBytes : null;
|
|
718
|
-
this.aggregator = new ActivityAggregator({ checkpointOnInput: activity?.checkpointOnInput });
|
|
719
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
|
+
});
|
|
720
531
|
this._mode = config.mode ?? "normal";
|
|
721
532
|
this._cwd = config.cwd;
|
|
722
533
|
this._title = config.title;
|
|
723
534
|
this._internalSessionId = requestedInternalSessionId ?? null;
|
|
535
|
+
this.meteringConfig = Object.freeze({ ...(config.metering ?? {}) });
|
|
724
536
|
this.metering = new MeteringEngine({
|
|
725
537
|
agentSessionId: this.agentSessionId,
|
|
726
538
|
adapterId: config.adapterId,
|
|
@@ -738,46 +550,170 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
738
550
|
// not, and needs restored state to be attributable.
|
|
739
551
|
createdActiveThread: providerSession.kind === "new",
|
|
740
552
|
});
|
|
741
|
-
this.
|
|
742
|
-
adapter: config.adapter,
|
|
743
|
-
adapterId: config.adapterId,
|
|
744
|
-
mode: this._mode,
|
|
553
|
+
this.controllerDefaults = {
|
|
745
554
|
launcher: config.launcher,
|
|
746
555
|
execPrefix: config.execPrefix,
|
|
747
556
|
env: config.env,
|
|
748
557
|
cwd: config.cwd,
|
|
749
|
-
sessionId: requestedInternalSessionId,
|
|
750
|
-
sessionLoadFailure: providerSession.kind === "load"
|
|
751
|
-
? providerSession.onFailure ?? "error"
|
|
752
|
-
: undefined,
|
|
753
558
|
mcpServers: config.mcpServers,
|
|
754
559
|
defaultPermission: config.defaultPermission,
|
|
755
560
|
clientInfo: config.clientInfo,
|
|
756
561
|
clientCapabilities: config.clientCapabilities,
|
|
757
562
|
clientHandlers: config.clientHandlers,
|
|
758
563
|
logger: config.logger,
|
|
759
|
-
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
|
+
}
|
|
604
|
+
});
|
|
605
|
+
this.detachControllerUsage = controller.subscribeUsageUpdate((update, sessionId) => {
|
|
606
|
+
if (this.controller === controller) this.applyUsageUpdate(update, sessionId);
|
|
760
607
|
});
|
|
761
|
-
|
|
762
|
-
|
|
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,
|
|
763
655
|
});
|
|
764
|
-
|
|
765
|
-
|
|
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 }),
|
|
766
690
|
});
|
|
767
691
|
}
|
|
768
692
|
|
|
693
|
+
private reportManagedControllerProgress(event: AgentControllerStartEvent): void {
|
|
694
|
+
if (!this.managedOpenProgress) return;
|
|
695
|
+
// A continuation policy may restart the same adapter after a failed load. The
|
|
696
|
+
// managed lifecycle reports capability discovery once, while the successful
|
|
697
|
+
// provider-thread acquisition is reported when it actually occurs.
|
|
698
|
+
if (event.stage === "initialized") {
|
|
699
|
+
if (this.managedInitializationReported) return;
|
|
700
|
+
this.managedInitializationReported = true;
|
|
701
|
+
}
|
|
702
|
+
this.managedOpenProgress(event);
|
|
703
|
+
}
|
|
704
|
+
|
|
769
705
|
/**
|
|
770
706
|
* Open a logical conversation. `agentSessionId` selects stable identity;
|
|
771
707
|
* `providerSession` independently selects a new or existing provider thread; transcript
|
|
772
708
|
* options independently select history storage. No catalog or transcript is read
|
|
773
709
|
* implicitly. Consumers compose a catalog record back into this method when reopening.
|
|
774
710
|
*/
|
|
775
|
-
static async create(config: AgentSessionConfig): Promise<
|
|
711
|
+
static async create(config: AgentSessionConfig): Promise<AgentConversation> {
|
|
776
712
|
const directPersistence = resolveDirectPersistence(config.persistence);
|
|
777
713
|
if (directPersistence !== false && directPersistence.auditLog !== false) {
|
|
778
714
|
throw new DirectAuditPersistenceUnsupportedError();
|
|
779
715
|
}
|
|
780
|
-
const session = new
|
|
716
|
+
const session = new AgentConversation(config);
|
|
781
717
|
try {
|
|
782
718
|
await session.start();
|
|
783
719
|
return session;
|
|
@@ -791,10 +727,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
791
727
|
static async createManaged(
|
|
792
728
|
config: AgentSessionConfig,
|
|
793
729
|
bootstrap: ManagedAgentSessionCreationBootstrap,
|
|
794
|
-
): Promise<
|
|
795
|
-
let session:
|
|
730
|
+
): Promise<AgentConversation> {
|
|
731
|
+
let session: AgentConversation;
|
|
796
732
|
try {
|
|
797
|
-
session = new
|
|
733
|
+
session = new AgentConversation(config, null, bootstrap);
|
|
798
734
|
} catch (error) {
|
|
799
735
|
await bootstrap.transcriptLock?.release().catch(() => undefined);
|
|
800
736
|
await bootstrap.auditLogLock?.release().catch(() => undefined);
|
|
@@ -813,7 +749,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
813
749
|
|
|
814
750
|
/** Restore one logical session by loading the exact provider thread in transcript authority. */
|
|
815
751
|
static async open(config: AgentSessionOpenConfig): Promise<AgentSessionOpenResult> {
|
|
816
|
-
return await
|
|
752
|
+
return await AgentConversation.openWithLock(config);
|
|
817
753
|
}
|
|
818
754
|
|
|
819
755
|
/** @internal Managed open after maintenance acquired the artifact lock. */
|
|
@@ -822,8 +758,15 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
822
758
|
transcriptLock?: SessionLogWriterLock,
|
|
823
759
|
audit?: AuditPersistenceRuntime,
|
|
824
760
|
stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
|
|
761
|
+
onOpenProgress?: ManagedOpenProgressReporter,
|
|
825
762
|
): Promise<AgentSessionOpenResult> {
|
|
826
|
-
return await
|
|
763
|
+
return await AgentConversation.openWithLock(
|
|
764
|
+
config,
|
|
765
|
+
transcriptLock,
|
|
766
|
+
audit,
|
|
767
|
+
stageContinuation,
|
|
768
|
+
onOpenProgress,
|
|
769
|
+
);
|
|
827
770
|
}
|
|
828
771
|
|
|
829
772
|
/** @internal Restore a registry-authoritative session without a transcript reader. */
|
|
@@ -832,6 +775,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
832
775
|
history: readonly InternalSessionHistoryEntry[],
|
|
833
776
|
audit?: AuditPersistenceRuntime,
|
|
834
777
|
stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
|
|
778
|
+
onOpenProgress?: ManagedOpenProgressReporter,
|
|
835
779
|
): Promise<AgentSessionOpenResult> {
|
|
836
780
|
const checkpoint = config.checkpoint;
|
|
837
781
|
if (!checkpoint || checkpoint.transcript !== null) {
|
|
@@ -845,7 +789,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
845
789
|
throw new Error("registry-managed open has no recorded internal session id");
|
|
846
790
|
}
|
|
847
791
|
const { checkpoint: _checkpoint, continuation: _continuation, ...runtime } = config;
|
|
848
|
-
const session = new
|
|
792
|
+
const session = new AgentConversation({
|
|
849
793
|
...runtime,
|
|
850
794
|
agentSessionId: checkpoint.agentSessionId,
|
|
851
795
|
creationId: checkpoint.incarnationId,
|
|
@@ -856,12 +800,12 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
856
800
|
onFailure: "error",
|
|
857
801
|
},
|
|
858
802
|
metering: { ...config.metering, initialState: checkpoint.metering },
|
|
859
|
-
});
|
|
803
|
+
}, null, null, onOpenProgress);
|
|
860
804
|
const primary = new RegistryPersistenceRuntime(checkpoint, history);
|
|
861
805
|
session.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
|
|
862
806
|
session.managedAuditLog = audit?.identity ?? null;
|
|
863
807
|
try {
|
|
864
|
-
const result = await session.controller.start();
|
|
808
|
+
const result = await session.controller.start((event) => session.reportManagedControllerProgress(event));
|
|
865
809
|
if (!result.resumed || !result.sessionId) {
|
|
866
810
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
867
811
|
}
|
|
@@ -871,7 +815,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
871
815
|
strategy: "load_internal_session",
|
|
872
816
|
status: "succeeded",
|
|
873
817
|
});
|
|
874
|
-
const continuation =
|
|
818
|
+
const continuation = createContinuationReport(
|
|
875
819
|
checkpoint, config.adapterId, session.v2Transcript, "available", [attempt],
|
|
876
820
|
{ kind: "loaded", activeInternalSessionId: result.sessionId },
|
|
877
821
|
);
|
|
@@ -897,6 +841,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
897
841
|
transcriptLock?: SessionLogWriterLock,
|
|
898
842
|
audit?: AuditPersistenceRuntime,
|
|
899
843
|
stageContinuation?: (state: StagedContinuationState) => Promise<StagedContinuationState>,
|
|
844
|
+
onOpenProgress?: ManagedOpenProgressReporter,
|
|
900
845
|
): Promise<AgentSessionOpenResult> {
|
|
901
846
|
const strategies = normalizeContinuationStrategies(config.continuation);
|
|
902
847
|
const persistence = resolveDirectPersistence(config.persistence);
|
|
@@ -939,7 +884,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
939
884
|
throw new AdapterMismatchError(checkpoint.adapterId, config.adapterId);
|
|
940
885
|
}
|
|
941
886
|
const { checkpoint: _suppliedCheckpoint, continuation: _continuation, ...runtimeConfig } = config;
|
|
942
|
-
const session = new
|
|
887
|
+
const session = new AgentConversation({
|
|
943
888
|
...runtimeConfig,
|
|
944
889
|
agentSessionId: checkpoint.agentSessionId,
|
|
945
890
|
creationId: checkpoint.incarnationId,
|
|
@@ -955,7 +900,12 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
955
900
|
...config.metering,
|
|
956
901
|
initialState: checkpoint.metering,
|
|
957
902
|
},
|
|
958
|
-
}, {
|
|
903
|
+
}, {
|
|
904
|
+
transcript,
|
|
905
|
+
transcriptPath: paths.transcriptPath,
|
|
906
|
+
stageContinuation,
|
|
907
|
+
onOpenProgress,
|
|
908
|
+
});
|
|
959
909
|
session.managedAuditLog = audit?.identity ?? null;
|
|
960
910
|
|
|
961
911
|
try {
|
|
@@ -1013,7 +963,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1013
963
|
this.v2Transcript = this.openBootstrap.transcript;
|
|
1014
964
|
this.v2TranscriptPath = this.openBootstrap.transcriptPath;
|
|
1015
965
|
this._recovery = this.v2Transcript.recovery;
|
|
1016
|
-
const result = await this.controller.start();
|
|
966
|
+
const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
|
|
1017
967
|
if (!result.resumed || !result.sessionId) {
|
|
1018
968
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
1019
969
|
}
|
|
@@ -1051,7 +1001,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1051
1001
|
}
|
|
1052
1002
|
if (!paths.transcriptPath || persistence.transcript === false) {
|
|
1053
1003
|
try {
|
|
1054
|
-
const result = await this.controller.start();
|
|
1004
|
+
const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
|
|
1055
1005
|
this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
|
|
1056
1006
|
if (this.managedCreation) {
|
|
1057
1007
|
const now = new Date().toISOString();
|
|
@@ -1122,7 +1072,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1122
1072
|
header,
|
|
1123
1073
|
writerLock: this.managedCreation?.transcriptLock,
|
|
1124
1074
|
initializeCheckpoint: async () => {
|
|
1125
|
-
const result = await this.controller.start();
|
|
1075
|
+
const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
|
|
1126
1076
|
this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
|
|
1127
1077
|
const now = new Date().toISOString();
|
|
1128
1078
|
const sessionConfiguration = snapshotSessionConfiguration({
|
|
@@ -1218,7 +1168,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1218
1168
|
continue;
|
|
1219
1169
|
}
|
|
1220
1170
|
try {
|
|
1221
|
-
const loaded = await this.controller.start();
|
|
1171
|
+
const loaded = await this.controller.start((event) => this.reportManagedControllerProgress(event));
|
|
1222
1172
|
if (!loaded.resumed || !loaded.sessionId) {
|
|
1223
1173
|
throw new Error("adapter did not confirm loading the recorded internal session");
|
|
1224
1174
|
}
|
|
@@ -1235,7 +1185,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1235
1185
|
this.continuationAcquired = true;
|
|
1236
1186
|
recordedThreadAvailability = "available";
|
|
1237
1187
|
attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
|
|
1238
|
-
return
|
|
1188
|
+
return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
|
|
1239
1189
|
kind: "loaded",
|
|
1240
1190
|
activeInternalSessionId: loaded.sessionId,
|
|
1241
1191
|
});
|
|
@@ -1297,7 +1247,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1297
1247
|
reasonCode: "continuation_reconstruction",
|
|
1298
1248
|
});
|
|
1299
1249
|
try {
|
|
1300
|
-
const created = await this.controller.startFresh();
|
|
1250
|
+
const created = await this.controller.startFresh((event) => this.reportManagedControllerProgress(event));
|
|
1301
1251
|
if (!created.sessionId) throw new Error("harness returned no session id for reconstructed continuation");
|
|
1302
1252
|
if (created.sessionId === checkpoint.internalSessionId && checkpoint.adapterId === this.adapterId) {
|
|
1303
1253
|
throw new Error("harness did not create a replacement internal session");
|
|
@@ -1374,7 +1324,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1374
1324
|
const seeded = await this.meteredInternalPrompt(
|
|
1375
1325
|
`${transitionId}:seed`,
|
|
1376
1326
|
"switch_seed",
|
|
1377
|
-
|
|
1327
|
+
buildContinuationPrompt(continuation.trim()),
|
|
1378
1328
|
records,
|
|
1379
1329
|
);
|
|
1380
1330
|
if (seeded.status !== "completed") {
|
|
@@ -1392,7 +1342,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1392
1342
|
});
|
|
1393
1343
|
this.continuationAcquired = true;
|
|
1394
1344
|
attempts.push(Object.freeze({ strategy: strategy.kind, status: "succeeded" }));
|
|
1395
|
-
return
|
|
1345
|
+
return createContinuationReport(checkpoint, this.adapterId, this.v2Transcript, recordedThreadAvailability, attempts, {
|
|
1396
1346
|
kind: "reconstructed",
|
|
1397
1347
|
source,
|
|
1398
1348
|
activeInternalSessionId: created.sessionId,
|
|
@@ -1424,7 +1374,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1424
1374
|
}
|
|
1425
1375
|
}
|
|
1426
1376
|
|
|
1427
|
-
return
|
|
1377
|
+
return createContinuationReport(
|
|
1428
1378
|
checkpoint,
|
|
1429
1379
|
this.adapterId,
|
|
1430
1380
|
this.v2Transcript,
|
|
@@ -1495,6 +1445,25 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1495
1445
|
return this._internalSessionId;
|
|
1496
1446
|
}
|
|
1497
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
|
+
|
|
1498
1467
|
/**
|
|
1499
1468
|
* Latest context-window observation for the ACTIVE provider thread, or null.
|
|
1500
1469
|
*
|
|
@@ -1547,6 +1516,37 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1547
1516
|
});
|
|
1548
1517
|
}
|
|
1549
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
|
+
|
|
1550
1550
|
get contextWindow(): ContextWindowStatus | null {
|
|
1551
1551
|
return this._contextWindow;
|
|
1552
1552
|
}
|
|
@@ -1646,7 +1646,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1646
1646
|
return this.phase !== "idle" && this.phase !== "stopped";
|
|
1647
1647
|
}
|
|
1648
1648
|
get queuedOperationCount(): number {
|
|
1649
|
-
return this.
|
|
1649
|
+
return this.operations.queuedCount;
|
|
1650
1650
|
}
|
|
1651
1651
|
/** Subscribe to future lifecycle changes. The current snapshot is available via state. */
|
|
1652
1652
|
subscribe(listener: AgentSessionListener): () => void {
|
|
@@ -1667,11 +1667,23 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1667
1667
|
return this.enqueuePrompt(text, "prompt", handlers, attachments);
|
|
1668
1668
|
}
|
|
1669
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
|
+
|
|
1670
1681
|
private enqueuePrompt(
|
|
1671
1682
|
text: string,
|
|
1672
1683
|
operationKind: MeteredOperationKind,
|
|
1673
1684
|
handlers?: PromptHandlers,
|
|
1674
1685
|
attachments?: Attachment[],
|
|
1686
|
+
participantId?: string,
|
|
1675
1687
|
): Promise<AgentSessionPromptResult> {
|
|
1676
1688
|
return new Promise<AgentSessionPromptResult>((resolve, reject) => {
|
|
1677
1689
|
if (this.phase === "stopped") {
|
|
@@ -1684,11 +1696,12 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1684
1696
|
reject(error);
|
|
1685
1697
|
return;
|
|
1686
1698
|
}
|
|
1687
|
-
this.
|
|
1699
|
+
this.operations.enqueue({
|
|
1688
1700
|
kind: "prompt",
|
|
1689
1701
|
turnId: this.mintTurnId(),
|
|
1690
1702
|
operationKind,
|
|
1691
1703
|
text,
|
|
1704
|
+
...(participantId ? { participantId } : {}),
|
|
1692
1705
|
handlers,
|
|
1693
1706
|
attachments,
|
|
1694
1707
|
resolve,
|
|
@@ -1738,12 +1751,12 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1738
1751
|
reject(error);
|
|
1739
1752
|
return;
|
|
1740
1753
|
}
|
|
1741
|
-
this.
|
|
1754
|
+
this.operations.enqueue({
|
|
1742
1755
|
kind: "handoff",
|
|
1743
1756
|
handoffId: this.mintOperationId(),
|
|
1744
1757
|
// A queued operation owns its arguments. Do not let a caller mutate the object
|
|
1745
1758
|
// while it waits behind an active prompt and silently change the handoff.
|
|
1746
|
-
options:
|
|
1759
|
+
options: ownHandoffOptions(options),
|
|
1747
1760
|
resolve,
|
|
1748
1761
|
reject,
|
|
1749
1762
|
});
|
|
@@ -1752,12 +1765,80 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1752
1765
|
});
|
|
1753
1766
|
}
|
|
1754
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
|
+
|
|
1755
1838
|
private async pump(): Promise<void> {
|
|
1756
|
-
if (this.
|
|
1757
|
-
this.pumping = true;
|
|
1839
|
+
if (this.operations.isDraining) return;
|
|
1758
1840
|
try {
|
|
1759
|
-
|
|
1760
|
-
const item = this.queue.shift()!;
|
|
1841
|
+
await this.operations.drain(async (item) => {
|
|
1761
1842
|
this.phase = item.kind === "prompt"
|
|
1762
1843
|
? "prompting"
|
|
1763
1844
|
: item.kind === "handoff"
|
|
@@ -1791,10 +1872,52 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1791
1872
|
} else if (item.kind === "set_config") {
|
|
1792
1873
|
this.emit({ kind: "configuration_started", operationId: item.operationId, configId: item.configId });
|
|
1793
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
|
+
}
|
|
1794
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
|
+
}
|
|
1795
1902
|
this.emit({ kind: "configuration_completed", operationId: item.operationId, configId: item.configId });
|
|
1796
1903
|
item.resolve();
|
|
1797
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
|
+
}
|
|
1798
1921
|
this.emit({ kind: "configuration_failed", operationId: item.operationId, configId: item.configId, error: String(err) });
|
|
1799
1922
|
item.reject(err);
|
|
1800
1923
|
}
|
|
@@ -1820,28 +1943,60 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1820
1943
|
const from = this._mode;
|
|
1821
1944
|
this.emit({ kind: "mode_change_started", transitionId: item.transitionId, from, to: item.mode });
|
|
1822
1945
|
try {
|
|
1946
|
+
await this.recordNativeAction(item.transitionId, "mode_change", "started", {
|
|
1947
|
+
input: { from, to: item.mode },
|
|
1948
|
+
});
|
|
1823
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
|
+
});
|
|
1824
1953
|
this.emit({ kind: "mode_change_completed", transitionId: item.transitionId, from, to: item.mode });
|
|
1825
1954
|
item.resolve(result);
|
|
1826
1955
|
} catch (err) {
|
|
1956
|
+
await this.recordNativeAction(item.transitionId, "mode_change", "failed", {
|
|
1957
|
+
error: String(err),
|
|
1958
|
+
}).catch(() => undefined);
|
|
1827
1959
|
this.emit({ kind: "mode_change_failed", transitionId: item.transitionId, from, to: item.mode, error: String(err) });
|
|
1828
1960
|
item.reject(err);
|
|
1829
1961
|
}
|
|
1830
1962
|
}
|
|
1831
|
-
|
|
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
|
+
});
|
|
1832
1970
|
} finally {
|
|
1833
|
-
this.pumping = false;
|
|
1834
1971
|
if (this.phase !== "stopped") this.phase = "idle";
|
|
1835
1972
|
this.emitStateIfChanged();
|
|
1836
1973
|
}
|
|
1837
1974
|
}
|
|
1838
1975
|
|
|
1976
|
+
private settleIdleIfDrained(): void {
|
|
1977
|
+
if (this.operations.queuedCount !== 0 || this.phase === "stopped") return;
|
|
1978
|
+
this.phase = "idle";
|
|
1979
|
+
this.emitStateIfChanged();
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1839
1982
|
private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
|
|
1840
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;
|
|
1841
1992
|
const fromDescriptor = this.v2Transcript ? this.v2Descriptor() : null;
|
|
1842
1993
|
let toInternalSessionId: string | undefined;
|
|
1843
1994
|
let toDescriptor: InternalSessionDescriptor | undefined;
|
|
1844
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;
|
|
1845
2000
|
let failedAfter: "start" | "target_created" | "target_activated" = "start";
|
|
1846
2001
|
// Records accumulate as they complete, so a handoff that fails partway still reports
|
|
1847
2002
|
// the operations it already paid for.
|
|
@@ -1851,14 +2006,22 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1851
2006
|
handoffId: item.handoffId,
|
|
1852
2007
|
fromInternalSessionId,
|
|
1853
2008
|
});
|
|
2009
|
+
await this.recordNativeAction(item.handoffId, action, "started", {
|
|
2010
|
+
input: {
|
|
2011
|
+
fromAdapterId,
|
|
2012
|
+
targetAdapterId,
|
|
2013
|
+
targetMode,
|
|
2014
|
+
continuation: continuation.kind,
|
|
2015
|
+
},
|
|
2016
|
+
});
|
|
1854
2017
|
if (this.v2Transcript) {
|
|
1855
2018
|
await this.v2Transcript.appendTransitionEvent({
|
|
1856
2019
|
kind: "transition",
|
|
1857
2020
|
transitionId: item.handoffId,
|
|
1858
|
-
transitionKind
|
|
2021
|
+
transitionKind,
|
|
1859
2022
|
event: "started",
|
|
1860
2023
|
from: fromDescriptor,
|
|
1861
|
-
...(
|
|
2024
|
+
...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
|
|
1862
2025
|
});
|
|
1863
2026
|
} else {
|
|
1864
2027
|
await this.appendTranscript({
|
|
@@ -1868,25 +2031,24 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1868
2031
|
ts: Date.now(),
|
|
1869
2032
|
handoffId: item.handoffId,
|
|
1870
2033
|
fromInternalSessionId,
|
|
1871
|
-
...(
|
|
2034
|
+
...(continuation.kind === "provided" ? { summary: continuation.content } : {}),
|
|
1872
2035
|
});
|
|
1873
2036
|
}
|
|
1874
2037
|
|
|
1875
2038
|
try {
|
|
1876
|
-
if (this.controller.isDegraded) {
|
|
1877
|
-
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");
|
|
1878
2041
|
}
|
|
1879
2042
|
|
|
1880
|
-
if (
|
|
1881
|
-
if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
|
|
2043
|
+
if (continuation.kind === "provided") {
|
|
1882
2044
|
// A supplied summary removes the generation operation entirely, so no
|
|
1883
2045
|
// `:summary` record is ever minted for it.
|
|
1884
|
-
summary =
|
|
1885
|
-
} else {
|
|
2046
|
+
summary = continuation.content;
|
|
2047
|
+
} else if (continuation.kind === "generated") {
|
|
1886
2048
|
const generated = await this.meteredInternalPrompt(
|
|
1887
2049
|
`${item.handoffId}:summary`,
|
|
1888
2050
|
"handoff_summary",
|
|
1889
|
-
|
|
2051
|
+
continuation.summaryPrompt,
|
|
1890
2052
|
records,
|
|
1891
2053
|
);
|
|
1892
2054
|
if (generated.status !== "completed" || !generated.text.trim()) {
|
|
@@ -1895,22 +2057,51 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1895
2057
|
// Handoff requires one seed string, so this internal boundary policy is explicit;
|
|
1896
2058
|
// it is not treated as the canonical shape of the provider response.
|
|
1897
2059
|
summary = formatResponseMessages(generated.messages, "\n\n").trim();
|
|
2060
|
+
} else {
|
|
2061
|
+
summary = "";
|
|
1898
2062
|
}
|
|
1899
2063
|
|
|
1900
|
-
const
|
|
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
|
+
}
|
|
1901
2085
|
if (!created.sessionId) throw new Error("harness returned no session id for handoff");
|
|
1902
2086
|
toInternalSessionId = created.sessionId;
|
|
1903
|
-
if (toInternalSessionId === fromInternalSessionId) {
|
|
2087
|
+
if (!replacingController && toInternalSessionId === fromInternalSessionId) {
|
|
1904
2088
|
throw new Error("harness did not replace the internal session during handoff");
|
|
1905
2089
|
}
|
|
1906
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
|
+
|
|
1907
2098
|
if (this.v2Transcript) {
|
|
1908
2099
|
const transitionAt = new Date().toISOString();
|
|
1909
2100
|
toDescriptor = this.v2Descriptor(toInternalSessionId, transitionAt);
|
|
1910
2101
|
await this.v2Transcript.appendTransitionEvent({
|
|
1911
2102
|
kind: "transition",
|
|
1912
2103
|
transitionId: item.handoffId,
|
|
1913
|
-
transitionKind
|
|
2104
|
+
transitionKind,
|
|
1914
2105
|
event: "target_created",
|
|
1915
2106
|
from: fromDescriptor,
|
|
1916
2107
|
to: toDescriptor,
|
|
@@ -1920,7 +2111,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1920
2111
|
await this.v2Transcript.activateTransition({
|
|
1921
2112
|
kind: "transition",
|
|
1922
2113
|
transitionId: item.handoffId,
|
|
1923
|
-
transitionKind
|
|
2114
|
+
transitionKind,
|
|
1924
2115
|
event: "target_activated",
|
|
1925
2116
|
from: fromDescriptor,
|
|
1926
2117
|
to: toDescriptor,
|
|
@@ -1934,7 +2125,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1934
2125
|
protocol: fromDescriptor.protocol,
|
|
1935
2126
|
activatedAt: fromDescriptor.activatedAt!,
|
|
1936
2127
|
deactivatedAt: transitionAt,
|
|
1937
|
-
transition: { kind:
|
|
2128
|
+
transition: { kind: transitionKind, transitionId: item.handoffId },
|
|
1938
2129
|
},
|
|
1939
2130
|
}
|
|
1940
2131
|
: {}),
|
|
@@ -1947,18 +2138,77 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1947
2138
|
});
|
|
1948
2139
|
failedAfter = "target_activated";
|
|
1949
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;
|
|
1950
2177
|
this.setInternalSessionId(toInternalSessionId);
|
|
2178
|
+
await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
|
|
1951
2179
|
this.emitStateIfChanged();
|
|
1952
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
|
+
}
|
|
1953
2189
|
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
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);
|
|
1962
2212
|
}
|
|
1963
2213
|
|
|
1964
2214
|
const result: HandoffResult = Object.freeze({
|
|
@@ -1966,14 +2216,16 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1966
2216
|
agentSessionId: this.agentSessionId,
|
|
1967
2217
|
fromInternalSessionId,
|
|
1968
2218
|
toInternalSessionId,
|
|
2219
|
+
...(transitionKind === "switch" ? { fromAdapterId, toAdapterId: targetAdapterId } : {}),
|
|
1969
2220
|
summary,
|
|
2221
|
+
...(targetResult ? { targetResult } : {}),
|
|
1970
2222
|
meteringRecords: Object.freeze([...records]),
|
|
1971
2223
|
});
|
|
1972
2224
|
if (this.v2Transcript) {
|
|
1973
2225
|
await this.v2Transcript.appendTransitionEvent({
|
|
1974
2226
|
kind: "transition",
|
|
1975
2227
|
transitionId: item.handoffId,
|
|
1976
|
-
transitionKind
|
|
2228
|
+
transitionKind,
|
|
1977
2229
|
event: "completed",
|
|
1978
2230
|
from: fromDescriptor,
|
|
1979
2231
|
to: toDescriptor,
|
|
@@ -1991,6 +2243,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
1991
2243
|
summary,
|
|
1992
2244
|
});
|
|
1993
2245
|
}
|
|
2246
|
+
await this.recordNativeAction(item.handoffId, action, "completed", {
|
|
2247
|
+
output: { internalSessionId: toInternalSessionId, adapterId: targetAdapterId },
|
|
2248
|
+
});
|
|
1994
2249
|
this.emit({ kind: "handoff_completed", result });
|
|
1995
2250
|
return result;
|
|
1996
2251
|
} catch (err) {
|
|
@@ -2002,6 +2257,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2002
2257
|
toInternalSessionId = actualSessionId;
|
|
2003
2258
|
this.emitStateIfChanged();
|
|
2004
2259
|
try {
|
|
2260
|
+
await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
|
|
2005
2261
|
await this.persist();
|
|
2006
2262
|
} catch (persistError) {
|
|
2007
2263
|
this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
|
|
@@ -2012,7 +2268,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2012
2268
|
await this.v2Transcript.appendTransitionEvent({
|
|
2013
2269
|
kind: "transition",
|
|
2014
2270
|
transitionId: item.handoffId,
|
|
2015
|
-
transitionKind
|
|
2271
|
+
transitionKind,
|
|
2016
2272
|
event: "failed",
|
|
2017
2273
|
from: fromDescriptor,
|
|
2018
2274
|
...(toDescriptor ? { to: toDescriptor } : {}),
|
|
@@ -2035,6 +2291,14 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2035
2291
|
error,
|
|
2036
2292
|
});
|
|
2037
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
|
+
);
|
|
2038
2302
|
this.emit({
|
|
2039
2303
|
kind: "handoff_failed",
|
|
2040
2304
|
handoffId: item.handoffId,
|
|
@@ -2409,6 +2673,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2409
2673
|
const result = await this.controller.setMode(item.mode);
|
|
2410
2674
|
this._mode = this.controller.currentMode;
|
|
2411
2675
|
this.setInternalSessionId(result.sessionId || null);
|
|
2676
|
+
await this.ownerLifecycle?.meteringStateChanged?.(this.metering.currentState);
|
|
2412
2677
|
await this.persist();
|
|
2413
2678
|
return result;
|
|
2414
2679
|
}
|
|
@@ -2508,6 +2773,19 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2508
2773
|
}
|
|
2509
2774
|
|
|
2510
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;
|
|
2511
2789
|
this.beginTurn(item.turnId);
|
|
2512
2790
|
let operation: OpenOperation;
|
|
2513
2791
|
if (this.v2Transcript) {
|
|
@@ -2527,9 +2805,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2527
2805
|
presentation: { id: `message:${item.turnId}:user`, revision: 1 },
|
|
2528
2806
|
});
|
|
2529
2807
|
await this.v2Transcript.syncBeforeDispatch();
|
|
2530
|
-
this.
|
|
2808
|
+
this.presentation.emitPersistedRecord(userRecord);
|
|
2531
2809
|
} catch (error) {
|
|
2532
|
-
this.endTurn(item.handlers);
|
|
2810
|
+
this.endTurn(item.turnId, item.handlers);
|
|
2533
2811
|
if (transcriptStarted) {
|
|
2534
2812
|
await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
|
|
2535
2813
|
(abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
|
|
@@ -2578,7 +2856,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2578
2856
|
assistantMessage.revision++;
|
|
2579
2857
|
assistantMessage.dirty = false;
|
|
2580
2858
|
const message = assistantMessage;
|
|
2581
|
-
this.
|
|
2859
|
+
this.presentation.queuePresentation({
|
|
2582
2860
|
kind: "message",
|
|
2583
2861
|
operationId: item.turnId,
|
|
2584
2862
|
role: "assistant",
|
|
@@ -2605,9 +2883,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2605
2883
|
item.handlers?.onChunk?.(chunk);
|
|
2606
2884
|
},
|
|
2607
2885
|
onResponseChunk: (chunk) => {
|
|
2608
|
-
const settledReasoning = this.
|
|
2886
|
+
const settledReasoning = this.presentation.closeReasoningBoundary();
|
|
2609
2887
|
if (settledReasoning) {
|
|
2610
|
-
|
|
2888
|
+
this.queueActivityRecords(item.turnId, [settledReasoning]);
|
|
2611
2889
|
item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
|
|
2612
2890
|
}
|
|
2613
2891
|
response.append(chunk);
|
|
@@ -2632,19 +2910,55 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2632
2910
|
// The message snapshot must enter the shared queue before an activity first seen
|
|
2633
2911
|
// after it. Later activity revisions keep their original presentation position.
|
|
2634
2912
|
flushAssistantMessage("in_progress");
|
|
2635
|
-
const result = this.
|
|
2636
|
-
|
|
2637
|
-
for (const record of result.emitted) this.writeActivity(record);
|
|
2638
|
-
}
|
|
2913
|
+
const result = this.presentation.applyActivity(event);
|
|
2914
|
+
this.queueActivityRecords(item.turnId, result.emitted);
|
|
2639
2915
|
item.handlers?.onRecord?.(result);
|
|
2640
2916
|
item.handlers?.onActivity?.(event);
|
|
2641
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
|
+
},
|
|
2642
2954
|
};
|
|
2643
2955
|
|
|
2644
2956
|
let closed: OperationMeteringRecord | null = null;
|
|
2645
2957
|
let transcriptClosed = false;
|
|
2958
|
+
let providerSettled = false;
|
|
2646
2959
|
try {
|
|
2647
|
-
const res = await this.controller.prompt(
|
|
2960
|
+
const res = await this.controller.prompt(providerText, wrappedHandlers, item.attachments);
|
|
2961
|
+
providerSettled = true;
|
|
2648
2962
|
if (this.v2Transcript) {
|
|
2649
2963
|
if (assistantOrdinal === 0) {
|
|
2650
2964
|
for (const message of res.messages) {
|
|
@@ -2659,7 +2973,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2659
2973
|
}
|
|
2660
2974
|
// Before the assistant msg: `msg` delimits a turn, so anything still open has to
|
|
2661
2975
|
// land inside those fences.
|
|
2662
|
-
this.endTurn(item.handlers);
|
|
2976
|
+
this.endTurn(item.turnId, item.handlers);
|
|
2663
2977
|
if (!this._title && item.text.trim()) {
|
|
2664
2978
|
this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
|
2665
2979
|
}
|
|
@@ -2675,9 +2989,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2675
2989
|
// a worse failure than the one closing early prevents.
|
|
2676
2990
|
const record = await this.closeOperation(operation, res.status, res.usage);
|
|
2677
2991
|
closed = record;
|
|
2992
|
+
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
2678
2993
|
await this.persist();
|
|
2679
2994
|
if (this.v2Transcript) {
|
|
2680
|
-
await this.
|
|
2995
|
+
await this.presentation.drain();
|
|
2681
2996
|
await this.finishV2Prompt(res.status, record);
|
|
2682
2997
|
transcriptClosed = true;
|
|
2683
2998
|
} else {
|
|
@@ -2693,11 +3008,21 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2693
3008
|
status: res.status,
|
|
2694
3009
|
});
|
|
2695
3010
|
}
|
|
2696
|
-
|
|
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;
|
|
2697
3022
|
} catch (err) {
|
|
2698
3023
|
// Easy to miss, and the whole point of R4: a turn that died mid-tool still records
|
|
2699
3024
|
// what it was doing, at its real status.
|
|
2700
|
-
this.endTurn(item.handlers);
|
|
3025
|
+
this.endTurn(item.turnId, item.handlers);
|
|
2701
3026
|
const structured = response.snapshot();
|
|
2702
3027
|
const text = structured.length > 0 ? response.text : chunks.join("");
|
|
2703
3028
|
const messages: readonly ResponseMessage[] = structured.length > 0
|
|
@@ -2705,6 +3030,22 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2705
3030
|
: text
|
|
2706
3031
|
? Object.freeze([{ text }])
|
|
2707
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
|
+
});
|
|
2708
3049
|
if (this.v2Transcript) {
|
|
2709
3050
|
if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
|
|
2710
3051
|
for (const message of messages) {
|
|
@@ -2716,7 +3057,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2716
3057
|
} else if (!transcriptClosed) {
|
|
2717
3058
|
flushAssistantMessage("error", "error", true);
|
|
2718
3059
|
}
|
|
2719
|
-
await this.
|
|
3060
|
+
await this.presentation.drain().catch(() => undefined);
|
|
2720
3061
|
} else {
|
|
2721
3062
|
await this.appendTranscript({
|
|
2722
3063
|
v: 1,
|
|
@@ -2734,6 +3075,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2734
3075
|
// Already metered: the failure happened after the operation closed (a transcript or
|
|
2735
3076
|
// catalog write), so the record stands and must not be minted a second time.
|
|
2736
3077
|
const record = closed ?? (await this.closeOperation(operation, "error", null, String(err)));
|
|
3078
|
+
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
2737
3079
|
if (this.v2Transcript && !transcriptClosed) {
|
|
2738
3080
|
await this.finishV2Prompt("error", record, "unknown").catch(
|
|
2739
3081
|
(persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
|
|
@@ -2796,7 +3138,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2796
3138
|
before: AgentSessionMeteringState;
|
|
2797
3139
|
after: AgentSessionMeteringState;
|
|
2798
3140
|
}> {
|
|
2799
|
-
if (this.isBusy || this.
|
|
3141
|
+
if (this.isBusy || this.operations.queuedCount > 0) {
|
|
2800
3142
|
throw new Error("reconcileMetering requires an idle session with no queued operations");
|
|
2801
3143
|
}
|
|
2802
3144
|
if (!reconciliation.reason?.trim()) {
|
|
@@ -2819,6 +3161,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2819
3161
|
// Validated first: state is replaced atomically or not at all.
|
|
2820
3162
|
const { before } = this.metering.reconcile(restoration.state);
|
|
2821
3163
|
const after = this.metering.currentState;
|
|
3164
|
+
await this.ownerLifecycle?.meteringStateChanged?.(after);
|
|
2822
3165
|
this.emit({
|
|
2823
3166
|
kind: "metering_reconciled",
|
|
2824
3167
|
before,
|
|
@@ -2883,6 +3226,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2883
3226
|
const record = await this.closeOperation(operation, result.status, result.usage);
|
|
2884
3227
|
records.push(record);
|
|
2885
3228
|
closed = true;
|
|
3229
|
+
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
2886
3230
|
if (this.v2Transcript) {
|
|
2887
3231
|
await this.v2Transcript.appendEvent({
|
|
2888
3232
|
kind: "message",
|
|
@@ -2902,6 +3246,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2902
3246
|
const record = await this.closeOperation(operation, "error", null, String(err));
|
|
2903
3247
|
records.push(record);
|
|
2904
3248
|
closed = true;
|
|
3249
|
+
await this.ownerLifecycle?.meteringRecorded?.(record);
|
|
2905
3250
|
}
|
|
2906
3251
|
if (this.v2Transcript && !transcriptClosed) {
|
|
2907
3252
|
const record = records[records.length - 1]!;
|
|
@@ -2993,26 +3338,15 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2993
3338
|
* activity in its log before the messages around it had loaded.
|
|
2994
3339
|
*/
|
|
2995
3340
|
activitySnapshot(): ActivitySnapshot {
|
|
2996
|
-
return this.
|
|
3341
|
+
return this.presentation.snapshot();
|
|
2997
3342
|
}
|
|
2998
3343
|
|
|
2999
3344
|
private beginTurn(turnId: string): void {
|
|
3000
|
-
|
|
3001
|
-
// ever doesn't, keeping the records (loudly) beats dropping them.
|
|
3002
|
-
const leftover = this.aggregator.startTurn(turnId);
|
|
3003
|
-
if (leftover.length > 0) {
|
|
3004
|
-
this.log.warn("activity_turn_not_flushed", { records: leftover.length });
|
|
3005
|
-
if (this.transcriptActivity || this.v2Transcript) for (const record of leftover) this.writeActivity(record);
|
|
3006
|
-
}
|
|
3345
|
+
this.presentation.beginTurn(turnId);
|
|
3007
3346
|
}
|
|
3008
3347
|
|
|
3009
|
-
private endTurn(handlers?: PromptHandlers): void {
|
|
3010
|
-
|
|
3011
|
-
if (emitted.length === 0) return;
|
|
3012
|
-
if (this.transcriptActivity || this.v2Transcript) for (const record of emitted) this.writeActivity(record);
|
|
3013
|
-
// Live subscribers need these too: without them, a tool call on a turn that was
|
|
3014
|
-
// cancelled or crashed spins forever in the UI. `wireFrames()` handles this shape.
|
|
3015
|
-
handlers?.onRecord?.({ current: null, delta: null, emitted });
|
|
3348
|
+
private endTurn(turnId: string, handlers?: PromptHandlers): void {
|
|
3349
|
+
this.queueActivityRecords(turnId, this.presentation.endTurn(handlers));
|
|
3016
3350
|
}
|
|
3017
3351
|
|
|
3018
3352
|
/**
|
|
@@ -3032,80 +3366,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3032
3366
|
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
3033
3367
|
}
|
|
3034
3368
|
|
|
3035
|
-
/**
|
|
3036
|
-
* Persist one settled record. Filtering lives here, not in the aggregator: the
|
|
3037
|
-
* aggregator owns semantics, the writer owns policy.
|
|
3038
|
-
*
|
|
3039
|
-
* Fire and forget — `appendTranscript` serializes writes in call order, so ordering
|
|
3040
|
-
* holds without blocking the agent's update stream on disk.
|
|
3041
|
-
*/
|
|
3042
|
-
private writeActivity(record: AggregatedRecord): void {
|
|
3043
|
-
if (this.v2Transcript) {
|
|
3044
|
-
const operationId = this.v2Transcript.checkpoint.boundary.status === "in_flight"
|
|
3045
|
-
? this.v2Transcript.checkpoint.boundary.interruptedOperationId
|
|
3046
|
-
: record.recordId.split(":", 1)[0] ?? record.recordId;
|
|
3047
|
-
const projected = persistenceEventFromActivity(record, operationId);
|
|
3048
|
-
this.queueV2Presentation({
|
|
3049
|
-
...projected,
|
|
3050
|
-
presentation: {
|
|
3051
|
-
id: `${projected.kind}:${operationId}:${record.recordId}`,
|
|
3052
|
-
revision: record.seq,
|
|
3053
|
-
},
|
|
3054
|
-
});
|
|
3055
|
-
return;
|
|
3056
|
-
}
|
|
3057
|
-
if (!this._transcriptPath) return;
|
|
3058
|
-
if (!this.activityKinds.has(record.event.kind)) return;
|
|
3059
|
-
void this.appendTranscript(this.toActivityLine(record));
|
|
3060
|
-
}
|
|
3061
|
-
|
|
3062
|
-
private queueV2Presentation(event: PresentationPersistenceEvent): void {
|
|
3063
|
-
this.v2PresentationWrite = this.v2PresentationWrite.then(async () => {
|
|
3064
|
-
if (!this.v2Transcript) return;
|
|
3065
|
-
const record = await this.v2Transcript.appendPresentationEvent(event);
|
|
3066
|
-
this.emitPresentationRecord(record);
|
|
3067
|
-
});
|
|
3068
|
-
}
|
|
3069
|
-
|
|
3070
|
-
private emitPresentationRecord(
|
|
3071
|
-
record: Awaited<ReturnType<PersistenceStateRuntime["appendPresentationEvent"]>>,
|
|
3072
|
-
): void {
|
|
3073
|
-
if (!record) return;
|
|
3074
|
-
const item = presentationItemFromRecord(record);
|
|
3075
|
-
if (item) this.emit({ kind: "presentation_recorded", item });
|
|
3076
|
-
}
|
|
3077
|
-
|
|
3078
|
-
private async drainV2Presentation(): Promise<void> {
|
|
3079
|
-
await this.v2PresentationWrite;
|
|
3080
|
-
}
|
|
3081
|
-
|
|
3082
|
-
private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
|
|
3083
|
-
let fields: Record<string, unknown> = { ...record.event };
|
|
3084
|
-
if (!this.activityRawOutput) delete fields.rawOutput;
|
|
3085
|
-
|
|
3086
|
-
let truncated = false;
|
|
3087
|
-
if (this.activityMaxBytes != null) {
|
|
3088
|
-
const capped = capActivityStrings(fields, this.activityMaxBytes);
|
|
3089
|
-
fields = capped.fields;
|
|
3090
|
-
truncated = capped.truncated;
|
|
3091
|
-
}
|
|
3092
|
-
|
|
3093
|
-
const line: TranscriptActivityLine = {
|
|
3094
|
-
...fields,
|
|
3095
|
-
v: 1,
|
|
3096
|
-
t: "activity",
|
|
3097
|
-
ts: Date.now(),
|
|
3098
|
-
recordId: record.recordId,
|
|
3099
|
-
reason: record.reason,
|
|
3100
|
-
kind: record.event.kind,
|
|
3101
|
-
};
|
|
3102
|
-
if (truncated) line.truncated = true;
|
|
3103
|
-
return line;
|
|
3104
|
-
}
|
|
3105
|
-
|
|
3106
3369
|
interrupt(options?: InterruptOptions): void {
|
|
3107
3370
|
if (options?.clearQueue) {
|
|
3108
|
-
const dropped = this.
|
|
3371
|
+
const dropped = this.operations.clear();
|
|
3109
3372
|
for (const item of dropped) {
|
|
3110
3373
|
if (item.kind === "prompt") {
|
|
3111
3374
|
// Cancelled before dispatch: nothing was sent, so nothing was consumed and no
|
|
@@ -3144,7 +3407,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3144
3407
|
this.phase = "stopped";
|
|
3145
3408
|
this.emitStateIfChanged();
|
|
3146
3409
|
await this.controller.stop();
|
|
3147
|
-
await this.
|
|
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);
|
|
3148
3414
|
await this.v2Transcript?.close();
|
|
3149
3415
|
}
|
|
3150
3416
|
|
|
@@ -3153,7 +3419,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3153
3419
|
if (this.phase === "stopped") throw new Error("AgentSession is stopped");
|
|
3154
3420
|
this.assertPromptable();
|
|
3155
3421
|
return await new Promise<ConnectResult>((resolve, reject) => {
|
|
3156
|
-
this.
|
|
3422
|
+
this.operations.enqueue({
|
|
3157
3423
|
kind: "set_mode",
|
|
3158
3424
|
transitionId: this.mintOperationId(),
|
|
3159
3425
|
mode,
|
|
@@ -3192,7 +3458,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3192
3458
|
return Promise.reject(new Error(`configuration value cannot be cloned: ${String(error)}`));
|
|
3193
3459
|
}
|
|
3194
3460
|
return new Promise<void>((resolve, reject) => {
|
|
3195
|
-
this.
|
|
3461
|
+
this.operations.enqueue({
|
|
3196
3462
|
kind: "set_config",
|
|
3197
3463
|
operationId: this.mintOperationId(),
|
|
3198
3464
|
configId,
|
|
@@ -3223,7 +3489,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3223
3489
|
return Promise.reject(new Error(`configuration resolution cannot be cloned: ${String(error)}`));
|
|
3224
3490
|
}
|
|
3225
3491
|
return new Promise((resolve, reject) => {
|
|
3226
|
-
this.
|
|
3492
|
+
this.operations.enqueue({ kind: "resolve_config", resolution: owned, resolve, reject });
|
|
3227
3493
|
this.emitStateIfChanged();
|
|
3228
3494
|
void this.pump();
|
|
3229
3495
|
});
|
|
@@ -3247,7 +3513,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3247
3513
|
...(resolution.continuation === undefined ? {} : { continuation: resolution.continuation }),
|
|
3248
3514
|
});
|
|
3249
3515
|
return new Promise((resolve, reject) => {
|
|
3250
|
-
this.
|
|
3516
|
+
this.operations.enqueue({ kind: "resolve_recovery", resolution: owned, resolve, reject });
|
|
3251
3517
|
this.emitStateIfChanged();
|
|
3252
3518
|
void this.pump();
|
|
3253
3519
|
});
|
|
@@ -3439,96 +3705,101 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3439
3705
|
}
|
|
3440
3706
|
}
|
|
3441
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
|
+
|
|
3442
3720
|
function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
|
|
3443
|
-
|
|
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;
|
|
3444
3728
|
}
|
|
3445
3729
|
|
|
3446
|
-
function
|
|
3447
|
-
checkpoint: AgentSessionCheckpoint,
|
|
3448
|
-
requestedAdapterId: string,
|
|
3449
|
-
transcript: PersistenceStateRuntime,
|
|
3450
|
-
recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"],
|
|
3451
|
-
attempts: readonly ContinuationAttempt[],
|
|
3452
|
-
outcome: ContinuationReport["outcome"],
|
|
3453
|
-
): ContinuationReport {
|
|
3730
|
+
function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
|
|
3454
3731
|
return Object.freeze({
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
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 }),
|
|
3462
3763
|
});
|
|
3463
3764
|
}
|
|
3464
3765
|
|
|
3465
|
-
function
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
}
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
options:
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
return Object.freeze(strategies.map((strategy): ContinuationStrategy => {
|
|
3487
|
-
if (strategy.kind === "load_internal_session") {
|
|
3488
|
-
return Object.freeze({ kind: strategy.kind });
|
|
3489
|
-
}
|
|
3490
|
-
if (strategy.kind === "new_from_transcript") {
|
|
3491
|
-
if (!strategy.strategyId.trim()) throw new Error("transcript continuation strategyId cannot be blank");
|
|
3492
|
-
if (typeof strategy.buildContinuation !== "function") {
|
|
3493
|
-
throw new Error("transcript continuation strategy requires buildContinuation");
|
|
3494
|
-
}
|
|
3495
|
-
return Object.freeze({
|
|
3496
|
-
kind: strategy.kind,
|
|
3497
|
-
strategyId: strategy.strategyId,
|
|
3498
|
-
buildContinuation: strategy.buildContinuation,
|
|
3499
|
-
});
|
|
3500
|
-
}
|
|
3501
|
-
if (!strategy.continuationId.trim()) throw new Error("consumer continuationId cannot be blank");
|
|
3502
|
-
if (!strategy.continuation.trim()) throw new Error("consumer continuation cannot be blank");
|
|
3503
|
-
return Object.freeze({
|
|
3504
|
-
kind: strategy.kind,
|
|
3505
|
-
continuationId: strategy.continuationId,
|
|
3506
|
-
continuation: strategy.continuation,
|
|
3507
|
-
});
|
|
3508
|
-
}));
|
|
3509
|
-
}
|
|
3510
|
-
|
|
3511
|
-
async function stageOpeningContinuation(
|
|
3512
|
-
stage: ((state: StagedContinuationState) => Promise<StagedContinuationState>) | undefined,
|
|
3513
|
-
checkpoint: AgentSessionCheckpoint,
|
|
3514
|
-
internalSessionId: string,
|
|
3515
|
-
): Promise<void> {
|
|
3516
|
-
if (!stage) return;
|
|
3517
|
-
const observed: StagedContinuationState = {
|
|
3518
|
-
adapterId: checkpoint.adapterId,
|
|
3519
|
-
mode: checkpoint.mode,
|
|
3520
|
-
internalSessionId,
|
|
3521
|
-
internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
|
|
3522
|
-
model: checkpoint.model,
|
|
3523
|
-
sessionConfiguration: checkpoint.sessionConfiguration,
|
|
3524
|
-
protocol: checkpoint.protocol,
|
|
3525
|
-
};
|
|
3526
|
-
const persisted = await stage(observed);
|
|
3527
|
-
if (persisted.adapterId !== observed.adapterId
|
|
3528
|
-
|| persisted.mode !== observed.mode
|
|
3529
|
-
|| persisted.internalSessionId !== observed.internalSessionId) {
|
|
3530
|
-
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 });
|
|
3531
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");
|
|
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 });
|
|
3532
3803
|
}
|
|
3533
3804
|
|
|
3534
3805
|
function configurationTargetIssue(
|
|
@@ -3579,6 +3850,130 @@ function sameJsonValue(left: unknown, right: JsonValue): boolean {
|
|
|
3579
3850
|
}
|
|
3580
3851
|
}
|
|
3581
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
|
+
|
|
3582
3977
|
/** Do not let one notification observer mutate the PromptResult another observer sees. */
|
|
3583
3978
|
function copyPromptResult(result: PromptResult): PromptResult {
|
|
3584
3979
|
const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
|
|
@@ -3590,58 +3985,3 @@ function copyPromptResult(result: PromptResult): PromptResult {
|
|
|
3590
3985
|
usage: result.usage ? Object.freeze({ ...result.usage }) : null,
|
|
3591
3986
|
});
|
|
3592
3987
|
}
|
|
3593
|
-
|
|
3594
|
-
const encoder = new TextEncoder();
|
|
3595
|
-
const decoder = new TextDecoder();
|
|
3596
|
-
|
|
3597
|
-
/**
|
|
3598
|
-
* Cap the fields that can realistically reach megabytes — terminal output, text content,
|
|
3599
|
-
* diffs, and a stringified `rawInput` — one field at a time so the JSON structure survives.
|
|
3600
|
-
* An oversized `rawInput` object becomes its truncated serialization, which is lossy by
|
|
3601
|
-
* design; `truncated: true` on the line says so.
|
|
3602
|
-
*/
|
|
3603
|
-
function capActivityStrings(
|
|
3604
|
-
fields: Record<string, unknown>,
|
|
3605
|
-
maxBytes: number,
|
|
3606
|
-
): { fields: Record<string, unknown>; truncated: boolean } {
|
|
3607
|
-
let truncated = false;
|
|
3608
|
-
const cap = (text: string): string => {
|
|
3609
|
-
const bytes = encoder.encode(text);
|
|
3610
|
-
if (bytes.length <= maxBytes) return text;
|
|
3611
|
-
// Back up off a continuation byte (0b10xxxxxx) so a multi-byte character is never
|
|
3612
|
-
// split — decoding a partial sequence would yield U+FFFD.
|
|
3613
|
-
let end = maxBytes;
|
|
3614
|
-
while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
|
|
3615
|
-
truncated = true;
|
|
3616
|
-
return `${decoder.decode(bytes.subarray(0, end))}… [truncated ${bytes.length - end} bytes]`;
|
|
3617
|
-
};
|
|
3618
|
-
const capUnknown = (value: unknown): unknown => {
|
|
3619
|
-
if (typeof value === "string") return cap(value);
|
|
3620
|
-
const text = JSON.stringify(value) ?? "";
|
|
3621
|
-
const capped = cap(text);
|
|
3622
|
-
return capped === text ? value : capped;
|
|
3623
|
-
};
|
|
3624
|
-
|
|
3625
|
-
const out = { ...fields };
|
|
3626
|
-
if (out.rawInput !== undefined) out.rawInput = capUnknown(out.rawInput);
|
|
3627
|
-
if (out.rawOutput !== undefined) out.rawOutput = capUnknown(out.rawOutput);
|
|
3628
|
-
if (typeof out.text === "string") out.text = cap(out.text);
|
|
3629
|
-
if (Array.isArray(out.content)) {
|
|
3630
|
-
out.content = (out.content as unknown[]).map((entry) => {
|
|
3631
|
-
if (entry === null || typeof entry !== "object") return entry;
|
|
3632
|
-
const item = { ...(entry as Record<string, unknown>) };
|
|
3633
|
-
if (typeof item.text === "string") item.text = cap(item.text);
|
|
3634
|
-
if (typeof item.output === "string") item.output = cap(item.output);
|
|
3635
|
-
if (typeof item.oldText === "string") item.oldText = cap(item.oldText);
|
|
3636
|
-
if (typeof item.newText === "string") item.newText = cap(item.newText);
|
|
3637
|
-
// `text` on a content entry is our convenience copy; the block itself still holds it.
|
|
3638
|
-
if (item.content !== null && typeof item.content === "object") {
|
|
3639
|
-
const block = { ...(item.content as Record<string, unknown>) };
|
|
3640
|
-
if (typeof block.text === "string") block.text = cap(block.text);
|
|
3641
|
-
item.content = block;
|
|
3642
|
-
}
|
|
3643
|
-
return item;
|
|
3644
|
-
});
|
|
3645
|
-
}
|
|
3646
|
-
return { fields: out, truncated };
|
|
3647
|
-
}
|