@qlairoslabs/acp-client 0.7.1 → 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 +32 -0
- package/package.json +2 -2
- package/src/activity.ts +8 -0
- package/src/agent-session.ts +137 -31
- package/src/index.ts +12 -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 +11 -1
- package/src/types.ts +2 -2
- package/LICENSE +0 -21
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -214,9 +214,19 @@ const unsubscribe = session.subscribe((notification: AgentSessionNotification) =
|
|
|
214
214
|
if (notification.event.kind === "metering_recorded") {
|
|
215
215
|
persistBillingMetadata(notification.event.record);
|
|
216
216
|
}
|
|
217
|
+
|
|
218
|
+
if (notification.event.kind === "presentation_recorded") {
|
|
219
|
+
upsertChatItem(notification.event.item.id, notification.event.item);
|
|
220
|
+
}
|
|
217
221
|
});
|
|
218
222
|
```
|
|
219
223
|
|
|
224
|
+
`onResponseChunk` and activity callbacks are provisional live streams. A
|
|
225
|
+
`presentation_recorded` notification means the displayed item revision has been appended
|
|
226
|
+
to the V2 transcript. Its ID, first position, revision, record sequence, and operation ID
|
|
227
|
+
are exactly the values the presentation reader returns after a restart. Upsert by `id`
|
|
228
|
+
and ignore revisions older than the one already rendered.
|
|
229
|
+
|
|
220
230
|
Useful live properties include:
|
|
221
231
|
|
|
222
232
|
```ts
|
|
@@ -584,6 +594,24 @@ const records = await reader.readPage({
|
|
|
584
594
|
});
|
|
585
595
|
```
|
|
586
596
|
|
|
597
|
+
For an end-user chat timeline, prefer the folded presentation projection:
|
|
598
|
+
|
|
599
|
+
```ts
|
|
600
|
+
const presentation = await reader.readPresentationPage({ limit: 50 });
|
|
601
|
+
|
|
602
|
+
for (const item of presentation.items) {
|
|
603
|
+
// message, reasoning, or activity; activity revisions are already folded.
|
|
604
|
+
renderOrReplace(item.id, item);
|
|
605
|
+
}
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
`readPresentationPage()` preserves the order in which logical items first appeared. A
|
|
609
|
+
tool that settles later keeps its original position, and distinct assistant messages stay
|
|
610
|
+
separate around intervening activity. The raw `timeline` view intentionally remains
|
|
611
|
+
available when the consumer needs every physical lifecycle revision rather than a chat
|
|
612
|
+
projection. Presentation pagination scans the snapshot with bounded item memory and does
|
|
613
|
+
not require the consumer to load the entire transcript.
|
|
614
|
+
|
|
587
615
|
Each page is ordered oldest-first within that page, while the initial page selects the
|
|
588
616
|
newest matching records. Navigate using `olderCursor` and `newerCursor`:
|
|
589
617
|
|
|
@@ -602,6 +630,10 @@ Navigation cursors are bound to the snapshot, view, and filter. Reusing one with
|
|
|
602
630
|
view or filter fails explicitly. Appends after the snapshot do not reorder the page being
|
|
603
631
|
read, while rewrites before its boundary invalidate the cursor.
|
|
604
632
|
|
|
633
|
+
Presentation navigation uses its own cursor type and the same stable snapshot semantics.
|
|
634
|
+
V1 and older V2 records without presentation metadata remain readable through `readPage`
|
|
635
|
+
but are not assigned invented interleaving in the folded V2 presentation view.
|
|
636
|
+
|
|
605
637
|
Fold revisioned activities at the same snapshot:
|
|
606
638
|
|
|
607
639
|
```ts
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qlairoslabs/acp-client",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "src/index.ts",
|
|
7
|
-
"license": "
|
|
7
|
+
"license": "UNLICENSED",
|
|
8
8
|
"author": "Facundo Hannoch <ffacu594@gmail.com>",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
package/src/activity.ts
CHANGED
|
@@ -235,6 +235,14 @@ export class ActivityAggregator {
|
|
|
235
235
|
return out;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Close only the current reasoning block when another presentation item begins.
|
|
240
|
+
* Long-running tools remain open: later revisions keep the tool's first position.
|
|
241
|
+
*/
|
|
242
|
+
closeReasoningBoundary(): AggregatedRecord | null {
|
|
243
|
+
return this.closeThinking();
|
|
244
|
+
}
|
|
245
|
+
|
|
238
246
|
/**
|
|
239
247
|
* Full state of the turn so far. A subscriber that joins mid-turn takes this, then
|
|
240
248
|
* discards any frame whose `seq` is not greater than the snapshot's — otherwise a
|
package/src/agent-session.ts
CHANGED
|
@@ -53,6 +53,7 @@ import type {
|
|
|
53
53
|
Attachment,
|
|
54
54
|
PromptHandlers,
|
|
55
55
|
PromptResult,
|
|
56
|
+
ResponseMessage,
|
|
56
57
|
SessionListEntry,
|
|
57
58
|
TokenUsage,
|
|
58
59
|
WireEntry,
|
|
@@ -79,9 +80,17 @@ import type {
|
|
|
79
80
|
OperationKind,
|
|
80
81
|
} from "./persistence/records.ts";
|
|
81
82
|
import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.ts";
|
|
82
|
-
import {
|
|
83
|
+
import {
|
|
84
|
+
RegistryPersistenceRuntime,
|
|
85
|
+
type PersistenceStateRuntime,
|
|
86
|
+
type PresentationPersistenceEvent,
|
|
87
|
+
} from "./persistence/state-runtime.ts";
|
|
83
88
|
import { AuditPersistenceRuntime, AuditedPersistenceRuntime, type AuditLogIdentity } from "./persistence/audit-runtime.ts";
|
|
84
89
|
import { TranscriptReader } from "./persistence/transcript-reader.ts";
|
|
90
|
+
import {
|
|
91
|
+
presentationItemFromRecord,
|
|
92
|
+
type TranscriptPresentationItem,
|
|
93
|
+
} from "./persistence/presentation.ts";
|
|
85
94
|
import {
|
|
86
95
|
snapshotSessionConfiguration,
|
|
87
96
|
snapshotSessionConfigurationAfterSelection,
|
|
@@ -336,6 +345,8 @@ export type AgentSessionEvent =
|
|
|
336
345
|
| { kind: "turn_started"; turnId: string }
|
|
337
346
|
| { kind: "turn_completed"; turnId: string; result: PromptResult }
|
|
338
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 }
|
|
339
350
|
/** The active ACP harness changed the slash commands it advertises. */
|
|
340
351
|
| { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
|
|
341
352
|
| {
|
|
@@ -599,7 +610,8 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
599
610
|
private readonly creationId: string;
|
|
600
611
|
private v2Transcript: PersistenceStateRuntime | null = null;
|
|
601
612
|
private v2TranscriptPath: string | null = null;
|
|
602
|
-
|
|
613
|
+
/** One display queue preserves the live message/activity interleaving seen by consumers. */
|
|
614
|
+
private v2PresentationWrite: Promise<void> = Promise.resolve();
|
|
603
615
|
private readonly transcriptActivity: boolean;
|
|
604
616
|
private readonly activityKinds: Set<string>;
|
|
605
617
|
private readonly activityRawOutput: boolean;
|
|
@@ -2504,13 +2516,16 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2504
2516
|
operation = await this.openMeteredOperation(item);
|
|
2505
2517
|
await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
|
|
2506
2518
|
transcriptStarted = true;
|
|
2507
|
-
await this.v2Transcript.
|
|
2519
|
+
const userRecord = await this.v2Transcript.appendPresentationEvent({
|
|
2508
2520
|
kind: "message",
|
|
2509
2521
|
operationId: item.turnId,
|
|
2510
2522
|
role: "user",
|
|
2511
2523
|
text: item.text,
|
|
2524
|
+
status: "completed",
|
|
2525
|
+
presentation: { id: `message:${item.turnId}:user`, revision: 1 },
|
|
2512
2526
|
});
|
|
2513
2527
|
await this.v2Transcript.syncBeforeDispatch();
|
|
2528
|
+
this.emitPresentationRecord(userRecord);
|
|
2514
2529
|
} catch (error) {
|
|
2515
2530
|
this.endTurn(item.handlers);
|
|
2516
2531
|
if (transcriptStarted) {
|
|
@@ -2533,6 +2548,51 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2533
2548
|
|
|
2534
2549
|
const chunks: string[] = [];
|
|
2535
2550
|
const response = new ResponseAccumulator();
|
|
2551
|
+
let assistantOrdinal = 0;
|
|
2552
|
+
let assistantMessage: {
|
|
2553
|
+
readonly id: string;
|
|
2554
|
+
providerMessageId?: string;
|
|
2555
|
+
text: string;
|
|
2556
|
+
revision: number;
|
|
2557
|
+
dirty: boolean;
|
|
2558
|
+
} | null = null;
|
|
2559
|
+
const beginAssistantMessage = (providerMessageId?: string) => {
|
|
2560
|
+
assistantOrdinal++;
|
|
2561
|
+
assistantMessage = {
|
|
2562
|
+
id: `message:${item.turnId}:assistant:${assistantOrdinal}`,
|
|
2563
|
+
...(providerMessageId === undefined ? {} : { providerMessageId }),
|
|
2564
|
+
text: "",
|
|
2565
|
+
revision: 0,
|
|
2566
|
+
dirty: false,
|
|
2567
|
+
};
|
|
2568
|
+
return assistantMessage;
|
|
2569
|
+
};
|
|
2570
|
+
const flushAssistantMessage = (
|
|
2571
|
+
status: "in_progress" | "completed" | "cancelled" | "error",
|
|
2572
|
+
stopReason?: string,
|
|
2573
|
+
force = false,
|
|
2574
|
+
) => {
|
|
2575
|
+
if (!this.v2Transcript || !assistantMessage || (!assistantMessage.dirty && !force)) return;
|
|
2576
|
+
assistantMessage.revision++;
|
|
2577
|
+
assistantMessage.dirty = false;
|
|
2578
|
+
const message = assistantMessage;
|
|
2579
|
+
this.queueV2Presentation({
|
|
2580
|
+
kind: "message",
|
|
2581
|
+
operationId: item.turnId,
|
|
2582
|
+
role: "assistant",
|
|
2583
|
+
text: message.text,
|
|
2584
|
+
...(message.providerMessageId === undefined ? {} : { providerMessageId: message.providerMessageId }),
|
|
2585
|
+
structured: {
|
|
2586
|
+
version: 1,
|
|
2587
|
+
messages: [message.providerMessageId === undefined
|
|
2588
|
+
? { text: message.text }
|
|
2589
|
+
: { messageId: message.providerMessageId, text: message.text }],
|
|
2590
|
+
},
|
|
2591
|
+
status,
|
|
2592
|
+
...(stopReason === undefined ? {} : { stopReason }),
|
|
2593
|
+
presentation: { id: message.id, revision: message.revision },
|
|
2594
|
+
});
|
|
2595
|
+
};
|
|
2536
2596
|
const wrappedHandlers: PromptHandlers = {
|
|
2537
2597
|
...item.handlers,
|
|
2538
2598
|
// Fired from here, from the one aggregator this session owns — nothing below needs
|
|
@@ -2543,10 +2603,33 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2543
2603
|
item.handlers?.onChunk?.(chunk);
|
|
2544
2604
|
},
|
|
2545
2605
|
onResponseChunk: (chunk) => {
|
|
2606
|
+
const settledReasoning = this.aggregator.closeReasoningBoundary();
|
|
2607
|
+
if (settledReasoning) {
|
|
2608
|
+
if (this.transcriptActivity || this.v2Transcript) this.writeActivity(settledReasoning);
|
|
2609
|
+
item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
|
|
2610
|
+
}
|
|
2546
2611
|
response.append(chunk);
|
|
2612
|
+
if (this.v2Transcript) {
|
|
2613
|
+
if (chunk.startsMessage) {
|
|
2614
|
+
flushAssistantMessage("completed", undefined, assistantMessage !== null);
|
|
2615
|
+
beginAssistantMessage(chunk.messageId);
|
|
2616
|
+
}
|
|
2617
|
+
const current = assistantMessage ?? beginAssistantMessage(chunk.messageId);
|
|
2618
|
+
if (current.providerMessageId === undefined && chunk.messageId !== undefined) {
|
|
2619
|
+
current.providerMessageId = chunk.messageId;
|
|
2620
|
+
}
|
|
2621
|
+
current.text += chunk.text;
|
|
2622
|
+
current.dirty = true;
|
|
2623
|
+
// Persist the first usable snapshot. Later token chunks remain in memory until
|
|
2624
|
+
// an interleaving item, a new message, or the operation boundary.
|
|
2625
|
+
if (current.revision === 0) flushAssistantMessage("in_progress");
|
|
2626
|
+
}
|
|
2547
2627
|
item.handlers?.onResponseChunk?.(chunk);
|
|
2548
2628
|
},
|
|
2549
2629
|
onActivity: (event) => {
|
|
2630
|
+
// The message snapshot must enter the shared queue before an activity first seen
|
|
2631
|
+
// after it. Later activity revisions keep their original presentation position.
|
|
2632
|
+
flushAssistantMessage("in_progress");
|
|
2550
2633
|
const result = this.aggregator.apply(event);
|
|
2551
2634
|
if (this.transcriptActivity || this.v2Transcript) {
|
|
2552
2635
|
for (const record of result.emitted) this.writeActivity(record);
|
|
@@ -2560,6 +2643,18 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2560
2643
|
let transcriptClosed = false;
|
|
2561
2644
|
try {
|
|
2562
2645
|
const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
|
|
2646
|
+
if (this.v2Transcript) {
|
|
2647
|
+
if (assistantOrdinal === 0) {
|
|
2648
|
+
for (const message of res.messages) {
|
|
2649
|
+
const current = beginAssistantMessage(message.messageId);
|
|
2650
|
+
current.text = message.text;
|
|
2651
|
+
current.dirty = true;
|
|
2652
|
+
flushAssistantMessage(res.status, res.stopReason, true);
|
|
2653
|
+
}
|
|
2654
|
+
} else {
|
|
2655
|
+
flushAssistantMessage(res.status, res.stopReason, true);
|
|
2656
|
+
}
|
|
2657
|
+
}
|
|
2563
2658
|
// Before the assistant msg: `msg` delimits a turn, so anything still open has to
|
|
2564
2659
|
// land inside those fences.
|
|
2565
2660
|
this.endTurn(item.handlers);
|
|
@@ -2580,16 +2675,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2580
2675
|
closed = record;
|
|
2581
2676
|
await this.persist();
|
|
2582
2677
|
if (this.v2Transcript) {
|
|
2583
|
-
await this.
|
|
2584
|
-
await this.v2Transcript.appendEvent({
|
|
2585
|
-
kind: "message",
|
|
2586
|
-
operationId: item.turnId,
|
|
2587
|
-
role: "assistant",
|
|
2588
|
-
text: res.text,
|
|
2589
|
-
structured: { version: 1, messages: res.messages },
|
|
2590
|
-
stopReason: res.stopReason,
|
|
2591
|
-
status: res.status,
|
|
2592
|
-
});
|
|
2678
|
+
await this.drainV2Presentation();
|
|
2593
2679
|
await this.finishV2Prompt(res.status, record);
|
|
2594
2680
|
transcriptClosed = true;
|
|
2595
2681
|
} else {
|
|
@@ -2610,26 +2696,25 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2610
2696
|
// Easy to miss, and the whole point of R4: a turn that died mid-tool still records
|
|
2611
2697
|
// what it was doing, at its real status.
|
|
2612
2698
|
this.endTurn(item.handlers);
|
|
2613
|
-
const text = chunks.join("");
|
|
2614
2699
|
const structured = response.snapshot();
|
|
2615
|
-
const
|
|
2700
|
+
const text = structured.length > 0 ? response.text : chunks.join("");
|
|
2701
|
+
const messages: readonly ResponseMessage[] = structured.length > 0
|
|
2616
2702
|
? structured
|
|
2617
2703
|
: text
|
|
2618
2704
|
? Object.freeze([{ text }])
|
|
2619
2705
|
: Object.freeze([]);
|
|
2620
2706
|
if (this.v2Transcript) {
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
status: "error",
|
|
2631
|
-
}).catch(() => undefined);
|
|
2707
|
+
if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
|
|
2708
|
+
for (const message of messages) {
|
|
2709
|
+
const current = beginAssistantMessage(message.messageId);
|
|
2710
|
+
current.text = message.text;
|
|
2711
|
+
current.dirty = true;
|
|
2712
|
+
flushAssistantMessage("error", "error", true);
|
|
2713
|
+
}
|
|
2714
|
+
} else if (!transcriptClosed) {
|
|
2715
|
+
flushAssistantMessage("error", "error", true);
|
|
2632
2716
|
}
|
|
2717
|
+
await this.drainV2Presentation().catch(() => undefined);
|
|
2633
2718
|
} else {
|
|
2634
2719
|
await this.appendTranscript({
|
|
2635
2720
|
v: 1,
|
|
@@ -2957,8 +3042,13 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2957
3042
|
const operationId = this.v2Transcript.checkpoint.boundary.status === "in_flight"
|
|
2958
3043
|
? this.v2Transcript.checkpoint.boundary.interruptedOperationId
|
|
2959
3044
|
: record.recordId.split(":", 1)[0] ?? record.recordId;
|
|
2960
|
-
|
|
2961
|
-
|
|
3045
|
+
const projected = persistenceEventFromActivity(record, operationId);
|
|
3046
|
+
this.queueV2Presentation({
|
|
3047
|
+
...projected,
|
|
3048
|
+
presentation: {
|
|
3049
|
+
id: `${projected.kind}:${operationId}:${record.recordId}`,
|
|
3050
|
+
revision: record.seq,
|
|
3051
|
+
},
|
|
2962
3052
|
});
|
|
2963
3053
|
return;
|
|
2964
3054
|
}
|
|
@@ -2967,8 +3057,24 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
2967
3057
|
void this.appendTranscript(this.toActivityLine(record));
|
|
2968
3058
|
}
|
|
2969
3059
|
|
|
2970
|
-
private
|
|
2971
|
-
|
|
3060
|
+
private queueV2Presentation(event: PresentationPersistenceEvent): void {
|
|
3061
|
+
this.v2PresentationWrite = this.v2PresentationWrite.then(async () => {
|
|
3062
|
+
if (!this.v2Transcript) return;
|
|
3063
|
+
const record = await this.v2Transcript.appendPresentationEvent(event);
|
|
3064
|
+
this.emitPresentationRecord(record);
|
|
3065
|
+
});
|
|
3066
|
+
}
|
|
3067
|
+
|
|
3068
|
+
private emitPresentationRecord(
|
|
3069
|
+
record: Awaited<ReturnType<PersistenceStateRuntime["appendPresentationEvent"]>>,
|
|
3070
|
+
): void {
|
|
3071
|
+
if (!record) return;
|
|
3072
|
+
const item = presentationItemFromRecord(record);
|
|
3073
|
+
if (item) this.emit({ kind: "presentation_recorded", item });
|
|
3074
|
+
}
|
|
3075
|
+
|
|
3076
|
+
private async drainV2Presentation(): Promise<void> {
|
|
3077
|
+
await this.v2PresentationWrite;
|
|
2972
3078
|
}
|
|
2973
3079
|
|
|
2974
3080
|
private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
|
|
@@ -3036,7 +3142,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
3036
3142
|
this.phase = "stopped";
|
|
3037
3143
|
this.emitStateIfChanged();
|
|
3038
3144
|
await this.controller.stop();
|
|
3039
|
-
await this.
|
|
3145
|
+
await this.drainV2Presentation().catch(() => undefined);
|
|
3040
3146
|
await this.v2Transcript?.close();
|
|
3041
3147
|
}
|
|
3042
3148
|
|
package/src/index.ts
CHANGED
|
@@ -248,8 +248,17 @@ export type {
|
|
|
248
248
|
AuditProjectionContext,
|
|
249
249
|
NormalizedActivityProjection,
|
|
250
250
|
NormalizedPersistenceEvent,
|
|
251
|
+
NormalizedPresentationMetadata,
|
|
251
252
|
TranscriptProjectionContext,
|
|
252
253
|
} from "./persistence/projection.ts";
|
|
254
|
+
export { presentationItemFromRecord } from "./persistence/presentation.ts";
|
|
255
|
+
export type {
|
|
256
|
+
TranscriptPresentationActivity,
|
|
257
|
+
TranscriptPresentationItem,
|
|
258
|
+
TranscriptPresentationMessage,
|
|
259
|
+
TranscriptPresentationReasoning,
|
|
260
|
+
TranscriptPresentationRecord,
|
|
261
|
+
} from "./persistence/presentation.ts";
|
|
253
262
|
export {
|
|
254
263
|
SessionLogTruncationError,
|
|
255
264
|
truncateSessionLogRecord,
|
|
@@ -337,9 +346,12 @@ export type {
|
|
|
337
346
|
PersistedActivityState,
|
|
338
347
|
PersistedActivityStatePage,
|
|
339
348
|
ReadTranscriptPageOptions,
|
|
349
|
+
ReadTranscriptPresentationPageOptions,
|
|
340
350
|
TranscriptConversationItem,
|
|
341
351
|
TranscriptCursor,
|
|
342
352
|
TranscriptPage,
|
|
353
|
+
TranscriptPresentationCursor,
|
|
354
|
+
TranscriptPresentationPage,
|
|
343
355
|
TranscriptSnapshotCursor,
|
|
344
356
|
TranscriptTimelineItem,
|
|
345
357
|
TranscriptReadableRecord,
|
|
@@ -3,6 +3,11 @@ import type { ActivityEvent, ToolActivity } from "../types.ts";
|
|
|
3
3
|
import type { JsonObject, JsonValue } from "./checkpoint.ts";
|
|
4
4
|
import type { NormalizedPersistenceEvent } from "./projection.ts";
|
|
5
5
|
|
|
6
|
+
type NormalizedActivityPersistenceEvent = Extract<
|
|
7
|
+
NormalizedPersistenceEvent,
|
|
8
|
+
{ kind: "reasoning" | "activity" }
|
|
9
|
+
>;
|
|
10
|
+
|
|
6
11
|
/**
|
|
7
12
|
* Classify an already-folded live activity record into persistence security buckets.
|
|
8
13
|
* This function deliberately does not serialize or hash values: capture projection gets
|
|
@@ -11,7 +16,7 @@ import type { NormalizedPersistenceEvent } from "./projection.ts";
|
|
|
11
16
|
export function persistenceEventFromActivity(
|
|
12
17
|
record: AggregatedRecord,
|
|
13
18
|
operationId: string,
|
|
14
|
-
):
|
|
19
|
+
): NormalizedActivityPersistenceEvent {
|
|
15
20
|
if (record.event.kind === "thinking") {
|
|
16
21
|
return {
|
|
17
22
|
kind: "reasoning",
|
|
@@ -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
|
}
|
|
@@ -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,16 @@ export interface IncomingResponseChunk {
|
|
|
7
7
|
startsMessage?: boolean;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Produce the legacy combined-text view without erasing protocol message boundaries.
|
|
12
|
+
* Message text is preserved verbatim; the only inserted content is the boundary between
|
|
13
|
+
* entries. Empty entries therefore participate in the literal join rather than being
|
|
14
|
+
* silently removed.
|
|
15
|
+
*/
|
|
16
|
+
export function joinResponseMessages(messages: readonly ResponseMessage[]): string {
|
|
17
|
+
return messages.map((message) => message.text).join("\n\n");
|
|
18
|
+
}
|
|
19
|
+
|
|
10
20
|
/**
|
|
11
21
|
* Fold response deltas without inventing separators. Only a change between two explicit
|
|
12
22
|
* ACP message ids proves that a new assistant message started; missing ids remain part of
|
|
@@ -45,7 +55,7 @@ export class ResponseAccumulator {
|
|
|
45
55
|
}
|
|
46
56
|
|
|
47
57
|
get text(): string {
|
|
48
|
-
return this.entries
|
|
58
|
+
return joinResponseMessages(this.entries);
|
|
49
59
|
}
|
|
50
60
|
|
|
51
61
|
snapshot(): readonly ResponseMessage[] {
|
package/src/types.ts
CHANGED
|
@@ -58,7 +58,7 @@ export type Usage = TokenUsage;
|
|
|
58
58
|
* call RESOLVES (not rejects) with whatever partial text arrived.
|
|
59
59
|
*/
|
|
60
60
|
export interface PromptResult {
|
|
61
|
-
/**
|
|
61
|
+
/** Combined display projection of `messages`, separated by one blank line. */
|
|
62
62
|
text: string;
|
|
63
63
|
/** Assistant messages in protocol order, preserving ACP `messageId` boundaries. */
|
|
64
64
|
messages: readonly ResponseMessage[];
|
|
@@ -242,7 +242,7 @@ export interface PermissionRequest {
|
|
|
242
242
|
|
|
243
243
|
/** Per-prompt callbacks. All optional. */
|
|
244
244
|
export interface PromptHandlers {
|
|
245
|
-
/** Legacy text
|
|
245
|
+
/** Legacy raw text stream. Concatenation does not encode message boundaries. */
|
|
246
246
|
onChunk?: (text: string) => void;
|
|
247
247
|
/** Boundary-aware response stream preserving ACP `messageId`. */
|
|
248
248
|
onResponseChunk?: (chunk: ResponseChunk) => void;
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Facundo Hannoch
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|