@qlairoslabs/acp-client 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONSUMER_GUIDE.md +72 -0
- package/package.json +2 -2
- package/src/activity.ts +8 -0
- package/src/agent-session.ts +137 -31
- package/src/command-descriptors.ts +22 -0
- package/src/controller.ts +74 -37
- 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/repl/agent-session-commands.ts +74 -1
- package/src/repl/commands.ts +1 -1
- package/src/repl/index.ts +7 -1
- package/src/response.ts +11 -1
- package/src/types.ts +2 -2
- package/LICENSE +0 -21
|
@@ -3,7 +3,7 @@ import { projectAuditEvent, type NormalizedPersistenceEvent } from "./projection
|
|
|
3
3
|
import type { InternalSessionHistoryEntry, OperationAbortReason, OperationKind, AuditLogHeaderRecord } from "./records.ts";
|
|
4
4
|
import type { PersistedMachineCode } from "./integrity.ts";
|
|
5
5
|
import type { PersistenceRepair } from "./reducer.ts";
|
|
6
|
-
import type { PersistenceStateRuntime } from "./state-runtime.ts";
|
|
6
|
+
import type { PersistenceStateRuntime, PresentationPersistenceEvent } from "./state-runtime.ts";
|
|
7
7
|
import type { TranscriptTerminalCheckpointChanges } from "./transcript-runtime.ts";
|
|
8
8
|
import { FileSessionLogWriter, type SessionLogWriterLock } from "./session-log-writer.ts";
|
|
9
9
|
|
|
@@ -126,6 +126,14 @@ export class AuditedPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
126
126
|
return primary || audit;
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
+
async appendPresentationEvent(event: PresentationPersistenceEvent, ts = Date.now()) {
|
|
130
|
+
const [primary] = await Promise.all([
|
|
131
|
+
this.primary.appendPresentationEvent(event, ts),
|
|
132
|
+
this.audit.append(event, false, ts),
|
|
133
|
+
]);
|
|
134
|
+
return primary;
|
|
135
|
+
}
|
|
136
|
+
|
|
129
137
|
async appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options: { readonly durable?: boolean; readonly ts?: number } = {}): Promise<void> {
|
|
130
138
|
const ts = options.ts ?? Date.now();
|
|
131
139
|
await this.primary.appendTransitionEvent(event, options);
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { JsonObject } from "./checkpoint.ts";
|
|
2
|
+
import type {
|
|
3
|
+
TranscriptActivityRecord,
|
|
4
|
+
TranscriptMessageRecord,
|
|
5
|
+
TranscriptReasoningRecord,
|
|
6
|
+
} from "./records.ts";
|
|
7
|
+
|
|
8
|
+
export type TranscriptPresentationRecord =
|
|
9
|
+
| TranscriptMessageRecord
|
|
10
|
+
| TranscriptReasoningRecord
|
|
11
|
+
| TranscriptActivityRecord;
|
|
12
|
+
|
|
13
|
+
interface TranscriptPresentationItemBase {
|
|
14
|
+
/** Stable identity of the logical display item across persisted revisions. */
|
|
15
|
+
readonly id: string;
|
|
16
|
+
/** Sequence allocated to the item's first appended revision. */
|
|
17
|
+
readonly position: number;
|
|
18
|
+
/** Logical revision of this item. */
|
|
19
|
+
readonly revision: number;
|
|
20
|
+
/** Physical transcript sequence containing this revision. */
|
|
21
|
+
readonly recordSequence: number;
|
|
22
|
+
readonly operationId: string;
|
|
23
|
+
readonly transcriptId: string;
|
|
24
|
+
readonly generation: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface TranscriptPresentationMessage extends TranscriptPresentationItemBase {
|
|
28
|
+
readonly kind: "message";
|
|
29
|
+
readonly role: "user" | "assistant";
|
|
30
|
+
readonly text: string;
|
|
31
|
+
readonly providerMessageId?: string;
|
|
32
|
+
readonly status?: string;
|
|
33
|
+
readonly stopReason?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface TranscriptPresentationReasoning extends TranscriptPresentationItemBase {
|
|
37
|
+
readonly kind: "reasoning";
|
|
38
|
+
readonly text: string;
|
|
39
|
+
readonly status: "in_progress" | "completed";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface TranscriptPresentationActivity extends TranscriptPresentationItemBase {
|
|
43
|
+
readonly kind: "activity";
|
|
44
|
+
readonly activityId: string;
|
|
45
|
+
readonly activityKind: string;
|
|
46
|
+
readonly reason: TranscriptActivityRecord["reason"];
|
|
47
|
+
readonly status?: string;
|
|
48
|
+
readonly data: JsonObject;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Folded, display-only transcript projection. It is never continuation authority. */
|
|
52
|
+
export type TranscriptPresentationItem =
|
|
53
|
+
| TranscriptPresentationMessage
|
|
54
|
+
| TranscriptPresentationReasoning
|
|
55
|
+
| TranscriptPresentationActivity;
|
|
56
|
+
|
|
57
|
+
export function presentationItemFromRecord(
|
|
58
|
+
record: TranscriptPresentationRecord,
|
|
59
|
+
): TranscriptPresentationItem | null {
|
|
60
|
+
const presentation = record.presentation;
|
|
61
|
+
if (!presentation) return null;
|
|
62
|
+
const base = {
|
|
63
|
+
id: presentation.id,
|
|
64
|
+
position: presentation.position,
|
|
65
|
+
revision: presentation.revision,
|
|
66
|
+
recordSequence: record.seq,
|
|
67
|
+
operationId: record.operationId,
|
|
68
|
+
transcriptId: record.transcriptId,
|
|
69
|
+
generation: record.generation,
|
|
70
|
+
} as const;
|
|
71
|
+
if (record.t === "message") {
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
...base,
|
|
74
|
+
kind: "message" as const,
|
|
75
|
+
role: record.role,
|
|
76
|
+
text: record.text,
|
|
77
|
+
...(record.providerMessageId === undefined ? {} : { providerMessageId: record.providerMessageId }),
|
|
78
|
+
...(record.status === undefined ? {} : { status: record.status }),
|
|
79
|
+
...(record.stopReason === undefined ? {} : { stopReason: record.stopReason }),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (record.t === "reasoning") {
|
|
83
|
+
return Object.freeze({
|
|
84
|
+
...base,
|
|
85
|
+
kind: "reasoning" as const,
|
|
86
|
+
text: record.text,
|
|
87
|
+
status: record.status,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
...base,
|
|
92
|
+
kind: "activity" as const,
|
|
93
|
+
activityId: record.activityId,
|
|
94
|
+
activityKind: record.kind,
|
|
95
|
+
reason: record.reason,
|
|
96
|
+
...(record.status === undefined ? {} : { status: record.status }),
|
|
97
|
+
data: structuredClone(record.data) as JsonObject,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -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
|
}
|