@qlairoslabs/acp-client 0.10.1 → 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 +99 -0
- package/README.md +0 -3
- package/package.json +1 -1
- 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 +121 -65
- package/src/agent.ts +17 -7
- package/src/client.ts +3 -1
- package/src/index.ts +10 -0
- 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
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -920,6 +920,105 @@ deprecated `result.text` property is only a compatibility projection and inserts
|
|
|
920
920
|
line between messages. `formatResponseMessages()` makes any deliberate flattening policy
|
|
921
921
|
consumer-owned.
|
|
922
922
|
|
|
923
|
+
## Send a message while a turn is running
|
|
924
|
+
|
|
925
|
+
A prompt sent while a turn runs waits. How it waits is its **delivery**:
|
|
926
|
+
|
|
927
|
+
- `"queue"` (the default): it runs after the running turn ends, as its own turn.
|
|
928
|
+
- `"steer"`: it is delivered at the next tool boundary. The library cancels the running turn once a
|
|
929
|
+
tool call has settled and nothing else is running, then sends the message, so the agent gets the
|
|
930
|
+
information without losing the work it has done. If the turn ends first, the message is sent as the
|
|
931
|
+
next prompt, so a message is never delivered later than the end of the turn. A text-only turn is not
|
|
932
|
+
cut short: use `interrupt()` for that.
|
|
933
|
+
|
|
934
|
+
```ts
|
|
935
|
+
const turn = conversation.prompt("Refactor the parser.");
|
|
936
|
+
|
|
937
|
+
// A second message, sent while the first turn is running.
|
|
938
|
+
const note = conversation.prompt({ text: "Also keep the public API unchanged.", delivery: "steer" });
|
|
939
|
+
|
|
940
|
+
const first = await turn; // stopReason "cancelled", endedBy "steer", followedBy [note.id]
|
|
941
|
+
const answer = await note; // the turn that carried the message
|
|
942
|
+
```
|
|
943
|
+
|
|
944
|
+
`prompt()` and `promptFrom()` return a handle: the promise of that prompt's result, plus `id` and
|
|
945
|
+
`withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
|
|
946
|
+
|
|
947
|
+
Set the default for prompts that do not say, per Agent or per conversation. It is `"queue"` unless you
|
|
948
|
+
change it:
|
|
949
|
+
|
|
950
|
+
```ts
|
|
951
|
+
const agent = await Agent.open({
|
|
952
|
+
// ...
|
|
953
|
+
conversationDefaults: { busyDelivery: "steer" },
|
|
954
|
+
});
|
|
955
|
+
```
|
|
956
|
+
|
|
957
|
+
### What waits, and in what order
|
|
958
|
+
|
|
959
|
+
The conversation keeps one FIFO. A `steer` message is appended like any other, so a `queue` message sent
|
|
960
|
+
earlier keeps its place ahead of it. At a boundary the library only delivers a message if the head of the
|
|
961
|
+
queue is a `steer` message.
|
|
962
|
+
|
|
963
|
+
**Consecutive `steer` messages at the head are sent as one prompt**, so the agent sees the whole
|
|
964
|
+
correction at once:
|
|
965
|
+
|
|
966
|
+
```text
|
|
967
|
+
> working...
|
|
968
|
+
Also, remember x
|
|
969
|
+
and y
|
|
970
|
+
and z
|
|
971
|
+
no, actually forget about y and z <- the agent receives all four together
|
|
972
|
+
```
|
|
973
|
+
|
|
974
|
+
The text is the messages in order, separated by a blank line; the library adds nothing, not even sender
|
|
975
|
+
names. It is one operation with one metering record, and every message's promise resolves with the same
|
|
976
|
+
result. Each original message is still stored as its own user message, with its own `participantId` and
|
|
977
|
+
`consumerMetadata`, so a consumer can render or filter them from its own metadata. Each message's
|
|
978
|
+
streaming handlers receive the events of the shared turn.
|
|
979
|
+
|
|
980
|
+
```ts
|
|
981
|
+
conversation.pendingMessages; // what waits, in the order it will be sent
|
|
982
|
+
conversation.withdraw(note.id); // take a message back; also note.withdraw()
|
|
983
|
+
conversation.interrupt(); // cancel now; pending steer messages are then sent
|
|
984
|
+
conversation.interrupt({ clearQueue: true }); // cancel and drop what waits
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
A withdrawn or dropped message settles as a cancelled prompt (`stopReason: "cancelled"`, `usage: null`,
|
|
988
|
+
`metering: null`).
|
|
989
|
+
|
|
990
|
+
### Events and results
|
|
991
|
+
|
|
992
|
+
Messages that had to wait emit events on the conversation event stream:
|
|
993
|
+
|
|
994
|
+
| Event | Meaning |
|
|
995
|
+
|---|---|
|
|
996
|
+
| `message_pending { id, delivery }` | Accepted and waiting. `delivery` is the mode in effect: `"queue"` while the running operation is not a consumer prompt turn (a handoff, a configuration change). |
|
|
997
|
+
| `message_delivered { ids, via, turnId }` | Sent to the agent. `ids` lists every message in the prompt; `via` is `"tool_boundary"`, `"interrupt"` or `"turn_end"`. |
|
|
998
|
+
| `message_withdrawn { id }` | Removed before delivery. |
|
|
999
|
+
|
|
1000
|
+
A turn cancelled by steering or by `interrupt()` carries `endedBy: "steer" | "interrupt"` and
|
|
1001
|
+
`followedBy` (the messages sent after it). They are set only when the provider really stopped the turn:
|
|
1002
|
+
if the turn finished by itself before the cancel took effect, neither is present.
|
|
1003
|
+
|
|
1004
|
+
### Limits to know about
|
|
1005
|
+
|
|
1006
|
+
Cancelling is the only control ACP offers during a turn, so what a harness does with the cancelled turn
|
|
1007
|
+
is its own. Measured with the `test11-steerTurn` smoke test:
|
|
1008
|
+
|
|
1009
|
+
- Work the agent has completed is kept: the follow-up continues the task rather than restarting it.
|
|
1010
|
+
- Codex: a shell command already running keeps running after the cancel, and text the agent was
|
|
1011
|
+
streaming when cancelled is dropped from its context. OpenCode aborts the command.
|
|
1012
|
+
- Usage reported over ACP for a cancelled turn is unreliable (OpenCode reports 0 over ACP for a turn
|
|
1013
|
+
whose inference had completed). Only a certified metering integration sees the real spend, so with
|
|
1014
|
+
plain ACP telemetry a steered conversation can under-count the cancelled turn.
|
|
1015
|
+
- Codex reports usage in a way the cumulative-counter check can reject: the turn after a cancel was
|
|
1016
|
+
recorded with status `counter_reset` and no attributed tokens in testing. This looks like a property of
|
|
1017
|
+
Codex usage reporting rather than of steering (see the `s9` control in `test11-steerTurn`).
|
|
1018
|
+
- `status` and the stored message status follow what the provider reported: a turn the provider ended
|
|
1019
|
+
normally despite a late cancel is `completed`, and `endedBy` is absent.
|
|
1020
|
+
- Pending messages live in memory only. They are lost if the process stops, like queued prompts.
|
|
1021
|
+
|
|
923
1022
|
## Observe state, context, and usage
|
|
924
1023
|
|
|
925
1024
|
Read a snapshot first, then subscribe to changes:
|
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AgentMode } from "./controller.ts";
|
|
2
|
+
import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
|
|
2
3
|
import type { Adapter } from "./adapters.ts";
|
|
3
4
|
import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
|
|
4
5
|
import type { OperationMeteringRecord } from "./metering/record.ts";
|
|
@@ -204,6 +205,7 @@ export type AgentSessionEvent =
|
|
|
204
205
|
| { kind: "turn_started"; turnId: string }
|
|
205
206
|
| { kind: "turn_completed"; turnId: string; result: PromptResult }
|
|
206
207
|
| { kind: "turn_failed"; turnId: string; error: string }
|
|
208
|
+
| MessageEvent
|
|
207
209
|
| { kind: "presentation_recorded"; item: TranscriptPresentationItem }
|
|
208
210
|
| { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
|
|
209
211
|
| { kind: "handoff_started"; handoffId: string; fromInternalSessionId: string | null }
|
|
@@ -252,6 +254,13 @@ export interface AgentSessionPromptResult extends PromptResult {
|
|
|
252
254
|
readonly operationId: string;
|
|
253
255
|
/** Null only when a queued prompt was cancelled before provider dispatch. */
|
|
254
256
|
readonly metering: OperationMeteringRecord | null;
|
|
257
|
+
/**
|
|
258
|
+
* Why this turn was cancelled, when steering or `interrupt()` cancelled it and the provider really
|
|
259
|
+
* stopped it (`stopReason: "cancelled"`). Absent when the turn ended on its own.
|
|
260
|
+
*/
|
|
261
|
+
readonly endedBy?: PromptEndedBy;
|
|
262
|
+
/** The messages sent after this turn was cancelled by steering or `interrupt()`, in order. */
|
|
263
|
+
readonly followedBy?: readonly PendingMessageId[];
|
|
255
264
|
}
|
|
256
265
|
|
|
257
266
|
/** Ordered envelope delivered to every current AgentSession subscriber. */
|
|
@@ -3,6 +3,7 @@ import type { Adapter } from "./adapters.ts";
|
|
|
3
3
|
import type { AgentMode } from "./controller.ts";
|
|
4
4
|
import type { NewConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
|
|
5
5
|
import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
|
|
6
|
+
import type { PromptPart } from "./steering/contracts.ts";
|
|
6
7
|
import type { ResponseMessage } from "./types.ts";
|
|
7
8
|
import type { OperationMeteringRecord } from "./metering/record.ts";
|
|
8
9
|
import type { AgentSessionMeteringState } from "./metering/state.ts";
|
|
@@ -19,12 +20,16 @@ export interface OwnedPromptInput {
|
|
|
19
20
|
readonly targetProviderContextId?: string;
|
|
20
21
|
readonly participantId?: string;
|
|
21
22
|
readonly consumerMetadata?: PersistenceJsonValue;
|
|
23
|
+
/** Present when several messages were combined into this one prompt: each is recorded as sent. */
|
|
24
|
+
readonly parts?: readonly PromptPart[];
|
|
22
25
|
readonly text: string;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
export interface OwnedPromptPreparation {
|
|
26
29
|
readonly providerText?: string;
|
|
27
30
|
readonly participant?: ParticipantRef;
|
|
31
|
+
/** Every participant of a combined prompt, in order. `participant` is the first. */
|
|
32
|
+
readonly participants?: readonly ParticipantRef[];
|
|
28
33
|
readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
|
|
29
34
|
}
|
|
30
35
|
|
|
@@ -25,6 +25,29 @@ export class AgentConversationQueue<T> {
|
|
|
25
25
|
return this.#items.splice(0);
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
/** The next queued item, without removing it. */
|
|
29
|
+
peek(): T | undefined {
|
|
30
|
+
return this.#items[0];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Queued (not active) work in FIFO order. The returned array is a copy. */
|
|
34
|
+
snapshot(): readonly T[] {
|
|
35
|
+
return [...this.#items];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Remove and return the first queued item the predicate accepts, if any. */
|
|
39
|
+
remove(predicate: (item: T) => boolean): T | undefined {
|
|
40
|
+
const index = this.#items.findIndex(predicate);
|
|
41
|
+
return index < 0 ? undefined : this.#items.splice(index, 1)[0];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Remove and return the consecutive items at the head of the queue the predicate accepts. */
|
|
45
|
+
takeWhile(predicate: (item: T) => boolean): T[] {
|
|
46
|
+
let count = 0;
|
|
47
|
+
while (count < this.#items.length && predicate(this.#items[count]!)) count += 1;
|
|
48
|
+
return this.#items.splice(0, count);
|
|
49
|
+
}
|
|
50
|
+
|
|
28
51
|
/**
|
|
29
52
|
* Drain every item serially. Concurrent calls share the active drain; an item
|
|
30
53
|
* enqueued by an active operation is observed by the same loop.
|
package/src/agent-session.ts
CHANGED
|
@@ -162,6 +162,14 @@ import type {
|
|
|
162
162
|
TranscriptContinuationBuilderContext,
|
|
163
163
|
} from "./agent-conversation-contracts.ts";
|
|
164
164
|
import { AgentConversationQueue } from "./agent-conversation-queue.ts";
|
|
165
|
+
import {
|
|
166
|
+
SteeringController,
|
|
167
|
+
type PendingMessage,
|
|
168
|
+
type PendingMessageId,
|
|
169
|
+
type PromptDelivery,
|
|
170
|
+
type PromptHandle,
|
|
171
|
+
type SteeringPrompt,
|
|
172
|
+
} from "./steering/index.ts";
|
|
165
173
|
import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
|
|
166
174
|
import {
|
|
167
175
|
HANDOFF_SUMMARY_PROMPT,
|
|
@@ -216,18 +224,9 @@ export type {
|
|
|
216
224
|
TranscriptContinuationBuilderContext,
|
|
217
225
|
} from "./agent-conversation-contracts.ts";
|
|
218
226
|
|
|
219
|
-
interface PromptQueueItem {
|
|
220
|
-
kind: "prompt";
|
|
221
|
-
turnId: string;
|
|
227
|
+
interface PromptQueueItem extends SteeringPrompt {
|
|
222
228
|
/** How this operation is classified in its metering record. */
|
|
223
229
|
operationKind: MeteredOperationKind;
|
|
224
|
-
text: string;
|
|
225
|
-
participantId?: string;
|
|
226
|
-
consumerMetadata?: PersistenceJsonValue;
|
|
227
|
-
handlers?: PromptHandlers;
|
|
228
|
-
attachments?: Attachment[];
|
|
229
|
-
resolve: (r: AgentSessionPromptResult) => void;
|
|
230
|
-
reject: (e: unknown) => void;
|
|
231
230
|
}
|
|
232
231
|
|
|
233
232
|
/** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
|
|
@@ -236,6 +235,8 @@ export interface AgentConversationPromptInput {
|
|
|
236
235
|
readonly consumerMetadata?: PersistenceJsonValue;
|
|
237
236
|
readonly handlers?: PromptHandlers;
|
|
238
237
|
readonly attachments?: Attachment[];
|
|
238
|
+
/** How this prompt waits if a turn is running. Defaults to the conversation's `busyDelivery`. */
|
|
239
|
+
readonly delivery?: PromptDelivery;
|
|
239
240
|
}
|
|
240
241
|
|
|
241
242
|
export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
|
|
@@ -322,6 +323,11 @@ export interface AgentSessionConfig {
|
|
|
322
323
|
/** Default MCP servers bound at session creation/switch, unless a call overrides them. */
|
|
323
324
|
mcpServers?: schema.McpServer[];
|
|
324
325
|
defaultPermission?: "approve" | "cancel";
|
|
326
|
+
/**
|
|
327
|
+
* How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
|
|
328
|
+
* the turn ends; `steer` delivers it at the next tool boundary. Default `queue`.
|
|
329
|
+
*/
|
|
330
|
+
busyDelivery?: PromptDelivery;
|
|
325
331
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
326
332
|
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
327
333
|
clientCapabilities?: AgentControllerConfig["clientCapabilities"];
|
|
@@ -449,6 +455,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
449
455
|
private readonly log: Logger;
|
|
450
456
|
private transcriptWrite: Promise<void> = Promise.resolve();
|
|
451
457
|
private readonly operations = new AgentConversationQueue<QueueItem>();
|
|
458
|
+
private readonly steering: SteeringController<QueueItem>;
|
|
452
459
|
private stopPromise: Promise<void> | null = null;
|
|
453
460
|
private phase: AgentSessionPhase = "idle";
|
|
454
461
|
private notificationSeq = 0;
|
|
@@ -543,6 +550,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
543
550
|
?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
|
|
544
551
|
this.ownerLifecycle = config.ownerLifecycle;
|
|
545
552
|
this.defaultPermission = config.defaultPermission ?? "cancel";
|
|
553
|
+
this.steering = new SteeringController<QueueItem>(
|
|
554
|
+
{
|
|
555
|
+
queue: this.operations,
|
|
556
|
+
emit: (event) => this.emit(event),
|
|
557
|
+
cancelProviderTurn: () => this.controller.interrupt(),
|
|
558
|
+
emitState: () => this.emitStateIfChanged(),
|
|
559
|
+
},
|
|
560
|
+
config.busyDelivery ?? "queue",
|
|
561
|
+
);
|
|
546
562
|
this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
|
|
547
563
|
this._adapterId = config.adapterId;
|
|
548
564
|
this.activeAdapter = config.adapter;
|
|
@@ -1770,48 +1786,67 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1770
1786
|
}
|
|
1771
1787
|
|
|
1772
1788
|
// --- AgentClient -------------------------------------------------------------
|
|
1773
|
-
prompt(input: AgentConversationPromptInput):
|
|
1789
|
+
prompt(input: AgentConversationPromptInput): PromptHandle;
|
|
1774
1790
|
prompt(
|
|
1775
1791
|
text: string,
|
|
1776
1792
|
handlers?: PromptHandlers,
|
|
1777
1793
|
attachments?: Attachment[],
|
|
1778
|
-
):
|
|
1779
|
-
|
|
1794
|
+
): PromptHandle;
|
|
1795
|
+
prompt(
|
|
1780
1796
|
input: string | AgentConversationPromptInput,
|
|
1781
1797
|
handlers?: PromptHandlers,
|
|
1782
1798
|
attachments?: Attachment[],
|
|
1783
|
-
):
|
|
1799
|
+
): PromptHandle {
|
|
1784
1800
|
return typeof input === "string"
|
|
1785
1801
|
? this.enqueuePrompt(input, "prompt", handlers, attachments)
|
|
1786
|
-
: this.enqueuePrompt(
|
|
1802
|
+
: this.enqueuePrompt(
|
|
1803
|
+
input.text, "prompt", input.handlers, input.attachments,
|
|
1804
|
+
undefined, input.consumerMetadata, input.delivery,
|
|
1805
|
+
);
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
/** Messages waiting behind the running operation, in the order they will be sent. */
|
|
1809
|
+
get pendingMessages(): readonly PendingMessage[] {
|
|
1810
|
+
return this.steering.pending();
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
/** Take back a message that has not been sent yet. Returns whether it was still pending. */
|
|
1814
|
+
withdraw(id: PendingMessageId): boolean {
|
|
1815
|
+
return this.steering.withdraw(id);
|
|
1787
1816
|
}
|
|
1788
1817
|
|
|
1789
1818
|
/** Prompt while attributing the caller to a stable participant identity. */
|
|
1790
|
-
promptFrom(input: AgentConversationAttributedPromptInput):
|
|
1819
|
+
promptFrom(input: AgentConversationAttributedPromptInput): PromptHandle;
|
|
1791
1820
|
promptFrom(
|
|
1792
1821
|
participantId: string,
|
|
1793
1822
|
text: string,
|
|
1794
1823
|
handlers?: PromptHandlers,
|
|
1795
1824
|
attachments?: Attachment[],
|
|
1796
|
-
):
|
|
1825
|
+
): PromptHandle;
|
|
1797
1826
|
promptFrom(
|
|
1798
1827
|
input: string | AgentConversationAttributedPromptInput,
|
|
1799
1828
|
text?: string,
|
|
1800
1829
|
handlers?: PromptHandlers,
|
|
1801
1830
|
attachments?: Attachment[],
|
|
1802
|
-
):
|
|
1831
|
+
): PromptHandle {
|
|
1803
1832
|
if (typeof input !== "string") {
|
|
1804
|
-
if (!input.participantId.trim()) return
|
|
1833
|
+
if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
|
|
1805
1834
|
return this.enqueuePrompt(
|
|
1806
1835
|
input.text, "prompt", input.handlers, input.attachments,
|
|
1807
|
-
input.participantId.trim(), input.consumerMetadata,
|
|
1836
|
+
input.participantId.trim(), input.consumerMetadata, input.delivery,
|
|
1808
1837
|
);
|
|
1809
1838
|
}
|
|
1810
1839
|
const participantId = input;
|
|
1811
|
-
if (!participantId.trim()) return
|
|
1840
|
+
if (!participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
|
|
1812
1841
|
return this.enqueuePrompt(text!, "prompt", handlers, attachments, participantId.trim());
|
|
1813
1842
|
}
|
|
1814
1843
|
|
|
1844
|
+
private rejectedPrompt(error: Error): PromptHandle {
|
|
1845
|
+
const id = this.mintTurnId();
|
|
1846
|
+
const rejected = Promise.reject<AgentSessionPromptResult>(error);
|
|
1847
|
+
return Object.assign(rejected, { id, withdraw: () => false });
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1815
1850
|
private enqueuePrompt(
|
|
1816
1851
|
text: string,
|
|
1817
1852
|
operationKind: MeteredOperationKind,
|
|
@@ -1819,8 +1854,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1819
1854
|
attachments?: Attachment[],
|
|
1820
1855
|
participantId?: string,
|
|
1821
1856
|
consumerMetadata?: PersistenceJsonValue,
|
|
1822
|
-
|
|
1823
|
-
|
|
1857
|
+
delivery?: PromptDelivery,
|
|
1858
|
+
): PromptHandle {
|
|
1859
|
+
const id = this.mintTurnId();
|
|
1860
|
+
const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
|
|
1824
1861
|
if (this.phase === "stopped") {
|
|
1825
1862
|
reject(new Error("AgentSession is stopped"));
|
|
1826
1863
|
return;
|
|
@@ -1840,10 +1877,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1840
1877
|
reject(error);
|
|
1841
1878
|
return;
|
|
1842
1879
|
}
|
|
1843
|
-
this.
|
|
1880
|
+
// Anything already running or queued means this prompt has to wait.
|
|
1881
|
+
const waited = this.operations.isDraining || this.operations.queuedCount > 0;
|
|
1882
|
+
const item: PromptQueueItem = {
|
|
1844
1883
|
kind: "prompt",
|
|
1845
|
-
turnId:
|
|
1884
|
+
turnId: id,
|
|
1846
1885
|
operationKind,
|
|
1886
|
+
delivery: this.steering.resolveDelivery(delivery),
|
|
1887
|
+
waited,
|
|
1847
1888
|
text,
|
|
1848
1889
|
...(participantId ? { participantId } : {}),
|
|
1849
1890
|
...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
|
|
@@ -1851,10 +1892,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1851
1892
|
attachments,
|
|
1852
1893
|
resolve,
|
|
1853
1894
|
reject,
|
|
1854
|
-
}
|
|
1895
|
+
};
|
|
1896
|
+
this.operations.enqueue(item);
|
|
1897
|
+
this.steering.accepted(item);
|
|
1855
1898
|
this.emitStateIfChanged();
|
|
1856
1899
|
void this.pump();
|
|
1857
1900
|
});
|
|
1901
|
+
return Object.assign(promise, { id, withdraw: () => this.steering.withdraw(id) });
|
|
1858
1902
|
}
|
|
1859
1903
|
|
|
1860
1904
|
/**
|
|
@@ -1995,18 +2039,25 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1995
2039
|
: "switching_mode";
|
|
1996
2040
|
this.emitStateIfChanged();
|
|
1997
2041
|
if (item.kind === "prompt") {
|
|
1998
|
-
|
|
2042
|
+
// A run of steer messages at the head of the queue goes out as one prompt.
|
|
2043
|
+
const prompt = this.steering.prepareRun(item) as PromptQueueItem;
|
|
2044
|
+
this.steering.turnStarted(prompt);
|
|
2045
|
+
this.emit({ kind: "turn_started", turnId: prompt.turnId });
|
|
2046
|
+
let stopReason: string | undefined;
|
|
1999
2047
|
try {
|
|
2000
|
-
const result = await this.runPrompt(
|
|
2048
|
+
const result = await this.runPrompt(prompt);
|
|
2049
|
+
stopReason = result.stopReason;
|
|
2001
2050
|
this.emit({
|
|
2002
2051
|
kind: "turn_completed",
|
|
2003
|
-
turnId:
|
|
2052
|
+
turnId: prompt.turnId,
|
|
2004
2053
|
result: copyPromptResult(result),
|
|
2005
2054
|
});
|
|
2006
|
-
|
|
2055
|
+
prompt.resolve(result);
|
|
2007
2056
|
} catch (err) {
|
|
2008
|
-
this.emit({ kind: "turn_failed", turnId:
|
|
2009
|
-
|
|
2057
|
+
this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
|
|
2058
|
+
prompt.reject(err);
|
|
2059
|
+
} finally {
|
|
2060
|
+
this.steering.turnEnded(stopReason);
|
|
2010
2061
|
}
|
|
2011
2062
|
} else if (item.kind === "handoff") {
|
|
2012
2063
|
try {
|
|
@@ -3014,11 +3065,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3014
3065
|
targetProviderContextId,
|
|
3015
3066
|
...(item.participantId ? { participantId: item.participantId } : {}),
|
|
3016
3067
|
...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
|
|
3068
|
+
...(item.parts ? { parts: item.parts } : {}),
|
|
3017
3069
|
text: item.text,
|
|
3018
3070
|
})
|
|
3019
3071
|
: undefined;
|
|
3020
|
-
|
|
3021
|
-
this._participants
|
|
3072
|
+
for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
|
|
3073
|
+
if (!this._participants.some((known) => known.id === participant.id)) {
|
|
3074
|
+
this._participants = [...this._participants, Object.freeze({ ...participant })];
|
|
3075
|
+
}
|
|
3022
3076
|
}
|
|
3023
3077
|
const providerText = owned?.providerText ?? item.text;
|
|
3024
3078
|
this.beginTurn(item.turnId);
|
|
@@ -3031,16 +3085,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3031
3085
|
operation = await this.openMeteredOperation(item);
|
|
3032
3086
|
await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
|
|
3033
3087
|
transcriptStarted = true;
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3088
|
+
// A combined prompt shows each original message, as it was sent.
|
|
3089
|
+
const userTexts = item.parts ? item.parts.map((part) => part.text) : [item.text];
|
|
3090
|
+
const userRecords = [];
|
|
3091
|
+
for (const [index, text] of userTexts.entries()) {
|
|
3092
|
+
userRecords.push(await this.v2Transcript.appendPresentationEvent({
|
|
3093
|
+
kind: "message",
|
|
3094
|
+
operationId: item.turnId,
|
|
3095
|
+
role: "user",
|
|
3096
|
+
text,
|
|
3097
|
+
status: "completed",
|
|
3098
|
+
presentation: { id: `message:${item.turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
|
|
3099
|
+
}));
|
|
3100
|
+
}
|
|
3042
3101
|
await this.v2Transcript.syncBeforeDispatch();
|
|
3043
|
-
this.presentation.emitPersistedRecord(userRecord);
|
|
3102
|
+
for (const userRecord of userRecords) this.presentation.emitPersistedRecord(userRecord);
|
|
3044
3103
|
} catch (error) {
|
|
3045
3104
|
this.endTurn(item.turnId, item.handlers);
|
|
3046
3105
|
if (transcriptStarted) {
|
|
@@ -3161,6 +3220,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3161
3220
|
// The message snapshot must enter the shared queue before an activity first seen
|
|
3162
3221
|
// after it. Later activity revisions keep their original presentation position.
|
|
3163
3222
|
flushAssistantMessage("in_progress");
|
|
3223
|
+
this.steering.observeActivity(item.turnId, event);
|
|
3164
3224
|
const result = this.presentation.applyActivity(event);
|
|
3165
3225
|
this.queueActivityRecords(item.turnId, result.emitted);
|
|
3166
3226
|
item.handlers?.onRecord?.(result);
|
|
@@ -3285,7 +3345,12 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3285
3345
|
status: res.status,
|
|
3286
3346
|
});
|
|
3287
3347
|
}
|
|
3288
|
-
const result = Object.freeze({
|
|
3348
|
+
const result = Object.freeze({
|
|
3349
|
+
...res,
|
|
3350
|
+
operationId: item.turnId,
|
|
3351
|
+
metering: record,
|
|
3352
|
+
...this.steering.resultFields(item.turnId, res.stopReason),
|
|
3353
|
+
});
|
|
3289
3354
|
await this.ownerRecordWrite;
|
|
3290
3355
|
if (this.ownerLifecycle) {
|
|
3291
3356
|
const completed = {
|
|
@@ -3714,31 +3779,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
3714
3779
|
}
|
|
3715
3780
|
|
|
3716
3781
|
interrupt(options?: InterruptOptions): void {
|
|
3782
|
+
this.steering.interrupted();
|
|
3717
3783
|
if (options?.clearQueue) {
|
|
3718
3784
|
const dropped = this.operations.clear();
|
|
3785
|
+
// Cancelled before dispatch: nothing was sent, so nothing was consumed and no
|
|
3786
|
+
// metering record is minted (§16).
|
|
3787
|
+
this.steering.dropped(dropped.filter((item): item is PromptQueueItem => item.kind === "prompt"));
|
|
3719
3788
|
for (const item of dropped) {
|
|
3720
|
-
if (item.kind === "prompt")
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
item.
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
status: "cancelled",
|
|
3728
|
-
usage: null,
|
|
3729
|
-
operationId: item.turnId,
|
|
3730
|
-
metering: null,
|
|
3731
|
-
});
|
|
3732
|
-
} else {
|
|
3733
|
-
const label = item.kind === "handoff"
|
|
3734
|
-
? "handoff"
|
|
3735
|
-
: item.kind === "set_config" || item.kind === "resolve_config"
|
|
3736
|
-
? "configuration change"
|
|
3737
|
-
: item.kind === "resolve_recovery"
|
|
3738
|
-
? "recovery resolution"
|
|
3789
|
+
if (item.kind === "prompt") continue;
|
|
3790
|
+
const label = item.kind === "handoff"
|
|
3791
|
+
? "handoff"
|
|
3792
|
+
: item.kind === "set_config" || item.kind === "resolve_config"
|
|
3793
|
+
? "configuration change"
|
|
3794
|
+
: item.kind === "resolve_recovery"
|
|
3795
|
+
? "recovery resolution"
|
|
3739
3796
|
: "mode change";
|
|
3740
|
-
|
|
3741
|
-
}
|
|
3797
|
+
item.reject(new Error(`${label} cancelled before it started`));
|
|
3742
3798
|
}
|
|
3743
3799
|
this.emitStateIfChanged();
|
|
3744
3800
|
}
|
package/src/agent.ts
CHANGED
|
@@ -1186,7 +1186,16 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
1186
1186
|
) {}
|
|
1187
1187
|
|
|
1188
1188
|
async beforePrompt(input: OwnedPromptInput) {
|
|
1189
|
-
|
|
1189
|
+
// A combined prompt records each original message as it was sent, under the same operation.
|
|
1190
|
+
const parts = input.parts ?? [{
|
|
1191
|
+
id: input.operationId,
|
|
1192
|
+
text: input.text,
|
|
1193
|
+
...(input.participantId ? { participantId: input.participantId } : {}),
|
|
1194
|
+
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
1195
|
+
}];
|
|
1196
|
+
const participants: ParticipantRef[] = [];
|
|
1197
|
+
for (const part of parts) participants.push(await this.resolveParticipant(part.participantId));
|
|
1198
|
+
const participant = participants[0]!;
|
|
1190
1199
|
const identity = await this.agent.identity.load({
|
|
1191
1200
|
agentSessionId: this.agent.id,
|
|
1192
1201
|
agentConversationId: this.conversationId,
|
|
@@ -1198,19 +1207,19 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
1198
1207
|
? { timeoutMs: this.settings.identityTimeoutMs }
|
|
1199
1208
|
: {}),
|
|
1200
1209
|
});
|
|
1201
|
-
const records = await this.appendMessages(
|
|
1202
|
-
recordId: `${input.operationId}:user`,
|
|
1210
|
+
const records = await this.appendMessages(parts.map((part, index): NewConversationRecord => ({
|
|
1211
|
+
recordId: index === 0 ? `${input.operationId}:user` : `${input.operationId}:user:${index + 1}`,
|
|
1203
1212
|
agentSessionId: this.agent.id,
|
|
1204
1213
|
agentConversationId: this.conversationId,
|
|
1205
1214
|
kind: "message",
|
|
1206
1215
|
timestamp: new Date().toISOString(),
|
|
1207
1216
|
role: "user",
|
|
1208
|
-
participantId:
|
|
1209
|
-
...(
|
|
1210
|
-
content:
|
|
1217
|
+
participantId: participants[index]!.id,
|
|
1218
|
+
...(part.consumerMetadata !== undefined ? { consumerMetadata: part.consumerMetadata } : {}),
|
|
1219
|
+
content: part.text,
|
|
1211
1220
|
status: "completed",
|
|
1212
1221
|
metadata: JSON.stringify({ operationId: input.operationId }),
|
|
1213
|
-
}
|
|
1222
|
+
})));
|
|
1214
1223
|
await this.updateIdentity(records);
|
|
1215
1224
|
// Read after the user record commits so a concurrent append falls in this turn or the next.
|
|
1216
1225
|
const outOfBand = records[0]
|
|
@@ -1224,6 +1233,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
1224
1233
|
return Object.freeze({
|
|
1225
1234
|
providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
|
|
1226
1235
|
participant,
|
|
1236
|
+
participants: Object.freeze(participants),
|
|
1227
1237
|
...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
|
|
1228
1238
|
});
|
|
1229
1239
|
}
|
package/src/client.ts
CHANGED
|
@@ -720,7 +720,9 @@ export class AcpClient implements AgentClient {
|
|
|
720
720
|
} as schema.PromptRequest);
|
|
721
721
|
this.log.debug("prompt_response", { response: res });
|
|
722
722
|
|
|
723
|
-
|
|
723
|
+
// What the provider reported, not what we asked for: a cancel can lose the race with a normal
|
|
724
|
+
// ending, and the turn is then complete, not cancelled.
|
|
725
|
+
const cancelled = res.stopReason === "cancelled";
|
|
724
726
|
const text = this.active.response.text;
|
|
725
727
|
const messages = this.active.response.snapshot();
|
|
726
728
|
// ACP usage is optional and experimental: validate rather than cast. An
|
package/src/index.ts
CHANGED
|
@@ -254,6 +254,16 @@ export type { TerminalHandlers } from "./transport/acp-transport.ts";
|
|
|
254
254
|
|
|
255
255
|
export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
|
|
256
256
|
export { formatResponseMessages } from "./response.ts";
|
|
257
|
+
export type {
|
|
258
|
+
MessageDeliveryVia,
|
|
259
|
+
MessageEvent,
|
|
260
|
+
PendingMessage,
|
|
261
|
+
PendingMessageId,
|
|
262
|
+
PromptDelivery,
|
|
263
|
+
PromptEndedBy,
|
|
264
|
+
PromptHandle,
|
|
265
|
+
PromptPart,
|
|
266
|
+
} from "./steering/index.ts";
|
|
257
267
|
|
|
258
268
|
export {
|
|
259
269
|
ActivityAggregator,
|
|
@@ -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> {
|