@qlairoslabs/acp-client 0.6.0 → 0.7.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.
Files changed (44) hide show
  1. package/CONSUMER_GUIDE.md +618 -291
  2. package/README.md +25 -0
  3. package/package.json +1 -1
  4. package/src/agent-session.ts +2188 -96
  5. package/src/cli/index.ts +33 -5
  6. package/src/cli/managed.ts +220 -0
  7. package/src/command-descriptors.ts +22 -0
  8. package/src/controller.ts +87 -37
  9. package/src/index.ts +229 -3
  10. package/src/metering/engine.ts +9 -1
  11. package/src/metering/record.ts +2 -1
  12. package/src/persistence/activity-projection.ts +71 -0
  13. package/src/persistence/audit-log-reader.ts +506 -0
  14. package/src/persistence/audit-runtime.ts +162 -0
  15. package/src/persistence/checkpoint.ts +304 -0
  16. package/src/persistence/config.ts +538 -0
  17. package/src/persistence/configuration-state.ts +191 -0
  18. package/src/persistence/deletion.ts +227 -0
  19. package/src/persistence/file-registry-store.ts +740 -0
  20. package/src/persistence/integrity.ts +147 -0
  21. package/src/persistence/legacy-registry-import.ts +240 -0
  22. package/src/persistence/managed-checkpoint.ts +81 -0
  23. package/src/persistence/managed-creation.ts +456 -0
  24. package/src/persistence/managed-load.ts +172 -0
  25. package/src/persistence/managed-registry.ts +57 -0
  26. package/src/persistence/migration.ts +298 -0
  27. package/src/persistence/paths.ts +172 -0
  28. package/src/persistence/projection.ts +373 -0
  29. package/src/persistence/reconfiguration.ts +453 -0
  30. package/src/persistence/records.ts +873 -0
  31. package/src/persistence/reducer.ts +498 -0
  32. package/src/persistence/registry.ts +446 -0
  33. package/src/persistence/restoration.ts +689 -0
  34. package/src/persistence/session-log-writer.ts +480 -0
  35. package/src/persistence/state-runtime.ts +176 -0
  36. package/src/persistence/transcript-reader.ts +980 -0
  37. package/src/persistence/transcript-runtime.ts +667 -0
  38. package/src/persistence/transcript-scanner.ts +385 -0
  39. package/src/persistence/truncation.ts +276 -0
  40. package/src/repl/agent-session-commands.ts +74 -1
  41. package/src/repl/commands.ts +1 -1
  42. package/src/repl/index.ts +7 -1
  43. package/src/session-manager.ts +257 -7
  44. package/src/transcript.ts +3 -3
package/src/cli/index.ts CHANGED
@@ -9,6 +9,14 @@
9
9
  // [--no-activity] [--degraded] [--wire[=FILE]]
10
10
  // acp-client chat [--adapter ID] --adapter-command '["agent","--acp"]'
11
11
  // [--pty-command '["agent"]'] [--adapter-name "My Agent"]
12
+ // acp-client sessions [--root PATH] [--all] [--json]
13
+ // acp-client create [AGENT_SESSION_ID] [--adapter ID] [--root PATH] [--no-repl]
14
+ // acp-client open AGENT_SESSION_ID [--adapter-command COMMAND] [--root PATH]
15
+ // acp-client restore AGENT_SESSION_ID [--replacement-transcript PATH] [--root PATH]
16
+ // acp-client info|checkpoint|maintenance [AGENT_SESSION_ID] [--root PATH]
17
+ // acp-client reconfigure AGENT_SESSION_ID --disable-transcript|--replace-transcript
18
+ // acp-client delete AGENT_SESSION_ID [--root PATH] [--delete-transcript]
19
+ // [--delete-audit-log] [--remove-registry-entry] [--yes]
12
20
  //
13
21
  // activity (thinking/tool markers) shows by DEFAULT; --no-activity disables it.
14
22
  // --verbose (-v): lifecycle summaries (connect, session_new, prompt_end)
