@qlairoslabs/acp-client 0.11.0 → 0.12.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 (85) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +311 -17
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +3 -1
  8. package/src/agent/adoption/checkpoint-floor.ts +47 -0
  9. package/src/agent/adoption/index.ts +3 -1
  10. package/src/agent/adoption/replay.ts +15 -0
  11. package/src/agent/config.ts +4 -0
  12. package/src/agent/conversation-manager.ts +223 -153
  13. package/src/agent/error-record-writer.ts +77 -0
  14. package/src/agent/persisted-lifecycle.ts +152 -35
  15. package/src/agent/record-capture.ts +18 -18
  16. package/src/agent-adapter-registry.ts +2 -0
  17. package/src/agent-client.ts +9 -3
  18. package/src/agent-conversation-contracts.ts +6 -0
  19. package/src/agent-conversation-owner.ts +31 -6
  20. package/src/agent-conversation-presentation.ts +12 -1
  21. package/src/agent-conversation-queue.ts +3 -2
  22. package/src/agent-session.ts +537 -96
  23. package/src/agent.ts +46 -23
  24. package/src/audit/config.ts +4 -0
  25. package/src/audit/projection.ts +3 -0
  26. package/src/checkpointing/contracts.ts +28 -3
  27. package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
  28. package/src/checkpointing/recovery.ts +9 -2
  29. package/src/checkpointing/strategy.ts +27 -2
  30. package/src/client.ts +120 -30
  31. package/src/controller.ts +116 -7
  32. package/src/degraded/pty-client.ts +25 -1
  33. package/src/identity/checkpoint-backed.ts +2 -2
  34. package/src/index.ts +17 -0
  35. package/src/internal-inference/config.ts +7 -0
  36. package/src/internal-inference/contracts.ts +3 -0
  37. package/src/internal-inference/coordination/handles.ts +11 -2
  38. package/src/internal-inference/coordination/manager.ts +20 -3
  39. package/src/internal-inference/index.ts +2 -0
  40. package/src/internal-inference/persistence/records.ts +3 -1
  41. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  42. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  43. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  44. package/src/media/acp.ts +118 -0
  45. package/src/media/capture.ts +15 -0
  46. package/src/media/content.ts +142 -0
  47. package/src/media/files.ts +28 -0
  48. package/src/media/parts.ts +145 -0
  49. package/src/media/pending.ts +51 -0
  50. package/src/media/redact.ts +14 -0
  51. package/src/media/store.ts +127 -0
  52. package/src/metering/provider.ts +8 -1
  53. package/src/operations/activity-tracker.ts +31 -0
  54. package/src/operations/contracts.ts +63 -0
  55. package/src/operations/errors.ts +31 -0
  56. package/src/operations/index.ts +6 -0
  57. package/src/operations/stale-policy.ts +51 -0
  58. package/src/operations/supervisor.ts +209 -0
  59. package/src/operations/timers.ts +12 -0
  60. package/src/out-of-band-messages.ts +49 -32
  61. package/src/persistence/audit-runtime.ts +14 -2
  62. package/src/persistence/backend.ts +108 -12
  63. package/src/persistence/error-records.ts +27 -0
  64. package/src/persistence/index.ts +8 -0
  65. package/src/persistence/presentation.ts +9 -1
  66. package/src/persistence/projection.ts +20 -0
  67. package/src/persistence/records.ts +45 -6
  68. package/src/persistence/sqlite-backend.ts +207 -16
  69. package/src/persistence/sqlite-conversation-records.ts +31 -4
  70. package/src/persistence/sqlite-files.ts +95 -0
  71. package/src/persistence/sqlite-media-store.ts +67 -0
  72. package/src/persistence/sqlite-schema.ts +146 -13
  73. package/src/persistence/state-runtime.ts +2 -0
  74. package/src/persistence/timeline-reconcile.ts +21 -4
  75. package/src/persistence/transcript-reader.ts +11 -4
  76. package/src/persistence/transcript-runtime.ts +105 -12
  77. package/src/repl/repl.ts +1 -1
  78. package/src/response.ts +40 -8
  79. package/src/steering/combine.ts +11 -4
  80. package/src/steering/contracts.ts +14 -4
  81. package/src/steering/controller.ts +96 -21
  82. package/src/steering/index.ts +1 -0
  83. package/src/transport/acp-transport.ts +18 -7
  84. package/src/types.ts +7 -0
  85. package/src/updates.ts +4 -4
