@qlairoslabs/acp-client 0.3.4 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  // interactive consumer (CLI, hub terminal mode, etc).
4
4
  //
5
5
  // Usage:
6
- // const { onSlashCommand } = createAgentCommands({ client, note, color });
6
+ // const { onSlashCommand } = createControllerCommands({ client, note, color });
7
7
  // await runRepl(client, { onSlashCommand });
8
8
 
9
9
  import type {
@@ -21,14 +21,14 @@ import type {
21
21
  SwitchSessionOptions,
22
22
  } from "../index.ts";
23
23
  import type {
24
- AgentCommand,
24
+ InternalSessionCommand,
25
25
  SessionListEntry,
26
26
  SessionListPage,
27
27
  } from "../types.ts";
28
28
  import type { SessionManager, MergedSession } from "../session-manager.ts";
29
29
 
30
30
  /** The control-plane surface required by the reusable slash commands. */
31
- export interface InteractiveAgentClient extends AgentClient, Bridgeable {
31
+ export interface InteractiveControllerClient extends AgentClient, Bridgeable {
32
32
  /** Optional durable AgentSession identity, when the client is session-backed. */
33
33
  readonly agentSessionId?: string;
34
34
  readonly currentAdapterId: string;
@@ -38,7 +38,7 @@ export interface InteractiveAgentClient extends AgentClient, Bridgeable {
38
38
  readonly isDegraded: boolean;
39
39
  readonly capabilities: Capabilities;
40
40
  readonly authMethods: AuthMethod[];
41
- readonly agentCommands: AgentCommand[];
41
+ readonly availableCommands: readonly InternalSessionCommand[];
42
42
  readonly configOptions: ConfigOptions;
43
43
 
44
44
  getCommands(): ControllerCommand[];
@@ -71,9 +71,9 @@ export interface InteractiveAgentClient extends AgentClient, Bridgeable {
71
71
  ): Promise<SetConfigFromStringResult>;
72
72
  }
73
73
 
74
- export interface CommandHandlerDeps {
74
+ export interface ControllerCommandHandlerDeps {
75
75
  /** Prompt client plus the interactive control-plane operations used by commands. */
76
- client: InteractiveAgentClient;
76
+ client: InteractiveControllerClient;
77
77
  /** Output sink for command responses. */
78
78
  note: (msg: string) => void;
79
79
  /** Whether to emit color codes. Default false. */
@@ -84,16 +84,18 @@ export interface CommandHandlerDeps {
84
84
  adapterId?: string;
85
85
  }
86
86
 
87
- /** Return value from createAgentCommands. */
88
- export interface AgentCommands {
87
+ /** Local command handlers for the low-level AgentController REPL. */
88
+ export interface ControllerCommandHandlers {
89
89
  onSlashCommand: (command: string, args: string[]) => Promise<boolean>;
90
90
  }
91
91
 
92
92
  /**
93
- * Create a reusable slash-command handler for interactive REPL sessions.
94
- * Handles /help, /login, /new, /sessions, /load, etc.
93
+ * Create the legacy low-level AgentController command set. It changes ACP provider
94
+ * sessions directly (/new, /load, /resume, /fork); it does not manage AgentSessions.
95
95
  */
96
- export function createAgentCommands(deps: CommandHandlerDeps): AgentCommands {
96
+ export function createControllerCommands(
97
+ deps: ControllerCommandHandlerDeps,
98
+ ): ControllerCommandHandlers {
97
99
  const { client, note, color = false, sessionManager, adapterId } = deps;
98
100
 
99
101
  const recordSession = async (internalSessionId: string | null): Promise<void> => {
@@ -118,11 +120,11 @@ export function createAgentCommands(deps: CommandHandlerDeps): AgentCommands {
118
120
  `commands: /help ${client.getCommands().map((c) => c.usage).join(" ")} ` +
119
121
  `/degrade /upgrade /exit`,
120
122
  );
121
- const agentCmds = client.agentCommands;
122
- if (agentCmds.length > 0) {
123
- note(`agent commands (send with //name): ${agentCmds.map((c: AgentCommand) => `/${c.name}`).join(" ")}`);
123
+ const availableCommands = client.availableCommands;
124
+ if (availableCommands.length > 0) {
125
+ note(`internal session commands (send with //name): ${availableCommands.map((c: InternalSessionCommand) => `/${c.name}`).join(" ")}`);
124
126
  } else if (!client.isDegraded) {
125
- note("agent commands: (none advertised) — //name still forwards a /name to the agent");
127
+ note("internal session commands: (none advertised) — //name still forwards a /name to the agent");
126
128
  } else {
127
129
  note("//name forwards a /name slash command to the agent's TUI");
128
130
  }
@@ -340,7 +342,7 @@ export function createAgentCommands(deps: CommandHandlerDeps): AgentCommands {
340
342
  return true;
341
343
  }
342
344
  default:
343
- return false; // unknown → treat as a normal prompt
345
+ return false; // generic REPL reports an unknown local command
344
346
  }
345
347
  };
346
348
 
package/src/repl/index.ts CHANGED
@@ -1,9 +1,17 @@
1
- export { createAgentCommands } from "./commands.ts";
1
+ export { createControllerCommands } from "./commands.ts";
2
2
  export type {
3
- AgentCommands,
4
- CommandHandlerDeps,
5
- InteractiveAgentClient,
3
+ ControllerCommandHandlers,
4
+ ControllerCommandHandlerDeps,
5
+ InteractiveControllerClient,
6
6
  } from "./commands.ts";
7
7
 
8
- export { runRepl } from "./repl.ts";
9
- export type { ReplOptions } from "./repl.ts";
8
+ export { createAgentSessionCommands, runAgentSessionRepl } from "./agent-session-commands.ts";
9
+ export type {
10
+ AgentSessionCommandHandlerDeps,
11
+ AgentSessionCommandHandlers,
12
+ AgentSessionReplOptions,
13
+ InteractiveAgentSession,
14
+ } from "./agent-session-commands.ts";
15
+
16
+ export { dispatchReplInput, parseReplInput, runRepl } from "./repl.ts";
17
+ export type { ReplInput, ReplInputActions, ReplOptions } from "./repl.ts";
package/src/repl/repl.ts CHANGED
@@ -19,7 +19,12 @@
19
19
  // and a fresh-per-line interface there would drop buffered lines.
20
20
 
21
21
  import * as readline from "node:readline";
22
- import type { AgentClient, ActivityEvent } from "../index.ts";
22
+ import type {
23
+ AgentClient,
24
+ ActivityEvent,
25
+ PromptHandlers,
26
+ PromptResult,
27
+ } from "../index.ts";
23
28
  import { BOLD, CYAN, DIM, colorEnabled, paint } from "./colors.ts";
24
29
 
25
30
  const ESC = 0x1b;
@@ -34,14 +39,83 @@ export interface ReplOptions {
34
39
  /** Optional line printed (stderr) before the loop starts. Styled by the REPL. */
35
40
  intro?: string;
36
41
  /**
37
- * Handle a `/slash` command. Return true if handled (the loop continues without
38
- * prompting the agent); return false to treat the line as a normal prompt.
42
+ * Handle a local `/slash` command. Return true if handled. Returning false reports an
43
+ * unknown local command; slash-prefixed input is never silently treated as a prompt.
39
44
  * `/exit` and `/quit` are always handled by the REPL itself.
40
45
  *
41
46
  * Extension seam for consumers (e.g. the orchestration hub's direct mode): add
42
47
  * `/new`, `/model`, `/switch`, etc. without forking the REPL.
43
48
  */
44
49
  onSlashCommand?: (command: string, args: string[]) => boolean | Promise<boolean>;
50
+ /**
51
+ * Execute an explicit `//name [input]` command against the active internal session.
52
+ * When omitted, the generic REPL sends the equivalent `/name [input]` prompt directly.
53
+ * `runAgentSessionRepl()` supplies this using executeInternalSessionCommand().
54
+ */
55
+ onInternalSessionCommand?: (
56
+ command: string,
57
+ input: string | undefined,
58
+ handlers: PromptHandlers,
59
+ ) => Promise<PromptResult>;
60
+ }
61
+
62
+ export type ReplInput =
63
+ | { kind: "exit" }
64
+ | { kind: "prompt"; text: string }
65
+ | { kind: "local_command"; command: string; args: string[] }
66
+ | { kind: "internal_session_command"; command: string; input?: string };
67
+
68
+ /** Pure syntax split used by both interactive paths and pinned independently in tests. */
69
+ export function parseReplInput(raw: string): ReplInput {
70
+ const line = raw.trim();
71
+ if (line === "/exit" || line === "/quit") return { kind: "exit" };
72
+ if (line.startsWith("//")) {
73
+ const body = line.slice(2).trim();
74
+ const separator = body.search(/\s/);
75
+ if (separator < 0) return { kind: "internal_session_command", command: body };
76
+ const input = body.slice(separator).trim();
77
+ return {
78
+ kind: "internal_session_command",
79
+ command: body.slice(0, separator),
80
+ ...(input ? { input } : {}),
81
+ };
82
+ }
83
+ if (line.startsWith("/")) {
84
+ const [command = "", ...args] = line.slice(1).split(/\s+/);
85
+ return { kind: "local_command", command, args };
86
+ }
87
+ return { kind: "prompt", text: line };
88
+ }
89
+
90
+ export interface ReplInputActions {
91
+ prompt(text: string): Promise<void>;
92
+ localCommand(command: string, args: string[]): Promise<boolean>;
93
+ internalSessionCommand(command: string, input: string | undefined): Promise<void>;
94
+ unknownLocalCommand(command: string): void;
95
+ missingInternalSessionCommand(): void;
96
+ }
97
+
98
+ /** Execute one classified input without any terminal dependency. Returns false on exit. */
99
+ export async function dispatchReplInput(
100
+ input: ReplInput,
101
+ actions: ReplInputActions,
102
+ ): Promise<boolean> {
103
+ switch (input.kind) {
104
+ case "exit":
105
+ return false;
106
+ case "prompt":
107
+ await actions.prompt(input.text);
108
+ return true;
109
+ case "internal_session_command":
110
+ if (!input.command) actions.missingInternalSessionCommand();
111
+ else await actions.internalSessionCommand(input.command, input.input);
112
+ return true;
113
+ case "local_command":
114
+ if (!await actions.localCommand(input.command, input.args)) {
115
+ actions.unknownLocalCommand(input.command);
116
+ }
117
+ return true;
118
+ }
45
119
  }
46
120
 
47
121
  export async function runRepl(
@@ -63,28 +137,38 @@ export async function runRepl(
63
137
  let busy = false;
64
138
 
65
139
  // ---- handle one accepted line; returns true to keep looping, false to exit ----
66
- const handleLine = async (line: string): Promise<boolean> => {
67
- if (line === "/exit" || line === "/quit") return false;
68
- // `//foo` = verbatim passthrough: send `/foo` to the AGENT as a prompt (its own slash
69
- // command), bypassing our handlers. The escape hatch for name clashes like /sessions.
70
- if (line.startsWith("//")) {
71
- await runTurn(line.slice(1));
72
- return true;
73
- }
74
- if (line.startsWith("/") && options.onSlashCommand) {
75
- const [command = "", ...rest] = line.slice(1).split(/\s+/);
76
- try {
77
- if (await options.onSlashCommand(command, rest)) return true;
78
- } catch (e) {
79
- // A failing command (e.g. /load on a session with no rollout) must not crash the REPL.
80
- err(paint(color, DIM, `(/${command} failed: ${String(e)})`) + "\n");
81
- return true;
82
- }
83
- // not handled → fall through and send it as a normal prompt
84
- }
85
- await runTurn(line);
86
- return true;
87
- };
140
+ const handleLine = (line: string): Promise<boolean> =>
141
+ dispatchReplInput(parseReplInput(line), {
142
+ prompt: (text) => runTurn(text),
143
+ internalSessionCommand: (command, input) => {
144
+ const promptText = `/${command}${input ? ` ${input}` : ""}`;
145
+ return runTurn(
146
+ promptText,
147
+ options.onInternalSessionCommand
148
+ ? (handlers) => options.onInternalSessionCommand!(command, input, handlers)
149
+ : undefined,
150
+ );
151
+ },
152
+ missingInternalSessionCommand: () => {
153
+ err(paint(color, DIM, "(internal session command name is required after //)") + "\n");
154
+ },
155
+ localCommand: async (command, args) => {
156
+ try {
157
+ return await options.onSlashCommand?.(command, args) === true;
158
+ } catch (e) {
159
+ // A failing command must not crash the REPL or become a harness prompt.
160
+ err(paint(color, DIM, `(/${command} failed: ${String(e)})`) + "\n");
161
+ return true;
162
+ }
163
+ },
164
+ unknownLocalCommand: (command) => err(
165
+ paint(
166
+ color,
167
+ DIM,
168
+ `(unknown local command: /${command || "(empty)"}; use //name for an internal-session command)`,
169
+ ) + "\n",
170
+ ),
171
+ });
88
172
 
89
173
  try {
90
174
  if (interactive) await runInteractive(prompt, handleLine);
@@ -174,7 +258,10 @@ export async function runRepl(
174
258
  }
175
259
 
176
260
  // ---- one turn ------------------------------------------------------------------
177
- async function runTurn(text: string): Promise<void> {
261
+ async function runTurn(
262
+ text: string,
263
+ execute?: (handlers: PromptHandlers) => Promise<PromptResult>,
264
+ ): Promise<void> {
178
265
  let wroteLabel = false;
179
266
  let lastMarker = "";
180
267
  let sawActivity = false;
@@ -220,7 +307,8 @@ export async function runRepl(
220
307
 
221
308
  busy = true;
222
309
  try {
223
- const result = await client.prompt(text, { onChunk, onActivity });
310
+ const handlers: PromptHandlers = { onChunk, onActivity };
311
+ const result = await (execute ? execute(handlers) : client.prompt(text, handlers));
224
312
  spinner?.stop();
225
313
 
226
314
  if (wroteLabel) {
@@ -18,6 +18,7 @@ export interface MergedSession {
18
18
  mode?: "normal" | "degraded";
19
19
  cwd?: string;
20
20
  title?: string;
21
+ transcriptPath?: string;
21
22
  updatedAt?: string;
22
23
  source: "catalog" | "agent" | "both";
23
24
  }
@@ -91,6 +92,7 @@ export function mergeSessions(
91
92
  mode: rec.mode,
92
93
  cwd: e.cwd ?? rec.cwd,
93
94
  title: e.title ?? rec.title,
95
+ transcriptPath: rec.transcriptPath,
94
96
  updatedAt: e.updatedAt ?? rec.updatedAt,
95
97
  source: "both",
96
98
  });
@@ -117,6 +119,7 @@ export function mergeSessions(
117
119
  mode: r.mode,
118
120
  cwd: r.cwd,
119
121
  title: r.title,
122
+ transcriptPath: r.transcriptPath,
120
123
  updatedAt: r.updatedAt,
121
124
  source: "catalog",
122
125
  });
@@ -25,9 +25,10 @@ export interface SessionRecord {
25
25
  mode: "normal" | "degraded";
26
26
  cwd?: string;
27
27
  title?: string;
28
+ /** Resolved logical transcript location, when history persistence is enabled. */
29
+ transcriptPath?: string;
28
30
  createdAt: string;
29
31
  updatedAt: string;
30
- // (transcript storage slots in here later without breaking the schema.)
31
32
  }
32
33
 
33
34
  export interface SessionStore {
package/src/transcript.ts CHANGED
@@ -21,6 +21,10 @@
21
21
  // written final line (torn write) costs that line only.
22
22
  // - `ts` is wall-clock milliseconds and is the ordering key ACROSS types, so a reader can
23
23
  // interleave `msg` and `activity` on one timeline.
24
+ // - `t:"handoff"` marks one logical AgentSession replacing its provider thread. Internal
25
+ // summary/continuation prompts are not `msg` lines, so they cannot be mistaken for user
26
+ // conversation. A start followed by failed is an attempted boundary; start followed by
27
+ // complete is a committed handoff.
24
28
  //
25
29
  // Any future change to fold semantics or line meaning bumps `v`.
26
30
 
@@ -89,12 +93,30 @@ export interface TranscriptRawLine {
89
93
  data: unknown;
90
94
  }
91
95
 
96
+ /**
97
+ * A stable AgentSession replacing its underlying ACP thread. Library-generated summary
98
+ * and continuation prompts are represented by this boundary, never as user-authored
99
+ * `t:"msg"` lines.
100
+ */
101
+ export interface TranscriptHandoffLine {
102
+ v: 1;
103
+ t: "handoff";
104
+ event: "start" | "complete" | "failed";
105
+ ts: number;
106
+ handoffId: string;
107
+ fromInternalSessionId: string | null;
108
+ toInternalSessionId?: string;
109
+ summary?: string;
110
+ error?: string;
111
+ }
112
+
92
113
  export type TranscriptLine =
93
114
  | TranscriptMetaLine
94
115
  | TranscriptMessageLine
95
116
  | TranscriptActivityLine
96
117
  | TranscriptPermissionLine
97
- | TranscriptRawLine;
118
+ | TranscriptRawLine
119
+ | TranscriptHandoffLine;
98
120
 
99
121
  export type TranscriptEntry = TranscriptMessageLine;
100
122
 
@@ -345,6 +367,15 @@ function isTranscriptLine(value: unknown): value is TranscriptLine {
345
367
  return true;
346
368
  case "raw":
347
369
  return typeof value.protocol === "string" && typeof value.event === "string";
370
+ case "handoff":
371
+ return (
372
+ (value.event === "start" || value.event === "complete" || value.event === "failed") &&
373
+ typeof value.handoffId === "string" &&
374
+ (value.fromInternalSessionId === null || typeof value.fromInternalSessionId === "string") &&
375
+ (value.toInternalSessionId === undefined || typeof value.toInternalSessionId === "string") &&
376
+ (value.summary === undefined || typeof value.summary === "string") &&
377
+ (value.error === undefined || typeof value.error === "string")
378
+ );
348
379
  default:
349
380
  return false;
350
381
  }
package/src/types.ts CHANGED
@@ -5,12 +5,20 @@
5
5
  import type { ApplyResult } from "./activity.ts";
6
6
 
7
7
  /**
8
- * A slash command the AGENT itself exposes (e.g. codex /model, kimi /sessions), learned
9
- * from the `available_commands_update` notification. Invoke with the `//name` passthrough.
8
+ * A slash command exposed by the replaceable ACP-backed internal session (e.g. codex
9
+ * /model, kimi /sessions), learned from `available_commands_update`.
10
10
  */
11
- export interface AgentCommand {
12
- name: string;
13
- description: string;
11
+ export interface InternalSessionCommand {
12
+ readonly name: string;
13
+ readonly description: string;
14
+ /** ACP currently defines command input as unstructured text after the command name. */
15
+ readonly input?: InternalSessionCommandInput;
16
+ }
17
+
18
+ export interface InternalSessionCommandInput {
19
+ readonly kind: "unstructured";
20
+ /** Placeholder/help text supplied by the harness. */
21
+ readonly hint: string;
14
22
  }
15
23
 
16
24
  /** Token accounting for a turn. Nullable per-field — not all providers report all of it. */
@@ -144,8 +152,8 @@ export type ActivityEvent =
144
152
  /** Per-plan update (experimental protocol extension). */
145
153
  | { kind: "plan_update"; planId: string; plan: unknown }
146
154
  | { kind: "plan_removed"; planId: string }
147
- /** The agent's slash commands changed; also reflected in `client.agentCommands`. */
148
- | { kind: "commands"; commands: AgentCommand[] }
155
+ /** ACP available commands changed; also reflected in `client.availableCommands`. */
156
+ | { kind: "commands"; commands: readonly InternalSessionCommand[] }
149
157
  /** The agent switched session mode. */
150
158
  | { kind: "mode"; modeId: string }
151
159
  /** Context-window accounting. `used`/`size` are tokens. */
package/src/updates.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  import type * as schema from "@agentclientprotocol/sdk";
12
12
  import type {
13
13
  ActivityEvent,
14
- AgentCommand,
14
+ InternalSessionCommand,
15
15
  ContentBlock,
16
16
  PlanEntry,
17
17
  ToolActivity,
@@ -94,7 +94,7 @@ export function toActivityEvent(update: schema.SessionUpdate): ActivityEvent | n
94
94
  return { kind: "plan_removed", planId: u.id };
95
95
 
96
96
  case "available_commands_update":
97
- return { kind: "commands", commands: toAgentCommands(u.availableCommands) };
97
+ return { kind: "commands", commands: toAvailableCommands(u.availableCommands) };
98
98
  case "current_mode_update":
99
99
  return { kind: "mode", modeId: u.currentModeId };
100
100
  case "config_option_update":
@@ -121,12 +121,27 @@ export function toActivityEvent(update: schema.SessionUpdate): ActivityEvent | n
121
121
  }
122
122
 
123
123
  /** Slash commands from an available_commands_update payload. */
124
- export function toAgentCommands(raw: unknown): AgentCommand[] {
125
- if (!Array.isArray(raw)) return [];
126
- return raw.map((c: Record<string, any>) => ({
127
- name: c?.name,
128
- description: c?.description ?? "",
129
- }));
124
+ export function toAvailableCommands(raw: unknown): readonly InternalSessionCommand[] {
125
+ if (!Array.isArray(raw)) return Object.freeze([]);
126
+ const commands: InternalSessionCommand[] = [];
127
+ const names = new Set<string>();
128
+ for (const item of raw) {
129
+ const c = item as Record<string, unknown> | null;
130
+ if (!c || typeof c.name !== "string" || c.name.trim() === "") continue;
131
+ const name = c.name.trim();
132
+ if (names.has(name)) continue;
133
+ names.add(name);
134
+ const input = c.input as Record<string, unknown> | null | undefined;
135
+ const command: InternalSessionCommand = {
136
+ name,
137
+ description: typeof c.description === "string" ? c.description : "",
138
+ ...(input && typeof input.hint === "string"
139
+ ? { input: Object.freeze({ kind: "unstructured" as const, hint: input.hint }) }
140
+ : {}),
141
+ };
142
+ commands.push(Object.freeze(command));
143
+ }
144
+ return Object.freeze(commands);
130
145
  }
131
146
 
132
147
  /** Normalize a ToolCallContent[] — keeping unrecognized shapes verbatim. */