@qlairoslabs/acp-client 0.5.0 → 0.7.0

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 (62) hide show
  1. package/CHANGELOG-metering.md +288 -0
  2. package/CONSUMER_GUIDE.md +579 -292
  3. package/README.md +25 -0
  4. package/package.json +6 -3
  5. package/src/agent-session.ts +2589 -96
  6. package/src/cli/index.ts +33 -5
  7. package/src/cli/managed.ts +220 -0
  8. package/src/client.ts +57 -1
  9. package/src/controller.ts +43 -0
  10. package/src/index.ts +379 -3
  11. package/src/metering/catalog/build.ts +285 -0
  12. package/src/metering/catalog/index.ts +243 -0
  13. package/src/metering/catalog/live.ts +171 -0
  14. package/src/metering/catalog/models-dev.catalog.json +8797 -0
  15. package/src/metering/catalog/models-dev.meta.json +6 -0
  16. package/src/metering/categories.ts +129 -0
  17. package/src/metering/certification.ts +86 -0
  18. package/src/metering/context.ts +134 -0
  19. package/src/metering/delta.ts +108 -0
  20. package/src/metering/engine.ts +999 -0
  21. package/src/metering/money.ts +356 -0
  22. package/src/metering/opencode/channel.ts +389 -0
  23. package/src/metering/opencode/index.ts +159 -0
  24. package/src/metering/opencode/plugin.js +90 -0
  25. package/src/metering/opencode/profile.ts +159 -0
  26. package/src/metering/pricing.ts +285 -0
  27. package/src/metering/provider.ts +121 -0
  28. package/src/metering/rating.ts +349 -0
  29. package/src/metering/record.ts +275 -0
  30. package/src/metering/state.ts +421 -0
  31. package/src/metering/usage.ts +72 -0
  32. package/src/persistence/activity-projection.ts +71 -0
  33. package/src/persistence/audit-log-reader.ts +506 -0
  34. package/src/persistence/audit-runtime.ts +162 -0
  35. package/src/persistence/checkpoint.ts +304 -0
  36. package/src/persistence/config.ts +538 -0
  37. package/src/persistence/configuration-state.ts +191 -0
  38. package/src/persistence/deletion.ts +227 -0
  39. package/src/persistence/file-registry-store.ts +740 -0
  40. package/src/persistence/integrity.ts +147 -0
  41. package/src/persistence/legacy-registry-import.ts +240 -0
  42. package/src/persistence/managed-checkpoint.ts +81 -0
  43. package/src/persistence/managed-creation.ts +456 -0
  44. package/src/persistence/managed-load.ts +172 -0
  45. package/src/persistence/managed-registry.ts +57 -0
  46. package/src/persistence/migration.ts +298 -0
  47. package/src/persistence/paths.ts +172 -0
  48. package/src/persistence/projection.ts +373 -0
  49. package/src/persistence/reconfiguration.ts +453 -0
  50. package/src/persistence/records.ts +873 -0
  51. package/src/persistence/reducer.ts +498 -0
  52. package/src/persistence/registry.ts +446 -0
  53. package/src/persistence/restoration.ts +689 -0
  54. package/src/persistence/session-log-writer.ts +480 -0
  55. package/src/persistence/state-runtime.ts +176 -0
  56. package/src/persistence/transcript-reader.ts +980 -0
  57. package/src/persistence/transcript-runtime.ts +667 -0
  58. package/src/persistence/transcript-scanner.ts +385 -0
  59. package/src/persistence/truncation.ts +276 -0
  60. package/src/session-manager.ts +257 -7
  61. package/src/transcript.ts +3 -3
  62. package/src/types.ts +28 -5
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
+ }
package/src/client.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
20
20
  import { extractResponseChunk, toActivityEvent, toAvailableCommands } from "./updates.ts";
21
21
  import { ResponseAccumulator } from "./response.ts";
22
+ import { normalizeTokenUsage } from "./metering/usage.ts";
22
23
  import { TerminalRegistry } from "./terminals.ts";
23
24
  import { readTextFile, writeTextFile } from "./fs-access.ts";
24
25
  import { NotConnectedError } from "./errors.ts";