@@ -25,6 +33,11 @@ import {
25
33
  import { createControllerCommands, runRepl } from "../repl/index.ts";
26
34
  import { DIM, colorEnabled, paint } from "../repl/colors.ts";
27
35
  import { parseCommandArg, resolveCliAdapter } from "./adapter.ts";
36
+ import {
37
+ ManagedCliUsageError,
38
+ parseManagedCliCommand,
39
+ runManagedCliCommand,
40
+ } from "./managed.ts";
28
41
 
29
42
  interface Args {
30
43
  command: string;
@@ -145,9 +158,24 @@ async function chat(args: Args): Promise<void> {
145
158
  }
146
159
  }
147
160
 
148
- const args = parseArgs(process.argv.slice(2));
149
- if (args.command !== "chat") {
150
- console.error(`unknown command: ${args.command}`);
151
- process.exit(1);
161
+ const argv = process.argv.slice(2);
162
+ const managedCommands = new Set([
163
+ "sessions", "create", "open", "load", "resume", "restore", "info", "checkpoint",
164
+ "maintenance", "reconfigure", "delete",
165
+ ]);
166
+ if (argv[0] && managedCommands.has(argv[0])) {
167
+ try {
168
+ await runManagedCliCommand(parseManagedCliCommand(argv));
169
+ } catch (error) {
170
+ console.error(error instanceof Error ? error.message : String(error));
171
+ process.exitCode = error instanceof ManagedCliUsageError ? 2 : 1;
172
+ }
173
+ } else {
174
+ const args = parseArgs(argv);
175
+ if (args.command !== "chat") {
176
+ console.error(`unknown command: ${args.command}`);
177
+ process.exitCode = 2;
178
+ } else {
179
+ await chat(args);
180
+ }
152
181
  }
153
- await chat(args);
@@ -0,0 +1,220 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createInterface } from "node:readline/promises";
3
+ import type { AgentSession, AgentSessionOpenResult } from "../agent-session.ts";
4
+ import type { TranscriptPreset } from "../persistence/config.ts";
5
+ import type { AgentSessionSummary, DeletionMaintenance, SessionMaintenance } from "../persistence/registry.ts";
6
+ import { runAgentSessionRepl } from "../repl/index.ts";
7
+ import { SessionManager } from "../session-manager.ts";
8
+ import { parseCommandArg, resolveCliAdapter, type CliAdapterSelection } from "./adapter.ts";
9
+
10
+ interface Common { readonly root?: string }
11
+ interface Live extends Common, CliAdapterSelection {
12
+ readonly cwd?: string;
13
+ readonly execPrefix: readonly string[];
14
+ readonly approve: boolean;
15
+ readonly activity: boolean;
16
+ readonly repl: boolean;
17
+ }
18
+ type Change =
19
+ | { readonly artifact: "transcript"; readonly action: "disable" }
20
+ | { readonly artifact: "transcript"; readonly action: "replace"; readonly preset?: TranscriptPreset }
21
+ | { readonly artifact: "audit"; readonly action: "disable" }
22
+ | { readonly artifact: "audit"; readonly action: "replace"; readonly path: string };
23
+
24
+ export type ManagedCliCommand =
25
+ | Common & { readonly kind: "sessions"; readonly includeDeleted: boolean; readonly json: boolean }
26
+ | Common & { readonly kind: "info"; readonly agentSessionId: string; readonly includeDeleted: boolean; readonly json: boolean }
27
+ | Common & { readonly kind: "checkpoint"; readonly agentSessionId: string; readonly includeDeleted: boolean; readonly registryProjection: boolean }
28
+ | Common & { readonly kind: "maintenance"; readonly agentSessionId?: string; readonly json: boolean }
29
+ | Live & { readonly kind: "create"; readonly agentSessionId?: string; readonly title?: string; readonly transcript: false | { readonly path?: string; readonly preset?: TranscriptPreset } | undefined; readonly auditLogPath?: string }
30
+ | Live & { readonly kind: "open"; readonly agentSessionId: string }
31
+ | Live & { readonly kind: "restore"; readonly agentSessionId: string; readonly replacementTranscript?: false | { readonly path: string; readonly preset?: TranscriptPreset }; readonly replacementAuditLog?: false | { readonly path: string } }
32
+ | Common & { readonly kind: "reconfigure"; readonly agentSessionId: string; readonly change: Change; readonly yes: boolean }
33
+ | Common & { readonly kind: "delete"; readonly agentSessionId: string; readonly deleteTranscript: boolean; readonly deleteAuditLog: boolean; readonly removeRegistryEntry: boolean; readonly yes: boolean };
34
+
35
+ export interface ManagedCliIo {
36
+ readonly out?: (text: string) => void;
37
+ readonly error?: (text: string) => void;
38
+ readonly interactive?: boolean;
39
+ readonly confirm?: (prompt: string) => Promise<string>;
40
+ /** Embedding/test seam; defaults to the public one-AgentSession REPL. */
41
+ readonly runSession?: (session: AgentSession, options: { readonly activity: boolean }) => Promise<void>;
42
+ }
43
+
44
+ export class ManagedCliUsageError extends Error {
45
+ constructor(message: string) { super(message); this.name = "ManagedCliUsageError"; }
46
+ }
47
+
48
+ export function parseManagedCliCommand(argv: readonly string[]): ManagedCliCommand {
49
+ const rawKind = argv[0];
50
+ const kind = rawKind === "resume" || rawKind === "load" ? "open" : rawKind;
51
+ if (!kind || !COMMANDS.has(kind)) throw new ManagedCliUsageError(`unsupported managed command: ${rawKind ?? "(missing)"}`);
52
+ const v: Parsed = { seen: new Set(), execPrefix: [], approve: false, activity: true, repl: true, includeDeleted: false, json: false, registryProjection: false, yes: false, transcriptDisabled: false, replacementTranscriptDisabled: false, replacementAuditDisabled: false, disableTranscript: false, replaceTranscript: false, disableAudit: false, deleteTranscript: false, deleteAuditLog: false, removeRegistryEntry: false, positionals: [] };
53
+ for (let i = 1; i < argv.length; i++) {
54
+ const arg = argv[i];
55
+ if (arg?.startsWith("--")) v.seen.add(arg);
56
+ if (arg === "--root") v.root = required(argv[++i], arg);
57
+ else if (arg === "--json") v.json = true;
58
+ else if (arg === "--all" || arg === "--include-deleted") v.includeDeleted = true;
59
+ else if (arg === "--registry-projection") v.registryProjection = true;
60
+ else if (arg === "--adapter") v.adapterId = required(argv[++i], arg);
61
+ else if (arg === "--adapter-command") v.command = parseCommandArg(argv[++i], arg);
62
+ else if (arg === "--pty-command") v.ptyCommand = parseCommandArg(argv[++i], arg);
63
+ else if (arg === "--adapter-name") v.displayName = required(argv[++i], arg);
64
+ else if (arg === "--cwd") v.cwd = required(argv[++i], arg);
65
+ else if (arg === "--exec") v.execPrefix = required(argv[++i], arg).split(" ").filter(Boolean);
66
+ else if (arg === "--approve") v.approve = true;
67
+ else if (arg === "--no-activity") v.activity = false;
68
+ else if (arg === "--no-repl") v.repl = false;
69
+ else if (arg === "--title") v.title = required(argv[++i], arg);
70
+ else if (arg === "--no-transcript") v.transcriptDisabled = true;
71
+ else if (arg === "--transcript") v.transcriptPath = required(argv[++i], arg);
72
+ else if (arg === "--preset") v.preset = parsePreset(argv[++i]);
73
+ else if (arg === "--audit-log") v.auditLogPath = required(argv[++i], arg);
74
+ else if (arg === "--replacement-transcript") v.replacementTranscriptPath = required(argv[++i], arg);
75
+ else if (arg === "--no-replacement-transcript") v.replacementTranscriptDisabled = true;
76
+ else if (arg === "--replacement-audit-log") v.replacementAuditPath = required(argv[++i], arg);
77
+ else if (arg === "--no-replacement-audit-log") v.replacementAuditDisabled = true;
78
+ else if (arg === "--disable-transcript") v.disableTranscript = true;
79
+ else if (arg === "--replace-transcript") v.replaceTranscript = true;
80
+ else if (arg === "--disable-audit-log") v.disableAudit = true;
81
+ else if (arg === "--replace-audit-log") v.replaceAuditPath = required(argv[++i], arg);
82
+ else if (arg === "--delete-transcript") v.deleteTranscript = true;
83
+ else if (arg === "--delete-audit-log") v.deleteAuditLog = true;
84
+ else if (arg === "--remove-registry-entry") v.removeRegistryEntry = true;
85
+ else if (arg === "--yes") v.yes = true;
86
+ else if (arg?.startsWith("--")) throw new ManagedCliUsageError(`unknown option for ${kind}: ${arg}`);
87
+ else if (arg) v.positionals.push(arg);
88
+ }
89
+ validateOptions(kind, v.seen);
90
+ if (kind === "sessions") { maxArgs(kind, v, 0); return { kind, root: v.root, includeDeleted: v.includeDeleted, json: v.json }; }
91
+ if (kind === "maintenance") { maxArgs(kind, v, 1); return { kind, root: v.root, ...(v.positionals[0] ? { agentSessionId: v.positionals[0] } : {}), json: v.json }; }
92
+ if (kind === "create") {
93
+ maxArgs(kind, v, 1); conflict(v.transcriptDisabled && !!v.transcriptPath, "--no-transcript and --transcript");
94
+ const transcript = v.transcriptDisabled ? false : v.transcriptPath || v.preset ? { ...(v.transcriptPath ? { path: v.transcriptPath } : {}), ...(v.preset ? { preset: v.preset } : {}) } : undefined;
95
+ return { kind, ...live(v), ...(v.positionals[0] ? { agentSessionId: v.positionals[0] } : {}), ...(v.title ? { title: v.title } : {}), transcript, ...(v.auditLogPath ? { auditLogPath: v.auditLogPath } : {}) };
96
+ }
97
+ const agentSessionId = identity(kind, v);
98
+ if (kind === "info") return { kind, root: v.root, agentSessionId, includeDeleted: v.includeDeleted, json: v.json };
99
+ if (kind === "checkpoint") return { kind, root: v.root, agentSessionId, includeDeleted: v.includeDeleted, registryProjection: v.registryProjection };
100
+ if (kind === "open") return { kind, ...live(v), agentSessionId };
101
+ if (kind === "restore") {
102
+ conflict(v.replacementTranscriptDisabled && !!v.replacementTranscriptPath, "replacement transcript flags");
103
+ conflict(v.replacementAuditDisabled && !!v.replacementAuditPath, "replacement audit flags");
104
+ return { kind, ...live(v), agentSessionId,
105
+ ...(v.replacementTranscriptDisabled ? { replacementTranscript: false as const } : v.replacementTranscriptPath ? { replacementTranscript: { path: v.replacementTranscriptPath, ...(v.preset ? { preset: v.preset } : {}) } } : {}),
106
+ ...(v.replacementAuditDisabled ? { replacementAuditLog: false as const } : v.replacementAuditPath ? { replacementAuditLog: { path: v.replacementAuditPath } } : {}) };
107
+ }
108
+ if (kind === "reconfigure") {
109
+ const count = Number(v.disableTranscript) + Number(v.replaceTranscript) + Number(v.disableAudit) + Number(!!v.replaceAuditPath);
110
+ if (count !== 1) throw new ManagedCliUsageError("reconfigure requires exactly one --disable-* or --replace-* operation");
111
+ const change: Change = v.disableTranscript ? { artifact: "transcript", action: "disable" }
112
+ : v.replaceTranscript ? { artifact: "transcript", action: "replace", ...(v.preset ? { preset: v.preset } : {}) }
113
+ : v.disableAudit ? { artifact: "audit", action: "disable" }
114
+ : { artifact: "audit", action: "replace", path: v.replaceAuditPath! };
115
+ return { kind, root: v.root, agentSessionId, change, yes: v.yes };
116
+ }
117
+ return { kind: "delete", root: v.root, agentSessionId, deleteTranscript: v.deleteTranscript, deleteAuditLog: v.deleteAuditLog, removeRegistryEntry: v.removeRegistryEntry, yes: v.yes };
118
+ }
119
+
120
+ export async function runManagedCliCommand(command: ManagedCliCommand, io: ManagedCliIo = {}, suppliedManager?: SessionManager): Promise<void> {
121
+ const out = io.out ?? ((s: string) => process.stdout.write(s));
122
+ const error = io.error ?? ((s: string) => process.stderr.write(s));
123
+ const manager = suppliedManager ?? await SessionManager.open({ root: command.root });
124
+ if (command.kind === "sessions") {
125
+ const rows = await allSessions(manager, command.includeDeleted);
126
+ if (command.json) out(`${JSON.stringify(rows, null, 2)}\n`); else if (!rows.length) out("No managed agent sessions.\n"); else rows.forEach((row) => out(formatSession(row)));
127
+ return;
128
+ }
129
+ if (command.kind === "info") { const row = await summary(manager, command.agentSessionId, command.includeDeleted); out(command.json ? `${JSON.stringify(row, null, 2)}\n` : formatSession(row)); return; }
130
+ if (command.kind === "checkpoint") {
131
+ const value = await manager.getAgentSessionCheckpoint(command.agentSessionId, { includeDeleted: command.includeDeleted, source: command.registryProjection ? "registry_projection" : "resolved" });
132
+ if (!value) throw missing(command.agentSessionId); out(`${JSON.stringify(value, null, 2)}\n`); return;
133
+ }
134
+ if (command.kind === "maintenance") {
135
+ if (command.agentSessionId) { const value = await manager.getSessionMaintenance(command.agentSessionId); out(command.json ? `${JSON.stringify(value, null, 2)}\n` : value ? formatMaintenance(command.agentSessionId, value) : `No pending maintenance for ${command.agentSessionId}.\n`); return; }
136
+ const rows = await allMaintenance(manager); if (command.json) out(`${JSON.stringify(rows, null, 2)}\n`); else if (!rows.length) out("No pending managed-session maintenance.\n"); else rows.forEach((row) => out(`${row.agentSessionId}\n ${row.kind} ${row.operationId} · started ${row.startedAt}\n`)); return;
137
+ }
138
+ if (command.kind === "create") {
139
+ const adapter = resolveCliAdapter(command);
140
+ const pending = command.agentSessionId ? await manager.getSessionMaintenance(command.agentSessionId) : null;
141
+ if (pending && pending.kind !== "creation") throw new ManagedCliUsageError(`session has pending ${pending.kind} maintenance; complete it first`);
142
+ const session = await manager.createAgentSession({ adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.agentSessionId ? { agentSessionId: command.agentSessionId } : {}), ...(pending ? { creationId: pending.operationId } : {}), ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.title ? { title: command.title } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}), defaultPermission: command.approve ? "approve" : "cancel", persistence: { ...(command.transcript !== undefined ? { transcript: command.transcript } : {}), ...(command.auditLogPath ? { auditLog: { path: command.auditLogPath } } : {}) } });
143
+ out(`Created managed agent session ${session.agentSessionId}.\n`); await own(session, command, io); return;
144
+ }
145
+ if (command.kind === "open") {
146
+ const row = await summary(manager, command.agentSessionId, false); const adapter = recordedAdapter(command, row);
147
+ const opened = await manager.loadAgentSession(command.agentSessionId, runtime(command, adapter)); reportOpen(opened, error); await own(opened.session, command, io); return;
148
+ }
149
+ if (command.kind === "restore") {
150
+ const [row, pending] = await Promise.all([summary(manager, command.agentSessionId, true), manager.getSessionMaintenance(command.agentSessionId)]);
151
+ if (pending && pending.kind !== "restoration") throw new ManagedCliUsageError(`session has pending ${pending.kind} maintenance; complete it first`);
152
+ if (row.lifecycle !== "deleted" && pending?.kind !== "restoration") throw new ManagedCliUsageError("restore requires a deleted managed session");
153
+ const adapter = recordedAdapter(command, row);
154
+ const replacements = restorationReplacements(command, row, pending);
155
+ const opened = await manager.restoreAgentSession(command.agentSessionId, { ...runtime(command, adapter), restorationId: pending?.operationId ?? `cli-restore-${randomUUID()}`, expectedIncarnationId: pending?.incarnationId ?? row.incarnationId, expectedRecordRevision: pending?.baseRecordRevision ?? row.recordRevision, ...replacements });
156
+ reportOpen(opened, error); await own(opened.session, command, io); return;
157
+ }
158
+ if (command.kind === "reconfigure") {
159
+ const row = await summary(manager, command.agentSessionId, false); if (!command.yes && !await confirm(io, error, row, `About to ${command.change.action} ${command.change.artifact} persistence for ${row.agentSessionId}.\n`, "Reconfiguration")) return;
160
+ const base = { reconfigurationId: `cli-reconfigure-${randomUUID()}`, expectedIncarnationId: row.incarnationId, expectedRecordRevision: row.recordRevision };
161
+ if (command.change.artifact === "transcript") {
162
+ const resolved = await manager.getAgentSessionCheckpoint(command.agentSessionId); if (!resolved?.checkpoint.transcript) throw new ManagedCliUsageError("session has no transcript to reconfigure");
163
+ await manager.reconfigureAgentSessionPersistence(command.agentSessionId, { ...base, transcript: command.change.action === "disable" ? { action: "disable", checkpoint: resolved.checkpoint, deleteExistingLog: true, acknowledgeContinuationLoss: true } : { action: "replace", config: { path: resolved.checkpoint.transcript.path, ...(command.change.preset ? { preset: command.change.preset } : {}) }, checkpoint: resolved.checkpoint, acknowledgeContinuationLoss: true } });
164
+ } else await manager.reconfigureAgentSessionPersistence(command.agentSessionId, { ...base, auditLog: command.change.action === "disable" ? { action: "disable", deleteExistingLog: true, acknowledgeAuditGap: true } : { action: "replace", config: { path: command.change.path }, acknowledgeAuditGap: true } });
165
+ out(`Reconfigured ${command.change.artifact} persistence for ${command.agentSessionId}.\n`); return;
166
+ }
167
+ const [row, pending] = await Promise.all([manager.getAgentSessionInfo(command.agentSessionId, { includeDeleted: true }), manager.getSessionMaintenance(command.agentSessionId)]); if (!row) throw missing(command.agentSessionId);
168
+ const intent = { deleteTranscript: command.deleteTranscript, deleteAuditLog: command.deleteAuditLog, removeRegistryEntry: command.removeRegistryEntry }; const retry = pending ? deletionRetry(pending, intent) : null;
169
+ if (!command.yes && !await confirm(io, error, row, deletionPreview(row, intent), "Deletion")) return;
170
+ await manager.deleteAgentSession(row.agentSessionId, { deletionId: retry?.operationId ?? `cli-delete-${randomUUID()}`, expectedIncarnationId: retry?.incarnationId ?? row.incarnationId, expectedRecordRevision: retry?.baseRecordRevision ?? row.recordRevision, ...intent });
171
+ out(command.removeRegistryEntry ? `Removed managed agent session ${row.agentSessionId}.\n` : `Deleted managed agent session ${row.agentSessionId}; registry tombstone retained.\n`);
172
+ }
173
+
174
+ interface Parsed {
175
+ seen: Set<string>;
176
+ root?: string; adapterId?: string; command?: string[]; ptyCommand?: string[]; displayName?: string; cwd?: string; execPrefix: string[]; approve: boolean; activity: boolean; repl: boolean; includeDeleted: boolean; json: boolean; registryProjection: boolean; yes: boolean; title?: string; transcriptDisabled: boolean; transcriptPath?: string; preset?: TranscriptPreset; auditLogPath?: string; replacementTranscriptDisabled: boolean; replacementTranscriptPath?: string; replacementAuditDisabled: boolean; replacementAuditPath?: string; disableTranscript: boolean; replaceTranscript: boolean; disableAudit: boolean; replaceAuditPath?: string; deleteTranscript: boolean; deleteAuditLog: boolean; removeRegistryEntry: boolean; positionals: string[];
177
+ }
178
+ const COMMANDS = new Set(["sessions", "info", "checkpoint", "maintenance", "create", "open", "restore", "reconfigure", "delete"]);
179
+ function live(v: Parsed): Live { return { root: v.root, ...(v.adapterId ? { adapterId: v.adapterId } : {}), ...(v.command ? { command: v.command } : {}), ...(v.ptyCommand ? { ptyCommand: v.ptyCommand } : {}), ...(v.displayName ? { displayName: v.displayName } : {}), ...(v.cwd ? { cwd: v.cwd } : {}), execPrefix: v.execPrefix, approve: v.approve, activity: v.activity, repl: v.repl }; }
180
+ function runtime(command: Live, adapter: ReturnType<typeof resolveCliAdapter>) { return { adapter: adapter.adapter, adapterId: adapter.adapterId, ...(command.cwd ? { cwd: command.cwd } : {}), ...(command.execPrefix.length ? { execPrefix: [...command.execPrefix] } : {}), defaultPermission: command.approve ? "approve" as const : "cancel" as const }; }
181
+ function recordedAdapter(command: Live, row: AgentSessionSummary) { if (command.adapterId && command.adapterId !== row.adapterId && !command.command) throw new ManagedCliUsageError(`recorded adapter is ${row.adapterId}; changing adapters requires an explicit continuation strategy`); return resolveCliAdapter({ adapterId: command.adapterId ?? row.adapterId, command: command.command ? [...command.command] : undefined, ptyCommand: command.ptyCommand ? [...command.ptyCommand] : undefined, displayName: command.displayName }); }
182
+ async function own(session: AgentSession, command: Live, io: ManagedCliIo) { try { if (command.repl) io.runSession ? await io.runSession(session, { activity: command.activity }) : await runAgentSessionRepl(session, { activity: command.activity }); } finally { await session.stop(); } }
183
+ function reportOpen(opened: AgentSessionOpenResult, error: (s: string) => void) { error(`Continuation: ${opened.continuation.outcome.kind}; recovery: ${opened.recovery.kind}; configuration: ${opened.configuration.kind}; promptable: ${opened.promptability.promptable}.\n`); opened.repairs.forEach((repair) => error(`Persistence repair: ${JSON.stringify(repair)}\n`)); }
184
+ async function allSessions(manager: SessionManager, includeDeleted: boolean) { const rows: AgentSessionSummary[] = []; let cursor; do { const page = await manager.listAgentSessions({ cursor, limit: 100, includeDeleted }); rows.push(...page.sessions); cursor = page.nextCursor ?? undefined; } while (cursor); return rows; }
185
+ async function allMaintenance(manager: SessionManager) { const rows: Array<{ agentSessionId: string; kind: SessionMaintenance["kind"]; operationId: string; startedAt: string }> = []; let cursor; do { const page = await manager.listSessionMaintenance({ cursor, limit: 100 }); rows.push(...page.maintenance); cursor = page.nextCursor ?? undefined; } while (cursor); return rows; }
186
+ async function summary(manager: SessionManager, id: string, includeDeleted: boolean) { const row = await manager.getAgentSessionInfo(id, { includeDeleted }); if (!row) throw missing(id); return row; }
187
+ function missing(id: string) { return new ManagedCliUsageError(`managed agent session not found: ${id}`); }
188
+ function formatSession(row: AgentSessionSummary) { const state = row.lifecycle === "active" ? `active, recovery ${row.recovery}` : row.lifecycle === "deleted" ? `deleted ${row.deletedAt ?? ""}`.trim() : `maintenance pending (${row.maintenance?.kind ?? "unknown"})`; return `${row.agentSessionId}\n ${row.adapterId}/${row.mode}${row.model ? ` · ${row.model}` : ""}\n ${state} · transcript ${row.transcriptAvailable ? "available" : "unavailable"} · audit ${row.auditLogAvailable ? "available" : "unavailable"}\n updated ${row.updatedAt}\n`; }
189
+ function formatMaintenance(id: string, value: SessionMaintenance) { return `${id}\n ${value.kind} ${value.operationId} · started ${value.startedAt}\n`; }
190
+ function deletionPreview(row: AgentSessionSummary, intent: { deleteTranscript: boolean; deleteAuditLog: boolean; removeRegistryEntry: boolean }) { const actions = ["tombstone the managed session"]; if (intent.deleteTranscript) actions.push("permanently delete its transcript"); if (intent.deleteAuditLog) actions.push("permanently delete its audit log"); if (intent.removeRegistryEntry) actions.push("permanently remove its registry entry"); return `About to ${actions.join(", ")} for ${row.agentSessionId}.\n`; }
191
+ async function confirm(io: ManagedCliIo, error: (s: string) => void, row: AgentSessionSummary, preview: string, label: string) { if (io.interactive === false || (io.interactive === undefined && !process.stdin.isTTY)) throw new ManagedCliUsageError("refusing non-interactive destructive operation without --yes"); error(preview); const answer = io.confirm ? await io.confirm(`Type ${row.agentSessionId} to confirm: `) : await prompt(`Type ${row.agentSessionId} to confirm: `); if (answer.trim() === row.agentSessionId) return true; error(`${label} cancelled.\n`); return false; }
192
+ function deletionRetry(value: SessionMaintenance, intent: { deleteTranscript: boolean; deleteAuditLog: boolean; removeRegistryEntry: boolean }): DeletionMaintenance { if (value.kind !== "deletion") throw new ManagedCliUsageError(`session has pending ${value.kind} maintenance; complete it first`); if (value.details.deleteTranscript !== intent.deleteTranscript || value.details.deleteAuditLog !== intent.deleteAuditLog || value.details.removeRegistryEntry !== intent.removeRegistryEntry) throw new ManagedCliUsageError("session has a different pending deletion; repeat the original deletion flags"); return value; }
193
+ function restorationReplacements(command: Extract<ManagedCliCommand, { kind: "restore" }>, row: AgentSessionSummary, pending: Extract<SessionMaintenance, { kind: "restoration" }> | null) {
194
+ const transcript = command.replacementTranscript ?? (pending ? pending.details.transcript.action === "retain" ? undefined : pending.details.transcript.action === "disable" ? false : { path: pending.details.transcript.path } : row.transcriptAvailable ? undefined : false);
195
+ const auditLog = command.replacementAuditLog ?? (pending ? pending.details.auditLog.action === "retain" ? undefined : pending.details.auditLog.action === "disable" ? false : { path: pending.details.auditLog.path } : row.auditLogAvailable ? undefined : false);
196
+ return { replacementTranscript: transcript, replacementAuditLog: auditLog };
197
+ }
198
+ async function prompt(text: string) { const rl = createInterface({ input: process.stdin, output: process.stderr }); try { return await rl.question(text); } finally { rl.close(); } }
199
+ function identity(kind: string, v: Parsed) { maxArgs(kind, v, 1); if (!v.positionals[0]?.trim()) throw new ManagedCliUsageError(`${kind} requires AGENT_SESSION_ID`); return v.positionals[0]; }
200
+ function maxArgs(kind: string, v: Parsed, max: number) { if (v.positionals.length > max) throw new ManagedCliUsageError(`unexpected argument for ${kind}: ${v.positionals[max]}`); }
201
+ function required(value: string | undefined, flag: string) { if (!value?.trim()) throw new ManagedCliUsageError(`${flag} requires a value`); return value; }
202
+ function parsePreset(value: string | undefined): TranscriptPreset { const p = required(value, "--preset"); if (p !== "conversation" && p !== "activity" && p !== "detailed" && p !== "diagnostic") throw new ManagedCliUsageError(`unknown transcript preset: ${p}`); return p; }
203
+ function conflict(condition: boolean, description: string) { if (condition) throw new ManagedCliUsageError(`conflicting options: ${description}`); }
204
+ function validateOptions(kind: string, seen: ReadonlySet<string>) {
205
+ const common = ["--root"];
206
+ const live = ["--adapter", "--adapter-command", "--pty-command", "--adapter-name", "--cwd", "--exec", "--approve", "--no-activity", "--no-repl"];
207
+ const byKind: Record<string, readonly string[]> = {
208
+ sessions: ["--all", "--include-deleted", "--json"],
209
+ info: ["--all", "--include-deleted", "--json"],
210
+ checkpoint: ["--all", "--include-deleted", "--registry-projection"],
211
+ maintenance: ["--json"],
212
+ create: [...live, "--title", "--no-transcript", "--transcript", "--preset", "--audit-log"],
213
+ open: live,
214
+ restore: [...live, "--replacement-transcript", "--no-replacement-transcript", "--replacement-audit-log", "--no-replacement-audit-log", "--preset"],
215
+ reconfigure: ["--disable-transcript", "--replace-transcript", "--disable-audit-log", "--replace-audit-log", "--preset", "--yes"],
216
+ delete: ["--delete-transcript", "--delete-audit-log", "--remove-registry-entry", "--yes"],
217
+ };
218
+ const allowed = new Set([...common, ...(byKind[kind] ?? [])]);
219
+ for (const flag of seen) if (!allowed.has(flag)) throw new ManagedCliUsageError(`unknown option for ${kind}: ${flag}`);
220
+ }
@@ -0,0 +1,22 @@
1
+ /** One positional argument accepted by a discoverable local command. */
2
+ export interface CommandArgumentDescriptor {
3
+ /** Stable machine-readable argument name. */
4
+ readonly name: string;
5
+ /** Human-readable explanation suitable for command palettes and help text. */
6
+ readonly description: string;
7
+ readonly required: boolean;
8
+ /** Whether this argument consumes the remaining input rather than one token. */
9
+ readonly variadic?: boolean;
10
+ }
11
+
12
+ /** Metadata shared by the logical-session and low-level controller command surfaces. */
13
+ export interface CommandDescriptor<Id extends string = string> {
14
+ readonly id: Id;
15
+ /** Compact terminal representation retained for help output and compatibility. */
16
+ readonly usage: string;
17
+ readonly description: string;
18
+ readonly arguments: readonly CommandArgumentDescriptor[];
19
+ readonly available: boolean;
20
+ /** Present only when the command is currently unavailable. */
21
+ readonly unavailableReason?: string;
22
+ }
package/src/controller.ts CHANGED
@@ -9,6 +9,7 @@ import type * as schema from "@agentclientprotocol/sdk";
9
9
  import type { Adapter } from "./adapters.ts";
