@qlairoslabs/acp-client 0.11.1 → 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 (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +287 -12
  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/replay.ts +1 -0
  9. package/src/agent/config.ts +4 -0
  10. package/src/agent/conversation-manager.ts +178 -150
  11. package/src/agent/error-record-writer.ts +77 -0
  12. package/src/agent/persisted-lifecycle.ts +152 -35
  13. package/src/agent/record-capture.ts +18 -18
  14. package/src/agent-adapter-registry.ts +2 -0
  15. package/src/agent-client.ts +9 -3
  16. package/src/agent-conversation-contracts.ts +6 -0
  17. package/src/agent-conversation-owner.ts +31 -6
  18. package/src/agent-conversation-presentation.ts +12 -1
  19. package/src/agent-conversation-queue.ts +3 -2
  20. package/src/agent-session.ts +535 -94
  21. package/src/agent.ts +46 -23
  22. package/src/audit/config.ts +4 -0
  23. package/src/audit/projection.ts +3 -0
  24. package/src/checkpointing/recovery.ts +5 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +120 -30
  27. package/src/controller.ts +116 -7
  28. package/src/degraded/pty-client.ts +25 -1
  29. package/src/index.ts +17 -0
  30. package/src/internal-inference/config.ts +7 -0
  31. package/src/internal-inference/contracts.ts +3 -0
  32. package/src/internal-inference/coordination/handles.ts +11 -2
  33. package/src/internal-inference/coordination/manager.ts +20 -3
  34. package/src/internal-inference/index.ts +2 -0
  35. package/src/internal-inference/persistence/records.ts +3 -1
  36. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  37. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  38. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  39. package/src/media/acp.ts +118 -0
  40. package/src/media/capture.ts +15 -0
  41. package/src/media/content.ts +142 -0
  42. package/src/media/files.ts +28 -0
  43. package/src/media/parts.ts +145 -0
  44. package/src/media/pending.ts +51 -0
  45. package/src/media/redact.ts +14 -0
  46. package/src/media/store.ts +127 -0
  47. package/src/metering/provider.ts +8 -1
  48. package/src/operations/activity-tracker.ts +31 -0
  49. package/src/operations/contracts.ts +63 -0
  50. package/src/operations/errors.ts +31 -0
  51. package/src/operations/index.ts +6 -0
  52. package/src/operations/stale-policy.ts +51 -0
  53. package/src/operations/supervisor.ts +209 -0
  54. package/src/operations/timers.ts +12 -0
  55. package/src/out-of-band-messages.ts +49 -32
  56. package/src/persistence/audit-runtime.ts +14 -2
  57. package/src/persistence/backend.ts +108 -12
  58. package/src/persistence/error-records.ts +27 -0
  59. package/src/persistence/index.ts +8 -0
  60. package/src/persistence/presentation.ts +9 -1
  61. package/src/persistence/projection.ts +20 -0
  62. package/src/persistence/records.ts +45 -6
  63. package/src/persistence/sqlite-backend.ts +207 -16
  64. package/src/persistence/sqlite-conversation-records.ts +31 -4
  65. package/src/persistence/sqlite-files.ts +95 -0
  66. package/src/persistence/sqlite-media-store.ts +67 -0
  67. package/src/persistence/sqlite-schema.ts +86 -10
  68. package/src/persistence/state-runtime.ts +2 -0
  69. package/src/persistence/timeline-reconcile.ts +21 -4
  70. package/src/persistence/transcript-reader.ts +11 -4
  71. package/src/persistence/transcript-runtime.ts +105 -12
  72. package/src/repl/repl.ts +1 -1
  73. package/src/response.ts +40 -8
  74. package/src/steering/combine.ts +11 -4
  75. package/src/steering/contracts.ts +14 -4
  76. package/src/steering/controller.ts +96 -21
  77. package/src/steering/index.ts +1 -0
  78. package/src/transport/acp-transport.ts +18 -7
  79. package/src/types.ts +7 -0
  80. package/src/updates.ts +4 -4
@@ -1,3 +1,5 @@
1
+ import { OperationSupervisor } from "../../operations/supervisor.ts";
2
+ import type { OutputListener } from "../../operations/contracts.ts";
1
3
  import { AgentController, type AgentControllerConfig } from "../../controller.ts";
2
4
  import type { PromptResult } from "../../types.ts";
3
5
  import type {
@@ -16,6 +18,9 @@ export interface HarnessInternalInferenceRuntimeConfig {
16
18
  export interface InternalInferenceController {
17
19
  startFresh(): Promise<{ sessionId: string }>;
18
20
  prompt(text: string): Promise<PromptResult>;
21
+ subscribeOutput?(listener: OutputListener): () => void;
22
+ cancel?(): void;
23
+ forceStop?(): Promise<void>;
19
24
  interrupt(): void;
20
25
  stop(): Promise<void>;
21
26
  }
@@ -41,7 +46,8 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
41
46
  };
42
47
  const controller = this.config.createController?.(controllerConfig)
43
48
  ?? new AgentController(controllerConfig);
44
- const abort = () => controller.interrupt();
49
+ let supervisor: OperationSupervisor | undefined;
50
+ const abort = () => supervisor ? supervisor.cancel("abort") : controller.interrupt();
45
51
  signal?.addEventListener("abort", abort, { once: true });
46
52
  try {
47
53
  if (signal?.aborted) throw abortError();
@@ -50,7 +56,17 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
50
56
  await lifecycle?.sessionStarted({ internalSessionId: connection.sessionId, model: null });
51
57
  if (signal?.aborted) throw abortError();
52
58
  lifecycle?.stageChanged?.("prompting");
53
- const result = await controller.prompt(request.prompt);
59
+ supervisor = new OperationSupervisor({
60
+ prompt: () => controller.prompt(request.prompt),
61
+ subscribeOutput: (listener) => controller.subscribeOutput?.(listener) ?? (() => {}),
62
+ cancel: () => controller.cancel ? controller.cancel() : controller.interrupt(),
63
+ forceStop: () => controller.forceStop ? controller.forceStop() : controller.stop(),
64
+ }, { operationId: request.internalInferenceId, kind: "internal_inference", sessionId: connection.sessionId,
65
+ cancelGraceMs: controllerConfig.adapter.cancelGraceMs,
66
+ limits: controllerConfig.operationLifecycle?.internalInference,
67
+ onStageChanged: () => lifecycle?.operationChanged?.(() => supervisor!.activity),
68
+ });
69
+ const result = await supervisor.run();
54
70
  if (result.status !== "completed") {
55
71
  throw new Error(`internal inference prompt ${result.status}: ${result.stopReason}`);
56
72
  }
@@ -65,6 +81,7 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
65
81
  ...(request.metadata ? { metadata: request.metadata } : {}),
66
82
  });
67
83
  } finally {
84
+ lifecycle?.operationChanged?.(null);
68
85
  signal?.removeEventListener("abort", abort);
69
86
  await controller.stop();
70
87
  }