@@ -169,6 +170,15 @@ interface QueueItem {
169
170
 
170
171
  export type AvailableCommandsListener = (commands: readonly InternalSessionCommand[]) => void;
171
172
 
173
+ /**
174
+ * A raw ACP `usage_update`, with the session it named.
175
+ *
176
+ * Delivered raw rather than as an ActivityEvent because metering needs two things the
177
+ * folded event discards: ACP's absent-versus-null `cost`, and un-coerced counters (the
178
+ * activity projection defaults them to zero).
179
+ */
180
+ export type UsageUpdateListener = (update: unknown, sessionId: string | null) => void;
181
+
172
182
  interface CommandTransition {
173
183
  previous: readonly InternalSessionCommand[];
174
184
  bySession: Map<string, readonly InternalSessionCommand[]>;
@@ -180,6 +190,15 @@ export class AcpClient implements AgentClient {
180
190
  private _configOptions: ConfigOptions = new Map();
181
191
  private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
182
192
  private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
193
+ private readonly usageUpdateListeners = new Set<UsageUpdateListener>();
194
+ /**
195
+ * Latest usage_update seen, replayed to a late subscriber.
196
+ *
197
+ * Listeners are attached after connect + session/new, so a harness that notifies during
198
+ * startup would otherwise be unobserved. Mirrors how `availableCommands` is cached and
199
+ * re-emitted on attach.
200
+ */
201
+ private lastUsageUpdate: { update: unknown; sessionId: string | null } | null = null;
183
202
  private commandTransition: CommandTransition | null = null;
184
203
  private _sessionId: string | null = null;
185
204
 
@@ -245,6 +264,26 @@ export class AcpClient implements AgentClient {
245
264
  this.availableCommandListeners.add(listener);
246
265
  return () => this.availableCommandListeners.delete(listener);
247
266
  }
267
+ /**
268
+ * Observe `usage_update` notifications — context window and provider cost.
269
+ *
270
+ * Session-scoped rather than per-turn: ACP gives no ordering guarantee between a
271
+ * prompt response and the usage update describing it, so an update can arrive well
272
+ * after the turn's handlers are gone. Routing these only through PromptHandlers would
273
+ * drop exactly the observations metering needs.
274
+ */
275
+ subscribeUsageUpdate(listener: UsageUpdateListener): () => void {
276
+ this.usageUpdateListeners.add(listener);
277
+ const buffered = this.lastUsageUpdate;
278
+ if (buffered) {
279
+ try {
280
+ listener(buffered.update, buffered.sessionId);
281
+ } catch (err) {
282
+ this.log.warn("usage_update_listener_failed", { error: String(err) });
283
+ }
284
+ }
285
+ return () => this.usageUpdateListeners.delete(listener);
286
+ }
248
287
  get currentSessionId(): string | null {
249
288
  return this._sessionId;
250
289
  }
@@ -684,6 +723,10 @@ export class AcpClient implements AgentClient {
684
723
  const cancelled = this.active.cancelled;
685
724
  const text = this.active.response.text;
686
725
  const messages = this.active.response.snapshot();
726
+ // ACP usage is optional and experimental: validate rather than cast. An
727
+ // unavailable report is logged and surfaced as null — never zero-filled.
728
+ const usage = normalizeTokenUsage(res.usage);
729
+ if (!usage.ok) this.log.debug("prompt_usage_unavailable", { reason: usage.reason });
687
730
  this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
688
731
  stopReason: res.stopReason,
689
732
  status: cancelled ? "cancelled" : "completed",
@@ -695,7 +738,7 @@ export class AcpClient implements AgentClient {
695
738
  messages,
696
739
  stopReason: res.stopReason,
697
740
  status: cancelled ? "cancelled" : "completed",
698
- usage: (res.usage ?? null) as PromptResult["usage"],
741
+ usage: usage.ok ? usage.usage : null,
699
742
  };
700
743
  } finally {
701
744
  this.active = null;
@@ -763,6 +806,19 @@ export class AcpClient implements AgentClient {
763
806
  }
764
807
  }
765
808
 
809
+ if (kind === "usage_update") {
810
+ // Fired before the active-turn gate: a usage update is session state, and dropping
811
+ // it between turns would lose the context/cost observation entirely.
812
+ this.lastUsageUpdate = { update, sessionId: notification.sessionId ?? null };
813
+ for (const listener of [...this.usageUpdateListeners]) {
814
+ try {
815
+ listener(update, notification.sessionId ?? null);
816
+ } catch (err) {
817
+ this.log.warn("usage_update_listener_failed", { error: String(err) });
818
+ }
819
+ }
820
+ }
821
+
766
822
  if (!this.active) {
767
823
  if (this.replay && (!notification.sessionId || notification.sessionId === this.replay.sessionId)) {
768
824
  this.replay.onUpdate?.(notification);
package/src/controller.ts CHANGED
@@ -111,6 +111,10 @@ export class AgentController implements AgentClient {
111
111
  (commands: readonly InternalSessionCommand[]) => void
112
112
  >();
113
113
  private detachAvailableCommands: (() => void) | null = null;
114
+ private readonly usageUpdateListeners = new Set<
115
+ (update: unknown, sessionId: string | null) => void
116
+ >();
117
+ private detachUsageUpdates: (() => void) | null = null;
114
118
 
115
119
  constructor(private readonly config: AgentControllerConfig) {
116
120
  this.mode = config.mode ?? "normal";
@@ -165,6 +169,16 @@ export class AgentController implements AgentClient {
165
169
  return () => this.availableCommandListeners.delete(listener);
166
170
  }
167
171
 
172
+ /**
173
+ * Observe raw ACP `usage_update` notifications (context window, provider cost).
174
+ *
175
+ * Degraded (pty) mode has no ACP notifications, so this simply never fires there.
176
+ */
177
+ subscribeUsageUpdate(listener: (update: unknown, sessionId: string | null) => void): () => void {
178
+ this.usageUpdateListeners.add(listener);
179
+ return () => this.usageUpdateListeners.delete(listener);
180
+ }
181
+
168
182
  async start(): Promise<ConnectResult> {
169
183
  if (this.current) {
170
184
  return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
@@ -176,6 +190,19 @@ export class AgentController implements AgentClient {
176
190
  return brought.result;
177
191
  }
178
192
 
193
+ /** Explicitly create a fresh provider thread, ignoring any startup load target. */
194
+ async startFresh(): Promise<ConnectResult> {
195
+ if (this.current) {
196
+ if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
197
+ return await this.newSession();
198
+ }
199
+ const brought = await this.bringUp(this.mode);
200
+ this.current = brought.client;
201
+ this.acp = brought.acp;
202
+ this.attachAvailableCommandSource();
203
+ return brought.result;
204
+ }
205
+
179
206
  prompt(
180
207
  text: string,
181
208
  handlers?: PromptHandlers,
@@ -223,6 +250,8 @@ export class AgentController implements AgentClient {
223
250
  this.acp = null;
224
251
  this.detachAvailableCommands?.();
225
252
  this.detachAvailableCommands = null;
253
+ this.detachUsageUpdates?.();
254
+ this.detachUsageUpdates = null;
226
255
  this.emitAvailableCommands(NO_AVAILABLE_COMMANDS);
227
256
  if (client) await client.stop();
228
257
  }
@@ -461,6 +490,20 @@ export class AgentController implements AgentClient {
461
490
  this.detachAvailableCommands = this.acp?.subscribeAvailableCommands((commands) =>
462
491
  this.emitAvailableCommands(commands)) ?? null;
463
492
  this.emitAvailableCommands(this.acp?.availableCommands ?? NO_AVAILABLE_COMMANDS);
493
+
494
+ this.detachUsageUpdates?.();
495
+ this.detachUsageUpdates =
496
+ this.acp?.subscribeUsageUpdate((update, sessionId) => {
497
+ for (const listener of [...this.usageUpdateListeners]) {
498
+ try {
499
+ listener(update, sessionId);
500
+ } catch (err) {
501
+ this.config.logger?.warn("controller_usage_update_listener_failed", {
502
+ error: String(err),
503
+ });
504
+ }
505
+ }
506
+ }) ?? null;
464
507
  }
465
508
 
466
509
  private emitAvailableCommands(commands: readonly InternalSessionCommand[]): void {