@qlairoslabs/acp-client 0.10.0 → 0.10.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 +184 -0
- package/README.md +0 -3
- package/package.json +4 -2
- package/src/agent-conversation-contracts.ts +9 -0
- package/src/agent-conversation-owner.ts +5 -0
- package/src/agent-conversation-queue.ts +23 -0
- package/src/agent-session.ts +123 -65
- package/src/agent.ts +397 -93
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +11 -0
- package/src/checkpointing/recovery.ts +23 -1
- package/src/client.ts +3 -1
- package/src/index.ts +33 -0
- package/src/out-of-band-messages.ts +187 -0
- package/src/persistence/backend.ts +46 -1
- package/src/persistence/error-records.ts +104 -0
- package/src/persistence/sqlite-conversation-records.ts +38 -0
- package/src/persistence/sqlite-schema.ts +128 -47
- package/src/steering/combine.ts +56 -0
- package/src/steering/contracts.ts +84 -0
- package/src/steering/controller.ts +205 -0
- package/src/steering/index.ts +14 -0
- package/src/transport/acp-transport.ts +8 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Database } from "bun:sqlite";
|
|
2
2
|
|
|
3
|
-
export const SQLITE_AGENT_SCHEMA_VERSION =
|
|
3
|
+
export const SQLITE_AGENT_SCHEMA_VERSION = 12;
|
|
4
4
|
|
|
5
5
|
const BASE_SCHEMA = `
|
|
6
6
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
@@ -65,7 +65,8 @@ CREATE TABLE IF NOT EXISTS conversation_records (
|
|
|
65
65
|
'agent_action',
|
|
66
66
|
'thinking',
|
|
67
67
|
'activity',
|
|
68
|
-
'metering'
|
|
68
|
+
'metering',
|
|
69
|
+
'error'
|
|
69
70
|
)),
|
|
70
71
|
timestamp TEXT NOT NULL,
|
|
71
72
|
operation_id TEXT,
|
|
@@ -210,6 +211,24 @@ CREATE TABLE IF NOT EXISTS conversation_metering_references (
|
|
|
210
211
|
CREATE INDEX IF NOT EXISTS conversation_metering_operation_idx
|
|
211
212
|
ON conversation_metering_references(operation_id, record_row_id);
|
|
212
213
|
|
|
214
|
+
CREATE TABLE IF NOT EXISTS conversation_error_records (
|
|
215
|
+
record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
|
|
216
|
+
source TEXT NOT NULL CHECK (source IN (
|
|
217
|
+
'provider_session', 'transport', 'operation', 'recovery'
|
|
218
|
+
)),
|
|
219
|
+
code TEXT NOT NULL CHECK (length(trim(code)) > 0),
|
|
220
|
+
recoverability TEXT NOT NULL CHECK (recoverability IN (
|
|
221
|
+
'retryable', 'recoverable', 'terminal', 'unknown'
|
|
222
|
+
)),
|
|
223
|
+
message TEXT,
|
|
224
|
+
transition_id TEXT,
|
|
225
|
+
internal_session_id TEXT,
|
|
226
|
+
details_json TEXT CHECK (details_json IS NULL OR json_valid(details_json))
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
CREATE INDEX IF NOT EXISTS conversation_error_source_code_idx
|
|
230
|
+
ON conversation_error_records(source, code, record_row_id);
|
|
231
|
+
|
|
213
232
|
CREATE TABLE IF NOT EXISTS conversation_checkpoints (
|
|
214
233
|
agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
|
|
215
234
|
revision INTEGER NOT NULL CHECK (revision >= 0),
|
|
@@ -518,58 +537,120 @@ END;
|
|
|
518
537
|
`;
|
|
519
538
|
|
|
520
539
|
export function migrateSqliteAgentSchema(database: Database): void {
|
|
521
|
-
database.
|
|
540
|
+
const hasMigrations = database.query<{ present: number }, []>(
|
|
541
|
+
"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
|
|
542
|
+
).get() !== null;
|
|
543
|
+
const existing = hasMigrations
|
|
544
|
+
? Number(database.query<{ version: number }, []>(
|
|
545
|
+
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
546
|
+
).get()?.version ?? 0)
|
|
547
|
+
: 0;
|
|
548
|
+
if (existing !== 0 && ![8, 9, 10, 11, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
|
|
549
|
+
throw new Error(
|
|
550
|
+
`SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
// Admitting the `error` kind means rebuilding conversation_records: its kind CHECK is a
|
|
554
|
+
// closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
|
|
555
|
+
// the implicit delete would cascade into every detail table.
|
|
556
|
+
const rebuildRecords = existing > 0 && existing < 12;
|
|
557
|
+
if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
|
|
522
558
|
try {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
const existing = Number(database.query<{ version: number }, []>(
|
|
559
|
+
database.exec("BEGIN IMMEDIATE");
|
|
560
|
+
try {
|
|
561
|
+
database.exec(BASE_SCHEMA);
|
|
562
|
+
const row = database.query<{ version: number }, []>(
|
|
528
563
|
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
529
|
-
).get()
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
);
|
|
564
|
+
).get();
|
|
565
|
+
const version = Number(row?.version ?? 0);
|
|
566
|
+
if (version > 0 && version < 10) {
|
|
567
|
+
database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
|
|
568
|
+
CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
|
|
569
|
+
database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
|
|
570
|
+
database.exec(`UPDATE conversations SET last_human_message_at = (
|
|
571
|
+
SELECT r.timestamp FROM conversation_records r
|
|
572
|
+
JOIN conversation_messages m ON m.record_row_id = r.row_id
|
|
573
|
+
JOIN participants p ON p.participant_id = m.participant_id
|
|
574
|
+
WHERE r.agent_conversation_id = conversations.agent_conversation_id
|
|
575
|
+
AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
|
|
576
|
+
ORDER BY r.sequence DESC LIMIT 1
|
|
577
|
+
)`);
|
|
535
578
|
}
|
|
579
|
+
if (version > 0 && version < 11) {
|
|
580
|
+
database.exec("ALTER TABLE conversation_messages ADD COLUMN logical_message_id TEXT");
|
|
581
|
+
}
|
|
582
|
+
database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
|
|
583
|
+
ON conversation_messages(logical_message_id, record_row_id)
|
|
584
|
+
WHERE logical_message_id IS NOT NULL`);
|
|
585
|
+
if (version > 0 && version < 12) {
|
|
586
|
+
rebuildConversationRecordsForErrorKind(database);
|
|
587
|
+
const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
|
|
588
|
+
if (violations.length > 0) {
|
|
589
|
+
throw new Error("SQLite schema migration to version 12 left foreign key violations");
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (version < SQLITE_AGENT_SCHEMA_VERSION) {
|
|
593
|
+
database.query<unknown, [number, string]>(
|
|
594
|
+
"INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
|
595
|
+
).run(SQLITE_AGENT_SCHEMA_VERSION, new Date().toISOString());
|
|
596
|
+
}
|
|
597
|
+
database.exec("COMMIT");
|
|
598
|
+
} catch (error) {
|
|
599
|
+
if (database.inTransaction) database.exec("ROLLBACK");
|
|
600
|
+
throw error;
|
|
536
601
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
540
|
-
).get();
|
|
541
|
-
const version = Number(row?.version ?? 0);
|
|
542
|
-
if (version > 0 && version < 10) {
|
|
543
|
-
database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
|
|
544
|
-
CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
|
|
545
|
-
database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
|
|
546
|
-
database.exec(`UPDATE conversations SET last_human_message_at = (
|
|
547
|
-
SELECT r.timestamp FROM conversation_records r
|
|
548
|
-
JOIN conversation_messages m ON m.record_row_id = r.row_id
|
|
549
|
-
JOIN participants p ON p.participant_id = m.participant_id
|
|
550
|
-
WHERE r.agent_conversation_id = conversations.agent_conversation_id
|
|
551
|
-
AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
|
|
552
|
-
ORDER BY r.sequence DESC LIMIT 1
|
|
553
|
-
)`);
|
|
554
|
-
}
|
|
555
|
-
if (version > 0 && version < 11) {
|
|
556
|
-
database.exec("ALTER TABLE conversation_messages ADD COLUMN logical_message_id TEXT");
|
|
557
|
-
}
|
|
558
|
-
database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
|
|
559
|
-
ON conversation_messages(logical_message_id, record_row_id)
|
|
560
|
-
WHERE logical_message_id IS NOT NULL`);
|
|
561
|
-
if (version < SQLITE_AGENT_SCHEMA_VERSION) {
|
|
562
|
-
database.query<unknown, [number, string]>(
|
|
563
|
-
"INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
|
564
|
-
).run(SQLITE_AGENT_SCHEMA_VERSION, new Date().toISOString());
|
|
565
|
-
}
|
|
566
|
-
database.exec("COMMIT");
|
|
567
|
-
} catch (error) {
|
|
568
|
-
if (database.inTransaction) database.exec("ROLLBACK");
|
|
569
|
-
throw error;
|
|
602
|
+
} finally {
|
|
603
|
+
if (rebuildRecords) database.exec("PRAGMA foreign_keys = ON");
|
|
570
604
|
}
|
|
571
605
|
}
|
|
572
606
|
|
|
607
|
+
/**
|
|
608
|
+
* Rebuild `conversation_records` so its `kind` CHECK admits `error`.
|
|
609
|
+
*
|
|
610
|
+
* Row ids are copied verbatim, so every detail table's `record_row_id` reference survives
|
|
611
|
+
* the swap. The caller runs this with foreign keys disabled and verifies with
|
|
612
|
+
* `PRAGMA foreign_key_check` afterward.
|
|
613
|
+
*/
|
|
614
|
+
function rebuildConversationRecordsForErrorKind(database: Database): void {
|
|
615
|
+
database.exec(`CREATE TABLE conversation_records_v12 (
|
|
616
|
+
row_id INTEGER PRIMARY KEY,
|
|
617
|
+
record_id TEXT NOT NULL UNIQUE,
|
|
618
|
+
agent_session_id TEXT NOT NULL,
|
|
619
|
+
agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
|
|
620
|
+
sequence INTEGER NOT NULL CHECK (sequence > 0),
|
|
621
|
+
kind TEXT NOT NULL CHECK (kind IN (
|
|
622
|
+
'message',
|
|
623
|
+
'tool_call',
|
|
624
|
+
'permission',
|
|
625
|
+
'configuration',
|
|
626
|
+
'protocol',
|
|
627
|
+
'native_action',
|
|
628
|
+
'agent_action',
|
|
629
|
+
'thinking',
|
|
630
|
+
'activity',
|
|
631
|
+
'metering',
|
|
632
|
+
'error'
|
|
633
|
+
)),
|
|
634
|
+
timestamp TEXT NOT NULL,
|
|
635
|
+
operation_id TEXT,
|
|
636
|
+
metadata TEXT,
|
|
637
|
+
UNIQUE (agent_conversation_id, sequence)
|
|
638
|
+
)`);
|
|
639
|
+
database.exec(`INSERT INTO conversation_records_v12(
|
|
640
|
+
row_id, record_id, agent_session_id, agent_conversation_id, sequence, kind, timestamp, operation_id, metadata
|
|
641
|
+
) SELECT row_id, record_id, agent_session_id, agent_conversation_id, sequence, kind, timestamp, operation_id, metadata
|
|
642
|
+
FROM conversation_records`);
|
|
643
|
+
database.exec("DROP TABLE conversation_records");
|
|
644
|
+
database.exec("ALTER TABLE conversation_records_v12 RENAME TO conversation_records");
|
|
645
|
+
database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_kind_idx
|
|
646
|
+
ON conversation_records(agent_conversation_id, kind, sequence)`);
|
|
647
|
+
database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_time_idx
|
|
648
|
+
ON conversation_records(timestamp, agent_conversation_id)`);
|
|
649
|
+
database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_operation_idx
|
|
650
|
+
ON conversation_records(agent_conversation_id, operation_id, sequence)
|
|
651
|
+
WHERE operation_id IS NOT NULL`);
|
|
652
|
+
}
|
|
653
|
+
|
|
573
654
|
export function installSqliteFts(database: Database): boolean {
|
|
574
655
|
const row = database.query<{ enabled: number }, []>(
|
|
575
656
|
"SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled",
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { PromptHandlers } from "../types.ts";
|
|
2
|
+
import type { PromptPart, SteeringPrompt } from "./contracts.ts";
|
|
3
|
+
|
|
4
|
+
/** Text of a combined prompt: the messages in order, separated by a blank line. Nothing is added. */
|
|
5
|
+
export const COMBINED_TEXT_SEPARATOR = "\n\n";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every combined message keeps its own handlers: each one receives the events of the shared turn.
|
|
9
|
+
* Permission requests have one answer, so the first message that handles them decides.
|
|
10
|
+
*/
|
|
11
|
+
export function mergeHandlers(list: readonly (PromptHandlers | undefined)[]): PromptHandlers | undefined {
|
|
12
|
+
const handlers = list.filter((entry): entry is PromptHandlers => entry !== undefined);
|
|
13
|
+
if (handlers.length === 0) return undefined;
|
|
14
|
+
if (handlers.length === 1) return handlers[0];
|
|
15
|
+
const merged: PromptHandlers = {
|
|
16
|
+
onChunk: (text) => handlers.forEach((entry) => entry.onChunk?.(text)),
|
|
17
|
+
onResponseChunk: (chunk) => handlers.forEach((entry) => entry.onResponseChunk?.(chunk)),
|
|
18
|
+
onActivity: (event) => handlers.forEach((entry) => entry.onActivity?.(event)),
|
|
19
|
+
onRecord: (record) => handlers.forEach((entry) => entry.onRecord?.(record)),
|
|
20
|
+
onUpdate: (notification) => handlers.forEach((entry) => entry.onUpdate?.(notification)),
|
|
21
|
+
};
|
|
22
|
+
const permission = handlers.find((entry) => entry.onPermissionRequest)?.onPermissionRequest;
|
|
23
|
+
if (permission) merged.onPermissionRequest = permission;
|
|
24
|
+
return merged;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function partOf(prompt: SteeringPrompt): PromptPart {
|
|
28
|
+
return {
|
|
29
|
+
id: prompt.turnId,
|
|
30
|
+
text: prompt.text,
|
|
31
|
+
...(prompt.participantId ? { participantId: prompt.participantId } : {}),
|
|
32
|
+
...(prompt.consumerMetadata !== undefined ? { consumerMetadata: prompt.consumerMetadata } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build the one prompt that carries a run of messages. The head keeps its id, so the combined prompt
|
|
38
|
+
* is one operation (one metering record). Every original promise settles with the same result.
|
|
39
|
+
* A run of one is returned unchanged.
|
|
40
|
+
*/
|
|
41
|
+
export function combinePrompts<T extends SteeringPrompt>(run: readonly T[]): T {
|
|
42
|
+
const [head] = run;
|
|
43
|
+
if (!head) throw new Error("cannot combine an empty run of prompts");
|
|
44
|
+
if (run.length === 1) return head;
|
|
45
|
+
const attachments = run.flatMap((prompt) => prompt.attachments ?? []);
|
|
46
|
+
const handlers = mergeHandlers(run.map((prompt) => prompt.handlers));
|
|
47
|
+
return {
|
|
48
|
+
...head,
|
|
49
|
+
text: run.map((prompt) => prompt.text).join(COMBINED_TEXT_SEPARATOR),
|
|
50
|
+
parts: run.map(partOf),
|
|
51
|
+
...(attachments.length > 0 ? { attachments } : { attachments: undefined }),
|
|
52
|
+
...(handlers ? { handlers } : { handlers: undefined }),
|
|
53
|
+
resolve: (result) => run.forEach((prompt) => prompt.resolve(result)),
|
|
54
|
+
reject: (error) => run.forEach((prompt) => prompt.reject(error)),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
|
|
2
|
+
import type { PersistenceJsonValue } from "../persistence/backend.ts";
|
|
3
|
+
import type { Attachment, PromptHandlers } from "../types.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* How a prompt sent while a turn is running waits.
|
|
7
|
+
*
|
|
8
|
+
* - `steer`: delivered at the next tool boundary, by cancelling the running turn and sending the
|
|
9
|
+
* message (together with any other `steer` messages waiting at the head of the queue).
|
|
10
|
+
* - `queue`: delivered after the running turn ends, as its own turn.
|
|
11
|
+
*/
|
|
12
|
+
export type PromptDelivery = "steer" | "queue";
|
|
13
|
+
|
|
14
|
+
/** Identifies one prompt while it waits. It is the prompt's operation id. */
|
|
15
|
+
export type PendingMessageId = string;
|
|
16
|
+
|
|
17
|
+
/** Why a pending message was delivered when it was. */
|
|
18
|
+
export type MessageDeliveryVia = "tool_boundary" | "interrupt" | "turn_end";
|
|
19
|
+
|
|
20
|
+
/** Why a turn was cancelled. Reported only when the turn really ended cancelled. */
|
|
21
|
+
export type PromptEndedBy = "steer" | "interrupt";
|
|
22
|
+
|
|
23
|
+
export interface PendingMessage {
|
|
24
|
+
readonly id: PendingMessageId;
|
|
25
|
+
/** What the consumer asked for. */
|
|
26
|
+
readonly delivery: PromptDelivery;
|
|
27
|
+
readonly participantId?: string;
|
|
28
|
+
readonly text: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What `prompt()` returns: the promise of that prompt's result, plus its id and a way to take it
|
|
33
|
+
* back while it still waits.
|
|
34
|
+
*/
|
|
35
|
+
export interface PromptHandle extends Promise<AgentSessionPromptResult> {
|
|
36
|
+
readonly id: PendingMessageId;
|
|
37
|
+
/** Remove the message if it has not been delivered yet. Returns whether it was still pending. */
|
|
38
|
+
withdraw(): boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Events about messages that wait. They go on the conversation event stream. */
|
|
42
|
+
export type MessageEvent =
|
|
43
|
+
| {
|
|
44
|
+
readonly kind: "message_pending";
|
|
45
|
+
readonly id: PendingMessageId;
|
|
46
|
+
/** The mode in effect: `queue` while the active operation is not a consumer prompt turn. */
|
|
47
|
+
readonly delivery: PromptDelivery;
|
|
48
|
+
}
|
|
49
|
+
| {
|
|
50
|
+
readonly kind: "message_delivered";
|
|
51
|
+
/** Every message sent in the prompt, in order. One id unless several were combined. */
|
|
52
|
+
readonly ids: readonly PendingMessageId[];
|
|
53
|
+
readonly via: MessageDeliveryVia;
|
|
54
|
+
/** The operation id of the prompt (equals the first id). */
|
|
55
|
+
readonly turnId: string;
|
|
56
|
+
}
|
|
57
|
+
| { readonly kind: "message_withdrawn"; readonly id: PendingMessageId };
|
|
58
|
+
|
|
59
|
+
/** One original message of a combined prompt. */
|
|
60
|
+
export interface PromptPart {
|
|
61
|
+
readonly id: PendingMessageId;
|
|
62
|
+
readonly text: string;
|
|
63
|
+
readonly participantId?: string;
|
|
64
|
+
readonly consumerMetadata?: PersistenceJsonValue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The fields of a queued prompt that steering reads and writes. */
|
|
68
|
+
export interface SteeringPrompt {
|
|
69
|
+
readonly kind: "prompt";
|
|
70
|
+
readonly turnId: string;
|
|
71
|
+
readonly operationKind: string;
|
|
72
|
+
readonly delivery: PromptDelivery;
|
|
73
|
+
/** True when it had to wait behind other work (so it emits message events). */
|
|
74
|
+
readonly waited: boolean;
|
|
75
|
+
text: string;
|
|
76
|
+
participantId?: string;
|
|
77
|
+
consumerMetadata?: PersistenceJsonValue;
|
|
78
|
+
handlers?: PromptHandlers;
|
|
79
|
+
attachments?: Attachment[];
|
|
80
|
+
/** Present only on a combined prompt: the original messages, in order. */
|
|
81
|
+
parts?: readonly PromptPart[];
|
|
82
|
+
resolve: (result: AgentSessionPromptResult) => void;
|
|
83
|
+
reject: (error: unknown) => void;
|
|
84
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
|
|
2
|
+
import type { AgentConversationQueue } from "../agent-conversation-queue.ts";
|
|
3
|
+
import type { ActivityEvent } from "../types.ts";
|
|
4
|
+
import { combinePrompts } from "./combine.ts";
|
|
5
|
+
import type {
|
|
6
|
+
MessageDeliveryVia,
|
|
7
|
+
MessageEvent,
|
|
8
|
+
PendingMessage,
|
|
9
|
+
PendingMessageId,
|
|
10
|
+
PromptDelivery,
|
|
11
|
+
PromptEndedBy,
|
|
12
|
+
SteeringPrompt,
|
|
13
|
+
} from "./contracts.ts";
|
|
14
|
+
|
|
15
|
+
/** What the controller needs from the conversation that owns it. */
|
|
16
|
+
export interface SteeringHost<T extends { readonly kind: string }> {
|
|
17
|
+
readonly queue: AgentConversationQueue<T>;
|
|
18
|
+
emit(event: MessageEvent): void;
|
|
19
|
+
/** Cancel the running provider turn. It must not touch the queue. */
|
|
20
|
+
cancelProviderTurn(): void;
|
|
21
|
+
/** Re-publish the conversation state (the queued count changed). */
|
|
22
|
+
emitState(): void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface ActiveTurn {
|
|
26
|
+
readonly turnId: string;
|
|
27
|
+
readonly tools: Map<string, string>;
|
|
28
|
+
endedBy?: PromptEndedBy;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const TERMINAL = new Set(["completed", "failed"]);
|
|
32
|
+
|
|
33
|
+
/** A prompt the consumer started and that steering may cancel. Hidden or internal turns are not. */
|
|
34
|
+
function isConsumerPrompt<T extends { readonly kind: string }>(item: T): item is T & SteeringPrompt {
|
|
35
|
+
return item.kind === "prompt" && (item as unknown as SteeringPrompt).operationKind === "prompt";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Messages that wait while a turn runs.
|
|
40
|
+
*
|
|
41
|
+
* There is one FIFO (the conversation's operations queue). This class adds a delivery mode to the
|
|
42
|
+
* prompts in it, watches the running turn for a tool boundary, and sends the head of the queue by
|
|
43
|
+
* cancelling the turn. It never reorders the queue and never cancels anything but a consumer prompt.
|
|
44
|
+
*/
|
|
45
|
+
export class SteeringController<T extends { readonly kind: string }> {
|
|
46
|
+
#active: ActiveTurn | null = null;
|
|
47
|
+
/** How the previous turn ended, for the `via` of the next delivery. */
|
|
48
|
+
#previousEndedBy: PromptEndedBy | null = null;
|
|
49
|
+
|
|
50
|
+
constructor(
|
|
51
|
+
private readonly host: SteeringHost<T>,
|
|
52
|
+
readonly defaultDelivery: PromptDelivery,
|
|
53
|
+
) {}
|
|
54
|
+
|
|
55
|
+
resolveDelivery(requested: PromptDelivery | undefined): PromptDelivery {
|
|
56
|
+
return requested ?? this.defaultDelivery;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The mode in effect for a message accepted now. */
|
|
60
|
+
effectiveDelivery(requested: PromptDelivery): PromptDelivery {
|
|
61
|
+
return this.#active ? requested : "queue";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Called when a prompt has been queued. Only prompts that had to wait are reported. */
|
|
65
|
+
accepted(item: SteeringPrompt): void {
|
|
66
|
+
if (!item.waited) return;
|
|
67
|
+
this.host.emit({
|
|
68
|
+
kind: "message_pending",
|
|
69
|
+
id: item.turnId,
|
|
70
|
+
delivery: this.effectiveDelivery(item.delivery),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// --- the running turn --------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
turnStarted(item: SteeringPrompt): void {
|
|
77
|
+
this.#active = item.operationKind === "prompt" ? { turnId: item.turnId, tools: new Map() } : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Activity of the running turn. A tool call settling is where a steer message is delivered. */
|
|
81
|
+
observeActivity(turnId: string, event: ActivityEvent): void {
|
|
82
|
+
const active = this.#active;
|
|
83
|
+
if (!active || active.turnId !== turnId) return;
|
|
84
|
+
if (event.kind !== "tool" && event.kind !== "tool_update") return;
|
|
85
|
+
const previous = active.tools.get(event.toolCallId);
|
|
86
|
+
const status = event.status ?? previous ?? "pending";
|
|
87
|
+
active.tools.set(event.toolCallId, status);
|
|
88
|
+
const settled = TERMINAL.has(status) && !(previous !== undefined && TERMINAL.has(previous));
|
|
89
|
+
if (!settled) return;
|
|
90
|
+
const inFlight = [...active.tools.values()].some((value) => !TERMINAL.has(value));
|
|
91
|
+
if (!inFlight) this.#boundary(active);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A tool call has settled and nothing else is running: send the head of the queue if it steers. */
|
|
95
|
+
#boundary(active: ActiveTurn): void {
|
|
96
|
+
if (active.endedBy) return;
|
|
97
|
+
const head = this.host.queue.peek();
|
|
98
|
+
if (!head || !isConsumerPrompt(head) || head.delivery !== "steer") return;
|
|
99
|
+
active.endedBy = "steer";
|
|
100
|
+
this.host.cancelProviderTurn();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The consumer called `interrupt()`. */
|
|
104
|
+
interrupted(): void {
|
|
105
|
+
if (this.#active && !this.#active.endedBy) this.#active.endedBy = "interrupt";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The turn finished. `endedBy` is reported only if the provider really stopped the turn. */
|
|
109
|
+
turnEnded(stopReason: string | undefined): void {
|
|
110
|
+
const endedBy = this.#active?.endedBy;
|
|
111
|
+
this.#previousEndedBy = endedBy && stopReason === "cancelled" ? endedBy : null;
|
|
112
|
+
this.#active = null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Extra fields of the result of a turn that was cancelled by steering or by `interrupt()`. */
|
|
116
|
+
resultFields(turnId: string, stopReason: string): { endedBy?: PromptEndedBy; followedBy?: readonly PendingMessageId[] } {
|
|
117
|
+
const endedBy = this.#active?.turnId === turnId ? this.#active.endedBy : undefined;
|
|
118
|
+
if (!endedBy || stopReason !== "cancelled") return {};
|
|
119
|
+
const followedBy = this.#headRun().map((item) => item.turnId);
|
|
120
|
+
return { endedBy, ...(followedBy.length > 0 ? { followedBy } : {}) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// --- delivery ----------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Called when a prompt reaches the head of the queue. A run of consecutive `steer` messages is
|
|
127
|
+
* sent as one prompt; anything else is sent as it is.
|
|
128
|
+
*/
|
|
129
|
+
prepareRun(head: SteeringPrompt): SteeringPrompt {
|
|
130
|
+
const run = head.operationKind === "prompt" && head.delivery === "steer"
|
|
131
|
+
? [head, ...(this.host.queue.takeWhile((item) => isConsumerPrompt(item) && item.delivery === "steer") as unknown as SteeringPrompt[])]
|
|
132
|
+
: [head];
|
|
133
|
+
const waited = run.filter((item) => item.waited);
|
|
134
|
+
if (waited.length > 0) {
|
|
135
|
+
this.host.emit({
|
|
136
|
+
kind: "message_delivered",
|
|
137
|
+
ids: waited.map((item) => item.turnId),
|
|
138
|
+
via: this.#via(),
|
|
139
|
+
turnId: head.turnId,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
this.#previousEndedBy = null;
|
|
143
|
+
if (run.length > 1) this.host.emitState();
|
|
144
|
+
return combinePrompts(run);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
#via(): MessageDeliveryVia {
|
|
148
|
+
return this.#previousEndedBy === "steer"
|
|
149
|
+
? "tool_boundary"
|
|
150
|
+
: this.#previousEndedBy === "interrupt"
|
|
151
|
+
? "interrupt"
|
|
152
|
+
: "turn_end";
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#headRun(): SteeringPrompt[] {
|
|
156
|
+
const run: SteeringPrompt[] = [];
|
|
157
|
+
for (const item of this.host.queue.snapshot()) {
|
|
158
|
+
if (!isConsumerPrompt(item) || item.delivery !== "steer") break;
|
|
159
|
+
run.push(item);
|
|
160
|
+
}
|
|
161
|
+
return run;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// --- the queue ---------------------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
/** What waits in the queue, in order. */
|
|
167
|
+
pending(): readonly PendingMessage[] {
|
|
168
|
+
return this.host.queue.snapshot().filter(isConsumerPrompt).map((item) => ({
|
|
169
|
+
id: item.turnId,
|
|
170
|
+
delivery: item.delivery,
|
|
171
|
+
...(item.participantId ? { participantId: item.participantId } : {}),
|
|
172
|
+
text: item.text,
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Take back a message that has not been delivered. Its promise settles as a cancelled prompt. */
|
|
177
|
+
withdraw(id: PendingMessageId): boolean {
|
|
178
|
+
const item = this.host.queue.remove((candidate) => isConsumerPrompt(candidate) && candidate.turnId === id);
|
|
179
|
+
if (!item) return false;
|
|
180
|
+
this.dropped([item as unknown as SteeringPrompt]);
|
|
181
|
+
this.host.emitState();
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Settle prompts that left the queue without running (withdrawn, or dropped by `interrupt`). */
|
|
186
|
+
dropped(items: readonly SteeringPrompt[]): void {
|
|
187
|
+
for (const item of items) {
|
|
188
|
+
item.resolve(cancelledPromptResult(item));
|
|
189
|
+
if (item.waited) this.host.emit({ kind: "message_withdrawn", id: item.turnId });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The result of a prompt that never reached the provider: nothing was sent, so nothing was consumed. */
|
|
195
|
+
export function cancelledPromptResult(item: { readonly turnId: string }): AgentSessionPromptResult {
|
|
196
|
+
return {
|
|
197
|
+
text: "",
|
|
198
|
+
messages: Object.freeze([]),
|
|
199
|
+
stopReason: "cancelled",
|
|
200
|
+
status: "cancelled",
|
|
201
|
+
usage: null,
|
|
202
|
+
operationId: item.turnId,
|
|
203
|
+
metering: null,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { combinePrompts, mergeHandlers, COMBINED_TEXT_SEPARATOR } from "./combine.ts";
|
|
2
|
+
export { SteeringController, cancelledPromptResult } from "./controller.ts";
|
|
3
|
+
export type { SteeringHost } from "./controller.ts";
|
|
4
|
+
export type {
|
|
5
|
+
MessageDeliveryVia,
|
|
6
|
+
MessageEvent,
|
|
7
|
+
PendingMessage,
|
|
8
|
+
PendingMessageId,
|
|
9
|
+
PromptDelivery,
|
|
10
|
+
PromptEndedBy,
|
|
11
|
+
PromptHandle,
|
|
12
|
+
PromptPart,
|
|
13
|
+
SteeringPrompt,
|
|
14
|
+
} from "./contracts.ts";
|
|
@@ -364,6 +364,14 @@ class ClientHandler implements acp.Client {
|
|
|
364
364
|
this.opts.onUpdate?.(params);
|
|
365
365
|
}
|
|
366
366
|
|
|
367
|
+
/**
|
|
368
|
+
* Extension notifications (an agent's own `_vendor/...` updates, such as codex-acp's
|
|
369
|
+
* `_auth/status_update`) are not part of what this client models. ACP requires unknown
|
|
370
|
+
* notifications to be ignored; without this handler the SDK answers "Method not found" and logs an
|
|
371
|
+
* error every time one arrives.
|
|
372
|
+
*/
|
|
373
|
+
async extNotification(_method: string, _params: Record<string, unknown>): Promise<void> {}
|
|
374
|
+
|
|
367
375
|
async requestPermission(
|
|
368
376
|
params: schema.RequestPermissionRequest,
|
|
369
377
|
): Promise<schema.RequestPermissionResponse> {
|