@@ -0,0 +1,142 @@
1
+ import type { MediaCaptureLevel } from "./capture.ts";
2
+ import type { MediaStore } from "./store.ts";
3
+ import { isMediaPart, mediaMention, type ResolvedPart } from "./parts.ts";
4
+ import type { PersistedContent, PersistedContentBlock, PersistenceJsonValue } from "../persistence/backend.ts";
5
+
6
+ /** Keys whose values are bytes or store handles: never search text. */
7
+ const NON_TEXT_KEYS = new Set(["data", "blob", "bytes", "ref", "refs", "sha256"]);
8
+
9
+ /** The searchable text of recorded content. Media blocks have none: their metadata has its own search. */
10
+ export function contentText(content: PersistedContent | undefined): string {
11
+ if (typeof content === "string") return content;
12
+ if (!content) return "";
13
+ return content.map((block) => {
14
+ switch (block.type) {
15
+ case "text":
16
+ case "pasted":
17
+ return block.text;
18
+ case "image":
19
+ return block.alt ?? "";
20
+ case "resource":
21
+ return [block.title, block.text].filter(Boolean).join("\n");
22
+ case "media":
23
+ return "";
24
+ default:
25
+ return jsonText(block.value);
26
+ }
27
+ }).filter(Boolean).join("\n");
28
+ }
29
+
30
+ function jsonText(value: PersistenceJsonValue | undefined): string {
31
+ return value === undefined
32
+ ? ""
33
+ : JSON.stringify(value, (key, child) => (NON_TEXT_KEYS.has(key) ? undefined : child));
34
+ }
35
+
36
+ /**
37
+ * Reuse of kept copies across the revisions of one assistant message: a part already stored keeps its
38
+ * ref. Refs found during a transaction are added to `cache` only after it commits.
39
+ */
40
+ export interface StoredPartCache {
41
+ readonly cache: WeakMap<object, string>;
42
+ readonly pending: Array<readonly [object, string]>;
43
+ }
44
+
45
+ /**
46
+ * Build the byte-free blocks a record holds, storing the copies that are kept. This is where the
47
+ * `media` capture level and each part's `keep` and `record` are applied. With a backend store, call
48
+ * it inside the record's transaction so the bytes and the record commit together.
49
+ */
50
+ export async function persistParts(
51
+ parts: readonly ResolvedPart[],
52
+ owner: string,
53
+ store?: MediaStore,
54
+ capture: MediaCaptureLevel = "content",
55
+ reuse?: StoredPartCache,
56
+ ): Promise<PersistedContent> {
57
+ const blocks: PersistedContentBlock[] = [];
58
+ for (const part of parts) {
59
+ if (part.record === false) continue;
60
+ if (!isMediaPart(part)) {
61
+ blocks.push(part.kind === "text"
62
+ ? { type: "text", text: part.text }
63
+ : { type: "pasted", text: part.text, ...(part.name ? { name: part.name } : {}) });
64
+ continue;
65
+ }
66
+ // A part's own `keep` wins over the capture level.
67
+ if (capture === "none" && part.keep === undefined) continue;
68
+ const keep = part.mode === "copy" && (part.keep ?? (capture === "content" && Boolean(store)));
69
+ let ref: string | undefined;
70
+ if (keep) {
71
+ if (!store) throw new Error("keep: true requires a media store");
72
+ ref = part.ref ?? reuse?.cache.get(part) ?? await store.put(part.data!, {
73
+ owner,
74
+ kind: part.kind,
75
+ mimeType: part.mimeType,
76
+ ...(part.name ? { name: part.name } : {}),
77
+ size: part.data!.byteLength,
78
+ sha256: part.sha256!,
79
+ });
80
+ reuse?.pending.push([part, ref]);
81
+ }
82
+ blocks.push({
83
+ type: "media",
84
+ kind: part.kind,
85
+ mode: part.mode,
86
+ mimeType: part.mimeType,
87
+ ...(part.name ? { name: part.name } : {}),
88
+ ...(part.size !== undefined ? { size: part.size } : {}),
89
+ ...(part.sha256 ? { sha256: part.sha256 } : {}),
90
+ ...(ref ? { ref } : {}),
91
+ ...(part.uri ? { uri: part.uri } : {}),
92
+ });
93
+ }
94
+ return blocks.every((block) => block.type === "text")
95
+ ? blocks.map((block) => (block.type === "text" ? block.text : "")).join("")
96
+ : blocks;
97
+ }
98
+
99
+ /**
100
+ * Restore recorded content for delivery. Links are never opened by the library. A copy whose bytes
101
+ * were not kept, or were deleted since, is named instead of sent.
102
+ */
103
+ export async function contentParts(content: PersistedContent, store?: MediaStore): Promise<readonly ResolvedPart[]> {
104
+ if (typeof content === "string") return content ? [{ kind: "text", text: content }] : [];
105
+ const parts: ResolvedPart[] = [];
106
+ for (const block of content) {
107
+ if (block.type === "text") {
108
+ parts.push({ kind: "text", text: block.text });
109
+ } else if (block.type === "pasted") {
110
+ parts.push({ kind: "pasted", text: block.text, ...(block.name ? { name: block.name } : {}) });
111
+ } else if (block.type !== "media") {
112
+ const text = contentText([block]);
113
+ if (text) parts.push({ kind: "text", text });
114
+ } else if (block.mode === "link") {
115
+ parts.push({
116
+ kind: block.kind,
117
+ mode: "link",
118
+ uri: block.uri!,
119
+ mimeType: block.mimeType,
120
+ name: block.name,
121
+ size: block.size,
122
+ });
123
+ } else {
124
+ const stored = block.ref ? await store?.get(block.ref) : undefined;
125
+ if (!stored) {
126
+ parts.push({ kind: "text", text: mediaMention(block, "not available") });
127
+ continue;
128
+ }
129
+ parts.push({
130
+ kind: block.kind,
131
+ mode: "copy",
132
+ data: stored.data,
133
+ ref: stored.ref,
134
+ mimeType: block.mimeType,
135
+ name: block.name,
136
+ size: block.size,
137
+ sha256: block.sha256,
138
+ });
139
+ }
140
+ }
141
+ return parts;
142
+ }
@@ -0,0 +1,28 @@
1
+ import type { AgentConversationId } from "../agent-ids.ts";
2
+ import type { PersistedMediaBlock } from "../persistence/backend.ts";
3
+ import type { MediaKind } from "./parts.ts";
4
+
5
+ export interface SharedFileQuery {
6
+ readonly agentConversationId?: AgentConversationId;
7
+ readonly text?: string;
8
+ readonly name?: string;
9
+ readonly kind?: MediaKind;
10
+ readonly mimeType?: string;
11
+ readonly minSize?: number;
12
+ readonly maxSize?: number;
13
+ readonly limit?: number;
14
+ readonly cursor?: string;
15
+ }
16
+ export interface SharedFile extends PersistedMediaBlock {
17
+ readonly agentConversationId: AgentConversationId;
18
+ readonly recordId: string;
19
+ readonly sequence: number;
20
+ readonly timestamp: string;
21
+ readonly role: "assistant" | "user";
22
+ readonly partIndex: number;
23
+ }
24
+ export interface SharedFilePage { readonly files: readonly SharedFile[]; readonly nextCursor?: string; }
25
+ export interface SharedFilesPersistence {
26
+ list(query?: SharedFileQuery): Promise<SharedFilePage>;
27
+ search(query: SharedFileQuery & { readonly text: string }): Promise<SharedFilePage>;
28
+ }
@@ -0,0 +1,145 @@
1
+ /** Parts accepted for user, assistant, and out-of-band messages. */
2
+ export type MessagePart =
3
+ | { kind: "text"; text: string; record?: false }
4
+ | { kind: "pasted"; text: string; name?: string; record?: false }
5
+ | MediaPart;
6
+
7
+ export type MediaKind = "image" | "audio" | "file";
8
+
9
+ /**
10
+ * A media part has exactly one source: bytes (`data`), a file (`path`, a path or `file://` uri),
11
+ * or a copy already kept in the media store (`ref`). `mode` says what the agent receives: a copy of
12
+ * the content, or a link to the original. Unset, it is chosen by size.
13
+ */
14
+ export type MediaPart = {
15
+ kind: MediaKind;
16
+ mimeType?: string;
17
+ name?: string;
18
+ mode?: "copy" | "link";
19
+ /** Copies only: whether the bytes are kept in the media store. */
20
+ keep?: boolean;
21
+ /** `false`: sent to the agent, not recorded at all. */
22
+ record?: false;
23
+ } & (
24
+ | { data: Uint8Array; path?: never; ref?: never }
25
+ | { path: string; data?: never; ref?: never }
26
+ | { ref: string; data?: never; path?: never }
27
+ );
28
+
29
+ /** Size, in bytes, above which a `path` part with no `mode` goes as a link. */
30
+ export type MediaThresholds = Readonly<Partial<Record<MediaKind, number>>>;
31
+
32
+ /**
33
+ * Text costs about 4 bytes a token, so 100 KB of a text file is about 25k tokens. Images cost by their
34
+ * pixels, and the providers' per-image limits (about 5 MB) likely apply to the base64 form.
35
+ */
36
+ export const DEFAULT_MEDIA_THRESHOLDS = Object.freeze({ file: 100_000, image: 3_750_000, audio: 5_000_000 });
37
+
38
+ /** A media part after its source was read and its mode decided. */
39
+ export type ResolvedMediaPart = {
40
+ kind: MediaKind;
41
+ mode: "copy" | "link";
42
+ mimeType: string;
43
+ name?: string;
44
+ /** Unknown for a link the agent sent without one, or to a file that could not be read. */
45
+ size?: number;
46
+ sha256?: string;
47
+ /** Copies: the content to send. */
48
+ data?: Uint8Array;
49
+ /** Links: the absolute `file://` uri of the original. */
50
+ uri?: string;
51
+ /** A copy already kept by this conversation. */
52
+ ref?: string;
53
+ keep?: boolean;
54
+ record?: false;
55
+ };
56
+
57
+ export type ResolvedPart = Exclude<MessagePart, MediaPart> | ResolvedMediaPart;
58
+
59
+ /** SVG is XML text: it goes as a file, not as an image. */
60
+ export function mediaKind(mimeType?: string): MediaKind {
61
+ if (mimeType?.startsWith("image/") && mimeType !== "image/svg+xml") return "image";
62
+ if (mimeType?.startsWith("audio/")) return "audio";
63
+ return "file";
64
+ }
65
+
66
+ export function isMediaPart<T extends MessagePart | ResolvedPart>(
67
+ part: T,
68
+ ): part is Exclude<T, { kind: "text" | "pasted" }> {
69
+ return part.kind !== "text" && part.kind !== "pasted";
70
+ }
71
+
72
+ /** Validate source and policy before reading files or writing a store. */
73
+ export function normalizeParts(parts: readonly MessagePart[]): readonly MessagePart[] {
74
+ return parts.map((part) => {
75
+ if (!isMediaPart(part)) return { ...part };
76
+ const sources = [part.data, part.path, part.ref].filter((source) => source !== undefined);
77
+ if (sources.length !== 1) throw new Error("media requires exactly one of data, path, or ref");
78
+ if (part.mode !== undefined && part.mode !== "copy" && part.mode !== "link") {
79
+ throw new Error("media mode must be copy or link");
80
+ }
81
+ if (part.data !== undefined && !(part.data instanceof Uint8Array)) {
82
+ throw new Error("media data must be a Uint8Array");
83
+ }
84
+ if (part.path !== undefined && (typeof part.path !== "string" || !part.path.trim())) {
85
+ throw new Error("media path cannot be blank");
86
+ }
87
+ if (part.ref !== undefined && (typeof part.ref !== "string" || !part.ref.trim())) {
88
+ throw new Error("media ref cannot be blank");
89
+ }
90
+ if (part.keep !== undefined && typeof part.keep !== "boolean") throw new Error("media keep must be boolean");
91
+ // Only a file can be pointed to: bytes and kept copies are always copies.
92
+ if (part.mode === "link" && !part.path) throw new Error("link media requires path");
93
+ if (part.mode === "link" && part.keep !== undefined) throw new Error("keep is only valid for copies");
94
+ if (part.record === false && part.keep !== undefined) throw new Error("record: false cannot specify keep");
95
+ return { ...part, kind: part.mimeType === "image/svg+xml" ? "file" : part.kind };
96
+ });
97
+ }
98
+
99
+ /**
100
+ * The text parts, concatenated as they are sent: text parts are segments of one text (separators
101
+ * between combined messages are their own text parts), so nothing is inserted between them.
102
+ */
103
+ export function partsText(parts: readonly MessagePart[] | readonly ResolvedPart[]): string {
104
+ return parts.map((part) => (isMediaPart(part) ? "" : part.text)).join("");
105
+ }
106
+
107
+ /** Compact text-only view for the older JSONL transcript, which has no media store. */
108
+ export function transcriptParts(parts: readonly (MessagePart | ResolvedPart)[]): string {
109
+ return parts
110
+ .filter((part) => part.record !== false)
111
+ .map((part) => (isMediaPart(part) ? mediaMention(part) : part.text))
112
+ .join("\n");
113
+ }
114
+
115
+ /** How a media part is named in text: `[image plot.png]`. */
116
+ export function mediaMention(part: { kind: MediaKind; name?: string }, note?: string): string {
117
+ return `[${part.kind}${part.name ? ` ${part.name}` : ""}${note ? `: ${note}` : ""}]`;
118
+ }
119
+
120
+ /** Object-form text is an optional leading part when structured parts are supplied. */
121
+ export function promptParts(
122
+ input: { readonly text?: string; readonly parts?: readonly MessagePart[] },
123
+ ): readonly MessagePart[] | undefined {
124
+ if (!input.parts) return undefined;
125
+ return [...(input.text ? [{ kind: "text" as const, text: input.text }] : []), ...input.parts];
126
+ }
127
+
128
+ /**
129
+ * The input form of already resolved parts, to send them through a client: copies carry their bytes
130
+ * and links their uri, so resolving them again reads nothing and decides nothing new.
131
+ */
132
+ export function unresolvedParts(parts: readonly ResolvedPart[]): readonly MessagePart[] {
133
+ return parts.map((part): MessagePart => {
134
+ if (!isMediaPart(part)) return part;
135
+ const common = {
136
+ kind: part.kind,
137
+ mimeType: part.mimeType,
138
+ ...(part.name !== undefined ? { name: part.name } : {}),
139
+ ...(part.record === false ? { record: false as const } : {}),
140
+ };
141
+ return part.mode === "link"
142
+ ? { ...common, mode: "link", path: part.uri! }
143
+ : { ...common, mode: "copy", data: part.data!, ...(part.keep !== undefined ? { keep: part.keep } : {}) };
144
+ });
145
+ }
@@ -0,0 +1,51 @@
1
+ import type { AgentConversationId } from "../agent-ids.ts";
2
+ import { supportsCopy, type MediaCapabilities } from "./acp.ts";
3
+ import { isMediaPart, mediaMention, type ResolvedPart } from "./parts.ts";
4
+
5
+ /**
6
+ * Out-of-band parts waiting for the next turn, as they were appended, keyed by record id. They live
7
+ * in memory only: parts that are not kept (`keep: false`, `record: false`) are never written
8
+ * anywhere. After a restart a waiting message is delivered from its record, and a copy whose bytes
9
+ * were not kept is named instead of sent.
10
+ */
11
+ export type PendingOutOfBandParts = Map<string, {
12
+ readonly owner: AgentConversationId;
13
+ readonly parts: readonly ResolvedPart[];
14
+ }>;
15
+
16
+ const pendingByAgent = new WeakMap<object, PendingOutOfBandParts>();
17
+
18
+ /** The waiting parts of one Agent. */
19
+ export function pendingOutOfBandParts(agent: object): PendingOutOfBandParts {
20
+ let pending = pendingByAgent.get(agent);
21
+ if (!pending) {
22
+ pending = new Map();
23
+ pendingByAgent.set(agent, pending);
24
+ }
25
+ return pending;
26
+ }
27
+
28
+ /** Drop the waiting parts of one conversation. */
29
+ export function forgetPendingParts(agent: object, owner: AgentConversationId): void {
30
+ const pending = pendingOutOfBandParts(agent);
31
+ for (const [recordId, entry] of pending) if (entry.owner === owner) pending.delete(recordId);
32
+ }
33
+
34
+ /**
35
+ * What an out-of-band message can deliver to this agent. Its parts were accepted when it was appended,
36
+ * whatever agent would read them, so a copy the agent cannot take is named instead of refusing the
37
+ * turn: a refused turn would never deliver it, and every later turn would fail the same way. A pty
38
+ * agent takes text only.
39
+ */
40
+ export function deliverableParts(
41
+ parts: readonly ResolvedPart[],
42
+ capabilities: MediaCapabilities | undefined,
43
+ degraded = false,
44
+ ): readonly ResolvedPart[] {
45
+ return parts.map((part): ResolvedPart => {
46
+ if (!isMediaPart(part)) return part;
47
+ if (degraded) return { kind: "text", text: mediaMention(part) };
48
+ if (part.mode === "link" || supportsCopy(part.kind, capabilities)) return part;
49
+ return { kind: "text", text: mediaMention(part, "not supported by this agent") };
50
+ });
51
+ }
@@ -0,0 +1,14 @@
1
+ /** Remove inline bytes recursively before debug/protocol persistence. Never changes the wire. */
2
+ export function redactMedia<T>(value: T): T {
3
+ if (Array.isArray(value)) return value.map(redactMedia) as T;
4
+ if (!value || typeof value !== "object") return value;
5
+ if (value instanceof Uint8Array) return { byteLength: value.byteLength } as T;
6
+ const embedded = value as { uri?: unknown; text?: unknown };
7
+ if (typeof embedded.uri === "string" && typeof embedded.text === "string") {
8
+ return { ...value, text: { byteLength: Buffer.byteLength(embedded.text) } } as T;
9
+ }
10
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key,
11
+ (key === "data" || key === "blob") && typeof child === "string"
12
+ ? { byteLength: Buffer.byteLength(child, "base64") } : redactMedia(child),
13
+ ])) as T;
14
+ }
@@ -0,0 +1,127 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { basename, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { hashBytes, supportsCopy, type MediaCapabilities } from "./acp.ts";
5
+ import {
6
+ DEFAULT_MEDIA_THRESHOLDS,
7
+ isMediaPart,
8
+ normalizeParts,
9
+ type MediaKind,
10
+ type MessagePart,
11
+ type MediaThresholds,
12
+ type ResolvedPart,
13
+ } from "./parts.ts";
14
+
15
+ export interface MediaInfo {
16
+ /** The conversation the copy belongs to. */
17
+ readonly owner: string;
18
+ readonly kind: MediaKind;
19
+ readonly mimeType: string;
20
+ readonly name?: string;
21
+ readonly size: number;
22
+ readonly sha256: string;
23
+ }
24
+
25
+ export interface StoredMedia {
26
+ readonly ref: string;
27
+ readonly info: MediaInfo;
28
+ }
29
+
30
+ /** Where kept copies live. The SQLite backend provides one; a consumer can pass its own. */
31
+ export interface MediaStore {
32
+ put(bytes: Uint8Array, info: MediaInfo): Promise<string>;
33
+ get(ref: string): Promise<(StoredMedia & { readonly data: Uint8Array }) | null>;
34
+ delete(ref: string): Promise<void>;
35
+ /** Every copy of one conversation, so a cleanup pass can find bytes a failed write left behind. */
36
+ list(owner: string): Promise<readonly StoredMedia[]>;
37
+ }
38
+
39
+ export interface MediaConfig {
40
+ /** Replaces the persistence backend's own store. */
41
+ readonly store?: MediaStore;
42
+ readonly thresholds?: MediaThresholds;
43
+ }
44
+
45
+ export interface ResolvePartsOptions {
46
+ /** Relative paths resolve against it. */
47
+ cwd: string;
48
+ /** The conversation sending the parts: a ref it owns is reused, another one is copied. */
49
+ owner?: string;
50
+ store?: MediaStore;
51
+ thresholds?: MediaThresholds;
52
+ capabilities?: MediaCapabilities;
53
+ }
54
+
55
+ /**
56
+ * Read each part's source and decide its mode. A `path` part with no `mode` goes as a link above its
57
+ * kind's threshold, or when the agent cannot take a copy of its kind. An explicit copy the agent cannot
58
+ * take is refused.
59
+ */
60
+ export async function resolveParts(
61
+ parts: readonly MessagePart[],
62
+ options: ResolvePartsOptions,
63
+ ): Promise<readonly ResolvedPart[]> {
64
+ for (const [kind, threshold] of Object.entries(options.thresholds ?? {})) {
65
+ if (!["image", "audio", "file"].includes(kind) || !Number.isSafeInteger(threshold) || threshold < 0) {
66
+ throw new Error(`invalid media threshold for ${kind}`);
67
+ }
68
+ }
69
+ const result: ResolvedPart[] = [];
70
+ for (const part of normalizeParts(parts)) {
71
+ if (!isMediaPart(part)) {
72
+ result.push(part);
73
+ continue;
74
+ }
75
+ if (part.ref) {
76
+ const stored = await options.store?.get(part.ref);
77
+ if (!stored) throw new Error(`media ref is missing or removed: ${part.ref}`);
78
+ if (!supportsCopy(part.kind, options.capabilities)) throw new Error(`agent does not support ${part.kind} copies`);
79
+ result.push({
80
+ kind: part.kind,
81
+ mode: "copy",
82
+ mimeType: part.mimeType ?? stored.info.mimeType,
83
+ name: part.name ?? stored.info.name,
84
+ size: stored.data.byteLength,
85
+ sha256: stored.info.sha256,
86
+ data: new Uint8Array(stored.data),
87
+ // Another conversation's copy is stored again, so each conversation owns its copies.
88
+ ...(stored.info.owner === options.owner ? { ref: stored.ref } : {}),
89
+ ...(part.keep === undefined ? {} : { keep: part.keep }),
90
+ ...(part.record === false ? { record: false as const } : {}),
91
+ });
92
+ continue;
93
+ }
94
+ const path = part.path === undefined
95
+ ? undefined
96
+ : resolve(options.cwd, part.path.startsWith("file:") ? fileURLToPath(part.path) : part.path);
97
+ const mimeType = part.mimeType ?? ((path ? Bun.file(path).type : "") || "application/octet-stream");
98
+ const kind = mimeType === "image/svg+xml" ? "file" : part.kind;
99
+ // A link is not opened by the library: a file it cannot read is the agent's to report.
100
+ const size = path
101
+ ? await stat(path).then((info) => info.size, (error) => {
102
+ if (part.mode === "link") return undefined;
103
+ throw error;
104
+ })
105
+ : part.data!.byteLength;
106
+ const threshold = options.thresholds?.[kind] ?? DEFAULT_MEDIA_THRESHOLDS[kind];
107
+ let mode = part.mode ?? (path && size! > threshold ? "link" : "copy");
108
+ if (mode === "copy" && !supportsCopy(kind, options.capabilities)) {
109
+ if (part.mode === undefined && path) mode = "link";
110
+ else throw new Error(`agent does not support ${part.kind} copies`);
111
+ }
112
+ if (mode === "link" && part.keep !== undefined) throw new Error("keep is only valid for copies");
113
+ let data: Uint8Array | undefined;
114
+ if (mode === "copy") data = path ? new Uint8Array(await readFile(path)) : new Uint8Array(part.data!);
115
+ result.push({
116
+ kind,
117
+ mode,
118
+ mimeType,
119
+ name: part.name ?? (path ? basename(path) : undefined),
120
+ ...(data ? { size: data.byteLength } : size !== undefined ? { size } : {}),
121
+ ...(data ? { data, sha256: hashBytes(data) } : { uri: pathToFileURL(path!).href }),
122
+ ...(part.record === false ? { record: false as const } : {}),
123
+ ...(part.keep === undefined ? {} : { keep: part.keep }),
124
+ });
125
+ }
126
+ return result;
127
+ }
@@ -106,8 +106,15 @@ export type CounterInterpretation = "cumulative" | "per_turn";
106
106
  * (every turn re-reads the same cached context), which is why comparing totals is not a
107
107
  * valid test and reported "cumulative" until the components were checked.
108
108
  * See .res/somelogs.md/9-5+/9-6-harness-matrix-findings.md, Finding 5.
109
+ *
110
+ * Codex: two plain turns of one session (no cancel, no steering) reported
111
+ * total/input/output/cachedRead of 17948/782/14/17152 and then 18080/7059/13/11008. Each report
112
+ * satisfies `total === input + output + cachedRead` on its own, and input, output and cachedRead
113
+ * move both ways between turns, which no cumulative counter can do; read as cumulative the second
114
+ * turn was a `counter_reset` ("outputTokens decreased from 14 to 13").
115
+ * See .res/somelogs.md/9-22+/10-4-LOG-adopt-provider-session.md, "Real-harness pass".
109
116
  */
110
- const PER_TURN_ADAPTERS: ReadonlySet<string> = new Set(["opencode"]);
117
+ const PER_TURN_ADAPTERS: ReadonlySet<string> = new Set(["opencode", "codex"]);
111
118
 
112
119
  /**
113
120
  * The interpretation to apply for an adapter.
@@ -0,0 +1,31 @@
1
+ import type { ActivityEvent } from "../types.ts";
2
+
3
+ const terminal = new Set(["completed", "failed"]);
4
+
5
+ /**
6
+ * Which tool calls are in flight, and since when. Timing state only; tool content stays in the
7
+ * presentation aggregator.
8
+ */
9
+ export class ToolTracker {
10
+ private readonly tools = new Map<string, { status: string; startedAt: number }>();
11
+
12
+ get inFlight(): number {
13
+ return [...this.tools.values()].filter((tool) => !terminal.has(tool.status)).length;
14
+ }
15
+
16
+ get oldestStartedAt(): number | null {
17
+ const starts = [...this.tools.values()]
18
+ .filter((tool) => !terminal.has(tool.status))
19
+ .map((tool) => tool.startedAt);
20
+ return starts.length ? Math.min(...starts) : null;
21
+ }
22
+
23
+ /** True when this update settles a previously unsettled tool. */
24
+ observe(event: ActivityEvent, now = Date.now()): boolean {
25
+ if (event.kind !== "tool" && event.kind !== "tool_update") return false;
26
+ const previous = this.tools.get(event.toolCallId);
27
+ const status = event.status ?? previous?.status ?? "pending";
28
+ this.tools.set(event.toolCallId, { status, startedAt: previous?.startedAt ?? now });
29
+ return terminal.has(status) && !terminal.has(previous?.status ?? "pending");
30
+ }
31
+ }
@@ -0,0 +1,63 @@
1
+ // Shared types for the operation lifecycle: what a supervised provider request looks like from the
2
+ // outside (its stage and timestamps) and what the provider is observed to send while it runs.
3
+ // Spec: .res/somelogs.md/9-22+/10-17-SPEC-operation-lifecycle.md.
4
+
5
+ import type { ActivityEvent } from "../types.ts";
6
+
7
+ /**
8
+ * Anything the provider sent for a session: a `session/update`, or a request from the agent to the
9
+ * client. Permission requests are reported when they start and when they are answered.
10
+ */
11
+ export type ProviderOutput =
12
+ | { readonly kind: "update"; readonly sessionId: string | null; readonly activity?: ActivityEvent }
13
+ | { readonly kind: "request" | "permission_started" | "permission_ended"; readonly sessionId: string | null };
14
+
15
+ export type OutputListener = (output: ProviderOutput) => void;
16
+
17
+ /** What a running operation is waiting on. */
18
+ export type OperationStage = "waiting" | "streaming" | "tool_running" | "awaiting_permission" | "cancelling";
19
+
20
+ export type SupervisedOperationKind = "turn" | "internal_inference" | "recap";
21
+
22
+ /**
23
+ * Why a cancel was requested. The persisted copies (JSONL validation, SQLite CHECK) derive from or
24
+ * are tested against these lists.
25
+ */
26
+ export const CANCEL_REASONS = ["interrupt", "steer", "stalled", "stop", "abort"] as const;
27
+ export type CancelReason = typeof CANCEL_REASONS[number];
28
+
29
+ /**
30
+ * How a requested cancel ended: the provider stopped (`acknowledged`), the process was killed
31
+ * (`forced`), the operation finished on its own first (`too_late`), or it ended in an error, thrown or
32
+ * reported as an `error` result (`failed`).
33
+ */
34
+ export const CANCEL_OUTCOMES = ["acknowledged", "forced", "too_late", "failed"] as const;
35
+ export type CancelOutcome = typeof CANCEL_OUTCOMES[number];
36
+
37
+ /** The readable state of one running operation. Contains no content. */
38
+ export interface OperationActivity {
39
+ readonly operationId: string;
40
+ readonly kind: SupervisedOperationKind;
41
+ readonly stage: OperationStage;
42
+ readonly startedAt: number;
43
+ readonly lastOutputAt: number | null;
44
+ readonly toolsInFlight: number;
45
+ readonly cancel?: { readonly reason: CancelReason; readonly requestedAt: number };
46
+ }
47
+
48
+ /** When an operation counts as stale. `false` disables a condition. */
49
+ export interface StaleLimits {
50
+ /** No output at all since the request was sent. Default 120 000. */
51
+ readonly firstOutputMs?: number | false;
52
+ /** No output since the last one, with no tool or permission explaining it. Default 180 000. */
53
+ readonly nextOutputMs?: number | false;
54
+ /** One tool running longer than this. Off by default. */
55
+ readonly toolMs?: number | false;
56
+ }
57
+
58
+ /** Stale limits per operation kind. */
59
+ export interface OperationLifecycleConfig {
60
+ readonly turns?: StaleLimits;
61
+ readonly internalInference?: StaleLimits;
62
+ readonly recap?: StaleLimits;
63
+ }
@@ -0,0 +1,31 @@
1
+ import type { ResponseMessage } from "../types.ts";
2
+ import type { OperationMeteringRecord } from "../metering/record.ts";
3
+ import type { StallPhase } from "./stale-policy.ts";
4
+
5
+ /**
6
+ * The provider stopped producing output and the request was cancelled. `phase` says whether
7
+ * anything had arrived; `messages` holds what did.
8
+ */
9
+ export class OperationStalledError extends Error {
10
+ readonly code = "stalled";
11
+ readonly data: { providerCode: string; phase: StallPhase };
12
+ messages: readonly ResponseMessage[] = Object.freeze([]);
13
+ /** Steers delivered right after this turn, as the recovery prompt. */
14
+ followedBy?: readonly string[];
15
+ metering?: OperationMeteringRecord;
16
+ cancel?: "acknowledged" | "forced";
17
+
18
+ constructor(readonly operationId: string, readonly phase: StallPhase) {
19
+ super(`Provider operation stalled (${phase}).`);
20
+ this.name = "OperationStalledError";
21
+ this.data = { providerCode: "stalled", phase };
22
+ }
23
+ }
24
+
25
+ /** The in-flight request ended because its provider process was killed. */
26
+ export class ForcedStopError extends Error {
27
+ constructor() {
28
+ super("Provider process was forcibly stopped.");
29
+ this.name = "ForcedStopError";
30
+ }
31
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./contracts.ts";
2
+ export * from "./timers.ts";
3
+ export * from "./activity-tracker.ts";
4
+ export * from "./supervisor.ts";
5
+ export * from "./errors.ts";
6
+ export * from "./stale-policy.ts";