@qlairoslabs/acp-client 0.11.1 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG-consumer-fixes.md +62 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +288 -12
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +8 -1
- package/src/agent/adoption/replay.ts +1 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +178 -150
- package/src/agent/error-record-writer.ts +77 -0
- package/src/agent/persisted-lifecycle.ts +152 -35
- package/src/agent/record-capture.ts +18 -18
- package/src/agent-adapter-registry.ts +2 -0
- package/src/agent-client.ts +9 -3
- package/src/agent-conversation-contracts.ts +6 -0
- package/src/agent-conversation-owner.ts +31 -6
- package/src/agent-conversation-presentation.ts +12 -1
- package/src/agent-conversation-queue.ts +3 -2
- package/src/agent-session.ts +535 -94
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/recovery.ts +12 -0
- package/src/checkpointing/strategy.ts +2 -0
- package/src/client.ts +132 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/index.ts +17 -0
- package/src/internal-inference/config.ts +7 -0
- package/src/internal-inference/contracts.ts +3 -0
- package/src/internal-inference/coordination/handles.ts +11 -2
- package/src/internal-inference/coordination/manager.ts +20 -3
- package/src/internal-inference/index.ts +2 -0
- package/src/internal-inference/persistence/records.ts +3 -1
- package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
- package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
- package/src/internal-inference/runtime/harness-runtime.ts +19 -2
- package/src/media/acp.ts +118 -0
- package/src/media/capture.ts +15 -0
- package/src/media/content.ts +142 -0
- package/src/media/files.ts +28 -0
- package/src/media/parts.ts +145 -0
- package/src/media/pending.ts +51 -0
- package/src/media/redact.ts +14 -0
- package/src/media/store.ts +127 -0
- package/src/metering/provider.ts +8 -1
- package/src/operations/activity-tracker.ts +31 -0
- package/src/operations/contracts.ts +63 -0
- package/src/operations/errors.ts +31 -0
- package/src/operations/index.ts +6 -0
- package/src/operations/stale-policy.ts +51 -0
- package/src/operations/supervisor.ts +209 -0
- package/src/operations/timers.ts +12 -0
- package/src/out-of-band-messages.ts +49 -32
- package/src/persistence/audit-runtime.ts +14 -2
- package/src/persistence/backend.ts +108 -12
- package/src/persistence/error-records.ts +27 -0
- package/src/persistence/index.ts +8 -0
- package/src/persistence/presentation.ts +9 -1
- package/src/persistence/projection.ts +20 -0
- package/src/persistence/records.ts +45 -6
- package/src/persistence/sqlite-backend.ts +207 -16
- package/src/persistence/sqlite-conversation-records.ts +31 -4
- package/src/persistence/sqlite-files.ts +95 -0
- package/src/persistence/sqlite-media-store.ts +67 -0
- package/src/persistence/sqlite-schema.ts +86 -10
- package/src/persistence/state-runtime.ts +2 -0
- package/src/persistence/timeline-reconcile.ts +21 -4
- package/src/persistence/transcript-reader.ts +11 -4
- package/src/persistence/transcript-runtime.ts +105 -12
- package/src/repl/repl.ts +1 -1
- package/src/response.ts +40 -8
- package/src/steering/combine.ts +11 -4
- package/src/steering/contracts.ts +14 -4
- package/src/steering/controller.ts +96 -21
- package/src/steering/index.ts +1 -0
- package/src/transport/acp-transport.ts +18 -7
- package/src/types.ts +7 -0
- package/src/updates.ts +4 -4
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { MediaInfo, MediaStore, StoredMedia } from "../media/store.ts";
|
|
3
|
+
|
|
4
|
+
interface MediaRow {
|
|
5
|
+
ref: string;
|
|
6
|
+
owner: string;
|
|
7
|
+
kind: MediaInfo["kind"];
|
|
8
|
+
mime_type: string;
|
|
9
|
+
name: string | null;
|
|
10
|
+
size: number;
|
|
11
|
+
sha256: string;
|
|
12
|
+
data?: Uint8Array;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function storedMedia(row: MediaRow): StoredMedia {
|
|
16
|
+
return {
|
|
17
|
+
ref: row.ref,
|
|
18
|
+
info: {
|
|
19
|
+
owner: row.owner,
|
|
20
|
+
kind: row.kind,
|
|
21
|
+
mimeType: row.mime_type,
|
|
22
|
+
...(row.name === null ? {} : { name: row.name }),
|
|
23
|
+
size: row.size,
|
|
24
|
+
sha256: row.sha256,
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Kept copies in the agent's own database, out of the message rows. The scoped writer joins the
|
|
31
|
+
* enclosing record transaction when one is active, so a copy and its record commit together.
|
|
32
|
+
*/
|
|
33
|
+
export class SqliteMediaStore implements MediaStore {
|
|
34
|
+
constructor(
|
|
35
|
+
private readonly database: Database,
|
|
36
|
+
private readonly write: <T>(work: () => T) => Promise<T>,
|
|
37
|
+
) {}
|
|
38
|
+
|
|
39
|
+
async put(bytes: Uint8Array, info: MediaInfo): Promise<string> {
|
|
40
|
+
return this.write(() => {
|
|
41
|
+
const ref = `media-${crypto.randomUUID()}`;
|
|
42
|
+
this.database.query(
|
|
43
|
+
`INSERT INTO conversation_media(ref, owner, kind, mime_type, name, size, sha256, data)
|
|
44
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
45
|
+
).run(ref, info.owner, info.kind, info.mimeType, info.name ?? null, info.size, info.sha256, bytes);
|
|
46
|
+
return ref;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async get(ref: string): Promise<(StoredMedia & { data: Uint8Array }) | null> {
|
|
51
|
+
const row = this.database.query<MediaRow, [string]>("SELECT * FROM conversation_media WHERE ref = ?").get(ref);
|
|
52
|
+
return row ? { ...storedMedia(row), data: new Uint8Array(row.data!) } : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async delete(ref: string): Promise<void> {
|
|
56
|
+
await this.write(() => {
|
|
57
|
+
this.database.query("DELETE FROM conversation_media WHERE ref = ?").run(ref);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async list(owner: string): Promise<readonly StoredMedia[]> {
|
|
62
|
+
return this.database.query<MediaRow, [string]>(
|
|
63
|
+
`SELECT ref, owner, kind, mime_type, name, size, sha256
|
|
64
|
+
FROM conversation_media WHERE owner = ? ORDER BY rowid`,
|
|
65
|
+
).all(owner).map(storedMedia);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -1,8 +1,29 @@
|
|
|
1
1
|
import type { Database } from "bun:sqlite";
|
|
2
|
+
import { contentText } from "../media/content.ts";
|
|
3
|
+
import type { PersistedContent } from "./backend.ts";
|
|
2
4
|
|
|
3
|
-
export const SQLITE_AGENT_SCHEMA_VERSION =
|
|
5
|
+
export const SQLITE_AGENT_SCHEMA_VERSION = 16;
|
|
4
6
|
|
|
5
7
|
const BASE_SCHEMA = `
|
|
8
|
+
CREATE TABLE IF NOT EXISTS out_of_band_delivery (
|
|
9
|
+
owner TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
|
|
10
|
+
provider_context TEXT NOT NULL,
|
|
11
|
+
through_sequence INTEGER NOT NULL,
|
|
12
|
+
PRIMARY KEY(owner, provider_context)
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS conversation_media (
|
|
16
|
+
ref TEXT PRIMARY KEY,
|
|
17
|
+
owner TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
|
|
18
|
+
kind TEXT NOT NULL CHECK (kind IN ('image', 'audio', 'file')),
|
|
19
|
+
mime_type TEXT NOT NULL,
|
|
20
|
+
name TEXT,
|
|
21
|
+
size INTEGER NOT NULL CHECK (size >= 0),
|
|
22
|
+
sha256 TEXT NOT NULL,
|
|
23
|
+
data BLOB NOT NULL
|
|
24
|
+
);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS conversation_media_owner_idx ON conversation_media(owner);
|
|
26
|
+
|
|
6
27
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
7
28
|
version INTEGER PRIMARY KEY,
|
|
8
29
|
applied_at TEXT NOT NULL
|
|
@@ -68,7 +89,8 @@ CREATE TABLE IF NOT EXISTS conversation_records (
|
|
|
68
89
|
'thinking',
|
|
69
90
|
'activity',
|
|
70
91
|
'metering',
|
|
71
|
-
'error'
|
|
92
|
+
'error',
|
|
93
|
+
'cancellation'
|
|
72
94
|
)),
|
|
73
95
|
timestamp TEXT NOT NULL,
|
|
74
96
|
operation_id TEXT,
|
|
@@ -231,6 +253,14 @@ CREATE TABLE IF NOT EXISTS conversation_error_records (
|
|
|
231
253
|
CREATE INDEX IF NOT EXISTS conversation_error_source_code_idx
|
|
232
254
|
ON conversation_error_records(source, code, record_row_id);
|
|
233
255
|
|
|
256
|
+
CREATE TABLE IF NOT EXISTS conversation_cancellation_events (
|
|
257
|
+
record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
|
|
258
|
+
cancellation_id TEXT NOT NULL,
|
|
259
|
+
state TEXT NOT NULL CHECK (state IN ('requested', 'resolved')),
|
|
260
|
+
reason TEXT NOT NULL CHECK (reason IN ('interrupt', 'steer', 'stalled', 'stop', 'abort')),
|
|
261
|
+
outcome TEXT CHECK (outcome IS NULL OR outcome IN ('acknowledged', 'forced', 'too_late', 'failed'))
|
|
262
|
+
);
|
|
263
|
+
|
|
234
264
|
CREATE TABLE IF NOT EXISTS conversation_checkpoints (
|
|
235
265
|
agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
|
|
236
266
|
revision INTEGER NOT NULL CHECK (revision >= 0),
|
|
@@ -548,6 +578,31 @@ AFTER DELETE ON conversation_activity_events BEGIN
|
|
|
548
578
|
END;
|
|
549
579
|
`;
|
|
550
580
|
|
|
581
|
+
/**
|
|
582
|
+
* Version 15: records written before every write site passed its operation id recover it where it
|
|
583
|
+
* is still known. Runtime, permission and configuration record ids begin with it; native actions
|
|
584
|
+
* keep it as their transition id. Anything else stays without one.
|
|
585
|
+
*/
|
|
586
|
+
function backfillRecordOperationIds(database: Database): void {
|
|
587
|
+
for (const [separator, kinds] of [
|
|
588
|
+
[":runtime:", "'tool_call', 'thinking', 'activity'"],
|
|
589
|
+
[":permission:", "'permission'"],
|
|
590
|
+
[":configuration:", "'configuration'"],
|
|
591
|
+
] as const) {
|
|
592
|
+
database.query<unknown, [string, string]>(
|
|
593
|
+
`UPDATE conversation_records SET operation_id = substr(record_id, 1, instr(record_id, ?) - 1)
|
|
594
|
+
WHERE operation_id IS NULL AND kind IN (${kinds}) AND instr(record_id, ?) > 1`,
|
|
595
|
+
).run(separator, separator);
|
|
596
|
+
}
|
|
597
|
+
database.exec(`UPDATE conversation_records SET operation_id = (
|
|
598
|
+
SELECT n.transition_id FROM conversation_native_action_events n WHERE n.record_row_id = conversation_records.row_id
|
|
599
|
+
)
|
|
600
|
+
WHERE operation_id IS NULL AND kind = 'native_action' AND EXISTS (
|
|
601
|
+
SELECT 1 FROM conversation_native_action_events n
|
|
602
|
+
WHERE n.record_row_id = conversation_records.row_id AND n.transition_id IS NOT NULL
|
|
603
|
+
)`);
|
|
604
|
+
}
|
|
605
|
+
|
|
551
606
|
export function migrateSqliteAgentSchema(database: Database): void {
|
|
552
607
|
const hasMigrations = database.query<{ present: number }, []>(
|
|
553
608
|
"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
|
|
@@ -557,15 +612,15 @@ export function migrateSqliteAgentSchema(database: Database): void {
|
|
|
557
612
|
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
558
613
|
).get()?.version ?? 0)
|
|
559
614
|
: 0;
|
|
560
|
-
if (existing !== 0 && ![8, 9, 10, 11, 12, 13, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
|
|
615
|
+
if (existing !== 0 && ![8, 9, 10, 11, 12, 13, 14, 15, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
|
|
561
616
|
throw new Error(
|
|
562
617
|
`SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
|
|
563
618
|
);
|
|
564
619
|
}
|
|
565
|
-
// Admitting
|
|
620
|
+
// Admitting a new record kind means rebuilding conversation_records: its kind CHECK is a
|
|
566
621
|
// closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
|
|
567
622
|
// the implicit delete would cascade into every detail table.
|
|
568
|
-
const rebuildRecords = existing > 0 && existing <
|
|
623
|
+
const rebuildRecords = existing > 0 && existing < 15;
|
|
569
624
|
if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
|
|
570
625
|
try {
|
|
571
626
|
database.exec("BEGIN IMMEDIATE");
|
|
@@ -594,11 +649,12 @@ export function migrateSqliteAgentSchema(database: Database): void {
|
|
|
594
649
|
database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
|
|
595
650
|
ON conversation_messages(logical_message_id, record_row_id)
|
|
596
651
|
WHERE logical_message_id IS NOT NULL`);
|
|
597
|
-
if (version > 0 && version <
|
|
598
|
-
|
|
652
|
+
if (version > 0 && version < 15) {
|
|
653
|
+
// Version 12 admitted `error`, version 15 `cancellation`: one rebuild admits every kind.
|
|
654
|
+
rebuildConversationRecordsForKinds(database);
|
|
599
655
|
const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
|
|
600
656
|
if (violations.length > 0) {
|
|
601
|
-
throw new Error("SQLite schema migration to version
|
|
657
|
+
throw new Error("SQLite schema migration to version 15 left foreign key violations");
|
|
602
658
|
}
|
|
603
659
|
}
|
|
604
660
|
if (version > 0 && version < 13) {
|
|
@@ -614,6 +670,24 @@ export function migrateSqliteAgentSchema(database: Database): void {
|
|
|
614
670
|
throw new Error("SQLite schema migration to version 14 left foreign key violations");
|
|
615
671
|
}
|
|
616
672
|
}
|
|
673
|
+
if (version > 0 && version < 15) backfillRecordOperationIds(database);
|
|
674
|
+
if (version < 16) {
|
|
675
|
+
// Old structured search rows could contain inline base64 and media refs. Updating the
|
|
676
|
+
// source search text requires rebuilding an existing append-only FTS index as well.
|
|
677
|
+
const structured = database.query<{ record_row_id: number; content_json: string }, []>(
|
|
678
|
+
"SELECT record_row_id, content_json FROM conversation_messages WHERE content_json IS NOT NULL",
|
|
679
|
+
).iterate();
|
|
680
|
+
const update = database.query("UPDATE conversation_messages SET search_text = ? WHERE record_row_id = ?");
|
|
681
|
+
for (const row of structured) {
|
|
682
|
+
update.run(contentText(JSON.parse(row.content_json) as PersistedContent), row.record_row_id);
|
|
683
|
+
}
|
|
684
|
+
const fts = database.query(
|
|
685
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'conversation_messages_fts'",
|
|
686
|
+
).get();
|
|
687
|
+
if (fts) {
|
|
688
|
+
database.exec("INSERT INTO conversation_messages_fts(conversation_messages_fts) VALUES ('rebuild')");
|
|
689
|
+
}
|
|
690
|
+
}
|
|
617
691
|
if (version < SQLITE_AGENT_SCHEMA_VERSION) {
|
|
618
692
|
database.query<unknown, [number, string]>(
|
|
619
693
|
"INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
|
@@ -678,7 +752,8 @@ CREATE TABLE conversation_recovery_checkpoints (
|
|
|
678
752
|
* the swap. The caller runs this with foreign keys disabled and verifies with
|
|
679
753
|
* `PRAGMA foreign_key_check` afterward.
|
|
680
754
|
*/
|
|
681
|
-
|
|
755
|
+
/** Recreate conversation_records with the current kind CHECK, keeping every row and its row id. */
|
|
756
|
+
function rebuildConversationRecordsForKinds(database: Database): void {
|
|
682
757
|
database.exec(`CREATE TABLE conversation_records_v12 (
|
|
683
758
|
row_id INTEGER PRIMARY KEY,
|
|
684
759
|
record_id TEXT NOT NULL UNIQUE,
|
|
@@ -696,7 +771,8 @@ function rebuildConversationRecordsForErrorKind(database: Database): void {
|
|
|
696
771
|
'thinking',
|
|
697
772
|
'activity',
|
|
698
773
|
'metering',
|
|
699
|
-
'error'
|
|
774
|
+
'error',
|
|
775
|
+
'cancellation'
|
|
700
776
|
)),
|
|
701
777
|
timestamp TEXT NOT NULL,
|
|
702
778
|
operation_id TEXT,
|
|
@@ -29,6 +29,8 @@ export interface PersistenceStateRuntime {
|
|
|
29
29
|
event: PresentationPersistenceEvent,
|
|
30
30
|
ts?: number,
|
|
31
31
|
): Promise<TranscriptPresentationRecord | null>;
|
|
32
|
+
/** When a presentation item of the running operation was first written; forgotten when it ends. */
|
|
33
|
+
presentationStartedAt?(presentationId: string): number | undefined;
|
|
32
34
|
appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options?: { readonly durable?: boolean; readonly ts?: number }): Promise<void>;
|
|
33
35
|
publishCheckpoint(changes: TranscriptTerminalCheckpointChanges, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
34
36
|
activateTransition(event: Omit<TransitionEvent, "event"> & { readonly event: "target_activated" }, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
@@ -6,6 +6,10 @@ export interface ConversationTimelineItem {
|
|
|
6
6
|
readonly kind: ConversationRecordKind;
|
|
7
7
|
readonly firstSequence: number;
|
|
8
8
|
readonly lastSequence: number;
|
|
9
|
+
/** When the first revision was written: the item's own time, e.g. when a message began. */
|
|
10
|
+
readonly startedAt: string;
|
|
11
|
+
/** When the latest revision was written (also `current.timestamp`). */
|
|
12
|
+
readonly updatedAt: string;
|
|
9
13
|
/** Records in canonical order; retain these when rendering lifecycle details. */
|
|
10
14
|
readonly revisions: readonly ConversationRecord[];
|
|
11
15
|
/** Later fields override earlier ones, while omitted fields are retained. */
|
|
@@ -39,6 +43,8 @@ export function reconcileConversationTimeline(
|
|
|
39
43
|
kind: revisions[0]!.kind,
|
|
40
44
|
firstSequence: revisions[0]!.sequence,
|
|
41
45
|
lastSequence: revisions.at(-1)!.sequence,
|
|
46
|
+
startedAt: revisions[0]!.timestamp,
|
|
47
|
+
updatedAt: revisions.at(-1)!.timestamp,
|
|
42
48
|
revisions: Object.freeze(revisions),
|
|
43
49
|
current: Object.freeze(Object.assign({}, ...revisions)) as ConversationRecord,
|
|
44
50
|
}));
|
|
@@ -58,16 +64,27 @@ export function conversationTimelineItemId(record: ConversationRecord): string {
|
|
|
58
64
|
case "thinking": return `${prefix}${JSON.stringify([scope, record.thinkingId])}`;
|
|
59
65
|
case "activity": return `${prefix}${JSON.stringify([scope, record.activityId])}`;
|
|
60
66
|
case "native_action": return `${prefix}${JSON.stringify([record.transitionId ?? record.recordId])}`;
|
|
67
|
+
case "cancellation": return `${prefix}${JSON.stringify([record.cancellationId])}`;
|
|
61
68
|
default: return `${prefix}${JSON.stringify([record.recordId])}`;
|
|
62
69
|
}
|
|
63
70
|
}
|
|
64
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The operation an item's provider-local id (a tool call id, a permission id) is unique within, so
|
|
74
|
+
* two turns that reuse an id stay two items. The metadata's operation id comes first: items whose
|
|
75
|
+
* records carried it there keep the ids they had before records carried `operationId`.
|
|
76
|
+
*/
|
|
65
77
|
function operationScope(record: ConversationRecord): string {
|
|
66
|
-
|
|
78
|
+
const operationId = metadataOperationId(record.metadata) ?? record.operationId;
|
|
79
|
+
return operationId ? `${operationId}:` : "";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function metadataOperationId(metadata: string | undefined): string | undefined {
|
|
83
|
+
if (!metadata) return undefined;
|
|
67
84
|
try {
|
|
68
|
-
const parsed = JSON.parse(
|
|
69
|
-
return typeof parsed.operationId === "string" ?
|
|
85
|
+
const parsed = JSON.parse(metadata) as { operationId?: unknown };
|
|
86
|
+
return typeof parsed.operationId === "string" ? parsed.operationId : undefined;
|
|
70
87
|
} catch {
|
|
71
|
-
return
|
|
88
|
+
return undefined;
|
|
72
89
|
}
|
|
73
90
|
}
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
type TranscriptMessageRecord,
|
|
19
19
|
type TranscriptMeteringReferenceRecord,
|
|
20
20
|
type TranscriptPermissionRecord,
|
|
21
|
+
type TranscriptCancellationRecord,
|
|
21
22
|
type TranscriptProtocolMetadataRecord,
|
|
22
23
|
type TranscriptReasoningRecord,
|
|
23
24
|
type TranscriptRecordType,
|
|
@@ -41,12 +42,12 @@ const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
|
41
42
|
const RECORD_TYPE_ORDER: readonly TranscriptRecordType[] = Object.freeze([
|
|
42
43
|
"header", "checkpoint", "operation", "message", "reasoning", "activity",
|
|
43
44
|
"configuration", "permission", "transition", "metering_reference", "lifecycle",
|
|
44
|
-
"protocol", "raw",
|
|
45
|
+
"protocol", "raw", "cancellation",
|
|
45
46
|
]);
|
|
46
47
|
const RECORD_TYPES = new Set(RECORD_TYPE_ORDER);
|
|
47
48
|
const TIMELINE_TYPES = new Set<TranscriptRecordType>([
|
|
48
49
|
"message", "reasoning", "activity", "configuration", "permission", "transition",
|
|
49
|
-
"metering_reference", "lifecycle", "protocol",
|
|
50
|
+
"metering_reference", "lifecycle", "protocol", "cancellation",
|
|
50
51
|
]);
|
|
51
52
|
|
|
52
53
|
export type TranscriptView = "conversation" | "timeline" | "records";
|
|
@@ -92,6 +93,7 @@ export type TranscriptTimelineItem =
|
|
|
92
93
|
| TranscriptActivityRecord
|
|
93
94
|
| TranscriptConfigurationRecord
|
|
94
95
|
| TranscriptPermissionRecord
|
|
96
|
+
| TranscriptCancellationRecord
|
|
95
97
|
| TranscriptTransitionRecord
|
|
96
98
|
| TranscriptMeteringReferenceRecord
|
|
97
99
|
| TranscriptLifecycleRecord
|
|
@@ -309,6 +311,7 @@ export class TranscriptReader {
|
|
|
309
311
|
// position === physical seq, so candidates can be selected while scanning and
|
|
310
312
|
// later revisions can update only the bounded candidate set.
|
|
311
313
|
const latest = new Map<string, TranscriptPresentationRecord>();
|
|
314
|
+
const startedAt = new Map<string, number>();
|
|
312
315
|
const candidateIds: string[] = [];
|
|
313
316
|
let boundaryFound = navigation === null;
|
|
314
317
|
let expectedSequence = 1;
|
|
@@ -350,13 +353,17 @@ export class TranscriptReader {
|
|
|
350
353
|
: metadata.position > navigation.boundaryPosition);
|
|
351
354
|
if (!eligible) continue;
|
|
352
355
|
latest.set(metadata.id, record);
|
|
356
|
+
startedAt.set(metadata.id, record.ts);
|
|
353
357
|
candidateIds.push(metadata.id);
|
|
354
358
|
if (candidateIds.length > limit + 1) {
|
|
355
359
|
const removeIndex = navigation?.direction === "newer"
|
|
356
360
|
? candidateIds.length - 1
|
|
357
361
|
: 0;
|
|
358
362
|
const [removed] = candidateIds.splice(removeIndex, 1);
|
|
359
|
-
if (removed)
|
|
363
|
+
if (removed) {
|
|
364
|
+
latest.delete(removed);
|
|
365
|
+
startedAt.delete(removed);
|
|
366
|
+
}
|
|
360
367
|
}
|
|
361
368
|
}
|
|
362
369
|
if (!boundaryFound) {
|
|
@@ -367,7 +374,7 @@ export class TranscriptReader {
|
|
|
367
374
|
const pageIds = navigation?.direction === "newer"
|
|
368
375
|
? candidateIds.slice(0, limit)
|
|
369
376
|
: candidateIds.slice(Math.max(0, candidateIds.length - limit));
|
|
370
|
-
const selected = pageIds.map((id) => presentationItemFromRecord(latest.get(id)
|
|
377
|
+
const selected = pageIds.map((id) => presentationItemFromRecord(latest.get(id)!, startedAt.get(id))!);
|
|
371
378
|
const hasOlder = navigation?.direction === "newer" ? true : hasExtra;
|
|
372
379
|
const hasNewer = navigation?.direction === "older" ? true : navigation?.direction === "newer" ? hasExtra : false;
|
|
373
380
|
const first = selected[0];
|
|
@@ -104,13 +104,24 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
104
104
|
started: TranscriptOperationRecord;
|
|
105
105
|
} | null = null;
|
|
106
106
|
private failure: Error | null = null;
|
|
107
|
+
/**
|
|
108
|
+
* Writes run one at a time: each picks its sequence number from the writer when it runs, so two
|
|
109
|
+
* overlapping callers would otherwise claim the same number and the second would fail the transcript.
|
|
110
|
+
*/
|
|
111
|
+
private serial: Promise<unknown> = Promise.resolve();
|
|
107
112
|
private closed = false;
|
|
108
113
|
private checkpointPublisher: ((
|
|
109
114
|
checkpoint: AgentSessionCheckpoint,
|
|
110
115
|
history: readonly InternalSessionHistoryEntry[],
|
|
111
116
|
) => Promise<void>) | null = null;
|
|
117
|
+
/**
|
|
118
|
+
* Each presentation item's first position and time. An item's id names its operation and a
|
|
119
|
+
* revision from another operation is refused, so an item never outlives its operation: entries
|
|
120
|
+
* are dropped when it ends.
|
|
121
|
+
*/
|
|
112
122
|
private readonly presentationStates = new Map<string, {
|
|
113
123
|
readonly position: number;
|
|
124
|
+
readonly startedAt: number;
|
|
114
125
|
readonly revision: number;
|
|
115
126
|
readonly kind: PresentationPersistenceEvent["kind"];
|
|
116
127
|
readonly operationId: string;
|
|
@@ -256,7 +267,11 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
256
267
|
this.checkpointPublisher = publisher;
|
|
257
268
|
}
|
|
258
269
|
|
|
259
|
-
|
|
270
|
+
beginOperation(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
|
|
271
|
+
return this.exclusive(() => this.beginOperationNow(operationId, kind, ts));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async beginOperationNow(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
|
|
260
275
|
this.assertUsable();
|
|
261
276
|
if (this._recovery.kind !== "clean") throw new TranscriptRuntimeStateError("uncertain transcript recovery must be resolved before dispatch");
|
|
262
277
|
if (this.activeOperation) throw new TranscriptRuntimeStateError("another transcript operation is already active");
|
|
@@ -278,12 +293,16 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
278
293
|
} catch (error) {
|
|
279
294
|
// Registry publication is part of the managed pre-dispatch boundary. Close the
|
|
280
295
|
// transcript operation truthfully before reporting failure to the caller.
|
|
281
|
-
await this.
|
|
296
|
+
await this.abortOperationNow("pre_dispatch_persistence_failure").catch(() => undefined);
|
|
282
297
|
throw error;
|
|
283
298
|
}
|
|
284
299
|
}
|
|
285
300
|
|
|
286
|
-
|
|
301
|
+
appendEvent(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
|
|
302
|
+
return this.exclusive(() => this.appendEventNow(event, ts));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private async appendEventNow(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
|
|
287
306
|
this.assertUsable();
|
|
288
307
|
if (event.kind === "transition") {
|
|
289
308
|
throw new TranscriptRuntimeStateError("transitions require the dedicated transition boundary API");
|
|
@@ -306,7 +325,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
306
325
|
}
|
|
307
326
|
}
|
|
308
327
|
|
|
309
|
-
|
|
328
|
+
appendPresentationEvent(
|
|
329
|
+
event: PresentationPersistenceEvent,
|
|
330
|
+
ts = Date.now(),
|
|
331
|
+
): Promise<TranscriptPresentationRecord | null> {
|
|
332
|
+
return this.exclusive(() => this.appendPresentationEventNow(event, ts));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private async appendPresentationEventNow(
|
|
310
336
|
event: PresentationPersistenceEvent,
|
|
311
337
|
ts = Date.now(),
|
|
312
338
|
): Promise<TranscriptPresentationRecord | null> {
|
|
@@ -341,6 +367,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
341
367
|
await this.writer.append(record);
|
|
342
368
|
this.presentationStates.set(event.presentation.id, {
|
|
343
369
|
position,
|
|
370
|
+
startedAt: existing?.startedAt ?? ts,
|
|
344
371
|
revision: event.presentation.revision,
|
|
345
372
|
kind: event.kind,
|
|
346
373
|
operationId: presentationOperationId(event),
|
|
@@ -352,7 +379,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
352
379
|
}
|
|
353
380
|
}
|
|
354
381
|
|
|
355
|
-
|
|
382
|
+
appendTransitionEvent(
|
|
383
|
+
event: NonActivationTransitionEvent,
|
|
384
|
+
options: { readonly durable?: boolean; readonly ts?: number } = {},
|
|
385
|
+
): Promise<void> {
|
|
386
|
+
return this.exclusive(() => this.appendTransitionEventNow(event, options));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private async appendTransitionEventNow(
|
|
356
390
|
event: NonActivationTransitionEvent,
|
|
357
391
|
options: { readonly durable?: boolean; readonly ts?: number } = {},
|
|
358
392
|
): Promise<void> {
|
|
@@ -376,7 +410,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
376
410
|
}
|
|
377
411
|
|
|
378
412
|
/** Publish resumable non-routing state when no provider operation is active. */
|
|
379
|
-
|
|
413
|
+
publishCheckpoint(
|
|
414
|
+
changes: TranscriptTerminalCheckpointChanges,
|
|
415
|
+
ts = Date.now(),
|
|
416
|
+
): Promise<AgentSessionCheckpoint> {
|
|
417
|
+
return this.exclusive(() => this.publishCheckpointNow(changes, ts));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private async publishCheckpointNow(
|
|
380
421
|
changes: TranscriptTerminalCheckpointChanges,
|
|
381
422
|
ts = Date.now(),
|
|
382
423
|
): Promise<AgentSessionCheckpoint> {
|
|
@@ -411,7 +452,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
411
452
|
}
|
|
412
453
|
}
|
|
413
454
|
|
|
414
|
-
|
|
455
|
+
activateTransition(
|
|
456
|
+
event: TargetActivationEvent,
|
|
457
|
+
ts = Date.now(),
|
|
458
|
+
): Promise<AgentSessionCheckpoint> {
|
|
459
|
+
return this.exclusive(() => this.activateTransitionNow(event, ts));
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
private async activateTransitionNow(
|
|
415
463
|
event: TargetActivationEvent,
|
|
416
464
|
ts = Date.now(),
|
|
417
465
|
): Promise<AgentSessionCheckpoint> {
|
|
@@ -450,13 +498,26 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
450
498
|
}
|
|
451
499
|
|
|
452
500
|
/** Flush policy-projected input appended after beginOperation before provider dispatch. */
|
|
453
|
-
|
|
501
|
+
syncBeforeDispatch(): Promise<void> {
|
|
502
|
+
return this.exclusive(() => this.syncBeforeDispatchNow());
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private async syncBeforeDispatchNow(): Promise<void> {
|
|
454
506
|
this.assertUsable();
|
|
455
507
|
this.requireActive();
|
|
456
508
|
await this.writer.sync();
|
|
457
509
|
}
|
|
458
510
|
|
|
459
|
-
|
|
511
|
+
finishOperation(
|
|
512
|
+
event: "settled" | "failed" | "cancelled" | "interrupted",
|
|
513
|
+
changes: TranscriptTerminalCheckpointChanges = {},
|
|
514
|
+
errorCode?: PersistedMachineCode,
|
|
515
|
+
ts = Date.now(),
|
|
516
|
+
): Promise<AgentSessionCheckpoint> {
|
|
517
|
+
return this.exclusive(() => this.finishOperationNow(event, changes, errorCode, ts));
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private async finishOperationNow(
|
|
460
521
|
event: "settled" | "failed" | "cancelled" | "interrupted",
|
|
461
522
|
changes: TranscriptTerminalCheckpointChanges = {},
|
|
462
523
|
errorCode?: PersistedMachineCode,
|
|
@@ -504,6 +565,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
504
565
|
);
|
|
505
566
|
this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
|
|
506
567
|
this.activeOperation = null;
|
|
568
|
+
this.forgetPresentation(active.operationId);
|
|
507
569
|
await this.publishManagedCheckpoint();
|
|
508
570
|
return this.checkpoint;
|
|
509
571
|
} catch (error) {
|
|
@@ -512,7 +574,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
512
574
|
}
|
|
513
575
|
}
|
|
514
576
|
|
|
515
|
-
|
|
577
|
+
abortOperation(
|
|
578
|
+
reason: OperationAbortReason,
|
|
579
|
+
ts = Date.now(),
|
|
580
|
+
): Promise<AgentSessionCheckpoint> {
|
|
581
|
+
return this.exclusive(() => this.abortOperationNow(reason, ts));
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
private async abortOperationNow(
|
|
516
585
|
reason: OperationAbortReason,
|
|
517
586
|
ts = Date.now(),
|
|
518
587
|
): Promise<AgentSessionCheckpoint> {
|
|
@@ -543,6 +612,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
543
612
|
);
|
|
544
613
|
this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
|
|
545
614
|
this.activeOperation = null;
|
|
615
|
+
this.forgetPresentation(active.operationId);
|
|
546
616
|
await this.publishManagedCheckpoint();
|
|
547
617
|
return this.checkpoint;
|
|
548
618
|
} catch (error) {
|
|
@@ -558,7 +628,11 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
558
628
|
* already durable, only its missing checkpoint is materialized. The canonical reducer
|
|
559
629
|
* validates the complete opening tail before the runtime exposes clean state.
|
|
560
630
|
*/
|
|
561
|
-
|
|
631
|
+
acceptHarnessRecovery(ts = Date.now()): Promise<AgentSessionCheckpoint> {
|
|
632
|
+
return this.exclusive(() => this.acceptHarnessRecoveryNow(ts));
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
private async acceptHarnessRecoveryNow(ts = Date.now()): Promise<AgentSessionCheckpoint> {
|
|
562
636
|
this.assertUsable();
|
|
563
637
|
if (this.activeOperation) throw new TranscriptRuntimeStateError("cannot resolve recovery during an active operation");
|
|
564
638
|
if (this._recovery.kind !== "uncertain") {
|
|
@@ -607,7 +681,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
607
681
|
this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery, reduced.internalSessionHistory);
|
|
608
682
|
this.openingStructuralTail = [];
|
|
609
683
|
await this.publishManagedCheckpoint();
|
|
610
|
-
await this.
|
|
684
|
+
await this.appendEventNow({
|
|
611
685
|
kind: "lifecycle",
|
|
612
686
|
event: "recovery_resolved",
|
|
613
687
|
detail: {
|
|
@@ -624,11 +698,30 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
624
698
|
}
|
|
625
699
|
|
|
626
700
|
async close(): Promise<void> {
|
|
701
|
+
if (this.closed) return;
|
|
702
|
+
// Writes already requested still land; anything requested after this is refused.
|
|
703
|
+
await this.serial;
|
|
627
704
|
if (this.closed) return;
|
|
628
705
|
this.closed = true;
|
|
629
706
|
await this.writer.close();
|
|
630
707
|
}
|
|
631
708
|
|
|
709
|
+
presentationStartedAt(presentationId: string): number | undefined {
|
|
710
|
+
return this.presentationStates.get(presentationId)?.startedAt;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
private forgetPresentation(operationId: string): void {
|
|
714
|
+
for (const [id, state] of this.presentationStates) {
|
|
715
|
+
if (state.operationId === operationId) this.presentationStates.delete(id);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
private exclusive<T>(write: () => Promise<T>): Promise<T> {
|
|
720
|
+
const run = this.serial.then(write);
|
|
721
|
+
this.serial = run.catch(() => undefined);
|
|
722
|
+
return run;
|
|
723
|
+
}
|
|
724
|
+
|
|
632
725
|
private installCheckpoint(
|
|
633
726
|
record: TranscriptCheckpointRecord,
|
|
634
727
|
checkpoint: AgentSessionCheckpoint,
|
package/src/repl/repl.ts
CHANGED
|
@@ -308,7 +308,7 @@ export async function runRepl(
|
|
|
308
308
|
busy = true;
|
|
309
309
|
try {
|
|
310
310
|
const handlers: PromptHandlers = { onChunk, onActivity };
|
|
311
|
-
const result = await (execute ? execute(handlers) : client.prompt(text, handlers));
|
|
311
|
+
const result = await (execute ? execute(handlers) : client.prompt({ text, handlers }));
|
|
312
312
|
spinner?.stop();
|
|
313
313
|
|
|
314
314
|
if (wroteLabel) {
|