@qlairoslabs/acp-client 0.4.1 → 0.4.3
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 +10 -0
- package/README.md +23 -2
- package/package.json +1 -1
- package/src/adapters.ts +3 -0
- package/src/agent-session.ts +27 -2
- package/src/cli/adapter.ts +69 -0
- package/src/cli/index.ts +33 -10
- package/src/client.ts +23 -9
- package/src/degraded/pty-client.ts +6 -2
- package/src/index.ts +3 -1
- package/src/response.ts +56 -0
- package/src/transcript.ts +16 -3
- package/src/types.ts +20 -2
- package/src/updates.ts +16 -4
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -67,6 +67,7 @@ can supply any `Adapter` object.
|
|
|
67
67
|
const adapters: Record<string, Adapter> = {
|
|
68
68
|
codex: ADAPTERS.codex,
|
|
69
69
|
claude: ADAPTERS.claude,
|
|
70
|
+
pi: ADAPTERS.pi,
|
|
70
71
|
internal: {
|
|
71
72
|
command: ["internal-agent", "--acp"],
|
|
72
73
|
ptyCommand: ["internal-agent"],
|
|
@@ -84,6 +85,15 @@ function resolveAdapter(adapterId: string): Adapter {
|
|
|
84
85
|
The catalog stores `adapterId`, not executable configuration. This resolver therefore
|
|
85
86
|
belongs to the consumer.
|
|
86
87
|
|
|
88
|
+
Presets do not encode a provider's features. After the process starts, the library
|
|
89
|
+
discovers capabilities, authentication methods, configuration, sessions, and harness
|
|
90
|
+
commands through ACP. The Pi preset targets `@automatalabs/pi-acp`, which embeds Pi through
|
|
91
|
+
its published SDK and installs the `pi-acp` executable. The native `pi` command is used
|
|
92
|
+
only for interactive PTY mode.
|
|
93
|
+
|
|
94
|
+
Install the preset executable globally with `npm install -g @automatalabs/pi-acp`, or use
|
|
95
|
+
`{ command: ["npx", "-y", "@automatalabs/pi-acp"] }` as a custom adapter.
|
|
96
|
+
|
|
87
97
|
## Create the catalog and live-session registry
|
|
88
98
|
|
|
89
99
|
`SessionManager` is a metadata catalog, not a registry of running objects and not a
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @qlairoslabs/acp-client
|
|
2
2
|
|
|
3
3
|
An embeddable, model-agnostic **Agent Client Protocol (ACP)** client: talk to AI coding
|
|
4
|
-
agents (Codex, Claude, Kimi, Gemini, Copilot, OpenCode, …) over JSON-RPC 2.0, with a
|
|
4
|
+
agents (Codex, Claude, Kimi, Pi, Gemini, Copilot, OpenCode, …) over JSON-RPC 2.0, with a
|
|
5
5
|
**degraded PTY fallback** for agents that don't speak ACP.
|
|
6
6
|
|
|
7
7
|
```ts
|
|
@@ -61,7 +61,7 @@ bun add -g @qlairoslabs/acp-client
|
|
|
61
61
|
| **`AgentController`** | The control plane for **one** agent process: start/stop, prompt, interrupt, switch sessions, swap mode (normal ⇄ degraded), introspect capabilities & config. |
|
|
62
62
|
| **`AgentSession`** | A **durable conversation** with a stable identity that survives reconnects and mode-swaps. Wraps an `AgentController` and (optionally) records itself to a catalog. The front face for consumers that want persistence. |
|
|
63
63
|
| **`SessionManager` + `SessionStore`** | The session **catalog**: routing metadata (which adapter/mode/cwd a session belongs to), *not* conversation content. Merges your catalog with the agent's live `session/list`. Ships a `FileSessionStore`; inject your own (e.g. a database) for custom backends. |
|
|
64
|
-
| **Adapter** | Just how to *launch* an agent: the spawn command. `ADAPTERS` has presets (`codex`, `claude`, `kimi`, `gemini`, `copilot`, `opencode`); you can also pass a raw `{ command: [...] }`. |
|
|
64
|
+
| **Adapter** | Just how to *launch* an agent: the spawn command. `ADAPTERS` has convenience presets (`codex`, `claude`, `kimi`, `pi`, `gemini`, `copilot`, `opencode`); you can also pass a raw `{ command: [...] }`. Capabilities and commands are discovered after ACP initialization. |
|
|
65
65
|
| **Mode** | `"normal"` (real ACP over JSON-RPC) or `"degraded"` (drive the native CLI through a PTY and parse it). Both implement the same `AgentClient` output contract. |
|
|
66
66
|
|
|
67
67
|
---
|
|
@@ -464,6 +464,9 @@ A thin wrapper over the library is exposed as `acp-client`:
|
|
|
464
464
|
acp-client chat # new chat with the default adapter
|
|
465
465
|
acp-client chat <SESSION_ID> # resume a session
|
|
466
466
|
acp-client chat --adapter codex # pick an adapter
|
|
467
|
+
acp-client chat --adapter pi # @automatalabs/pi-acp (the pi-acp binary)
|
|
468
|
+
acp-client chat --adapter private --adapter-command '["private-agent","--acp"]'
|
|
469
|
+
acp-client chat --adapter private --adapter-command private-acp --pty-command private-agent
|
|
467
470
|
acp-client chat --exec "docker exec -i my-container" # talk to an agent in a container
|
|
468
471
|
acp-client chat --cwd /workspace --approve # auto-approve tool permissions
|
|
469
472
|
acp-client chat --degraded # force degraded (PTY) mode
|
|
@@ -473,6 +476,24 @@ acp-client chat --wire[=FILE] # dump every raw protocol line (stderr, or
|
|
|
473
476
|
|
|
474
477
|
Activity markers (thinking/tool) show by default; `--no-activity` disables them.
|
|
475
478
|
|
|
479
|
+
Presets are launch shortcuts, not provider definitions. For a custom harness,
|
|
480
|
+
`--adapter-command` accepts either one executable or a JSON argv array; `--pty-command`
|
|
481
|
+
optionally supplies its interactive/degraded counterpart, and `--adapter-name` sets a
|
|
482
|
+
display label. After launch, auth methods, capabilities, configuration, session support,
|
|
483
|
+
and harness commands are discovered over ACP exactly as they are for a preset.
|
|
484
|
+
|
|
485
|
+
The Pi preset expects the `pi-acp` executable installed by:
|
|
486
|
+
|
|
487
|
+
```bash
|
|
488
|
+
npm install -g @automatalabs/pi-acp
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
Alternatively, run it without a global install as a custom adapter:
|
|
492
|
+
|
|
493
|
+
```bash
|
|
494
|
+
acp-client chat --adapter pi --adapter-command '["npx","-y","@automatalabs/pi-acp"]'
|
|
495
|
+
```
|
|
496
|
+
|
|
476
497
|
---
|
|
477
498
|
|
|
478
499
|
## Package exports
|
package/package.json
CHANGED
package/src/adapters.ts
CHANGED
|
@@ -52,6 +52,9 @@ export const ADAPTERS = {
|
|
|
52
52
|
},
|
|
53
53
|
// verified — @agentclientprotocol/codex-acp. The `codex` CLI has no `acp` subcommand.
|
|
54
54
|
codex: { command: ["codex-acp"], ptyCommand: ["codex"], displayName: "Codex" },
|
|
55
|
+
// @automatalabs/pi-acp embeds Pi through its SDK and publishes the `pi-acp` binary.
|
|
56
|
+
// Pi itself remains the interactive PTY command for bridge/degraded mode.
|
|
57
|
+
pi: { command: ["pi-acp"], ptyCommand: ["pi"], displayName: "Pi" },
|
|
55
58
|
// Below: from each project's docs, not spawned here. Correct at time of writing, unverified.
|
|
56
59
|
gemini: { command: ["gemini", "--acp", "--stdio"], ptyCommand: ["gemini"], displayName: "Gemini" },
|
|
57
60
|
copilot: { command: ["copilot", "--acp", "--stdio"], ptyCommand: ["copilot"], displayName: "Copilot" },
|
package/src/agent-session.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { Capabilities } from "./capabilities.ts";
|
|
|
19
19
|
import type { ConfigOptions } from "./config-options.ts";
|
|
20
20
|
import type { ConnectResult } from "./client.ts";
|
|
21
21
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
22
|
+
import { ResponseAccumulator } from "./response.ts";
|
|
22
23
|
import type { SessionManager, MergedSession } from "./session-manager.ts";
|
|
23
24
|
import {
|
|
24
25
|
appendTranscriptLine,
|
|
@@ -638,6 +639,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
638
639
|
});
|
|
639
640
|
|
|
640
641
|
const chunks: string[] = [];
|
|
642
|
+
const response = new ResponseAccumulator();
|
|
641
643
|
const wrappedHandlers: PromptHandlers = {
|
|
642
644
|
...item.handlers,
|
|
643
645
|
// Fired from here, from the one aggregator this session owns — nothing below needs
|
|
@@ -647,6 +649,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
647
649
|
chunks.push(chunk);
|
|
648
650
|
item.handlers?.onChunk?.(chunk);
|
|
649
651
|
},
|
|
652
|
+
onResponseChunk: (chunk) => {
|
|
653
|
+
response.append(chunk);
|
|
654
|
+
item.handlers?.onResponseChunk?.(chunk);
|
|
655
|
+
},
|
|
650
656
|
onActivity: (event) => {
|
|
651
657
|
const result = this.aggregator.apply(event);
|
|
652
658
|
if (this.transcriptActivity) {
|
|
@@ -673,6 +679,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
673
679
|
t: "msg",
|
|
674
680
|
role: "assistant",
|
|
675
681
|
text: res.text,
|
|
682
|
+
messages: res.messages,
|
|
676
683
|
ts: Date.now(),
|
|
677
684
|
usage: res.usage,
|
|
678
685
|
stopReason: res.stopReason,
|
|
@@ -683,11 +690,19 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
683
690
|
// Easy to miss, and the whole point of R4: a turn that died mid-tool still records
|
|
684
691
|
// what it was doing, at its real status.
|
|
685
692
|
this.endTurn(item.handlers);
|
|
693
|
+
const text = chunks.join("");
|
|
694
|
+
const structured = response.snapshot();
|
|
695
|
+
const messages = structured.length > 0
|
|
696
|
+
? structured
|
|
697
|
+
: text
|
|
698
|
+
? Object.freeze([{ text }])
|
|
699
|
+
: Object.freeze([]);
|
|
686
700
|
await this.appendTranscript({
|
|
687
701
|
v: 1,
|
|
688
702
|
t: "msg",
|
|
689
703
|
role: "assistant",
|
|
690
|
-
text
|
|
704
|
+
text,
|
|
705
|
+
messages,
|
|
691
706
|
ts: Date.now(),
|
|
692
707
|
stopReason: "error",
|
|
693
708
|
status: "error",
|
|
@@ -789,7 +804,13 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
789
804
|
const dropped = this.queue.splice(0);
|
|
790
805
|
for (const item of dropped) {
|
|
791
806
|
if (item.kind === "prompt") {
|
|
792
|
-
item.resolve({
|
|
807
|
+
item.resolve({
|
|
808
|
+
text: "",
|
|
809
|
+
messages: Object.freeze([]),
|
|
810
|
+
stopReason: "cancelled",
|
|
811
|
+
status: "cancelled",
|
|
812
|
+
usage: null,
|
|
813
|
+
});
|
|
793
814
|
} else {
|
|
794
815
|
item.reject(new Error("handoff cancelled before it started"));
|
|
795
816
|
}
|
|
@@ -946,8 +967,12 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
946
967
|
|
|
947
968
|
/** Do not let one notification observer mutate the PromptResult another observer sees. */
|
|
948
969
|
function copyPromptResult(result: PromptResult): PromptResult {
|
|
970
|
+
const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
|
|
949
971
|
return Object.freeze({
|
|
950
972
|
...result,
|
|
973
|
+
messages: Object.freeze(
|
|
974
|
+
messages.map((message) => Object.freeze({ ...message })),
|
|
975
|
+
),
|
|
951
976
|
usage: result.usage ? Object.freeze({ ...result.usage }) : null,
|
|
952
977
|
});
|
|
953
978
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import { ADAPTERS, type Adapter } from "../adapters.ts";
|
|
3
|
+
|
|
4
|
+
export interface CliAdapterSelection {
|
|
5
|
+
/** Preset key, or the stable id assigned to a custom adapter. */
|
|
6
|
+
adapterId?: string;
|
|
7
|
+
/** Explicit ACP launch argv. When present, this takes precedence over presets. */
|
|
8
|
+
command?: string[];
|
|
9
|
+
/** Optional interactive launch argv for degraded mode and bridge. */
|
|
10
|
+
ptyCommand?: string[];
|
|
11
|
+
/** Optional custom display label. */
|
|
12
|
+
displayName?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ResolvedCliAdapter {
|
|
16
|
+
adapterId: string;
|
|
17
|
+
adapter: Adapter;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parse one CLI command value. A plain value represents one executable; commands with
|
|
22
|
+
* arguments use a JSON string array so paths and arguments containing spaces stay exact.
|
|
23
|
+
*/
|
|
24
|
+
export function parseCommandArg(value: string | undefined, flag: string): string[] {
|
|
25
|
+
if (!value?.trim()) throw new Error(`${flag} requires an executable or JSON argv array`);
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
if (!trimmed.startsWith("[")) return [trimmed];
|
|
28
|
+
|
|
29
|
+
let parsed: unknown;
|
|
30
|
+
try {
|
|
31
|
+
parsed = JSON.parse(trimmed);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
throw new Error(`${flag} must be valid JSON: ${String(error)}`);
|
|
34
|
+
}
|
|
35
|
+
if (
|
|
36
|
+
!Array.isArray(parsed) ||
|
|
37
|
+
parsed.length === 0 ||
|
|
38
|
+
parsed.some((part) => typeof part !== "string" || part.length === 0)
|
|
39
|
+
) {
|
|
40
|
+
throw new Error(`${flag} must be a non-empty JSON array of non-empty strings`);
|
|
41
|
+
}
|
|
42
|
+
return parsed;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Resolve a built-in preset or construct the custom adapter supplied by the CLI user. */
|
|
46
|
+
export function resolveCliAdapter(selection: CliAdapterSelection): ResolvedCliAdapter {
|
|
47
|
+
if (selection.command) {
|
|
48
|
+
if (selection.command.length === 0) throw new Error("custom adapter command cannot be empty");
|
|
49
|
+
const adapterId = selection.adapterId?.trim() || basename(selection.command[0]!) || "custom";
|
|
50
|
+
return {
|
|
51
|
+
adapterId,
|
|
52
|
+
adapter: {
|
|
53
|
+
command: [...selection.command],
|
|
54
|
+
...(selection.ptyCommand ? { ptyCommand: [...selection.ptyCommand] } : {}),
|
|
55
|
+
...(selection.displayName ? { displayName: selection.displayName } : {}),
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const adapterId = selection.adapterId?.trim() || "kimi";
|
|
61
|
+
if (!(adapterId in ADAPTERS)) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`unknown adapter preset: ${adapterId}; known presets: ${Object.keys(ADAPTERS).join(", ")}; ` +
|
|
64
|
+
"use --adapter-command for a custom ACP harness",
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const adapter = ADAPTERS[adapterId as keyof typeof ADAPTERS];
|
|
68
|
+
return { adapterId, adapter };
|
|
69
|
+
}
|
package/src/cli/index.ts
CHANGED
|
@@ -4,9 +4,11 @@
|
|
|
4
4
|
// See SPEC.md "library first, CLI second".
|
|
5
5
|
//
|
|
6
6
|
// Usage:
|
|
7
|
-
// acp-
|
|
7
|
+
// acp-client chat [SESSION_ID] [--adapter kimi] [--exec "docker exec -i <ctr>"]
|
|
8
8
|
// [--cwd /workspace] [--approve] [--verbose] [--debug]
|
|
9
9
|
// [--no-activity] [--degraded] [--wire[=FILE]]
|
|
10
|
+
// acp-client chat [--adapter ID] --adapter-command '["agent","--acp"]'
|
|
11
|
+
// [--pty-command '["agent"]'] [--adapter-name "My Agent"]
|
|
10
12
|
//
|
|
11
13
|
// activity (thinking/tool markers) shows by DEFAULT; --no-activity disables it.
|
|
12
14
|
// --verbose (-v): lifecycle summaries (connect, session_new, prompt_end)
|
|
@@ -16,18 +18,21 @@
|
|
|
16
18
|
|
|
17
19
|
import {
|
|
18
20
|
AgentController,
|
|
19
|
-
ADAPTERS,
|
|
20
21
|
createConsoleLogger,
|
|
21
22
|
createWireLog,
|
|
22
|
-
type
|
|
23
|
+
type Adapter,
|
|
23
24
|
} from "../index.ts";
|
|
24
25
|
import { createControllerCommands, runRepl } from "../repl/index.ts";
|
|
25
26
|
import { DIM, colorEnabled, paint } from "../repl/colors.ts";
|
|
27
|
+
import { parseCommandArg, resolveCliAdapter } from "./adapter.ts";
|
|
26
28
|
|
|
27
29
|
interface Args {
|
|
28
30
|
command: string;
|
|
29
31
|
sessionId?: string;
|
|
30
|
-
|
|
32
|
+
adapterId?: string;
|
|
33
|
+
adapterCommand?: string[];
|
|
34
|
+
ptyCommand?: string[];
|
|
35
|
+
adapterName?: string;
|
|
31
36
|
execPrefix: string[];
|
|
32
37
|
cwd?: string;
|
|
33
38
|
degraded: boolean;
|
|
@@ -42,7 +47,6 @@ interface Args {
|
|
|
42
47
|
function parseArgs(argv: string[]): Args {
|
|
43
48
|
const a: Args = {
|
|
44
49
|
command: argv[0] ?? "chat",
|
|
45
|
-
adapter: "kimi",
|
|
46
50
|
execPrefix: [],
|
|
47
51
|
degraded: false,
|
|
48
52
|
approve: false,
|
|
@@ -52,7 +56,14 @@ function parseArgs(argv: string[]): Args {
|
|
|
52
56
|
};
|
|
53
57
|
for (let i = 1; i < argv.length; i++) {
|
|
54
58
|
const arg = argv[i];
|
|
55
|
-
if (arg === "--adapter") a.
|
|
59
|
+
if (arg === "--adapter") a.adapterId = argv[++i];
|
|
60
|
+
else if (arg === "--adapter-command") {
|
|
61
|
+
a.adapterCommand = parseCommandArg(argv[++i], "--adapter-command");
|
|
62
|
+
}
|
|
63
|
+
else if (arg === "--pty-command") {
|
|
64
|
+
a.ptyCommand = parseCommandArg(argv[++i], "--pty-command");
|
|
65
|
+
}
|
|
66
|
+
else if (arg === "--adapter-name") a.adapterName = argv[++i];
|
|
56
67
|
else if (arg === "--exec") a.execPrefix = (argv[++i] ?? "").split(" ").filter(Boolean);
|
|
57
68
|
else if (arg === "--cwd") a.cwd = argv[++i];
|
|
58
69
|
else if (arg === "--degraded") a.degraded = true;
|
|
@@ -85,9 +96,16 @@ async function chat(args: Args): Promise<void> {
|
|
|
85
96
|
: createWireLog({ path: args.wire });
|
|
86
97
|
if (args.wire) process.stderr.write(`wire log: ${args.wire}\n`);
|
|
87
98
|
|
|
99
|
+
const resolved = resolveCliAdapter({
|
|
100
|
+
adapterId: args.adapterId,
|
|
101
|
+
command: args.adapterCommand,
|
|
102
|
+
ptyCommand: args.ptyCommand,
|
|
103
|
+
displayName: args.adapterName,
|
|
104
|
+
});
|
|
105
|
+
const adapter: Adapter = resolved.adapter;
|
|
88
106
|
const controller = new AgentController({
|
|
89
|
-
adapter
|
|
90
|
-
adapterId:
|
|
107
|
+
adapter,
|
|
108
|
+
adapterId: resolved.adapterId,
|
|
91
109
|
mode: args.degraded ? "degraded" : "normal",
|
|
92
110
|
execPrefix: args.execPrefix,
|
|
93
111
|
cwd: args.cwd,
|
|
@@ -98,7 +116,7 @@ async function chat(args: Args): Promise<void> {
|
|
|
98
116
|
});
|
|
99
117
|
|
|
100
118
|
const { sessionId, resumed } = await controller.start();
|
|
101
|
-
const label =
|
|
119
|
+
const label = adapter.displayName ?? resolved.adapterId;
|
|
102
120
|
const intro = controller.isDegraded
|
|
103
121
|
? `degraded (pty) session (${label}) — no ACP capabilities · /exit to quit, Ctrl-C to interrupt`
|
|
104
122
|
: `${resumed ? "resumed" : "new"} session ${sessionId} (${label}) — ` +
|
|
@@ -107,7 +125,12 @@ async function chat(args: Args): Promise<void> {
|
|
|
107
125
|
const color = colorEnabled(process.stderr);
|
|
108
126
|
const note = (s: string) => process.stderr.write(paint(color, DIM, s) + "\n");
|
|
109
127
|
|
|
110
|
-
const commands = createControllerCommands({
|
|
128
|
+
const commands = createControllerCommands({
|
|
129
|
+
client: controller,
|
|
130
|
+
note,
|
|
131
|
+
color,
|
|
132
|
+
adapterId: resolved.adapterId,
|
|
133
|
+
});
|
|
111
134
|
|
|
112
135
|
try {
|
|
113
136
|
await runRepl(controller, {
|
package/src/client.ts
CHANGED
|
@@ -18,7 +18,8 @@ import {
|
|
|
18
18
|
type ClientCapabilityConfig,
|
|
19
19
|
} from "./capabilities.ts";
|
|
20
20
|
import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
|
|
21
|
-
import {
|
|
21
|
+
import { extractResponseChunk, toActivityEvent, toAvailableCommands } from "./updates.ts";
|
|
22
|
+
import { ResponseAccumulator } from "./response.ts";
|
|
22
23
|
import { TerminalRegistry } from "./terminals.ts";
|
|
23
24
|
import { readTextFile, writeTextFile } from "./fs-access.ts";
|
|
24
25
|
import { NotConnectedError } from "./errors.ts";
|
|
@@ -129,7 +130,7 @@ export class AcpClient implements AgentClient {
|
|
|
129
130
|
|
|
130
131
|
// Per-turn streaming state (only the in-flight turn).
|
|
131
132
|
private active: {
|
|
132
|
-
|
|
133
|
+
response: ResponseAccumulator;
|
|
133
134
|
handlers?: PromptHandlers;
|
|
134
135
|
cancelled: boolean;
|
|
135
136
|
} | null = null;
|
|
@@ -592,7 +593,11 @@ export class AcpClient implements AgentClient {
|
|
|
592
593
|
}
|
|
593
594
|
if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
|
|
594
595
|
|
|
595
|
-
this.active = {
|
|
596
|
+
this.active = {
|
|
597
|
+
response: new ResponseAccumulator(),
|
|
598
|
+
handlers: item.handlers,
|
|
599
|
+
cancelled: false,
|
|
600
|
+
};
|
|
596
601
|
const t0 = Date.now();
|
|
597
602
|
this.log.debug("prompt_start", { chars: item.text.length });
|
|
598
603
|
this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
|
|
@@ -604,7 +609,8 @@ export class AcpClient implements AgentClient {
|
|
|
604
609
|
this.log.debug("prompt_response", { response: res });
|
|
605
610
|
|
|
606
611
|
const cancelled = this.active.cancelled;
|
|
607
|
-
const text = this.active.
|
|
612
|
+
const text = this.active.response.text;
|
|
613
|
+
const messages = this.active.response.snapshot();
|
|
608
614
|
this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
|
|
609
615
|
stopReason: res.stopReason,
|
|
610
616
|
status: cancelled ? "cancelled" : "completed",
|
|
@@ -613,6 +619,7 @@ export class AcpClient implements AgentClient {
|
|
|
613
619
|
});
|
|
614
620
|
return {
|
|
615
621
|
text,
|
|
622
|
+
messages,
|
|
616
623
|
stopReason: res.stopReason,
|
|
617
624
|
status: cancelled ? "cancelled" : "completed",
|
|
618
625
|
usage: (res.usage ?? null) as PromptResult["usage"],
|
|
@@ -626,7 +633,13 @@ export class AcpClient implements AgentClient {
|
|
|
626
633
|
if (options.clearQueue) {
|
|
627
634
|
const dropped = this.queue.splice(0);
|
|
628
635
|
for (const item of dropped) {
|
|
629
|
-
item.resolve({
|
|
636
|
+
item.resolve({
|
|
637
|
+
text: "",
|
|
638
|
+
messages: Object.freeze([]),
|
|
639
|
+
stopReason: "cancelled",
|
|
640
|
+
status: "cancelled",
|
|
641
|
+
usage: null,
|
|
642
|
+
});
|
|
630
643
|
}
|
|
631
644
|
}
|
|
632
645
|
if (this.active && this.transport && this._sessionId) {
|
|
@@ -687,10 +700,11 @@ export class AcpClient implements AgentClient {
|
|
|
687
700
|
|
|
688
701
|
this.active.handlers?.onUpdate?.(notification);
|
|
689
702
|
|
|
690
|
-
const
|
|
691
|
-
if (
|
|
692
|
-
this.active.
|
|
693
|
-
this.active.handlers?.
|
|
703
|
+
const responseChunk = extractResponseChunk(update);
|
|
704
|
+
if (responseChunk) {
|
|
705
|
+
const chunk = this.active.response.append(responseChunk);
|
|
706
|
+
this.active.handlers?.onResponseChunk?.(chunk);
|
|
707
|
+
this.active.handlers?.onChunk?.(chunk.text);
|
|
694
708
|
}
|
|
695
709
|
const activity = toActivityEvent(update);
|
|
696
710
|
if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
|
|
@@ -277,12 +277,16 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
277
277
|
}
|
|
278
278
|
|
|
279
279
|
const status = turn.cancelled ? "cancelled" : "completed";
|
|
280
|
-
|
|
280
|
+
const messages = text ? Object.freeze([{ text }]) : Object.freeze([]);
|
|
281
|
+
if (text) {
|
|
282
|
+
turn.handlers?.onResponseChunk?.({ text, startsMessage: true });
|
|
283
|
+
turn.handlers?.onChunk?.(text);
|
|
284
|
+
}
|
|
281
285
|
this.log[text.length === 0 && !turn.cancelled ? "warn" : "info"]("pty_turn_end", {
|
|
282
286
|
status,
|
|
283
287
|
chars: text.length,
|
|
284
288
|
});
|
|
285
|
-
turn.resolve({ text, stopReason, status, usage: null });
|
|
289
|
+
turn.resolve({ text, messages, stopReason, status, usage: null });
|
|
286
290
|
}
|
|
287
291
|
|
|
288
292
|
/** Resolve once the screen has been idle for settleMs (used to drain the banner). */
|
package/src/index.ts
CHANGED
|
@@ -69,7 +69,7 @@ export type {
|
|
|
69
69
|
TerminalRegistryOptions,
|
|
70
70
|
} from "./terminals.ts";
|
|
71
71
|
|
|
72
|
-
export { extractChunkText, toActivityEvent } from "./updates.ts";
|
|
72
|
+
export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
|
|
73
73
|
|
|
74
74
|
export {
|
|
75
75
|
ActivityAggregator,
|
|
@@ -132,6 +132,8 @@ export type { Logger, LogLevel, ConsoleLoggerOptions } from "./logger.ts";
|
|
|
132
132
|
export type {
|
|
133
133
|
PromptResult,
|
|
134
134
|
PromptHandlers,
|
|
135
|
+
ResponseChunk,
|
|
136
|
+
ResponseMessage,
|
|
135
137
|
ActivityEvent,
|
|
136
138
|
ToolActivity,
|
|
137
139
|
ToolUpdateActivity,
|
package/src/response.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { ResponseChunk, ResponseMessage } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
export interface IncomingResponseChunk {
|
|
4
|
+
text: string;
|
|
5
|
+
messageId?: string;
|
|
6
|
+
/** Supplied when an upstream client already resolved the boundary. */
|
|
7
|
+
startsMessage?: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Fold response deltas without inventing separators. Only a change between two explicit
|
|
12
|
+
* ACP message ids proves that a new assistant message started; missing ids remain part of
|
|
13
|
+
* the current message because no boundary can be inferred safely.
|
|
14
|
+
*/
|
|
15
|
+
export class ResponseAccumulator {
|
|
16
|
+
private readonly entries: Array<{ messageId?: string; text: string }> = [];
|
|
17
|
+
|
|
18
|
+
append(chunk: IncomingResponseChunk): ResponseChunk {
|
|
19
|
+
let current = this.entries.at(-1);
|
|
20
|
+
const inferredStart =
|
|
21
|
+
!current ||
|
|
22
|
+
(chunk.messageId !== undefined &&
|
|
23
|
+
current.messageId !== undefined &&
|
|
24
|
+
chunk.messageId !== current.messageId);
|
|
25
|
+
// The first observed chunk necessarily starts our first entry, even if a malformed
|
|
26
|
+
// upstream callback says otherwise.
|
|
27
|
+
const startsMessage = !current || (chunk.startsMessage ?? inferredStart);
|
|
28
|
+
|
|
29
|
+
if (startsMessage) {
|
|
30
|
+
current = chunk.messageId === undefined
|
|
31
|
+
? { text: chunk.text }
|
|
32
|
+
: { messageId: chunk.messageId, text: chunk.text };
|
|
33
|
+
this.entries.push(current);
|
|
34
|
+
} else {
|
|
35
|
+
const entry = current!;
|
|
36
|
+
if (entry.messageId === undefined && chunk.messageId !== undefined) {
|
|
37
|
+
entry.messageId = chunk.messageId;
|
|
38
|
+
}
|
|
39
|
+
entry.text += chunk.text;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return chunk.messageId === undefined
|
|
43
|
+
? { text: chunk.text, startsMessage }
|
|
44
|
+
: { text: chunk.text, messageId: chunk.messageId, startsMessage };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get text(): string {
|
|
48
|
+
return this.entries.map((entry) => entry.text).join("");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
snapshot(): readonly ResponseMessage[] {
|
|
52
|
+
return Object.freeze(
|
|
53
|
+
this.entries.map((entry) => Object.freeze({ ...entry })),
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/transcript.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
// - `t:"msg"` DELIMITS A TURN. A turn is `msg(user) → activity… → msg(assistant)`; writes
|
|
8
8
|
// serialize in call order, so that nesting always holds. A trailing user message with no
|
|
9
9
|
// assistant message after it means the turn DIED IN FLIGHT (crash, kill, cancel) — the
|
|
10
|
-
// activity lines inside it are the record of what it was doing.
|
|
10
|
+
// activity lines inside it are the record of what it was doing. Assistant lines retain
|
|
11
|
+
// their legacy flat `text` and may also carry structured `messages` with ACP boundaries.
|
|
11
12
|
// - `t:"activity"` lines are SETTLED RECORDS, not raw deltas. FOLD THEM LAST-WINS ON
|
|
12
13
|
// `recordId` — `foldRecords()` from `./activity.ts` is exactly that, and is the only
|
|
13
14
|
// supported way to read them. A tool call normally writes 2–3 lines (announced → input →
|
|
@@ -31,7 +32,7 @@
|
|
|
31
32
|
import { appendFile, mkdir, open, readFile, type FileHandle } from "node:fs/promises";
|
|
32
33
|
import { dirname } from "node:path";
|
|
33
34
|
import { foldRecords, type AggregatedRecord, type EmitReason } from "./activity.ts";
|
|
34
|
-
import type { ActivityEvent, PromptResult, Usage } from "./types.ts";
|
|
35
|
+
import type { ActivityEvent, PromptResult, ResponseMessage, Usage } from "./types.ts";
|
|
35
36
|
|
|
36
37
|
export type TranscriptRole = "user" | "assistant";
|
|
37
38
|
|
|
@@ -49,6 +50,8 @@ export interface TranscriptMessageLine {
|
|
|
49
50
|
t: "msg";
|
|
50
51
|
role: TranscriptRole;
|
|
51
52
|
text: string;
|
|
53
|
+
/** Assistant-message boundaries when supplied by the live client. */
|
|
54
|
+
messages?: readonly ResponseMessage[];
|
|
52
55
|
ts: number;
|
|
53
56
|
usage?: Usage | null;
|
|
54
57
|
stopReason?: string;
|
|
@@ -359,7 +362,9 @@ function isTranscriptLine(value: unknown): value is TranscriptLine {
|
|
|
359
362
|
case "msg":
|
|
360
363
|
return (
|
|
361
364
|
(value.role === "user" || value.role === "assistant") &&
|
|
362
|
-
typeof value.text === "string"
|
|
365
|
+
typeof value.text === "string" &&
|
|
366
|
+
(value.messages === undefined ||
|
|
367
|
+
(Array.isArray(value.messages) && value.messages.every(isResponseMessage)))
|
|
363
368
|
);
|
|
364
369
|
case "activity":
|
|
365
370
|
return typeof value.kind === "string";
|
|
@@ -381,6 +386,14 @@ function isTranscriptLine(value: unknown): value is TranscriptLine {
|
|
|
381
386
|
}
|
|
382
387
|
}
|
|
383
388
|
|
|
389
|
+
function isResponseMessage(value: unknown): value is ResponseMessage {
|
|
390
|
+
return (
|
|
391
|
+
isRecord(value) &&
|
|
392
|
+
typeof value.text === "string" &&
|
|
393
|
+
(value.messageId === undefined || typeof value.messageId === "string")
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
|
|
384
397
|
function isTranscriptMessageLine(value: TranscriptLine): value is TranscriptMessageLine {
|
|
385
398
|
return value.t === "msg";
|
|
386
399
|
}
|
package/src/types.ts
CHANGED
|
@@ -39,14 +39,30 @@ export interface Usage {
|
|
|
39
39
|
* call RESOLVES (not rejects) with whatever partial text arrived.
|
|
40
40
|
*/
|
|
41
41
|
export interface PromptResult {
|
|
42
|
-
/**
|
|
42
|
+
/** Legacy flattened projection of `messages` (partial if cancelled). */
|
|
43
43
|
text: string;
|
|
44
|
+
/** Assistant messages in protocol order, preserving ACP `messageId` boundaries. */
|
|
45
|
+
messages: readonly ResponseMessage[];
|
|
44
46
|
/** Raw protocol stop reason: "end_turn" | "cancelled" | "max_tokens" | ... */
|
|
45
47
|
stopReason: string;
|
|
46
48
|
status: "completed" | "cancelled" | "error";
|
|
47
49
|
usage: Usage | null;
|
|
48
50
|
}
|
|
49
51
|
|
|
52
|
+
/** One boundary-aware delta from an ACP `agent_message_chunk`. */
|
|
53
|
+
export interface ResponseChunk {
|
|
54
|
+
text: string;
|
|
55
|
+
messageId?: string;
|
|
56
|
+
/** True when this chunk begins a new assistant message. */
|
|
57
|
+
startsMessage: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One assistant message assembled from consecutive ACP response chunks. */
|
|
61
|
+
export interface ResponseMessage {
|
|
62
|
+
messageId?: string;
|
|
63
|
+
text: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
50
66
|
/**
|
|
51
67
|
* One line of raw traffic between us and the agent process — the debugging view.
|
|
52
68
|
*
|
|
@@ -203,8 +219,10 @@ export interface PermissionRequest {
|
|
|
203
219
|
|
|
204
220
|
/** Per-prompt callbacks. All optional. */
|
|
205
221
|
export interface PromptHandlers {
|
|
206
|
-
/**
|
|
222
|
+
/** Legacy text-only response stream. Prefer `onResponseChunk` when boundaries matter. */
|
|
207
223
|
onChunk?: (text: string) => void;
|
|
224
|
+
/** Boundary-aware response stream preserving ACP `messageId`. */
|
|
225
|
+
onResponseChunk?: (chunk: ResponseChunk) => void;
|
|
208
226
|
/** Observation-only activity (thinking, tool calls, plan) as RAW protocol deltas. */
|
|
209
227
|
onActivity?: (event: ActivityEvent) => void;
|
|
210
228
|
/**
|
package/src/updates.ts
CHANGED
|
@@ -18,14 +18,26 @@ import type {
|
|
|
18
18
|
ToolContent,
|
|
19
19
|
ToolLocation,
|
|
20
20
|
ToolUpdateActivity,
|
|
21
|
+
ResponseChunk,
|
|
21
22
|
} from "./types.ts";
|
|
22
23
|
|
|
23
|
-
/**
|
|
24
|
-
export function
|
|
24
|
+
/** A response delta preserving its ACP message id, or null for any other update. */
|
|
25
|
+
export function extractResponseChunk(
|
|
26
|
+
update: schema.SessionUpdate,
|
|
27
|
+
): Omit<ResponseChunk, "startsMessage"> | null {
|
|
25
28
|
const u = update as Record<string, any>;
|
|
26
|
-
if (u.sessionUpdate !== "agent_message_chunk") return
|
|
29
|
+
if (u.sessionUpdate !== "agent_message_chunk") return null;
|
|
27
30
|
const content = u.content;
|
|
28
|
-
|
|
31
|
+
const text = content?.type === "text" ? (content.text ?? "") : "";
|
|
32
|
+
if (!text) return null;
|
|
33
|
+
return u.messageId == null
|
|
34
|
+
? { text }
|
|
35
|
+
: { text, messageId: String(u.messageId) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @deprecated Prefer `extractResponseChunk` when message boundaries matter. */
|
|
39
|
+
export function extractChunkText(update: schema.SessionUpdate): string {
|
|
40
|
+
return extractResponseChunk(update)?.text ?? "";
|
|
29
41
|
}
|
|
30
42
|
|
|
31
43
|
/** Map an update to an ActivityEvent, or null if it carries no observable activity. */
|