@qlairoslabs/acp-client 0.7.1 → 0.7.3
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/CONSUMER_GUIDE.md +44 -1
- package/README.md +11 -2
- package/package.json +2 -2
- package/src/activity.ts +8 -0
- package/src/agent-session.ts +142 -34
- package/src/index.ts +13 -0
- package/src/persistence/activity-projection.ts +6 -1
- package/src/persistence/audit-runtime.ts +9 -1
- package/src/persistence/presentation.ts +99 -0
- package/src/persistence/projection.ts +40 -5
- package/src/persistence/records.ts +39 -0
- package/src/persistence/state-runtime.ts +11 -0
- package/src/persistence/transcript-reader.ts +232 -0
- package/src/persistence/transcript-runtime.ts +71 -1
- package/src/response.ts +27 -1
- package/src/types.ts +7 -3
- package/LICENSE +0 -21
|
@@ -21,6 +21,7 @@ import type {
|
|
|
21
21
|
TranscriptEnvelope,
|
|
22
22
|
TranscriptLifecycleRecord,
|
|
23
23
|
TranscriptTransitionRecord,
|
|
24
|
+
TranscriptPresentationMetadata,
|
|
24
25
|
InternalSessionDescriptor,
|
|
25
26
|
InternalSessionHistoryEntry,
|
|
26
27
|
} from "./records.ts";
|
|
@@ -64,6 +65,13 @@ export interface NormalizedActivityProjection {
|
|
|
64
65
|
readonly content?: JsonObject;
|
|
65
66
|
}
|
|
66
67
|
|
|
68
|
+
export interface NormalizedPresentationMetadata {
|
|
69
|
+
readonly id: string;
|
|
70
|
+
readonly revision: number;
|
|
71
|
+
/** Assigned by the transcript runtime on the first appended revision. */
|
|
72
|
+
readonly position?: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
67
75
|
export type NormalizedPersistenceEvent =
|
|
68
76
|
| {
|
|
69
77
|
readonly kind: "operation";
|
|
@@ -80,6 +88,8 @@ export type NormalizedPersistenceEvent =
|
|
|
80
88
|
readonly operationId: string;
|
|
81
89
|
readonly role: "user" | "assistant";
|
|
82
90
|
readonly text: string;
|
|
91
|
+
readonly providerMessageId?: string;
|
|
92
|
+
readonly presentation?: NormalizedPresentationMetadata;
|
|
83
93
|
readonly structured?: { readonly version: 1; readonly messages: readonly { readonly messageId?: string; readonly text: string }[] };
|
|
84
94
|
readonly status?: string;
|
|
85
95
|
readonly stopReason?: string;
|
|
@@ -91,8 +101,13 @@ export type NormalizedPersistenceEvent =
|
|
|
91
101
|
readonly operationId: string;
|
|
92
102
|
readonly text: string;
|
|
93
103
|
readonly status: "in_progress" | "completed";
|
|
104
|
+
readonly presentation?: NormalizedPresentationMetadata;
|
|
105
|
+
}
|
|
106
|
+
| {
|
|
107
|
+
readonly kind: "activity";
|
|
108
|
+
readonly activity: NormalizedActivityProjection;
|
|
109
|
+
readonly presentation?: NormalizedPresentationMetadata;
|
|
94
110
|
}
|
|
95
|
-
| { readonly kind: "activity"; readonly activity: NormalizedActivityProjection }
|
|
96
111
|
| {
|
|
97
112
|
readonly kind: "configuration";
|
|
98
113
|
readonly event: "announced" | "selected" | "restored" | "restore_failed" | "resolved";
|
|
@@ -167,17 +182,24 @@ export function projectTranscriptEvent(
|
|
|
167
182
|
if (context.policy.messages === "none") return null;
|
|
168
183
|
return {
|
|
169
184
|
...base, t: "message", operationId: event.operationId, role: event.role, text: event.text,
|
|
185
|
+
...(event.presentation === undefined ? {} : { presentation: persistedPresentation(event.presentation) }),
|
|
186
|
+
...(event.providerMessageId === undefined ? {} : { providerMessageId: event.providerMessageId }),
|
|
170
187
|
...(event.structured === undefined ? {} : { structured: structuredClone(event.structured) }),
|
|
171
188
|
...(event.status === undefined ? {} : { status: event.status }),
|
|
172
189
|
...(event.stopReason === undefined ? {} : { stopReason: event.stopReason }),
|
|
173
190
|
};
|
|
174
191
|
case "reasoning":
|
|
175
192
|
if (context.policy.reasoning === "none") return null;
|
|
176
|
-
return {
|
|
193
|
+
return {
|
|
194
|
+
...base, t: "reasoning", reasoningId: event.reasoningId,
|
|
195
|
+
reasoningRevision: event.reasoningRevision, operationId: event.operationId,
|
|
196
|
+
text: event.text, status: event.status,
|
|
197
|
+
...(event.presentation === undefined ? {} : { presentation: persistedPresentation(event.presentation) }),
|
|
198
|
+
};
|
|
177
199
|
case "activity": {
|
|
178
200
|
const data = activityData(event.activity, context.policy.tools);
|
|
179
201
|
if (!data) return null;
|
|
180
|
-
return activityRecord(base, event.activity, data);
|
|
202
|
+
return activityRecord(base, event.activity, data, event.presentation);
|
|
181
203
|
}
|
|
182
204
|
case "configuration": {
|
|
183
205
|
const projected = configurationData(event, context.policy.configuration);
|
|
@@ -307,21 +329,34 @@ function activityData(
|
|
|
307
329
|
return data;
|
|
308
330
|
}
|
|
309
331
|
|
|
310
|
-
function activityRecord(base: TranscriptEnvelope, activity: NormalizedActivityProjection, data: JsonObject): TranscriptActivityRecord;
|
|
311
|
-
function activityRecord(base: AuditLogEnvelope, activity: NormalizedActivityProjection, data: JsonObject): AuditLogActivityRecord;
|
|
332
|
+
function activityRecord(base: TranscriptEnvelope, activity: NormalizedActivityProjection, data: JsonObject, presentation?: NormalizedPresentationMetadata): TranscriptActivityRecord;
|
|
333
|
+
function activityRecord(base: AuditLogEnvelope, activity: NormalizedActivityProjection, data: JsonObject, presentation?: NormalizedPresentationMetadata): AuditLogActivityRecord;
|
|
312
334
|
function activityRecord(
|
|
313
335
|
base: TranscriptEnvelope | AuditLogEnvelope,
|
|
314
336
|
activity: NormalizedActivityProjection,
|
|
315
337
|
data: JsonObject,
|
|
338
|
+
presentation?: NormalizedPresentationMetadata,
|
|
316
339
|
): TranscriptActivityRecord | AuditLogActivityRecord {
|
|
317
340
|
return {
|
|
318
341
|
...base, t: "activity", activityId: activity.activityId,
|
|
319
342
|
activityRevision: activity.activityRevision, operationId: activity.operationId,
|
|
320
343
|
reason: activity.reason, kind: activity.kind,
|
|
321
344
|
...(activity.status === undefined ? {} : { status: activity.status }), data,
|
|
345
|
+
...("transcriptId" in base && presentation !== undefined
|
|
346
|
+
? { presentation: persistedPresentation(presentation) }
|
|
347
|
+
: {}),
|
|
322
348
|
} as TranscriptActivityRecord | AuditLogActivityRecord;
|
|
323
349
|
}
|
|
324
350
|
|
|
351
|
+
function persistedPresentation(
|
|
352
|
+
value: NormalizedPresentationMetadata,
|
|
353
|
+
): TranscriptPresentationMetadata {
|
|
354
|
+
if (value.position === undefined) {
|
|
355
|
+
throw new Error("transcript presentation position was not assigned");
|
|
356
|
+
}
|
|
357
|
+
return { id: value.id, position: value.position, revision: value.revision };
|
|
358
|
+
}
|
|
359
|
+
|
|
325
360
|
function configurationData(
|
|
326
361
|
event: Extract<NormalizedPersistenceEvent, { kind: "configuration" }>,
|
|
327
362
|
level: TranscriptCapturePolicy["configuration"],
|
|
@@ -159,11 +159,22 @@ export interface TranscriptStructuredMessagesV1 {
|
|
|
159
159
|
readonly messages: readonly TranscriptResponseMessageV1[];
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
/** Non-authoritative ordering metadata for one logical display item. */
|
|
163
|
+
export interface TranscriptPresentationMetadata {
|
|
164
|
+
readonly id: string;
|
|
165
|
+
/** Sequence of this item's first appended transcript revision. */
|
|
166
|
+
readonly position: number;
|
|
167
|
+
readonly revision: number;
|
|
168
|
+
}
|
|
169
|
+
|
|
162
170
|
export interface TranscriptMessageRecord extends TranscriptEnvelope {
|
|
163
171
|
readonly t: "message";
|
|
164
172
|
readonly operationId: string;
|
|
165
173
|
readonly role: "user" | "assistant";
|
|
166
174
|
readonly text: string;
|
|
175
|
+
readonly presentation?: TranscriptPresentationMetadata;
|
|
176
|
+
/** Provider-supplied ACP message identity, when one was announced. */
|
|
177
|
+
readonly providerMessageId?: string;
|
|
167
178
|
readonly structured?: TranscriptStructuredMessagesV1;
|
|
168
179
|
readonly status?: string;
|
|
169
180
|
readonly stopReason?: string;
|
|
@@ -176,6 +187,7 @@ export interface TranscriptReasoningRecord extends TranscriptEnvelope {
|
|
|
176
187
|
readonly operationId: string;
|
|
177
188
|
readonly text: string;
|
|
178
189
|
readonly status: "in_progress" | "completed";
|
|
190
|
+
readonly presentation?: TranscriptPresentationMetadata;
|
|
179
191
|
}
|
|
180
192
|
|
|
181
193
|
export interface TranscriptActivityRecord extends TranscriptEnvelope {
|
|
@@ -187,6 +199,7 @@ export interface TranscriptActivityRecord extends TranscriptEnvelope {
|
|
|
187
199
|
readonly kind: string;
|
|
188
200
|
readonly status?: string;
|
|
189
201
|
readonly data: Readonly<Record<string, JsonValue>>;
|
|
202
|
+
readonly presentation?: TranscriptPresentationMetadata;
|
|
190
203
|
}
|
|
191
204
|
|
|
192
205
|
export interface TranscriptConfigurationRecord extends TranscriptEnvelope {
|
|
@@ -516,6 +529,8 @@ function validateRecognizedRecord(
|
|
|
516
529
|
if (record.role !== "user" && record.role !== "assistant") fail("message.role is invalid");
|
|
517
530
|
if (typeof record.text !== "string") fail("message.text must be a string");
|
|
518
531
|
if (record.structured !== undefined) validateStructuredMessages(record.structured);
|
|
532
|
+
optionalNonblank(record.providerMessageId, "message.providerMessageId");
|
|
533
|
+
if (record.presentation !== undefined) validatePresentation(record.presentation, record.seq as number);
|
|
519
534
|
optionalString(record.status, "message.status");
|
|
520
535
|
optionalString(record.stopReason, "message.stopReason");
|
|
521
536
|
return;
|
|
@@ -525,6 +540,13 @@ function validateRecognizedRecord(
|
|
|
525
540
|
positiveInteger(record.reasoningRevision, "reasoningRevision");
|
|
526
541
|
if (typeof record.text !== "string") fail("reasoning.text must be a string");
|
|
527
542
|
oneOf(record.status, ["in_progress", "completed"], "reasoning.status");
|
|
543
|
+
if (sink === "audit" && record.presentation !== undefined) fail("presentation is invalid audit reasoning content");
|
|
544
|
+
if (record.presentation !== undefined) {
|
|
545
|
+
validatePresentation(record.presentation, record.seq as number);
|
|
546
|
+
if ((record.presentation as Record<string, unknown>).revision !== record.reasoningRevision) {
|
|
547
|
+
fail("reasoning presentation revision must equal reasoningRevision");
|
|
548
|
+
}
|
|
549
|
+
}
|
|
528
550
|
return;
|
|
529
551
|
case "activity":
|
|
530
552
|
requiredOperationId(record);
|
|
@@ -533,6 +555,13 @@ function validateRecognizedRecord(
|
|
|
533
555
|
oneOf(record.reason, ["announced", "input", "settled", "flushed", "snapshot"], "activity.reason");
|
|
534
556
|
nonblank(record.kind, "activity.kind");
|
|
535
557
|
if (!isRecord(record.data)) fail("activity.data must be an object");
|
|
558
|
+
if (sink === "audit" && record.presentation !== undefined) fail("presentation is invalid audit activity content");
|
|
559
|
+
if (record.presentation !== undefined) {
|
|
560
|
+
validatePresentation(record.presentation, record.seq as number);
|
|
561
|
+
if ((record.presentation as Record<string, unknown>).revision !== record.activityRevision) {
|
|
562
|
+
fail("activity presentation revision must equal activityRevision");
|
|
563
|
+
}
|
|
564
|
+
}
|
|
536
565
|
return;
|
|
537
566
|
case "configuration":
|
|
538
567
|
oneOf(record.event, ["announced", "selected", "restored", "restore_failed", "resolved"], "configuration.event");
|
|
@@ -579,6 +608,16 @@ function validateRecognizedRecord(
|
|
|
579
608
|
fail("unreachable record type");
|
|
580
609
|
}
|
|
581
610
|
|
|
611
|
+
function validatePresentation(value: unknown, recordSequence: number): void {
|
|
612
|
+
if (!isRecord(value)) fail("presentation must be an object");
|
|
613
|
+
nonblank(value.id, "presentation.id");
|
|
614
|
+
positiveInteger(value.position, "presentation.position");
|
|
615
|
+
positiveInteger(value.revision, "presentation.revision");
|
|
616
|
+
if ((value.position as number) > recordSequence) {
|
|
617
|
+
fail("presentation.position cannot follow its record sequence");
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
582
621
|
function validateHeader(record: Record<string, unknown>, sink: "transcript" | "audit"): void {
|
|
583
622
|
oneOf(record.event, sink === "transcript" ? ["created", "upgraded", "replaced"] : ["created", "replaced"], "header.event");
|
|
584
623
|
iso(record.createdAt, "header.createdAt");
|
|
@@ -6,8 +6,14 @@ import { sha256CanonicalJson } from "./integrity.ts";
|
|
|
6
6
|
import type { PersistenceRepair, SessionRecoveryStatus } from "./reducer.ts";
|
|
7
7
|
import type { TranscriptTerminalCheckpointChanges } from "./transcript-runtime.ts";
|
|
8
8
|
import type { PersistedMachineCode } from "./integrity.ts";
|
|
9
|
+
import type { TranscriptPresentationRecord } from "./presentation.ts";
|
|
9
10
|
|
|
10
11
|
type TransitionEvent = Extract<NormalizedPersistenceEvent, { kind: "transition" }>;
|
|
12
|
+
export type PresentationPersistenceEvent = Extract<
|
|
13
|
+
NormalizedPersistenceEvent,
|
|
14
|
+
{ kind: "message" | "reasoning" | "activity" }
|
|
15
|
+
>;
|
|
16
|
+
export type { TranscriptPresentationRecord } from "./presentation.ts";
|
|
11
17
|
|
|
12
18
|
export interface PersistenceStateRuntime {
|
|
13
19
|
readonly checkpoint: AgentSessionCheckpoint;
|
|
@@ -19,6 +25,10 @@ export interface PersistenceStateRuntime {
|
|
|
19
25
|
setCheckpointPublisher(publisher: (checkpoint: AgentSessionCheckpoint, history: readonly InternalSessionHistoryEntry[]) => Promise<void>): void;
|
|
20
26
|
beginOperation(operationId: string, kind: OperationKind, ts?: number): Promise<void>;
|
|
21
27
|
appendEvent(event: NormalizedPersistenceEvent, ts?: number): Promise<boolean>;
|
|
28
|
+
appendPresentationEvent(
|
|
29
|
+
event: PresentationPersistenceEvent,
|
|
30
|
+
ts?: number,
|
|
31
|
+
): Promise<TranscriptPresentationRecord | null>;
|
|
22
32
|
appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options?: { readonly durable?: boolean; readonly ts?: number }): Promise<void>;
|
|
23
33
|
publishCheckpoint(changes: TranscriptTerminalCheckpointChanges, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
24
34
|
activateTransition(event: Omit<TransitionEvent, "event"> & { readonly event: "target_activated" }, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
@@ -78,6 +88,7 @@ export class RegistryPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
78
88
|
}
|
|
79
89
|
|
|
80
90
|
async appendEvent(): Promise<boolean> { return false; }
|
|
91
|
+
async appendPresentationEvent(): Promise<null> { return null; }
|
|
81
92
|
async appendTransitionEvent(): Promise<void> {}
|
|
82
93
|
async syncBeforeDispatch(): Promise<void> {}
|
|
83
94
|
|
|
@@ -24,11 +24,17 @@ import {
|
|
|
24
24
|
type TranscriptTransitionRecord,
|
|
25
25
|
type UnknownTranscriptRecord,
|
|
26
26
|
} from "./records.ts";
|
|
27
|
+
import {
|
|
28
|
+
presentationItemFromRecord,
|
|
29
|
+
type TranscriptPresentationItem,
|
|
30
|
+
type TranscriptPresentationRecord,
|
|
31
|
+
} from "./presentation.ts";
|
|
27
32
|
|
|
28
33
|
const DEFAULT_LIMIT = 50;
|
|
29
34
|
const MAX_LIMIT = 500;
|
|
30
35
|
const READ_CHUNK_BYTES = 64 * 1024;
|
|
31
36
|
const HARD_MAX_RECORD_BYTES = 16_777_216;
|
|
37
|
+
const HARD_MAX_CURSOR_BYTES = 16_384;
|
|
32
38
|
const CURSOR_VERSION = 1;
|
|
33
39
|
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
34
40
|
|
|
@@ -46,6 +52,7 @@ const TIMELINE_TYPES = new Set<TranscriptRecordType>([
|
|
|
46
52
|
export type TranscriptView = "conversation" | "timeline" | "records";
|
|
47
53
|
export type TranscriptCursor = string & { readonly __transcriptCursor: unique symbol };
|
|
48
54
|
export type TranscriptSnapshotCursor = string & { readonly __transcriptSnapshotCursor: unique symbol };
|
|
55
|
+
export type TranscriptPresentationCursor = string & { readonly __transcriptPresentationCursor: unique symbol };
|
|
49
56
|
|
|
50
57
|
export interface ReadTranscriptPageOptions {
|
|
51
58
|
readonly cursor?: TranscriptCursor;
|
|
@@ -67,6 +74,17 @@ export interface TranscriptPage<
|
|
|
67
74
|
readonly snapshot: S;
|
|
68
75
|
}
|
|
69
76
|
|
|
77
|
+
export interface ReadTranscriptPresentationPageOptions {
|
|
78
|
+
readonly cursor?: TranscriptPresentationCursor;
|
|
79
|
+
readonly limit?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type TranscriptPresentationPage = TranscriptPage<
|
|
83
|
+
TranscriptPresentationItem,
|
|
84
|
+
TranscriptPresentationCursor,
|
|
85
|
+
TranscriptSnapshotCursor
|
|
86
|
+
>;
|
|
87
|
+
|
|
70
88
|
export type TranscriptConversationItem = TranscriptMessageRecord | LegacyTranscriptMessageLine;
|
|
71
89
|
export type TranscriptTimelineItem =
|
|
72
90
|
| TranscriptMessageRecord
|
|
@@ -149,6 +167,13 @@ interface NavigationPayload extends SnapshotBoundary {
|
|
|
149
167
|
readonly filterProvided: boolean;
|
|
150
168
|
}
|
|
151
169
|
|
|
170
|
+
interface PresentationNavigationPayload extends SnapshotBoundary {
|
|
171
|
+
readonly k: "transcript_presentation";
|
|
172
|
+
readonly direction: "older" | "newer";
|
|
173
|
+
readonly boundaryPosition: number;
|
|
174
|
+
readonly boundaryId: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
152
177
|
interface PhysicalRecord<T = TranscriptReadableRecord> {
|
|
153
178
|
readonly item: T;
|
|
154
179
|
readonly sequence: number;
|
|
@@ -249,6 +274,127 @@ export class TranscriptReader {
|
|
|
249
274
|
}
|
|
250
275
|
}
|
|
251
276
|
|
|
277
|
+
/**
|
|
278
|
+
* Read logical display items in their first-observed order. Revisions are folded by
|
|
279
|
+
* stable item id; a later activity/message revision never moves the original item.
|
|
280
|
+
* Legacy records and v2 records without presentation metadata are intentionally absent.
|
|
281
|
+
*/
|
|
282
|
+
async readPresentationPage(
|
|
283
|
+
options: ReadTranscriptPresentationPageOptions = {},
|
|
284
|
+
): Promise<TranscriptPresentationPage> {
|
|
285
|
+
const limit = validatedLimit(options.limit);
|
|
286
|
+
const navigation = options.cursor === undefined
|
|
287
|
+
? null
|
|
288
|
+
: decodePresentationCursor(options.cursor, HARD_MAX_CURSOR_BYTES);
|
|
289
|
+
const snapshot = navigation
|
|
290
|
+
? await this.openSnapshot(
|
|
291
|
+
encodeCursor(snapshotPayloadFrom(navigation)) as TranscriptSnapshotCursor,
|
|
292
|
+
"snapshot",
|
|
293
|
+
)
|
|
294
|
+
: await this.openSnapshot(undefined, "navigation");
|
|
295
|
+
try {
|
|
296
|
+
if (options.cursor !== undefined
|
|
297
|
+
&& Buffer.byteLength(options.cursor, "utf8") > snapshot.header.effectiveLimits.maxCursorBytes) {
|
|
298
|
+
throw new TranscriptCursorInvalidError("presentation cursor exceeds the transcript's engraved limit");
|
|
299
|
+
}
|
|
300
|
+
if (navigation && (navigation.id !== snapshot.payload.id
|
|
301
|
+
|| navigation.generation !== snapshot.payload.generation
|
|
302
|
+
|| navigation.highSequence !== snapshot.payload.highSequence
|
|
303
|
+
|| navigation.highOffset !== snapshot.payload.highOffset
|
|
304
|
+
|| navigation.prefixDigest !== snapshot.payload.prefixDigest)) {
|
|
305
|
+
throw new TranscriptCursorInvalidError("presentation cursor snapshot changed");
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Keep only this page plus one look-ahead item. Every first revision has
|
|
309
|
+
// position === physical seq, so candidates can be selected while scanning and
|
|
310
|
+
// later revisions can update only the bounded candidate set.
|
|
311
|
+
const latest = new Map<string, TranscriptPresentationRecord>();
|
|
312
|
+
const candidateIds: string[] = [];
|
|
313
|
+
let boundaryFound = navigation === null;
|
|
314
|
+
let expectedSequence = 1;
|
|
315
|
+
for await (const physical of forwardLines(
|
|
316
|
+
snapshot.handle,
|
|
317
|
+
legacyBoundary(snapshot.header),
|
|
318
|
+
snapshot.payload.highOffset,
|
|
319
|
+
snapshot.header.effectiveLimits.maxRecordBytes,
|
|
320
|
+
)) {
|
|
321
|
+
const parsed = parsePhysical(physical, snapshot.header);
|
|
322
|
+
if (!parsed) continue;
|
|
323
|
+
if (parsed.sequence !== expectedSequence) {
|
|
324
|
+
throw new TranscriptReaderError("transcript sequence is not physically contiguous");
|
|
325
|
+
}
|
|
326
|
+
expectedSequence++;
|
|
327
|
+
if (!isPresentationRecord(parsed.item) || !parsed.item.presentation) continue;
|
|
328
|
+
|
|
329
|
+
const record = parsed.item;
|
|
330
|
+
const metadata = record.presentation!;
|
|
331
|
+
const previous = latest.get(metadata.id);
|
|
332
|
+
if (previous) {
|
|
333
|
+
validatePresentationRevision(previous, record);
|
|
334
|
+
latest.set(metadata.id, record);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (metadata.position !== record.seq) {
|
|
338
|
+
// A revision for an item outside this bounded page needs no retained state.
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (navigation && metadata.position === navigation.boundaryPosition) {
|
|
342
|
+
if (identityTag(metadata.id) !== navigation.boundaryId) {
|
|
343
|
+
throw new TranscriptCursorInvalidError("presentation cursor boundary changed");
|
|
344
|
+
}
|
|
345
|
+
boundaryFound = true;
|
|
346
|
+
}
|
|
347
|
+
const eligible = !navigation
|
|
348
|
+
|| (navigation.direction === "older"
|
|
349
|
+
? metadata.position < navigation.boundaryPosition
|
|
350
|
+
: metadata.position > navigation.boundaryPosition);
|
|
351
|
+
if (!eligible) continue;
|
|
352
|
+
latest.set(metadata.id, record);
|
|
353
|
+
candidateIds.push(metadata.id);
|
|
354
|
+
if (candidateIds.length > limit + 1) {
|
|
355
|
+
const removeIndex = navigation?.direction === "newer"
|
|
356
|
+
? candidateIds.length - 1
|
|
357
|
+
: 0;
|
|
358
|
+
const [removed] = candidateIds.splice(removeIndex, 1);
|
|
359
|
+
if (removed) latest.delete(removed);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (!boundaryFound) {
|
|
363
|
+
throw new TranscriptCursorInvalidError("presentation cursor boundary is absent from its snapshot");
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const hasExtra = candidateIds.length > limit;
|
|
367
|
+
const pageIds = navigation?.direction === "newer"
|
|
368
|
+
? candidateIds.slice(0, limit)
|
|
369
|
+
: candidateIds.slice(Math.max(0, candidateIds.length - limit));
|
|
370
|
+
const selected = pageIds.map((id) => presentationItemFromRecord(latest.get(id)!)!);
|
|
371
|
+
const hasOlder = navigation?.direction === "newer" ? true : hasExtra;
|
|
372
|
+
const hasNewer = navigation?.direction === "older" ? true : navigation?.direction === "newer" ? hasExtra : false;
|
|
373
|
+
const first = selected[0];
|
|
374
|
+
const last = selected.at(-1);
|
|
375
|
+
return Object.freeze({
|
|
376
|
+
items: Object.freeze(selected.map((item) => structuredClone(item))),
|
|
377
|
+
olderCursor: hasOlder && first
|
|
378
|
+
? boundedPresentationCursor(
|
|
379
|
+
encodePresentationCursor(snapshot.payload, "older", first),
|
|
380
|
+
snapshot.header.effectiveLimits.maxCursorBytes,
|
|
381
|
+
)
|
|
382
|
+
: null,
|
|
383
|
+
newerCursor: hasNewer && last
|
|
384
|
+
? boundedPresentationCursor(
|
|
385
|
+
encodePresentationCursor(snapshot.payload, "newer", last),
|
|
386
|
+
snapshot.header.effectiveLimits.maxCursorBytes,
|
|
387
|
+
)
|
|
388
|
+
: null,
|
|
389
|
+
hasOlder,
|
|
390
|
+
hasNewer,
|
|
391
|
+
snapshot: snapshot.snapshotCursor,
|
|
392
|
+
});
|
|
393
|
+
} finally {
|
|
394
|
+
await snapshot.handle.close().catch(() => undefined);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
252
398
|
async listActivityStates(
|
|
253
399
|
options: ListTranscriptActivitiesOptions = {},
|
|
254
400
|
): Promise<PersistedActivityStatePage> {
|
|
@@ -760,6 +906,59 @@ function encodeNavigation(
|
|
|
760
906
|
}) as TranscriptCursor;
|
|
761
907
|
}
|
|
762
908
|
|
|
909
|
+
function encodePresentationCursor(
|
|
910
|
+
snapshot: SnapshotPayload,
|
|
911
|
+
direction: "older" | "newer",
|
|
912
|
+
boundary: TranscriptPresentationItem,
|
|
913
|
+
): TranscriptPresentationCursor {
|
|
914
|
+
const wire = [
|
|
915
|
+
1, "p", snapshot.id, snapshot.generation, snapshot.highSequence,
|
|
916
|
+
snapshot.highOffset, snapshot.prefixDigest,
|
|
917
|
+
direction === "older" ? "o" : "n", boundary.position, identityTag(boundary.id),
|
|
918
|
+
];
|
|
919
|
+
return Buffer.from(JSON.stringify(wire), "utf8").toString("base64url") as TranscriptPresentationCursor;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function decodePresentationCursor(
|
|
923
|
+
cursor: string,
|
|
924
|
+
maxBytes: number,
|
|
925
|
+
): PresentationNavigationPayload {
|
|
926
|
+
if (typeof cursor !== "string" || cursor.length === 0 || Buffer.byteLength(cursor, "utf8") > maxBytes) {
|
|
927
|
+
throw new TranscriptCursorInvalidError("presentation cursor is blank or exceeds its limit");
|
|
928
|
+
}
|
|
929
|
+
if (!/^[A-Za-z0-9_-]+$/.test(cursor)) {
|
|
930
|
+
throw new TranscriptCursorInvalidError("presentation cursor is not canonical base64url");
|
|
931
|
+
}
|
|
932
|
+
let value: unknown;
|
|
933
|
+
try {
|
|
934
|
+
const decoded = Buffer.from(cursor, "base64url");
|
|
935
|
+
if (decoded.toString("base64url") !== cursor) throw new Error("non-canonical base64url");
|
|
936
|
+
value = JSON.parse(decoded.toString("utf8"));
|
|
937
|
+
} catch (error) {
|
|
938
|
+
throw new TranscriptCursorInvalidError("presentation cursor is malformed", { cause: error });
|
|
939
|
+
}
|
|
940
|
+
if (!Array.isArray(value) || value.length !== 10
|
|
941
|
+
|| value[0] !== CURSOR_VERSION || value[1] !== "p"
|
|
942
|
+
|| !integrityTag(value[2]) || !positiveInteger(value[3])
|
|
943
|
+
|| !positiveInteger(value[4]) || !positiveInteger(value[5])
|
|
944
|
+
|| !integrityTag(value[6]) || (value[7] !== "o" && value[7] !== "n")
|
|
945
|
+
|| !positiveInteger(value[8]) || !integrityTag(value[9])) {
|
|
946
|
+
throw new TranscriptCursorInvalidError("presentation cursor payload is invalid");
|
|
947
|
+
}
|
|
948
|
+
return {
|
|
949
|
+
v: 1,
|
|
950
|
+
k: "transcript_presentation",
|
|
951
|
+
id: value[2],
|
|
952
|
+
generation: value[3] as number,
|
|
953
|
+
highSequence: value[4] as number,
|
|
954
|
+
highOffset: value[5] as number,
|
|
955
|
+
prefixDigest: value[6],
|
|
956
|
+
direction: value[7] === "o" ? "older" : "newer",
|
|
957
|
+
boundaryPosition: value[8] as number,
|
|
958
|
+
boundaryId: value[9] as string,
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
|
|
763
962
|
function snapshotPayloadFrom(payload: SnapshotBoundary): SnapshotPayload {
|
|
764
963
|
return {
|
|
765
964
|
v: CURSOR_VERSION,
|
|
@@ -930,6 +1129,16 @@ function boundedCursor(cursor: TranscriptCursor, maxBytes: number): TranscriptCu
|
|
|
930
1129
|
return cursor;
|
|
931
1130
|
}
|
|
932
1131
|
|
|
1132
|
+
function boundedPresentationCursor(
|
|
1133
|
+
cursor: TranscriptPresentationCursor,
|
|
1134
|
+
maxBytes: number,
|
|
1135
|
+
): TranscriptPresentationCursor {
|
|
1136
|
+
if (Buffer.byteLength(cursor, "utf8") > maxBytes) {
|
|
1137
|
+
throw new TranscriptReaderError("generated transcript presentation cursor exceeds the engraved limit");
|
|
1138
|
+
}
|
|
1139
|
+
return cursor;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
933
1142
|
function boundedSnapshotCursor(cursor: string, maxBytes: number): TranscriptSnapshotCursor {
|
|
934
1143
|
if (Buffer.byteLength(cursor, "utf8") > maxBytes) {
|
|
935
1144
|
throw new TranscriptReaderError("generated transcript snapshot cursor exceeds the engraved limit");
|
|
@@ -948,6 +1157,29 @@ function isActivityRecord(
|
|
|
948
1157
|
&& value.t === "activity" && "activityId" in value;
|
|
949
1158
|
}
|
|
950
1159
|
|
|
1160
|
+
function isPresentationRecord(
|
|
1161
|
+
value: TranscriptReadableRecord,
|
|
1162
|
+
): value is TranscriptPresentationRecord {
|
|
1163
|
+
return "transcriptId" in value && value.v === 2
|
|
1164
|
+
&& (value.t === "message" || value.t === "reasoning" || value.t === "activity");
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function validatePresentationRevision(
|
|
1168
|
+
previous: TranscriptPresentationRecord,
|
|
1169
|
+
record: TranscriptPresentationRecord,
|
|
1170
|
+
): void {
|
|
1171
|
+
const metadata = record.presentation!;
|
|
1172
|
+
if (previous.t !== record.t
|
|
1173
|
+
|| previous.operationId !== record.operationId
|
|
1174
|
+
|| previous.presentation!.position !== metadata.position
|
|
1175
|
+
|| previous.presentation!.revision >= metadata.revision) {
|
|
1176
|
+
throw new TranscriptReaderError(`invalid presentation revision for ${metadata.id}`);
|
|
1177
|
+
}
|
|
1178
|
+
if (previous.t === "message" && record.t === "message" && previous.role !== record.role) {
|
|
1179
|
+
throw new TranscriptReaderError(`presentation message role changed for ${metadata.id}`);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
951
1183
|
function legacyBoundary(header: TranscriptHeaderRecord): number {
|
|
952
1184
|
return header.event === "upgraded" ? header.upgradedFrom!.boundaryOffset : 0;
|
|
953
1185
|
}
|
|
@@ -20,6 +20,9 @@ import type {
|
|
|
20
20
|
OperationKind,
|
|
21
21
|
TranscriptCheckpointRecord,
|
|
22
22
|
TranscriptOperationRecord,
|
|
23
|
+
TranscriptActivityRecord,
|
|
24
|
+
TranscriptMessageRecord,
|
|
25
|
+
TranscriptReasoningRecord,
|
|
23
26
|
} from "./records.ts";
|
|
24
27
|
import type { PersistedMachineCode } from "./integrity.ts";
|
|
25
28
|
import {
|
|
@@ -29,7 +32,11 @@ import {
|
|
|
29
32
|
type SessionLogWriterLock,
|
|
30
33
|
} from "./session-log-writer.ts";
|
|
31
34
|
import type { TranscriptHeaderRecord } from "./records.ts";
|
|
32
|
-
import type {
|
|
35
|
+
import type {
|
|
36
|
+
PersistenceStateRuntime,
|
|
37
|
+
PresentationPersistenceEvent,
|
|
38
|
+
TranscriptPresentationRecord,
|
|
39
|
+
} from "./state-runtime.ts";
|
|
33
40
|
|
|
34
41
|
export interface TranscriptTerminalCheckpointChanges {
|
|
35
42
|
readonly model?: string | null;
|
|
@@ -90,6 +97,12 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
90
97
|
checkpoint: AgentSessionCheckpoint,
|
|
91
98
|
history: readonly InternalSessionHistoryEntry[],
|
|
92
99
|
) => Promise<void>) | null = null;
|
|
100
|
+
private readonly presentationStates = new Map<string, {
|
|
101
|
+
readonly position: number;
|
|
102
|
+
readonly revision: number;
|
|
103
|
+
readonly kind: PresentationPersistenceEvent["kind"];
|
|
104
|
+
readonly operationId: string;
|
|
105
|
+
}>();
|
|
93
106
|
|
|
94
107
|
private constructor(
|
|
95
108
|
private readonly writer: FileSessionLogWriter<"transcript">,
|
|
@@ -281,6 +294,52 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
281
294
|
}
|
|
282
295
|
}
|
|
283
296
|
|
|
297
|
+
async appendPresentationEvent(
|
|
298
|
+
event: PresentationPersistenceEvent,
|
|
299
|
+
ts = Date.now(),
|
|
300
|
+
): Promise<TranscriptPresentationRecord | null> {
|
|
301
|
+
this.assertUsable();
|
|
302
|
+
if (!event.presentation) {
|
|
303
|
+
throw new TranscriptRuntimeStateError("presentation event requires identity and revision");
|
|
304
|
+
}
|
|
305
|
+
const existing = this.presentationStates.get(event.presentation.id);
|
|
306
|
+
if (existing && (existing.kind !== event.kind
|
|
307
|
+
|| existing.operationId !== presentationOperationId(event)
|
|
308
|
+
|| existing.revision >= event.presentation.revision)) {
|
|
309
|
+
throw new TranscriptRuntimeStateError(`invalid presentation revision for ${event.presentation.id}`);
|
|
310
|
+
}
|
|
311
|
+
const position = existing?.position ?? this.writer.nextSequence;
|
|
312
|
+
const positioned = {
|
|
313
|
+
...event,
|
|
314
|
+
presentation: { ...event.presentation, position },
|
|
315
|
+
} as PresentationPersistenceEvent;
|
|
316
|
+
const record = projectTranscriptEvent(positioned, {
|
|
317
|
+
transcriptId: this.header.transcriptId,
|
|
318
|
+
generation: this.header.generation,
|
|
319
|
+
agentSessionId: this.header.agentSessionId,
|
|
320
|
+
seq: this.writer.nextSequence,
|
|
321
|
+
ts,
|
|
322
|
+
policy: this.header.effectivePolicy,
|
|
323
|
+
});
|
|
324
|
+
if (!record) return null;
|
|
325
|
+
if (!isTranscriptPresentationRecord(record)) {
|
|
326
|
+
throw new TranscriptRuntimeStateError("presentation event projected to a non-presentation record");
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
await this.writer.append(record);
|
|
330
|
+
this.presentationStates.set(event.presentation.id, {
|
|
331
|
+
position,
|
|
332
|
+
revision: event.presentation.revision,
|
|
333
|
+
kind: event.kind,
|
|
334
|
+
operationId: presentationOperationId(event),
|
|
335
|
+
});
|
|
336
|
+
return structuredClone(record);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
this.failure = error instanceof Error ? error : new Error(String(error));
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
284
343
|
async appendTransitionEvent(
|
|
285
344
|
event: NonActivationTransitionEvent,
|
|
286
345
|
options: { readonly durable?: boolean; readonly ts?: number } = {},
|
|
@@ -587,6 +646,17 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
587
646
|
}
|
|
588
647
|
}
|
|
589
648
|
|
|
649
|
+
function isTranscriptPresentationRecord(
|
|
650
|
+
record: ReturnType<typeof projectTranscriptEvent>,
|
|
651
|
+
): record is TranscriptMessageRecord | TranscriptReasoningRecord | TranscriptActivityRecord {
|
|
652
|
+
return record !== null
|
|
653
|
+
&& (record.t === "message" || record.t === "reasoning" || record.t === "activity");
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function presentationOperationId(event: PresentationPersistenceEvent): string {
|
|
657
|
+
return event.kind === "activity" ? event.activity.operationId : event.operationId;
|
|
658
|
+
}
|
|
659
|
+
|
|
590
660
|
function checkpointRecord(
|
|
591
661
|
seq: number,
|
|
592
662
|
checkpoint: AgentSessionCheckpoint,
|
package/src/response.ts
CHANGED
|
@@ -7,6 +7,31 @@ export interface IncomingResponseChunk {
|
|
|
7
7
|
startsMessage?: boolean;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Explicitly flatten structured response messages using a separator chosen by the
|
|
12
|
+
* consumer. This is a display conversion; it does not alter the messages themselves.
|
|
13
|
+
*/
|
|
14
|
+
export function formatResponseMessages(
|
|
15
|
+
messages: readonly ResponseMessage[],
|
|
16
|
+
separator: string,
|
|
17
|
+
): string {
|
|
18
|
+
if (typeof separator !== "string") throw new TypeError("response message separator must be a string");
|
|
19
|
+
return messages.map((message) => message.text).join(separator);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Produce the legacy combined-text view without erasing protocol message boundaries.
|
|
24
|
+
* Message text is preserved verbatim; the only inserted content is the boundary between
|
|
25
|
+
* entries. Empty entries therefore participate in the literal join rather than being
|
|
26
|
+
* silently removed.
|
|
27
|
+
*
|
|
28
|
+
* @deprecated Use the canonical message array, or call `formatResponseMessages` with an
|
|
29
|
+
* explicit consumer-selected separator.
|
|
30
|
+
*/
|
|
31
|
+
export function joinResponseMessages(messages: readonly ResponseMessage[]): string {
|
|
32
|
+
return formatResponseMessages(messages, "\n\n");
|
|
33
|
+
}
|
|
34
|
+
|
|
10
35
|
/**
|
|
11
36
|
* Fold response deltas without inventing separators. Only a change between two explicit
|
|
12
37
|
* ACP message ids proves that a new assistant message started; missing ids remain part of
|
|
@@ -44,8 +69,9 @@ export class ResponseAccumulator {
|
|
|
44
69
|
: { text: chunk.text, messageId: chunk.messageId, startsMessage };
|
|
45
70
|
}
|
|
46
71
|
|
|
72
|
+
/** @deprecated Prefer `snapshot()` and preserve the distinct response messages. */
|
|
47
73
|
get text(): string {
|
|
48
|
-
return this.entries
|
|
74
|
+
return joinResponseMessages(this.entries);
|
|
49
75
|
}
|
|
50
76
|
|
|
51
77
|
snapshot(): readonly ResponseMessage[] {
|