@@ -0,0 +1,118 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ContentBlock } from "@agentclientprotocol/sdk";
3
+ import type { Attachment } from "../types.ts";
4
+ import { isMediaPart, mediaKind, type MessagePart, type ResolvedPart } from "./parts.ts";
5
+
6
+ /** What an agent's `promptCapabilities` allow beyond text and links (always allowed by ACP). */
7
+ export interface MediaCapabilities {
8
+ image?: boolean;
9
+ audio?: boolean;
10
+ embeddedContext?: boolean;
11
+ }
12
+
13
+ /** The uri of an embedded copy, which names the copy, not a file. */
14
+ export const EMBEDDED_URI_SCHEME = "attachment:///";
15
+
16
+ /** MIME types sent as an embedded text resource rather than a base64 blob. */
17
+ const TEXT_MIME_TYPES = new Set(["image/svg+xml", "application/json"]);
18
+
19
+ /** Compatibility attachments are copies whose bytes are not kept. */
20
+ export function attachmentParts(attachments: readonly Attachment[] = []): MessagePart[] {
21
+ return attachments.map((attachment) => ({
22
+ kind: mediaKind(attachment.mimeType),
23
+ mimeType: attachment.mimeType,
24
+ data: new Uint8Array(attachment.data),
25
+ mode: "copy",
26
+ keep: false,
27
+ }));
28
+ }
29
+
30
+ /** Whether the agent accepts a copy of this kind. */
31
+ export function supportsCopy(kind: ResolvedPart["kind"], capabilities?: MediaCapabilities): boolean {
32
+ if (kind === "text" || kind === "pasted") return true;
33
+ return Boolean(capabilities?.[kind === "file" ? "embeddedContext" : kind]);
34
+ }
35
+
36
+ export function partsToAcp(parts: readonly ResolvedPart[]): ContentBlock[] {
37
+ return parts.map((part): ContentBlock => {
38
+ if (!isMediaPart(part)) return { type: "text", text: part.text };
39
+ if (part.mode === "link") {
40
+ return {
41
+ type: "resource_link",
42
+ uri: part.uri!,
43
+ name: part.name ?? "file",
44
+ mimeType: part.mimeType,
45
+ ...(part.size !== undefined ? { size: part.size } : {}),
46
+ };
47
+ }
48
+ const data = Buffer.from(part.data!).toString("base64");
49
+ if (part.kind === "image" || part.kind === "audio") return { type: part.kind, data, mimeType: part.mimeType };
50
+ // The content travels in the block: a `file://` uri would name a path that does not exist.
51
+ const uri = `${EMBEDDED_URI_SCHEME}${encodeURIComponent(part.name ?? "attachment")}`;
52
+ if (part.mimeType.startsWith("text/") || TEXT_MIME_TYPES.has(part.mimeType)) {
53
+ const text = new TextDecoder().decode(part.data);
54
+ return { type: "resource", resource: { uri, mimeType: part.mimeType, text } };
55
+ }
56
+ return { type: "resource", resource: { uri, mimeType: part.mimeType, blob: data } };
57
+ });
58
+ }
59
+
60
+ /** Normalize an agent content chunk without fetching resource links. */
61
+ export function acpToPart(block: ContentBlock): ResolvedPart | undefined {
62
+ switch (block.type) {
63
+ case "text":
64
+ return { kind: "text", text: block.text };
65
+ case "resource_link":
66
+ return {
67
+ kind: mediaKind(block.mimeType ?? undefined),
68
+ mode: "link",
69
+ uri: block.uri,
70
+ name: block.name,
71
+ mimeType: block.mimeType ?? "application/octet-stream",
72
+ ...(block.size != null ? { size: block.size } : {}),
73
+ };
74
+ case "image":
75
+ case "audio": {
76
+ const data = new Uint8Array(Buffer.from(block.data, "base64"));
77
+ return {
78
+ kind: block.type === "image" && block.mimeType === "image/svg+xml" ? "file" : block.type,
79
+ mode: "copy",
80
+ data,
81
+ mimeType: block.mimeType,
82
+ size: data.byteLength,
83
+ sha256: hashBytes(data),
84
+ };
85
+ }
86
+ case "resource": {
87
+ const resource = block.resource;
88
+ const isText = "text" in resource;
89
+ const data = isText
90
+ ? new TextEncoder().encode(resource.text)
91
+ : new Uint8Array(Buffer.from(resource.blob, "base64"));
92
+ const name = resource.uri.split("/").at(-1) || undefined;
93
+ return {
94
+ kind: "file",
95
+ mode: "copy",
96
+ data,
97
+ mimeType: resource.mimeType ?? (isText ? "text/plain" : "application/octet-stream"),
98
+ ...(name ? { name } : {}),
99
+ size: data.byteLength,
100
+ sha256: hashBytes(data),
101
+ };
102
+ }
103
+ default:
104
+ return undefined;
105
+ }
106
+ }
107
+
108
+ export function hashBytes(data: Uint8Array): string {
109
+ return createHash("sha256").update(data).digest("hex");
110
+ }
111
+
112
+ /** An explicit copy the agent cannot take is refused: nothing is silently dropped. */
113
+ export function assertPartCapabilities(parts: readonly ResolvedPart[], capabilities?: MediaCapabilities): void {
114
+ for (const part of parts) {
115
+ if (!isMediaPart(part) || part.mode === "link") continue;
116
+ if (!supportsCopy(part.kind, capabilities)) throw new Error(`agent does not support ${part.kind} copies`);
117
+ }
118
+ }
@@ -0,0 +1,15 @@
1
+ import type { PersistedContent, PersistedContentBlock } from "../persistence/backend.ts";
2
+
3
+ export type MediaCaptureLevel = "none" | "metadata" | "content";
4
+
5
+ /**
6
+ * Apply the message capture level to a record's content. Media blocks are left as they are: the
7
+ * `media` capture level, and each part's own `keep` and `record`, were applied when the parts were
8
+ * persisted (`persistParts`, the only place media blocks are built), so the record already holds
9
+ * what was decided for them.
10
+ */
11
+ export function captureMessageContent(content: PersistedContent, text: boolean): PersistedContent {
12
+ if (typeof content === "string") return text ? content : "";
13
+ const blocks: PersistedContentBlock[] = content.filter((block) => block.type === "media" || text);
14
+ return blocks.length === 0 ? "" : blocks;
15
+ }
@@ -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
+ }