@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/index.js ADDED
@@ -0,0 +1,18 @@
1
+ export * from "./acp.js";
2
+ export * from "./asks.js";
3
+ export * from "./completion.js";
4
+ export * from "./config.js";
5
+ export * from "./connection.js";
6
+ export * from "./controller.js";
7
+ export * from "./diff.js";
8
+ export * from "./input.js";
9
+ export * from "./layout.js";
10
+ export * from "./reduce.js";
11
+ export * from "./state.js";
12
+ export * from "./text.js";
13
+ export * from "./timing.js";
14
+ export * from "./v1.js";
15
+ export * from "./questions.js";
16
+ export * from "./locations.js";
17
+ export * from "./images.js";
18
+ export * from "./title.js";
@@ -0,0 +1,42 @@
1
+ import type { AvailableCommand, ContentBlock } from "./acp.ts";
2
+ import type { Abilities } from "./connection.ts";
3
+ import type { ChatState } from "./state.ts";
4
+ /** What an input in the composer's place needs to know of the session. */
5
+ export interface InputState {
6
+ /** A session is connected, so a prompt can be sent. */
7
+ connected: boolean;
8
+ /** The agent is working, or waiting on the user, in the foreground. */
9
+ working: boolean;
10
+ /** A prompt can be sent now to stop the work running and run first. */
11
+ canSteer: boolean;
12
+ /** The slash commands the agent last reported. */
13
+ commands: AvailableCommand[];
14
+ /** How many asks the agent waits on the user's answer to. */
15
+ openAsks: number;
16
+ }
17
+ /** An image sent with a prompt, as ACP's image content carries it. */
18
+ export interface ImageAttachment {
19
+ /** Base64 of the image's bytes. */
20
+ data: string;
21
+ mimeType: string;
22
+ uri?: string;
23
+ }
24
+ /** How a prompt is sent. */
25
+ export interface SendOptions {
26
+ /**
27
+ * `after` (the default) lets the agent take it in when the work running
28
+ * allows; `steer` stops the work running and takes it first, when the
29
+ * agent side can.
30
+ */
31
+ delivery?: "after" | "steer";
32
+ images?: ImageAttachment[];
33
+ /** More content to send after the text and images, such as `resource_link`s for paths. */
34
+ resources?: ContentBlock[];
35
+ }
36
+ export declare function inputStateOf(state: ChatState | null, abilities: Abilities): InputState;
37
+ export declare function sameInputState(a: InputState, b: InputState): boolean;
38
+ /** The prompt `text` and `options` make, and whether it steers; none when there is nothing to send. */
39
+ export declare function promptOf(text: string, options: SendOptions, input: InputState): {
40
+ prompt: ContentBlock[];
41
+ steer: boolean;
42
+ } | null;
package/dist/input.js ADDED
@@ -0,0 +1,37 @@
1
+ import { openAsks } from "./asks.js";
2
+ import { isWorking } from "./reduce.js";
3
+ export function inputStateOf(state, abilities) {
4
+ const working = state ? isWorking(state) : false;
5
+ return {
6
+ connected: state !== null,
7
+ working,
8
+ canSteer: working && abilities.steer === true,
9
+ commands: state?.commands ?? [],
10
+ openAsks: state ? openAsks(state).length : 0,
11
+ };
12
+ }
13
+ export function sameInputState(a, b) {
14
+ return (a.connected === b.connected &&
15
+ a.working === b.working &&
16
+ a.canSteer === b.canSteer &&
17
+ a.commands === b.commands &&
18
+ a.openAsks === b.openAsks);
19
+ }
20
+ /** The prompt `text` and `options` make, and whether it steers; none when there is nothing to send. */
21
+ export function promptOf(text, options, input) {
22
+ const prompt = [];
23
+ if (text.trim())
24
+ prompt.push({ type: "text", text });
25
+ for (const image of options.images ?? []) {
26
+ prompt.push({
27
+ type: "image",
28
+ data: image.data,
29
+ mimeType: image.mimeType,
30
+ ...(image.uri !== undefined ? { uri: image.uri } : {}),
31
+ });
32
+ }
33
+ prompt.push(...(options.resources ?? []));
34
+ if (prompt.length === 0)
35
+ return null;
36
+ return { prompt, steer: options.delivery === "steer" && input.canSteer };
37
+ }
@@ -0,0 +1,25 @@
1
+ import type { Entry, ToolEntry } from "./state.ts";
2
+ /** One line of the transcript as drawn. */
3
+ export type Row = {
4
+ type: "entry";
5
+ index: number;
6
+ }
7
+ /** A call of the agent's own machinery, told in one quiet line. */
8
+ | {
9
+ type: "quiet";
10
+ index: number;
11
+ }
12
+ /** A subagent's card, at the call that started it or where it was announced. */
13
+ | {
14
+ type: "subagent";
15
+ index: number;
16
+ sessionId: string;
17
+ };
18
+ export declare function isQuiet(tool: ToolEntry): boolean;
19
+ /** The subagent session a call started, when it says it started one. */
20
+ export declare function startedSubagent(tool: ToolEntry): string | null;
21
+ /**
22
+ * How `entries` are drawn: each in a row of its own, so a row, once drawn,
23
+ * keeps its place and its kind whatever comes after it.
24
+ */
25
+ export declare function layOut(entries: readonly Entry[]): Row[];
package/dist/layout.js ADDED
@@ -0,0 +1,48 @@
1
+ /** Kinds that are the agent's own machinery rather than work on the user's behalf. */
2
+ const QUIET_KINDS = ["think", "switch_mode"];
3
+ export function isQuiet(tool) {
4
+ // A call that asks the user questions is no machinery: its row tells them and their answers.
5
+ const asks = Array.isArray(tool.rawInput?.questions);
6
+ return QUIET_KINDS.includes(tool.toolKind) && !asks;
7
+ }
8
+ /** The subagent session a call started, when it says it started one. */
9
+ export function startedSubagent(tool) {
10
+ for (const c of tool.content)
11
+ if (c.type === "session")
12
+ return c.sessionId;
13
+ return null;
14
+ }
15
+ /**
16
+ * How `entries` are drawn: each in a row of its own, so a row, once drawn,
17
+ * keeps its place and its kind whatever comes after it.
18
+ */
19
+ export function layOut(entries) {
20
+ const started = new Set();
21
+ for (const e of entries) {
22
+ if (e.kind === "tool") {
23
+ const s = startedSubagent(e);
24
+ if (s)
25
+ started.add(s);
26
+ }
27
+ }
28
+ const rows = [];
29
+ const single = (index) => {
30
+ const e = entries[index];
31
+ if (e.kind === "tool") {
32
+ const s = startedSubagent(e);
33
+ if (s)
34
+ return { type: "subagent", index, sessionId: s };
35
+ if (isQuiet(e))
36
+ return { type: "quiet", index };
37
+ }
38
+ if (e.kind === "subagent")
39
+ return { type: "subagent", index, sessionId: e.id };
40
+ return { type: "entry", index };
41
+ };
42
+ entries.forEach((entry, at) => {
43
+ if (entry.kind === "subagent" && started.has(entry.id))
44
+ return;
45
+ rows.push(single(at));
46
+ });
47
+ return rows;
48
+ }
@@ -0,0 +1,33 @@
1
+ /** A place in a file the Chat shows, for the host to open. */
2
+ export interface Location {
3
+ /** The path as written. */
4
+ path: string;
5
+ /** The path resolved against the session's folder, when it can be. */
6
+ absolutePath?: string;
7
+ line?: number;
8
+ column?: number;
9
+ }
10
+ /**
11
+ * The location `written` names: a path, optionally `:line` and `:column`
12
+ * after it, or a `file://` URL; resolved against `cwd` when it is relative.
13
+ */
14
+ export declare function parseLocation(written: string, cwd: string | null): Location | null;
15
+ /**
16
+ * Whether inline `code` in an agent's reply names a file under the session's
17
+ * folder: a relative path, or an absolute one inside `cwd`, with a known
18
+ * extension, and nothing a path does not hold (spaces, calls, schemes).
19
+ * Conservative: an identifier such as `res.cookie` is left alone.
20
+ */
21
+ export declare function looksLikePath(code: string, cwd: string | null): boolean;
22
+ /**
23
+ * What a link in the Chat's Markdown points at: a file to open, a web or
24
+ * mail link to open elsewhere, or neither (a link within the page, or any
25
+ * other scheme).
26
+ */
27
+ export declare function linkTarget(href: string, cwd: string | null): {
28
+ type: "location";
29
+ location: Location;
30
+ } | {
31
+ type: "link";
32
+ url: string;
33
+ } | null;
@@ -0,0 +1,116 @@
1
+ /** The root a Windows path starts at: its drive (`C:`) or its share (`\\server\share`). */
2
+ function windowsRoot(path) {
3
+ const drive = /^[A-Za-z]:(?=[\\/]|$)/.exec(path);
4
+ if (drive)
5
+ return drive[0].toUpperCase();
6
+ const share = /^[\\/]{2}([^\\/]+)[\\/]+([^\\/]+)/.exec(path);
7
+ return share ? `\\\\${share[1]}\\${share[2]}` : null;
8
+ }
9
+ /** Whether `path` is absolute, on POSIX or on Windows. */
10
+ function isAbsolute(path) {
11
+ return path.startsWith("/") || windowsRoot(path) !== null;
12
+ }
13
+ /**
14
+ * `path`, which is absolute, with `.` and `..` resolved: a POSIX path, or a
15
+ * Windows one with backslashes after its drive or share.
16
+ */
17
+ function normalize(path) {
18
+ const root = windowsRoot(path);
19
+ const parts = [];
20
+ for (const part of path.slice(root?.length ?? 0).split(root ? /[\\/]/ : "/")) {
21
+ if (part === "" || part === ".")
22
+ continue;
23
+ if (part === "..")
24
+ parts.pop();
25
+ else
26
+ parts.push(part);
27
+ }
28
+ return root ? `${root}\\${parts.join("\\")}` : `/${parts.join("/")}`;
29
+ }
30
+ /**
31
+ * The location `written` names: a path, optionally `:line` and `:column`
32
+ * after it, or a `file://` URL; resolved against `cwd` when it is relative.
33
+ */
34
+ export function parseLocation(written, cwd) {
35
+ let text = written.trim();
36
+ if (text === "")
37
+ return null;
38
+ if (text.startsWith("file://")) {
39
+ try {
40
+ // A file URL names a file on a Windows drive as `/C:/…`, and one on a share by its host.
41
+ const url = new URL(text);
42
+ const path = decodeURIComponent(url.pathname);
43
+ text =
44
+ url.hostname && url.hostname !== "localhost"
45
+ ? `//${url.hostname}${path}`
46
+ : path.replace(/^\/(?=[A-Za-z]:\/)/, "");
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ const match = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(text);
53
+ const path = match?.[1] ?? text;
54
+ if (path === "")
55
+ return null;
56
+ const location = { path };
57
+ if (isAbsolute(path))
58
+ location.absolutePath = normalize(path);
59
+ else if (cwd)
60
+ location.absolutePath = normalize(`${cwd}/${path}`);
61
+ if (match?.[2])
62
+ location.line = Number(match[2]);
63
+ if (match?.[3])
64
+ location.column = Number(match[3]);
65
+ return location;
66
+ }
67
+ /** Extensions of files an agent names, for telling a file name from other code. */
68
+ const EXTENSIONS = new Set(("ts tsx js jsx mjs cjs rs py rb go java kt swift c h cc cpp hpp cs php lua sh bash zsh fish " +
69
+ "md mdx txt json jsonc toml yaml yml xml html css scss sass less vue svelte sql proto nix " +
70
+ "lock ini cfg conf env gradle csv tsv svg").split(" "));
71
+ /**
72
+ * Whether inline `code` in an agent's reply names a file under the session's
73
+ * folder: a relative path, or an absolute one inside `cwd`, with a known
74
+ * extension, and nothing a path does not hold (spaces, calls, schemes).
75
+ * Conservative: an identifier such as `res.cookie` is left alone.
76
+ */
77
+ export function looksLikePath(code, cwd) {
78
+ if (!/^[\w./@-]+(?::\d+(?::\d+)?)?$/.test(code))
79
+ return false;
80
+ if (code.startsWith("-") || code.startsWith("@") || code.includes("@"))
81
+ return false;
82
+ const location = parseLocation(code, cwd);
83
+ if (!location)
84
+ return false;
85
+ const name = location.path.split("/").pop() ?? "";
86
+ const dot = name.lastIndexOf(".");
87
+ if (dot <= 0 && !/^(Makefile|Dockerfile|justfile|LICENSE)$/.test(name))
88
+ return false;
89
+ if (dot > 0 && !EXTENSIONS.has(name.slice(dot + 1).toLowerCase()))
90
+ return false;
91
+ if (!/[A-Za-z]/.test(name.slice(0, dot > 0 ? dot : undefined)))
92
+ return false;
93
+ if (!cwd || !location.absolutePath)
94
+ return !location.path.startsWith("/");
95
+ const folder = normalize(cwd);
96
+ const separator = windowsRoot(folder) ? "\\" : "/";
97
+ const root = folder.endsWith(separator) ? folder : `${folder}${separator}`;
98
+ return location.absolutePath.startsWith(root);
99
+ }
100
+ /**
101
+ * What a link in the Chat's Markdown points at: a file to open, a web or
102
+ * mail link to open elsewhere, or neither (a link within the page, or any
103
+ * other scheme).
104
+ */
105
+ export function linkTarget(href, cwd) {
106
+ if (/^(https?|mailto):/i.test(href))
107
+ return { type: "link", url: href };
108
+ if (href.startsWith("#"))
109
+ return null;
110
+ // A drive letter is not a scheme.
111
+ const scheme = /^[a-z][a-z0-9+.-]*:/i.test(href) && windowsRoot(href) === null;
112
+ if (scheme && !href.startsWith("file:"))
113
+ return null;
114
+ const location = parseLocation(href, cwd);
115
+ return location ? { type: "location", location } : null;
116
+ }
@@ -0,0 +1,28 @@
1
+ import type { AskEntry, ToolEntry } from "./state.ts";
2
+ /** One question a call asked the user, with its options and what was answered. */
3
+ export interface AskedQuestion {
4
+ question: string;
5
+ header: string | null;
6
+ options: Array<{
7
+ label: string;
8
+ description: string | null;
9
+ }>;
10
+ multiSelect: boolean;
11
+ /** The options chosen, by label. */
12
+ chosen: string[];
13
+ /** An answer written instead of, or besides, choosing. */
14
+ text: string | null;
15
+ }
16
+ export interface AskedQuestions {
17
+ questions: AskedQuestion[];
18
+ status: "answered" | "unanswered" | "cancelled";
19
+ }
20
+ /**
21
+ * The questions `tool` asked the user (Claude Code's AskUserQuestion, by its
22
+ * `rawInput.questions`), with the answers from the call's
23
+ * `rawOutput.answers`, or else from `ask`, the form the Chat answered for
24
+ * it; none for a call that asks nothing.
25
+ */
26
+ export declare function askedQuestions(tool: ToolEntry, ask: AskEntry | null): AskedQuestions | null;
27
+ /** The questions and their answers in a row's line: `? question → answer`. */
28
+ export declare function questionsLine(asked: AskedQuestions | null): string;
@@ -0,0 +1,67 @@
1
+ const text = (v) => (typeof v === "string" && v !== "" ? v : null);
2
+ const labels = (v) => Array.isArray(v)
3
+ ? v.filter((l) => typeof l === "string")
4
+ : text(v)
5
+ ? [v]
6
+ : [];
7
+ /**
8
+ * The questions `tool` asked the user (Claude Code's AskUserQuestion, by its
9
+ * `rawInput.questions`), with the answers from the call's
10
+ * `rawOutput.answers`, or else from `ask`, the form the Chat answered for
11
+ * it; none for a call that asks nothing.
12
+ */
13
+ export function askedQuestions(tool, ask) {
14
+ const raw = tool.rawInput?.questions;
15
+ if (!Array.isArray(raw) || raw.length === 0)
16
+ return null;
17
+ const questions = raw.map((q) => ({
18
+ question: text(q.question) ?? "",
19
+ header: text(q.header),
20
+ options: (q.options ?? []).map((o) => ({
21
+ label: text(o.label) ?? "",
22
+ description: text(o.description),
23
+ })),
24
+ multiSelect: q.multiSelect === true,
25
+ chosen: [],
26
+ text: null,
27
+ }));
28
+ const output = tool.rawOutput?.answers;
29
+ if (Array.isArray(output)) {
30
+ output.forEach((answer, i) => {
31
+ const asked = questions.find((q) => q.question === answer.question) ?? questions[i];
32
+ if (!asked)
33
+ return;
34
+ asked.chosen = labels(answer.chosen);
35
+ asked.text = text(answer.text);
36
+ });
37
+ return { questions, status: "answered" };
38
+ }
39
+ const response = ask?.answer?.type === "elicitation"
40
+ ? ask.answer.response
41
+ : null;
42
+ if (response?.action === "accept") {
43
+ questions.forEach((q, i) => {
44
+ q.chosen = labels(response.content?.[`q${i}`]);
45
+ });
46
+ return { questions, status: "answered" };
47
+ }
48
+ if (response || tool.status === "cancelled" || tool.status === "failed") {
49
+ return { questions, status: "cancelled" };
50
+ }
51
+ return { questions, status: "unanswered" };
52
+ }
53
+ const answerOf = (q) => [...q.chosen, ...(q.text ? [q.text] : [])].join(", ");
54
+ /** The questions and their answers in a row's line: `? question → answer`. */
55
+ export function questionsLine(asked) {
56
+ if (!asked)
57
+ return "";
58
+ const end = asked.status === "cancelled" ? " — cancelled" : " — not answered";
59
+ const one = (q) => {
60
+ const answer = answerOf(q);
61
+ return answer ? `${q.question} → ${answer}` : `${q.question}${end}`;
62
+ };
63
+ const [only] = asked.questions;
64
+ if (asked.questions.length === 1 && only)
65
+ return `? ${one(only)}`;
66
+ return `? ${asked.questions.length} questions · ${asked.questions.map(one).join(" · ")}`;
67
+ }
@@ -0,0 +1,67 @@
1
+ import type { ContentBlock, CreateElicitationRequest, CreateElicitationResponse, RequestPermissionOutcome, RequestPermissionRequest, UpdateSessionNotification } from "./acp.ts";
2
+ import type { AuthStatus } from "./connection.ts";
3
+ import { type ChatState, type SignIn, type Transcript, type TurnEntry } from "./state.ts";
4
+ /** Everything the Chat is told: what the agent sent, and what became of the requests it made. */
5
+ export type ChatEvent =
6
+ /** What the agent sent, and when it came (ms since the epoch), which times its tool calls. */
7
+ {
8
+ type: "update";
9
+ notification: UpdateSessionNotification;
10
+ at?: number;
11
+ } | {
12
+ type: "prompt-sent";
13
+ id: string;
14
+ prompt: ContentBlock[];
15
+ idempotencyKey: string;
16
+ } | {
17
+ type: "prompt-inserted";
18
+ id: string;
19
+ messageId: string;
20
+ } | {
21
+ type: "prompt-failed";
22
+ id: string;
23
+ error: string;
24
+ code?: number;
25
+ } | {
26
+ type: "sign-in-required";
27
+ reason: SignIn["reason"];
28
+ } | {
29
+ type: "sign-in-failed";
30
+ error: string;
31
+ } | {
32
+ type: "signed-in";
33
+ } | {
34
+ type: "retry-done";
35
+ } | ({
36
+ type: "auth-status";
37
+ } & AuthStatus) | {
38
+ type: "prompt-dismissed";
39
+ id: string;
40
+ } | {
41
+ type: "cancel-requested";
42
+ } | {
43
+ type: "permission-asked";
44
+ id: string;
45
+ request: RequestPermissionRequest;
46
+ } | {
47
+ type: "permission-answered";
48
+ id: string;
49
+ outcome: RequestPermissionOutcome;
50
+ } | {
51
+ type: "elicitation-asked";
52
+ id: string;
53
+ request: CreateElicitationRequest;
54
+ } | {
55
+ type: "elicitation-answered";
56
+ id: string;
57
+ response: CreateElicitationResponse;
58
+ };
59
+ /**
60
+ * The Chat's state after `event`. A pure fold: the state holds nothing the
61
+ * agent did not report, so replaying a session rebuilds it.
62
+ */
63
+ export declare function reduce(state: ChatState, event: ChatEvent): ChatState;
64
+ /** Whether the agent reports foreground work, running or waiting on the user. */
65
+ export declare function isWorking(transcript: Transcript): boolean;
66
+ /** The latest stretch of foreground work, running or not. */
67
+ export declare function lastTurn(transcript: Transcript): TurnEntry | undefined;