10
10
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
11
11
  import type { Capabilities } from "./capabilities.ts";
12
+ import type { CommandDescriptor } from "./command-descriptors.ts";
12
13
  import type { ConfigOption, ConfigOptions } from "./config-options.ts";
13
14
  import type { Logger } from "./logger.ts";
14
15
  import type { AcpLauncher } from "./launcher.ts";
@@ -73,14 +74,11 @@ export type ControllerCommandId =
73
74
  | "load"
74
75
  | "resume"
75
76
  | "fork"
76
- | "bridge";
77
+ | "bridge"
78
+ | "degrade"
79
+ | "upgrade";
77
80
 
78
- export interface ControllerCommand {
79
- id: ControllerCommandId;
80
- usage: string;
81
- available: boolean;
82
- unavailableReason?: string;
83
- }
81
+ export interface ControllerCommand extends CommandDescriptor<ControllerCommandId> {}
84
82
 
85
83
  export type ConfigValueParseResult =
86
84
  | { ok: true; value: unknown }
@@ -190,6 +188,19 @@ export class AgentController implements AgentClient {
190
188
  return brought.result;
191
189
  }
192
190
 
191
+ /** Explicitly create a fresh provider thread, ignoring any startup load target. */
192
+ async startFresh(): Promise<ConnectResult> {
193
+ if (this.current) {
194
+ if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
195
+ return await this.newSession();
196
+ }
197
+ const brought = await this.bringUp(this.mode);
198
+ this.current = brought.client;
199
+ this.acp = brought.acp;
200
+ this.attachAvailableCommandSource();
201
+ return brought.result;
202
+ }
203
+
193
204
  prompt(
194
205
  text: string,
195
206
  handlers?: PromptHandlers,
@@ -334,58 +345,97 @@ export class AgentController implements AgentClient {
334
345
  // The rich ACP commands are unavailable when degraded — `acp` is null there.
335
346
  const acp = this.acp;
336
347
  const degradedReason = "unavailable in degraded (pty) mode";
348
+ const acpUnavailableReason = this.current ? degradedReason : "controller is not connected";
337
349
  const capabilities = acp ? acp.capabilities : null;
338
350
  const session = capabilities?.agent.sessionCapabilities;
351
+ const command = (
352
+ descriptor: Omit<ControllerCommand, "available" | "unavailableReason">,
353
+ available: boolean,
354
+ unavailableReason?: string,
355
+ ): ControllerCommand => ({
356
+ ...descriptor,
357
+ available,
358
+ ...(available || !unavailableReason ? {} : { unavailableReason }),
359
+ });
339
360
  return [
340
- { id: "caps", usage: "/caps", available: Boolean(acp), unavailableReason: degradedReason },
341
- { id: "session", usage: "/session", available: Boolean(this.current) },
361
+ command({
362
+ id: "caps",
363
+ usage: "/caps",
364
+ description: "Show capabilities negotiated with the active ACP harness.",
365
+ arguments: [],
366
+ }, Boolean(acp), acpUnavailableReason),
367
+ command({
368
+ id: "session",
369
+ usage: "/session",
370
+ description: "Show the active provider-thread identity, adapter, and transport mode.",
371
+ arguments: [],
372
+ }, Boolean(this.current), "controller is not connected"),
342
373
  {
343
374
  id: "login",
344
375
  usage: "/login [METHOD]",
376
+ description: "List authentication methods or authenticate through the active ACP harness.",
377
+ arguments: [{ name: "method", description: "Advertised authentication method ID.", required: false }],
345
378
  available: Boolean(acp),
346
- unavailableReason: degradedReason,
379
+ ...(acp ? {} : { unavailableReason: acpUnavailableReason }),
347
380
  },
348
- {
381
+ command({
349
382
  id: "new",
350
383
  usage: "/new",
351
- available: Boolean(acp),
352
- unavailableReason: degradedReason,
353
- },
354
- {
384
+ description: "Create a fresh provider thread in the active ACP harness.",
385
+ arguments: [],
386
+ }, Boolean(acp), acpUnavailableReason),
387
+ command({
355
388
  id: "sessions",
356
389
  usage: "/sessions",
357
- available: session?.list === true,
358
- unavailableReason: acp ? "agent does not support session/list" : degradedReason,
359
- },
360
- {
390
+ description: "List provider sessions advertised by the active ACP harness.",
391
+ arguments: [],
392
+ }, session?.list === true, acp ? "agent does not support session/list" : acpUnavailableReason),
393
+ command({
361
394
  id: "config",
362
395
  usage: "/config [CONFIG_ID [VALUE]]",
363
- available: Boolean(acp),
364
- unavailableReason: degradedReason,
365
- },
366
- {
396
+ description: "Inspect or change an ACP session configuration option.",
397
+ arguments: [
398
+ { name: "configId", description: "Advertised configuration option ID.", required: false },
399
+ { name: "value", description: "New value for the selected option.", required: false, variadic: true },
400
+ ],
401
+ }, Boolean(acp), acpUnavailableReason),
402
+ command({
367
403
  id: "load",
368
404
  usage: "/load SESSION_ID",
369
- available: capabilities?.agent.loadSession === true,
370
- unavailableReason: acp ? "load not supported by this agent" : degradedReason,
371
- },
372
- {
405
+ description: "Load a provider session by ID.",
406
+ arguments: [{ name: "sessionId", description: "Provider session ID to load.", required: true }],
407
+ }, capabilities?.agent.loadSession === true, acp ? "load not supported by this agent" : acpUnavailableReason),
408
+ command({
373
409
  id: "resume",
374
410
  usage: "/resume SESSION_ID",
375
- available: session?.resume === true,
376
- unavailableReason: acp ? "resume not supported by this agent" : degradedReason,
377
- },
378
- {
411
+ description: "Resume a provider session by ID.",
412
+ arguments: [{ name: "sessionId", description: "Provider session ID to resume.", required: true }],
413
+ }, session?.resume === true, acp ? "resume not supported by this agent" : acpUnavailableReason),
414
+ command({
379
415
  id: "fork",
380
416
  usage: "/fork SESSION_ID",
381
- available: session?.fork === true,
382
- unavailableReason: acp ? "fork not supported by this agent" : degradedReason,
383
- },
384
- {
417
+ description: "Fork a provider session into a new provider thread.",
418
+ arguments: [{ name: "sessionId", description: "Provider session ID to fork.", required: true }],
419
+ }, session?.fork === true, acp ? "fork not supported by this agent" : acpUnavailableReason),
420
+ command({
385
421
  id: "bridge",
386
422
  usage: "/bridge",
387
- available: Boolean(this.current),
388
- },
423
+ description: "Open the harness's interactive terminal interface.",
424
+ arguments: [],
425
+ }, Boolean(this.current), "controller is not connected"),
426
+ command({
427
+ id: "degrade",
428
+ usage: "/degrade",
429
+ description: "Replace the ACP connection with the adapter's interactive PTY mode.",
430
+ arguments: [],
431
+ }, this.mode !== "degraded" && Boolean(this.config.adapter.ptyCommand),
432
+ this.mode === "degraded" ? "already in degraded mode" : "adapter has no interactive PTY command"),
433
+ command({
434
+ id: "upgrade",
435
+ usage: "/upgrade",
436
+ description: "Replace degraded PTY mode with a fresh ACP connection.",
437
+ arguments: [],
438
+ }, this.mode === "degraded", "already in normal ACP mode"),
389
439
  ];
390
440
  }
391
441