@adroit-app/chat-core 0.0.0 → 0.1.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.
package/dist/config.js ADDED
@@ -0,0 +1,36 @@
1
+ /** The categories of setting the Chat shows, in the order it shows them, and their labels when the host names them. */
2
+ const SHOWN = [
3
+ ["model", "Model", "model"],
4
+ ["thought_level", "Effort", null],
5
+ ["mode", "Mode", "mode"],
6
+ ];
7
+ /**
8
+ * The model, effort and mode the session runs with now, named as the agent
9
+ * names them in its config options. Where the agent reports none, what the
10
+ * host started it with stands in.
11
+ */
12
+ export function sessionSettings(options, startedWith = {}) {
13
+ const settings = [];
14
+ for (const [category, hostLabel, host] of SHOWN) {
15
+ const reported = reportedIn(options, category);
16
+ if (reported.length > 0)
17
+ settings.push(...reported);
18
+ else if (host && startedWith[host]) {
19
+ settings.push({ category, label: hostLabel, value: startedWith[host] });
20
+ }
21
+ }
22
+ return settings;
23
+ }
24
+ function reportedIn(options, category) {
25
+ const settings = [];
26
+ for (const option of options) {
27
+ if (option.category !== category || option.type !== "select")
28
+ continue;
29
+ const select = option;
30
+ const choices = select.options.flatMap((o) => ("options" in o ? o.options : [o]));
31
+ const current = choices.find((c) => c.value === select.currentValue);
32
+ if (current)
33
+ settings.push({ category, label: select.name, value: current.name });
34
+ }
35
+ return settings;
36
+ }
@@ -0,0 +1,85 @@
1
+ import type { SignInMethod } from "./state.ts";
2
+ import type { ContentBlock, CreateElicitationRequest, CreateElicitationResponse, PromptResponse, SessionConfigOption, RequestPermissionRequest, RequestPermissionResponse, UpdateSessionNotification } from "./acp.ts";
3
+ /** What an agent side offers besides ACP v2's core, which the Chat shows controls for. */
4
+ export interface Abilities {
5
+ /** A prompt can be sent to stop the work running and run first. */
6
+ steer?: boolean;
7
+ /** A prompt sent and not yet taken in can be withdrawn. */
8
+ withdraw?: boolean;
9
+ }
10
+ /** Signing in to the agent, when it can ask for it. */
11
+ export interface AuthHandle {
12
+ /** The ways to sign in the agent offers (ACP's `authMethods`). */
13
+ readonly methods: SignInMethod[];
14
+ /** ACP's `authenticate` with a method the agent handles itself. */
15
+ authenticate(methodId: string): Promise<void>;
16
+ }
17
+ /**
18
+ * What the Chat calls on the agent's side of one ACP session, in ACP v2's
19
+ * terms. A host builds it from its ACP connection: `prompt` and `cancel` are
20
+ * `session/prompt` and `session/cancel` for `sessionId`. An agent that speaks
21
+ * v1 is reached through `fromV1`.
22
+ */
23
+ export interface ChatConnection {
24
+ readonly sessionId: string;
25
+ readonly abilities?: Abilities;
26
+ /** The session could not open until the user signs in. */
27
+ readonly signInRequired?: boolean;
28
+ /** Signing in, when the agent side offers it. */
29
+ readonly auth?: AuthHandle;
30
+ /**
31
+ * What a prompt may carry besides text, as the agent said in `initialize`
32
+ * (ACP's prompt capabilities): images only when `image` is true.
33
+ */
34
+ readonly promptCapabilities?: PromptCapabilities;
35
+ /** The session's settings (ACP's config options) as the response that opened it gave them. */
36
+ readonly configOptions?: SessionConfigOption[];
37
+ /**
38
+ * Sends a prompt. Resolves with the user message's id once the agent has
39
+ * inserted it, which may wait until work running ends; rejects with the
40
+ * JSON-RPC error when the agent did not insert it.
41
+ */
42
+ prompt(request: {
43
+ prompt: ContentBlock[];
44
+ idempotencyKey: string;
45
+ steer?: boolean;
46
+ }): Promise<PromptResponse>;
47
+ /** Asks the agent to stop the foreground work and drop the prompts it holds. */
48
+ cancel(): Promise<void>;
49
+ /** Withdraws a prompt not yet taken in; resolves whether it was. */
50
+ withdraw?(idempotencyKey: string): Promise<boolean>;
51
+ /**
52
+ * Renames the session (`session/set_title`), when the agent can; the agent
53
+ * then reports the title it took.
54
+ */
55
+ setTitle?(title: string): Promise<void>;
56
+ /**
57
+ * Routes the agent's calls on this session, and on the subagent sessions
58
+ * it owns, to `client` until the returned function is called. A host that
59
+ * resumes the session replays its history through the same client.
60
+ */
61
+ connect(client: ChatClient): () => void;
62
+ }
63
+ /** The ACP client methods the Chat answers; a host forwards them from its connection. */
64
+ export interface ChatClient {
65
+ sessionUpdate(notification: UpdateSessionNotification): void;
66
+ requestPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse>;
67
+ createElicitation(request: CreateElicitationRequest): Promise<CreateElicitationResponse>;
68
+ /** ACP's `auth/status_update`: whether, and as whom, the agent is signed in. */
69
+ authStatus?(status: AuthStatus): void;
70
+ /** The connection to the agent closed, with why when it is known: nothing more will come. */
71
+ closed?(error: string | null): void;
72
+ }
73
+ /** ACP's `auth/status` and `auth/status_update`. */
74
+ export interface AuthStatus {
75
+ state: string;
76
+ accounts?: Array<{
77
+ label: string;
78
+ description?: string | null;
79
+ active?: boolean | null;
80
+ }> | null;
81
+ }
82
+ /** ACP's prompt capabilities, as far as the Chat reads them. */
83
+ export interface PromptCapabilities {
84
+ image?: boolean;
85
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,59 @@
1
+ import type { ContentBlock, CreateElicitationResponse } from "./acp.ts";
2
+ import type { Abilities, AuthHandle, ChatConnection } from "./connection.ts";
3
+ import { type ChatState } from "./state.ts";
4
+ export type Listener = (state: ChatState) => void;
5
+ /**
6
+ * Connects the Chat's state to one session: folds what the connection
7
+ * delivers into the state, and carries the user's prompts and answers back.
8
+ * It decides nothing the agent owns: prompts are sent as written and the
9
+ * agent holds or inserts them; asks stay open until the user answers.
10
+ */
11
+ export declare class ChatController {
12
+ #private;
13
+ constructor(connection: ChatConnection);
14
+ get state(): ChatState;
15
+ /** Calls `listener` after every change; returns a function that stops it. */
16
+ subscribe(listener: Listener): () => void;
17
+ /** Signing in to the agent, when it offers it. */
18
+ get auth(): AuthHandle | undefined;
19
+ /** What the agent side offers besides ACP v2's core. */
20
+ get abilities(): Abilities;
21
+ /**
22
+ * Sends a prompt now, running or not; the agent decides when to insert it.
23
+ * Steered, it asks the agent to stop the work running and take it first.
24
+ */
25
+ send(prompt: string | ContentBlock[], options?: {
26
+ steer?: boolean;
27
+ }): void;
28
+ /** Withdraws a prompt the agent holds; it leaves the list once the agent lets it go. */
29
+ withdraw(id: string): void;
30
+ /** Takes a prompt the agent holds back and sends it again, steered. */
31
+ steer(id: string): void;
32
+ /** Sends a prompt the agent did not insert again, as the same submission. */
33
+ retry(id: string): void;
34
+ /** Forgets a prompt the agent did not insert. */
35
+ dismiss(id: string): void;
36
+ /**
37
+ * Stops the session's work. ACP has the session's own permission requests
38
+ * answered as cancelled, and leaves those of the sessions it started to them.
39
+ */
40
+ cancel(): void;
41
+ /**
42
+ * Answers a permission ask with an option, or cancels it with `null`. A
43
+ * reason, such as what to do instead of what was rejected, goes with the
44
+ * answer in `_meta.reason`, and to the agent as a prompt, since ACP has no
45
+ * field of its own for it.
46
+ */
47
+ answerPermission(id: string, optionId: string | null, reason?: string): void;
48
+ answerElicitation(id: string, response: CreateElicitationResponse): void;
49
+ /** Signs in with a method the agent handles; a failure stays asked for, with why. */
50
+ signIn(methodId: string): Promise<void>;
51
+ /** The user signed in elsewhere, as in a terminal the host opened. */
52
+ signedIn(): void;
53
+ /** Sends the prompt that failed for want of sign-in again, under its own key. */
54
+ retrySignedOut(): void;
55
+ /** Lets the prompt that failed for want of sign-in go. */
56
+ dismissRetry(): void;
57
+ /** Stops listening, and lets go of what the agent asked, so it waits on nothing. */
58
+ dispose(): void;
59
+ }
@@ -0,0 +1,235 @@
1
+ import { openAsks } from "./asks.js";
2
+ import { isWorking, reduce } from "./reduce.js";
3
+ import { initialState } from "./state.js";
4
+ /**
5
+ * Connects the Chat's state to one session: folds what the connection
6
+ * delivers into the state, and carries the user's prompts and answers back.
7
+ * It decides nothing the agent owns: prompts are sent as written and the
8
+ * agent holds or inserts them; asks stay open until the user answers.
9
+ */
10
+ export class ChatController {
11
+ #state;
12
+ #connection;
13
+ #listeners = new Set();
14
+ #asks = new Map();
15
+ #disconnect;
16
+ #next = 0;
17
+ constructor(connection) {
18
+ this.#connection = connection;
19
+ this.#state = initialState(connection.sessionId);
20
+ this.#disconnect = connection.connect({
21
+ sessionUpdate: (notification) => this.#apply({ type: "update", notification, at: Date.now() }),
22
+ requestPermission: (request) => new Promise((resolve) => {
23
+ const id = this.#id("ask");
24
+ this.#asks.set(id, (outcome) => resolve({ outcome: outcome }));
25
+ this.#apply({ type: "permission-asked", id, request });
26
+ }),
27
+ createElicitation: (request) => new Promise((resolve) => {
28
+ const id = this.#id("ask");
29
+ this.#asks.set(id, (response) => resolve(response));
30
+ this.#apply({ type: "elicitation-asked", id, request });
31
+ }),
32
+ authStatus: (status) => this.#apply({ type: "auth-status", ...status }),
33
+ closed: (error) => this.#closed(error),
34
+ });
35
+ if (connection.configOptions?.length) {
36
+ this.#apply({
37
+ type: "update",
38
+ notification: {
39
+ sessionId: connection.sessionId,
40
+ update: {
41
+ sessionUpdate: "config_option_update",
42
+ configOptions: connection.configOptions,
43
+ },
44
+ },
45
+ });
46
+ }
47
+ if (connection.signInRequired)
48
+ this.#apply({ type: "sign-in-required", reason: "not_signed_in" });
49
+ }
50
+ get state() {
51
+ return this.#state;
52
+ }
53
+ /** Calls `listener` after every change; returns a function that stops it. */
54
+ subscribe(listener) {
55
+ this.#listeners.add(listener);
56
+ return () => this.#listeners.delete(listener);
57
+ }
58
+ /** Signing in to the agent, when it offers it. */
59
+ get auth() {
60
+ return this.#connection.auth;
61
+ }
62
+ /** What the agent side offers besides ACP v2's core. */
63
+ get abilities() {
64
+ return this.#connection.abilities ?? {};
65
+ }
66
+ /**
67
+ * Sends a prompt now, running or not; the agent decides when to insert it.
68
+ * Steered, it asks the agent to stop the work running and take it first.
69
+ */
70
+ send(prompt, options = {}) {
71
+ const blocks = typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt;
72
+ this.#submit(this.#id("prompt"), blocks, crypto.randomUUID(), options.steer === true);
73
+ }
74
+ /** Withdraws a prompt the agent holds; it leaves the list once the agent lets it go. */
75
+ withdraw(id) {
76
+ const held = this.#state.pending.find((p) => p.id === id && p.error === null);
77
+ if (!held || !this.#connection.withdraw)
78
+ return;
79
+ void this.#connection.withdraw(held.idempotencyKey).then((withdrawn) => {
80
+ if (withdrawn)
81
+ this.#apply({ type: "prompt-dismissed", id });
82
+ });
83
+ }
84
+ /** Takes a prompt the agent holds back and sends it again, steered. */
85
+ steer(id) {
86
+ const held = this.#state.pending.find((p) => p.id === id && p.error === null);
87
+ if (!held || !this.#connection.withdraw)
88
+ return;
89
+ void this.#connection.withdraw(held.idempotencyKey).then((withdrawn) => {
90
+ if (withdrawn)
91
+ this.#submit(held.id, held.prompt, held.idempotencyKey, true);
92
+ });
93
+ }
94
+ /** Sends a prompt the agent did not insert again, as the same submission. */
95
+ retry(id) {
96
+ const failed = this.#state.pending.find((p) => p.id === id && p.error !== null);
97
+ if (failed)
98
+ this.#submit(failed.id, failed.prompt, failed.idempotencyKey);
99
+ }
100
+ /** Forgets a prompt the agent did not insert. */
101
+ dismiss(id) {
102
+ this.#apply({ type: "prompt-dismissed", id });
103
+ }
104
+ /**
105
+ * Stops the session's work. ACP has the session's own permission requests
106
+ * answered as cancelled, and leaves those of the sessions it started to them.
107
+ */
108
+ cancel() {
109
+ this.#apply({ type: "cancel-requested" });
110
+ for (const ask of openAsks(this.#state)) {
111
+ if (ask.ask.type === "permission" && ask.ask.request.sessionId === this.#state.sessionId) {
112
+ this.answerPermission(ask.id, null);
113
+ }
114
+ }
115
+ void this.#connection.cancel();
116
+ }
117
+ /**
118
+ * Answers a permission ask with an option, or cancels it with `null`. A
119
+ * reason, such as what to do instead of what was rejected, goes with the
120
+ * answer in `_meta.reason`, and to the agent as a prompt, since ACP has no
121
+ * field of its own for it.
122
+ */
123
+ answerPermission(id, optionId, reason) {
124
+ const said = reason?.trim() ? reason.trim() : null;
125
+ const outcome = optionId === null
126
+ ? { outcome: "cancelled" }
127
+ : said
128
+ ? { outcome: "selected", optionId, _meta: { reason: said } }
129
+ : { outcome: "selected", optionId };
130
+ if (!this.#asks.has(id))
131
+ return;
132
+ this.#answer(id, outcome, { type: "permission-answered", id, outcome });
133
+ if (optionId !== null && said)
134
+ this.send(said);
135
+ }
136
+ answerElicitation(id, response) {
137
+ this.#answer(id, response, { type: "elicitation-answered", id, response });
138
+ }
139
+ /** Signs in with a method the agent handles; a failure stays asked for, with why. */
140
+ async signIn(methodId) {
141
+ const auth = this.#connection.auth;
142
+ if (!auth)
143
+ return;
144
+ try {
145
+ await auth.authenticate(methodId);
146
+ this.#apply({ type: "signed-in" });
147
+ }
148
+ catch (error) {
149
+ this.#apply({ type: "sign-in-failed", error: messageOf(error) });
150
+ }
151
+ }
152
+ /** The user signed in elsewhere, as in a terminal the host opened. */
153
+ signedIn() {
154
+ this.#apply({ type: "signed-in" });
155
+ }
156
+ /** Sends the prompt that failed for want of sign-in again, under its own key. */
157
+ retrySignedOut() {
158
+ const retry = this.#state.retry;
159
+ if (!retry)
160
+ return;
161
+ this.#apply({ type: "retry-done" });
162
+ this.#submit(this.#id("prompt"), retry.prompt, retry.idempotencyKey);
163
+ }
164
+ /** Lets the prompt that failed for want of sign-in go. */
165
+ dismissRetry() {
166
+ this.#apply({ type: "retry-done" });
167
+ }
168
+ /** Stops listening, and lets go of what the agent asked, so it waits on nothing. */
169
+ dispose() {
170
+ this.#disconnect();
171
+ this.#listeners.clear();
172
+ this.#letGoOfAsks();
173
+ }
174
+ #letGoOfAsks() {
175
+ for (const ask of openAsks(this.#state)) {
176
+ if (ask.ask.type === "permission")
177
+ this.answerPermission(ask.id, null);
178
+ else
179
+ this.answerElicitation(ask.id, { action: "cancel" });
180
+ }
181
+ }
182
+ /**
183
+ * Nothing more will come from the agent: what it asked is let go, as if
184
+ * cancelled, and the work it was running ends as failed with why.
185
+ */
186
+ #closed(error) {
187
+ this.#letGoOfAsks();
188
+ const working = [this.#state, ...Object.values(this.#state.subagents)].filter(isWorking);
189
+ for (const { sessionId } of working) {
190
+ this.#apply({
191
+ type: "update",
192
+ notification: {
193
+ sessionId,
194
+ update: {
195
+ sessionUpdate: "state_update",
196
+ state: "idle",
197
+ stopReason: "error",
198
+ error: { code: -32603, message: error ?? "The agent has stopped" },
199
+ },
200
+ },
201
+ });
202
+ }
203
+ }
204
+ #answer(id, value, event) {
205
+ const resolve = this.#asks.get(id);
206
+ if (!resolve)
207
+ return;
208
+ this.#asks.delete(id);
209
+ this.#apply(event);
210
+ resolve(value);
211
+ }
212
+ #submit(id, prompt, idempotencyKey, steer = false) {
213
+ this.#apply({ type: "prompt-sent", id, prompt, idempotencyKey });
214
+ this.#connection.prompt({ prompt, idempotencyKey, ...(steer ? { steer } : {}) }).then((response) => this.#apply({ type: "prompt-inserted", id, messageId: response.messageId }), (error) => this.#apply({ type: "prompt-failed", id, error: messageOf(error), code: codeOf(error) }));
215
+ }
216
+ #apply(event) {
217
+ this.#state = reduce(this.#state, event);
218
+ for (const listener of this.#listeners)
219
+ listener(this.#state);
220
+ }
221
+ #id(prefix) {
222
+ return `${prefix}-${this.#next++}`;
223
+ }
224
+ }
225
+ function messageOf(error) {
226
+ if (error && typeof error === "object" && "message" in error)
227
+ return String(error.message);
228
+ return String(error);
229
+ }
230
+ function codeOf(error) {
231
+ if (error && typeof error === "object" && "code" in error && typeof error.code === "number") {
232
+ return error.code;
233
+ }
234
+ return undefined;
235
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `oldText` changed into `newText` as the hunks of a unified diff; nothing
3
+ * when they are the same. ACP v1 reports an edit as the whole text before and
4
+ * after it, where v2 sends the patch.
5
+ */
6
+ export declare function unifiedDiff(oldText: string | null | undefined, newText: string): string;
package/dist/diff.js ADDED
@@ -0,0 +1,137 @@
1
+ /** How many unchanged lines a hunk keeps on either side of a change. */
2
+ const CONTEXT = 3;
3
+ function lines(text) {
4
+ if (!text)
5
+ return [];
6
+ const all = text.split("\n");
7
+ return all[all.length - 1] === "" ? all.slice(0, -1) : all;
8
+ }
9
+ /**
10
+ * The most pairs of lines matched up by their longest common subsequence,
11
+ * whose table grows with their product. Past it, what lies between the
12
+ * common head and tail reads as removed, then added.
13
+ */
14
+ const MATCHED_PAIRS = 4_000_000;
15
+ /**
16
+ * The lines of `a` and `b` matched up: the lines they start and end with
17
+ * alike, and between them their longest common subsequence while it is small
18
+ * enough to find.
19
+ */
20
+ function ops(a, b) {
21
+ let head = 0;
22
+ while (head < a.length && head < b.length && a[head] === b[head])
23
+ head++;
24
+ let tail = 0;
25
+ while (tail < a.length - head &&
26
+ tail < b.length - head &&
27
+ a[a.length - 1 - tail] === b[b.length - 1 - tail])
28
+ tail++;
29
+ const out = [];
30
+ for (let k = 0; k < head; k++)
31
+ out.push({ op: " ", line: a[k], a: k, b: k });
32
+ const middleA = a.slice(head, a.length - tail);
33
+ const middleB = b.slice(head, b.length - tail);
34
+ const middle = middleA.length === 0 || middleB.length === 0 || middleA.length * middleB.length > MATCHED_PAIRS
35
+ ? [
36
+ ...middleA.map((line, k) => ({ op: "-", line, a: k, b: 0 })),
37
+ ...middleB.map((line, k) => ({ op: "+", line, a: middleA.length, b: k })),
38
+ ]
39
+ : matched(middleA, middleB);
40
+ for (const o of middle)
41
+ out.push({ ...o, a: o.a + head, b: o.b + head });
42
+ for (let k = 0; k < tail; k++) {
43
+ const i = a.length - tail + k;
44
+ out.push({ op: " ", line: a[i], a: i, b: b.length - tail + k });
45
+ }
46
+ return out;
47
+ }
48
+ /** The lines of `a` and `b` matched up by their longest common subsequence. */
49
+ function matched(a, b) {
50
+ const n = a.length;
51
+ const m = b.length;
52
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
53
+ for (let i = n - 1; i >= 0; i--) {
54
+ const row = lcs[i];
55
+ const below = lcs[i + 1];
56
+ for (let j = m - 1; j >= 0; j--) {
57
+ row[j] =
58
+ a[i] === b[j]
59
+ ? below[j + 1] + 1
60
+ : Math.max(below[j], row[j + 1]);
61
+ }
62
+ }
63
+ const out = [];
64
+ let i = 0;
65
+ let j = 0;
66
+ while (i < n || j < m) {
67
+ if (i < n && j < m && a[i] === b[j]) {
68
+ out.push({ op: " ", line: a[i], a: i, b: j });
69
+ i++;
70
+ j++;
71
+ }
72
+ else if (j < m && (i >= n || (lcs[i]?.[j + 1] ?? 0) >= (lcs[i + 1]?.[j] ?? 0))) {
73
+ out.push({ op: "+", line: b[j], a: i, b: j });
74
+ j++;
75
+ }
76
+ else {
77
+ out.push({ op: "-", line: a[i], a: i, b: j });
78
+ i++;
79
+ }
80
+ }
81
+ // Within a run of changes, the removed lines read first.
82
+ const ordered = [];
83
+ for (let k = 0; k < out.length;) {
84
+ let end = k;
85
+ while (end < out.length && out[end]?.op !== " ")
86
+ end++;
87
+ if (end === k) {
88
+ ordered.push(out[k++]);
89
+ continue;
90
+ }
91
+ for (let r = k; r < end; r++)
92
+ if (out[r]?.op === "-")
93
+ ordered.push(out[r]);
94
+ for (let r = k; r < end; r++)
95
+ if (out[r]?.op === "+")
96
+ ordered.push(out[r]);
97
+ k = end;
98
+ }
99
+ return ordered;
100
+ }
101
+ /**
102
+ * `oldText` changed into `newText` as the hunks of a unified diff; nothing
103
+ * when they are the same. ACP v1 reports an edit as the whole text before and
104
+ * after it, where v2 sends the patch.
105
+ */
106
+ export function unifiedDiff(oldText, newText) {
107
+ const all = ops(lines(oldText), lines(newText));
108
+ const changed = all.map((o, k) => (o.op !== " " ? k : -1)).filter((k) => k >= 0);
109
+ if (changed.length === 0)
110
+ return "";
111
+ const hunks = [];
112
+ for (const k of changed) {
113
+ const from = Math.max(0, k - CONTEXT);
114
+ const to = Math.min(all.length - 1, k + CONTEXT);
115
+ const last = hunks[hunks.length - 1];
116
+ if (last && from <= last[1] + 1)
117
+ last[1] = Math.max(last[1], to);
118
+ else
119
+ hunks.push([from, to]);
120
+ }
121
+ const out = [];
122
+ for (const [from, to] of hunks) {
123
+ const slice = all.slice(from, to + 1);
124
+ const first = slice[0];
125
+ // An op's index is exact only on its own side: a removed line's `a`, an added line's `b`.
126
+ const oldFirst = slice.find((o) => o.op !== "+");
127
+ const newFirst = slice.find((o) => o.op !== "-");
128
+ const oldCount = slice.filter((o) => o.op !== "+").length;
129
+ const newCount = slice.filter((o) => o.op !== "-").length;
130
+ const oldStart = oldFirst ? oldFirst.a + 1 : first.a;
131
+ const newStart = newFirst ? newFirst.b + 1 : first.b;
132
+ out.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
133
+ for (const o of slice)
134
+ out.push(`${o.op}${o.line}`);
135
+ }
136
+ return out.join("\n");
137
+ }
@@ -0,0 +1,48 @@
1
+ /** The images a prompt can carry: what ACP's image content and the agents behind it take. */
2
+ export declare const IMAGE_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp"];
3
+ /** The long side, in pixels, images are scaled down to before they are sent, unless the host says. */
4
+ export declare const IMAGE_MAX_DIMENSION = 1568;
5
+ /** What is known of a file before it is read. */
6
+ export interface FileLike {
7
+ name: string;
8
+ type: string;
9
+ size: number;
10
+ }
11
+ /** An image attached to the next prompt. */
12
+ export interface AttachedImage {
13
+ id: string;
14
+ name: string;
15
+ mimeType: string;
16
+ /** Base64 of the bytes that are sent. */
17
+ data: string;
18
+ /** How many bytes are sent. */
19
+ size: number;
20
+ }
21
+ /** An image to show on its own, as `open-image` carries it: its bytes or where it is. */
22
+ export interface OpenImage {
23
+ /** Base64 of the image's bytes. */
24
+ data?: string;
25
+ /** Where the image is, when it is not in the transcript itself. */
26
+ src?: string;
27
+ /** The image's file on disk, when it has one. */
28
+ path?: string;
29
+ mimeType?: string;
30
+ name?: string;
31
+ /** Where it was clicked: attached to the composer, in a message, a tool's output or Markdown. */
32
+ source: "attachment" | "message" | "tool" | "markdown";
33
+ }
34
+ /** Why `file` cannot be attached as an image; null when it can. */
35
+ export declare function imageRefusal(file: FileLike): string | null;
36
+ /** The size an image of `width` by `height` is sent at: its longer side at most `max`. */
37
+ export declare function fitWithin(width: number, height: number, max: number): {
38
+ width: number;
39
+ height: number;
40
+ scaled: boolean;
41
+ };
42
+ /** `bytes` as a file list says it: 900 B, 2 KB, 1.5 MB. */
43
+ export declare function formatBytes(bytes: number): string;
44
+ /** The images in `blocks`: image content, as itself or inside a tool's content. */
45
+ export declare function imagesOf(blocks: readonly unknown[]): Array<{
46
+ mimeType: string;
47
+ data: string;
48
+ }>;
package/dist/images.js ADDED
@@ -0,0 +1,45 @@
1
+ /** The images a prompt can carry: what ACP's image content and the agents behind it take. */
2
+ export const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
3
+ /** The long side, in pixels, images are scaled down to before they are sent, unless the host says. */
4
+ export const IMAGE_MAX_DIMENSION = 1568;
5
+ /** Why `file` cannot be attached as an image; null when it can. */
6
+ export function imageRefusal(file) {
7
+ if (!IMAGE_TYPES.includes(file.type)) {
8
+ return `${file.name} is not an image the agent can take: PNG, JPEG, GIF or WebP`;
9
+ }
10
+ if (file.size === 0)
11
+ return `${file.name} is empty`;
12
+ return null;
13
+ }
14
+ /** The size an image of `width` by `height` is sent at: its longer side at most `max`. */
15
+ export function fitWithin(width, height, max) {
16
+ const longer = Math.max(width, height);
17
+ if (longer <= max)
18
+ return { width, height, scaled: false };
19
+ const ratio = max / longer;
20
+ return { width: Math.round(width * ratio), height: Math.round(height * ratio), scaled: true };
21
+ }
22
+ /** `bytes` as a file list says it: 900 B, 2 KB, 1.5 MB. */
23
+ export function formatBytes(bytes) {
24
+ if (bytes < 1024)
25
+ return `${bytes} B`;
26
+ const units = ["KB", "MB", "GB"];
27
+ let size = bytes / 1024;
28
+ let unit = 0;
29
+ while (size >= 1024 && unit < units.length - 1) {
30
+ size /= 1024;
31
+ unit += 1;
32
+ }
33
+ const shown = size >= 10 ? Math.round(size) : Math.round(size * 10) / 10;
34
+ return `${shown} ${units[unit]}`;
35
+ }
36
+ /** The images in `blocks`: image content, as itself or inside a tool's content. */
37
+ export function imagesOf(blocks) {
38
+ return blocks.flatMap((block) => {
39
+ const b = block;
40
+ const image = b.type === "content" ? b.content : b;
41
+ return image?.type === "image" && typeof image.data === "string"
42
+ ? [{ mimeType: image.mimeType ?? "image/png", data: image.data }]
43
+ : [];
44
+ });
45
+ }
@@ -0,0 +1,18 @@
1
+ export * from "./acp.ts";
2
+ export * from "./asks.ts";
3
+ export * from "./completion.ts";
4
+ export * from "./config.ts";
5
+ export * from "./connection.ts";
6
+ export * from "./controller.ts";
7
+ export * from "./diff.ts";
8
+ export * from "./input.ts";
9
+ export * from "./layout.ts";
10
+ export * from "./reduce.ts";
11
+ export * from "./state.ts";
12
+ export * from "./text.ts";
13
+ export * from "./timing.ts";
14
+ export * from "./v1.ts";
15
+ export * from "./questions.ts";
16
+ export * from "./locations.ts";
17
+ export * from "./images.ts";
18
+ export * from "./title.ts";