@niwa-labs/harness 0.0.0-stage → 0.0.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/src/reading.ts ADDED
@@ -0,0 +1,415 @@
1
+ /**
2
+ * The reading side: how niwa reads what a harness already holds. One interface for every harness
3
+ *. Niwa copies nothing: it keeps a pointer and an index and reads
4
+ * through this side on demand.
5
+ */
6
+
7
+ import { z } from "zod";
8
+
9
+ import { JsonValueSchema } from "@niwa-labs/core";
10
+ import type { Timestamp } from "@niwa-labs/core";
11
+
12
+ import { HarnessIdSchema } from "./instance.ts";
13
+ import { ChecklistItemSchema, ToolCategorySchema } from "./tools.ts";
14
+
15
+ /** The id the harness gave a session. Niwa issues no session ids of its own. */
16
+ export const NativeSessionIdSchema = z.string().min(1).brand<"NativeSessionId">();
17
+ export type NativeSessionId = z.output<typeof NativeSessionIdSchema>;
18
+
19
+ /** The identity of a session: the harness id and the id that harness gave it. */
20
+ export const SessionIdSchema = z.object({
21
+ harness: HarnessIdSchema,
22
+ native: NativeSessionIdSchema,
23
+ });
24
+ export type SessionId = z.output<typeof SessionIdSchema>;
25
+
26
+ export function sessionId(harness: SessionId["harness"], native: string): SessionId {
27
+ return { harness, native: NativeSessionIdSchema.parse(native) };
28
+ }
29
+
30
+ export function sameSession(a: SessionId, b: SessionId): boolean {
31
+ return a.harness === b.harness && a.native === b.native;
32
+ }
33
+
34
+ /**
35
+ * The reading side's own pointer into the harness's storage, tied to the revision of the session
36
+ * file it was taken from. Opaque to everyone else: only the side that issued it may look inside,
37
+ * and it is not a cursor over niwa's journal.
38
+ */
39
+ export const LocatorSchema = z.string().min(1).brand<"Locator">();
40
+ export type Locator = z.output<typeof LocatorSchema>;
41
+
42
+ /** What the reading side knows for sure about a session; an unknown field is absent. */
43
+ export interface SessionInfo {
44
+ readonly id: SessionId;
45
+ /**
46
+ * A readable title: the harness's own name or summary of the session when it has one, else its
47
+ * first message from a person, trimmed (`titleFromText`).
48
+ */
49
+ readonly title?: string;
50
+ readonly cwd?: string;
51
+ readonly startedAt?: Timestamp;
52
+ readonly updatedAt?: Timestamp;
53
+ }
54
+
55
+ export interface SessionFilter {
56
+ readonly cwd?: string;
57
+ /** Only sessions changed at or after this moment. */
58
+ readonly since?: Timestamp;
59
+ /**
60
+ * Only the sessions with these native ids. The reading side leaves the others out before it
61
+ * reads anything of them, so what a caller wants of a few sessions does not cost a look at all.
62
+ */
63
+ readonly natives?: readonly string[];
64
+ }
65
+
66
+ /**
67
+ * How much of a session or a range was read. "I do not know" is never shown as "nothing": only
68
+ * `empty` means there is nothing there.
69
+ */
70
+ export type Coverage =
71
+ | { readonly status: "not-scanned" }
72
+ | { readonly status: "empty" }
73
+ | { readonly status: "failed"; readonly reason: string }
74
+ | { readonly status: "unavailable"; readonly reason: string };
75
+
76
+ export const NOT_SCANNED: Coverage = { status: "not-scanned" };
77
+ export const EMPTY: Coverage = { status: "empty" };
78
+
79
+ export function failedCoverage(reason: string): Coverage {
80
+ return { status: "failed", reason };
81
+ }
82
+
83
+ export function unavailableCoverage(reason: string): Coverage {
84
+ return { status: "unavailable", reason };
85
+ }
86
+
87
+ /**
88
+ * Who put a piece of text into a message that its sender did not write:
89
+ *
90
+ * - `harness`: the harness's own preamble, reminder or environment;
91
+ * - `command`: a slash command and what it ran;
92
+ * - `hook`: what a hook added;
93
+ * - `niwa`: what niwa added.
94
+ */
95
+ export const InsertionOriginSchema = z.enum(["harness", "command", "hook", "niwa"]);
96
+ export type InsertionOrigin = z.output<typeof InsertionOriginSchema>;
97
+
98
+ /** A stretch of a message's text that was inserted, not written: from `from` up to, not including, `to`, in UTF-16 units of the text. */
99
+ export const InsertedRangeSchema = z
100
+ .object({
101
+ from: z.number().int().nonnegative(),
102
+ to: z.number().int().positive(),
103
+ origin: InsertionOriginSchema,
104
+ })
105
+ .refine((range) => range.to > range.from, "an inserted range is not empty");
106
+ export type InsertedRange = z.output<typeof InsertedRangeSchema>;
107
+
108
+ /**
109
+ * An image in a message or in the result of a tool. The image itself is not kept: only that it was
110
+ * there, where, and its media type when the harness says it. `at` is where it stood in the content
111
+ * the record keeps: for a user message, a UTF-16 offset in `text`; for a tool result, the index
112
+ * among the blocks of `output` when that is a list of blocks (the image block itself is not in the
113
+ * list, so `at` is where it would go back), else an offset in `output` as text.
114
+ */
115
+ export const ImageMarkSchema = z.object({
116
+ at: z.number().int().nonnegative(),
117
+ mime: z.string().min(1).optional(),
118
+ });
119
+ export type ImageMark = z.output<typeof ImageMarkSchema>;
120
+
121
+ /** What every record carries: where it is, when it happened, and whether it is whole. */
122
+ const recordBase = {
123
+ locator: LocatorSchema,
124
+ at: z.number().int().nonnegative().optional(),
125
+ /** A half-written tail of a running session: marked, and the reader does not move past it. */
126
+ incomplete: z.boolean().default(false),
127
+ /**
128
+ * Set on the first record of a read that started over: the locator it was given belonged to
129
+ * another source (another file, another revision) and could not be followed, so what comes is
130
+ * the session from its beginning and not what followed the locator.
131
+ */
132
+ reanchored: z.literal(true).optional(),
133
+ };
134
+
135
+ export const UserRecordSchema = z.object({
136
+ kind: z.literal("user"),
137
+ text: z.string(),
138
+ /**
139
+ * The stretches of `text` somebody other than the person put there. Absent when the reader cannot
140
+ * tell what is inserted; present, even empty, it is the whole truth: everything outside the ranges
141
+ * is what the person said.
142
+ */
143
+ inserted: z.array(InsertedRangeSchema).optional(),
144
+ /** The images the message held, where they stood. */
145
+ images: z.array(ImageMarkSchema).optional(),
146
+ ...recordBase,
147
+ });
148
+
149
+ export const AssistantRecordSchema = z.object({
150
+ kind: z.literal("assistant"),
151
+ text: z.string(),
152
+ model: z.string().optional(),
153
+ ...recordBase,
154
+ });
155
+
156
+ /** What the model thought before it answered; a thought the harness keeps sealed has no text. */
157
+ export const ThinkingRecordSchema = z.object({
158
+ kind: z.literal("thinking"),
159
+ text: z.string(),
160
+ redacted: z.boolean(),
161
+ ...recordBase,
162
+ });
163
+
164
+ export const ToolCallRecordSchema = z.object({
165
+ kind: z.literal("tool-call"),
166
+ /** The harness's id of the call, so its result can be paired with it. */
167
+ callId: z.string().min(1),
168
+ /** The harness's own name of the tool. */
169
+ name: z.string().min(1),
170
+ /** What the call does, in the words every harness shares. */
171
+ category: ToolCategorySchema,
172
+ /** The path, command, pattern, address or task the call is about, when the kind can tell. */
173
+ target: z.string().optional(),
174
+ /**
175
+ * Every path an edit call names, when the kind can tell them all (one patch may change several
176
+ * files); `target` is the first of them. Absent when the call names at most `target`.
177
+ */
178
+ paths: z.array(z.string().min(1)).min(1).optional(),
179
+ input: JsonValueSchema.optional(),
180
+ ...recordBase,
181
+ });
182
+
183
+ export const ToolResultRecordSchema = z.object({
184
+ kind: z.literal("tool-result"),
185
+ callId: z.string().min(1),
186
+ name: z.string().optional(),
187
+ output: JsonValueSchema.optional(),
188
+ ok: z.boolean().optional(),
189
+ /** The images the result held, taken out of `output`, where they stood. */
190
+ images: z.array(ImageMarkSchema).optional(),
191
+ ...recordBase,
192
+ });
193
+
194
+ /** The harness replaced the context with its own summary. */
195
+ export const CompactionRecordSchema = z.object({
196
+ kind: z.literal("compaction"),
197
+ summary: z.string(),
198
+ ...recordBase,
199
+ });
200
+
201
+ /**
202
+ * The agent's checklist of its work, whole, as an update left it. `callId` names the tool call
203
+ * that made the update, when a call did.
204
+ */
205
+ export const ChecklistRecordSchema = z.object({
206
+ kind: z.literal("checklist"),
207
+ callId: z.string().min(1).optional(),
208
+ items: z.array(ChecklistItemSchema),
209
+ ...recordBase,
210
+ });
211
+
212
+ /**
213
+ * A tool call that asked for permission, as the harness recorded it, and what became of it:
214
+ * `allowed`, `denied`, or `unanswered` when the transcript holds no answer.
215
+ */
216
+ export const PermissionRecordSchema = z.object({
217
+ kind: z.literal("permission"),
218
+ callId: z.string().min(1).optional(),
219
+ /** The harness's own name of the tool. */
220
+ tool: z.string().min(1).optional(),
221
+ outcome: z.enum(["allowed", "denied", "unanswered"]),
222
+ ...recordBase,
223
+ });
224
+
225
+ /** The harness spawned a session inside this one. */
226
+ export const NestedRecordSchema = z.object({
227
+ kind: z.literal("nested"),
228
+ child: SessionIdSchema,
229
+ ...recordBase,
230
+ });
231
+
232
+ /**
233
+ * A record niwa does not understand: an unfamiliar record is "unknown" with its raw data kept,
234
+ * never an error.
235
+ */
236
+ export const UnknownRecordSchema = z.object({
237
+ kind: z.literal("unknown"),
238
+ raw: z.unknown(),
239
+ ...recordBase,
240
+ });
241
+
242
+ /**
243
+ * The common record kinds: few, and the same for every harness.
244
+
245
+ */
246
+ export const SessionRecordSchema = z.discriminatedUnion("kind", [
247
+ UserRecordSchema,
248
+ AssistantRecordSchema,
249
+ ThinkingRecordSchema,
250
+ ToolCallRecordSchema,
251
+ ToolResultRecordSchema,
252
+ ChecklistRecordSchema,
253
+ PermissionRecordSchema,
254
+ CompactionRecordSchema,
255
+ NestedRecordSchema,
256
+ UnknownRecordSchema,
257
+ ]);
258
+
259
+ export type SessionRecord = z.output<typeof SessionRecordSchema>;
260
+
261
+ /** The kind of a session record, by name. */
262
+ export type SessionRecordKind = SessionRecord["kind"];
263
+
264
+ /**
265
+ * The reading side of a harness. An undeclared ability is refused by name and an installation that
266
+ * cannot serve one says so (capabilities.ts).
267
+ */
268
+ export interface SessionReading {
269
+ /** Lists sessions from the harness's files; the harness need not be running. */
270
+ list(filter?: SessionFilter): AsyncIterable<SessionInfo>;
271
+
272
+ /** Reads a session; `from` is a locator taken from an earlier record of the same session. */
273
+ read(id: SessionId, from?: Locator): AsyncIterable<SessionRecord>;
274
+
275
+ /** Follows a session while it grows. */
276
+ watch?(id: SessionId): AsyncIterable<SessionRecord>;
277
+
278
+ /** The harness's own record whole, at a locator. Never written into niwa's journal. */
279
+ raw(id: SessionId, locator: Locator): Promise<unknown>;
280
+
281
+ /** The schema of `raw`. */
282
+ readonly rawSchema: z.ZodType<unknown>;
283
+
284
+ /** Coverage of a session, or of the range after `from`. */
285
+ coverage(id: SessionId, from?: Locator): Promise<Coverage>;
286
+ }
287
+
288
+ /**
289
+ * The stretches of a message's text that sit in a tag a harness wraps its own insertions in: `tags`
290
+ * names each tag and who puts it there. A stretch takes in the whitespace that follows it, so what
291
+ * is left of the message reads as the person wrote it, and tags that touch, from one origin, are one stretch. An unlisted tag is the person's own.
292
+ */
293
+ export function insertedRanges(text: string, tags: Readonly<Record<string, InsertionOrigin>>): InsertedRange[] {
294
+ const names = Object.keys(tags);
295
+ if (names.length === 0) return [];
296
+ const block = new RegExp(`<(${names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b[^>]*>[\\s\\S]*?</\\1>\\s*`, "g");
297
+ const ranges: InsertedRange[] = [];
298
+ for (const match of text.matchAll(block)) {
299
+ const origin = tags[match[1]!]!;
300
+ const last = ranges[ranges.length - 1];
301
+ // Tags that touch and come from the same place are one stretch.
302
+ if (last !== undefined && last.origin === origin && last.to === match.index) ranges[ranges.length - 1] = { ...last, to: match.index + match[0].length };
303
+ else ranges.push({ from: match.index, to: match.index + match[0].length, origin });
304
+ }
305
+ return ranges;
306
+ }
307
+
308
+ /**
309
+ * The images among the blocks of a message or a tool result, taken out: `image` says of a block
310
+ * whether it is an image, and its media type when it knows it. What is left is the blocks that are
311
+ * not images, in order, and each image is a mark whose `at` is how many of those stand before it.
312
+ */
313
+ export function takeImages<T>(
314
+ blocks: readonly T[],
315
+ image: (block: T) => { readonly mime?: string | undefined } | undefined,
316
+ ): { readonly rest: T[]; readonly images: ImageMark[] } {
317
+ const rest: T[] = [];
318
+ const images: ImageMark[] = [];
319
+ for (const block of blocks) {
320
+ const found = image(block);
321
+ if (found === undefined) rest.push(block);
322
+ else images.push({ at: rest.length, ...(found.mime === undefined ? {} : { mime: found.mime }) });
323
+ }
324
+ return { rest, images };
325
+ }
326
+
327
+ /** About how long a title made from a message is. */
328
+ export const TITLE_LENGTH = 60;
329
+
330
+ /**
331
+ * A readable title made from the text of a message.
332
+ *
333
+ * What a harness or niwa wrapped in a tag of its own is not what the person said, so it is cut
334
+ * out: `tags` names those tags, as for `insertedRanges`, and a tag it does not name is the
335
+ * person's own and stays in the title. Whitespace is collapsed and the rest is cut to about 60
336
+ * characters, at a word when one is near. `undefined` when nothing is left.
337
+ */
338
+ export function titleFromText(text: string, tags: Readonly<Record<string, InsertionOrigin>> = {}): string | undefined {
339
+ let rest = "";
340
+ let at = 0;
341
+ for (const range of insertedRanges(text, tags)) {
342
+ rest += `${text.slice(at, range.from)} `;
343
+ at = range.to;
344
+ }
345
+ const said = `${rest}${text.slice(at)}`.replace(/\s+/g, " ").trim();
346
+ if (said.length === 0) return undefined;
347
+ if (said.length <= TITLE_LENGTH) return said;
348
+ const head = said.slice(0, TITLE_LENGTH);
349
+ // A cut that falls between two words keeps the whole of the last one.
350
+ const space = said[TITLE_LENGTH] === " " ? TITLE_LENGTH : head.lastIndexOf(" ");
351
+ return `${(space > TITLE_LENGTH / 2 ? head.slice(0, space) : head).trimEnd()}…`;
352
+ }
353
+
354
+ /** How many records the title of a session is looked for in, at most. */
355
+ const TITLE_RECORDS = 50;
356
+
357
+ /**
358
+ * The title of a session made from its first message from a person, among its first records.
359
+ *
360
+ * A message that is not what a person said can be passed over with `skip` (a harness's own
361
+ * preamble, for one); `tags` are the wrappers of insertions to cut out of it (`titleFromText`). Reading stops at the first message that gives a title.
362
+ */
363
+ export async function firstMessageTitle(
364
+ records: AsyncIterable<SessionRecord>,
365
+ skip?: (text: string) => boolean,
366
+ tags?: Readonly<Record<string, InsertionOrigin>>,
367
+ ): Promise<string | undefined> {
368
+ let seen = 0;
369
+ for await (const record of records) {
370
+ if (seen >= TITLE_RECORDS) return undefined;
371
+ seen += 1;
372
+ if (record.kind !== "user" || (skip?.(record.text) ?? false)) continue;
373
+ const title = titleFromText(record.text, tags);
374
+ if (title !== undefined) return title;
375
+ }
376
+ return undefined;
377
+ }
378
+
379
+ /** The file a title was made from, as it was when the title was made. */
380
+ export interface TitleKey {
381
+ readonly size: number;
382
+ readonly mtimeMs: number;
383
+ }
384
+
385
+ /**
386
+ * The titles made from the first messages of session files, kept in memory by the reading side
387
+ * that made them.
388
+ *
389
+ * A title is found by reading the head of a file, which for a compressed one means decoding it,
390
+ * and a listing does that for every session. A title kept under the path of its file, with the
391
+ * size and the time the file had, is read again only when the file is not the same: a session
392
+ * that grows is looked at again, one that does not is not. A session without a title is kept
393
+ * too, so it is not looked for on every listing. The cache lives as long as the reading side,
394
+ * and nothing is written to disk.
395
+ */
396
+ export class TitleCache {
397
+ readonly #entries = new Map<string, { key: TitleKey; title: string | undefined }>();
398
+
399
+ /** The title kept for the file, `{ title: undefined }` for a kept absence, `undefined` for nothing kept. */
400
+ get(path: string, key: TitleKey): { title: string | undefined } | undefined {
401
+ const kept = this.#entries.get(path);
402
+ if (kept === undefined || kept.key.size !== key.size || kept.key.mtimeMs !== key.mtimeMs) return undefined;
403
+ return { title: kept.title };
404
+ }
405
+
406
+ /** Keep the title found in the file as it was at `key`. */
407
+ set(path: string, key: TitleKey, title: string | undefined): void {
408
+ this.#entries.set(path, { key, title });
409
+ }
410
+
411
+ /** How many files have a title or an absence kept. */
412
+ get size(): number {
413
+ return this.#entries.size;
414
+ }
415
+ }
package/src/reverse.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Reverse requests: what an agent asks of its client in the middle of a turn — permission to run
3
+ * a tool, a question for a person.
4
+ *
5
+ * This is the whole of what a harness adapter sees. The adapter turns the harness's own request
6
+ * into a `Question` (the question format of the core contracts), hands it over with the raw request, and gets an `Answer` back,
7
+ * which it turns into the harness's own reply. Where the answer comes from (a grant, niwa's own
8
+ * memory of an "allow always", the one who started the session) is the sessions module's business
9
+ * and never the adapter's.
10
+ */
11
+
12
+ import type { Answer, Question } from "@niwa-labs/core";
13
+
14
+ import type { SessionId } from "./reading.ts";
15
+
16
+ /** What an adapter hands over: the question in niwa's format, and the harness's own request as it came. */
17
+ export interface ReverseRequest {
18
+ readonly question: Question;
19
+ /** The harness's request whole: the method it came with and its parameters. Kept in the journal. */
20
+ readonly raw: { readonly method: string; readonly params: unknown };
21
+ /**
22
+ * Aborted when the harness no longer waits for the answer: it cancelled the request, ended the
23
+ * turn, or went away. The question is then closed and the answer is not wanted.
24
+ */
25
+ readonly signal: AbortSignal;
26
+ }
27
+
28
+ /**
29
+ * What a control side calls for each reverse request of a session. It always resolves: an
30
+ * answer, or `{ cancelled: true }` when none will come, so a turn never hangs on it.
31
+ */
32
+ export type ReverseHandler = (session: SessionId, request: ReverseRequest) => Promise<Answer>;
package/src/skills.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Where a harness kind reads agent skills from.
3
+ *
4
+ * A skill is a directory `<skills-root>/<name>/SKILL.md`. Each kind declares the roots it reads,
5
+ * next to the kind's own code; the `niwa skill` command installs into them and keeps no table of
6
+ * its own. A kind that has no skill mechanism declares nothing and is refused by name.
7
+ */
8
+
9
+ import { join } from "node:path";
10
+
11
+ /** The directories of skills a kind reads: the user's, and the project's. */
12
+ export interface SkillRoots {
13
+ /** The user's skills root, given the home of the user. */
14
+ readonly user: (home: string) => string;
15
+ /** The project's skills root, relative to the project directory. */
16
+ readonly project: string;
17
+ }
18
+
19
+ /** The roots of one kind, named by the kind. */
20
+ export interface KindSkills {
21
+ readonly kind: string;
22
+ readonly roots: SkillRoots;
23
+ }
24
+
25
+ /**
26
+ * The roots shared by the agents that read `.agents/skills`: Codex, ZCode, pi and MiniMax Code.
27
+ * Codex also reads `$CODEX_HOME/skills`; the shared root is the one every one of them reads.
28
+ */
29
+ export const SHARED_AGENTS_SKILLS: SkillRoots = {
30
+ user: (home) => join(home, ".agents", "skills"),
31
+ project: join(".agents", "skills"),
32
+ };
package/src/tools.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Tool calls and checklists in the common model.
3
+ *
4
+ * Every harness names its tools in its own words (`Bash`, `exec_command`, `bash`). A kind
5
+ * translates each call into a category and the target the call points at, so a consumer of the
6
+ * common model never has to know a harness's tool names. The same goes for the checklist an agent
7
+ * keeps of its work (`TodoWrite`, `update_plan`, an ACP plan): each kind reads its own and gives a
8
+ * `Checklist`.
9
+ */
10
+
11
+ import { z } from "zod";
12
+
13
+ /**
14
+ * What a tool call does, the same for every harness.
15
+ *
16
+ * - `shell`: runs a command;
17
+ * - `read`: reads a file or an image;
18
+ * - `edit`: writes, edits or patches files;
19
+ * - `search`: looks for files or for text in them;
20
+ * - `web`: fetches or searches the web;
21
+ * - `plan`: updates the agent's own checklist or plan;
22
+ * - `subagent`: hands work to another agent;
23
+ * - `mcp`: a tool of an MCP server;
24
+ * - `other`: anything else.
25
+ */
26
+ export const ToolCategorySchema = z.enum(["shell", "read", "edit", "search", "web", "plan", "subagent", "mcp", "other"]);
27
+ export type ToolCategory = z.output<typeof ToolCategorySchema>;
28
+
29
+ /** The state of one item of a checklist. */
30
+ export const ChecklistStateSchema = z.enum(["pending", "active", "done"]);
31
+ export type ChecklistState = z.output<typeof ChecklistStateSchema>;
32
+
33
+ export const ChecklistItemSchema = z.object({
34
+ text: z.string(),
35
+ state: ChecklistStateSchema,
36
+ });
37
+ export type ChecklistItem = z.output<typeof ChecklistItemSchema>;
38
+
39
+ /** The checklist an agent keeps of its work, whole, as it stood after an update. */
40
+ export const ChecklistSchema = z.object({
41
+ items: z.array(ChecklistItemSchema),
42
+ });
43
+ export type Checklist = z.output<typeof ChecklistSchema>;
44
+
45
+ /** How far a checklist is: the items that are done, of all of them. */
46
+ export interface ChecklistProgress {
47
+ readonly done: number;
48
+ readonly total: number;
49
+ }
50
+
51
+ export function checklistProgress(checklist: Checklist): ChecklistProgress {
52
+ return { done: checklist.items.filter((item) => item.state === "done").length, total: checklist.items.length };
53
+ }
54
+
55
+ /** What a kind says of a call of one of its tools. */
56
+ export interface ToolShape {
57
+ readonly category: ToolCategory;
58
+ /** The path, command, pattern, address or task the call is about, when its input names one. */
59
+ readonly target?: string;
60
+ /** Every path an edit names, when it names several (`target` is the first); absent when it names at most one. */
61
+ readonly paths?: string[];
62
+ }
63
+
64
+ /**
65
+ * The first string among `keys` of an input: the target a kind takes from the input of a tool
66
+ * whose shape it knows. It is trimmed to one line, unless `exact`: a path names a file by every
67
+ * character, and two files that differ in their whitespace stay two.
68
+ */
69
+ export function targetOf(input: unknown, keys: readonly string[], exact = false): string | undefined {
70
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined;
71
+ for (const key of keys) {
72
+ const value = Object.getOwnPropertyDescriptor(input, key)?.value;
73
+ if (typeof value === "string" && value.trim().length > 0) return exact ? value : value.replace(/\s+/g, " ").trim();
74
+ if (Array.isArray(value) && value.every((part) => typeof part === "string") && value.length > 0) {
75
+ return exact ? value.join(" ") : value.join(" ").replace(/\s+/g, " ").trim();
76
+ }
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ /** How a kind describes one of its own tools: its category, and the input keys that name its target. */
82
+ export interface ToolEntry {
83
+ readonly category: ToolCategory;
84
+ readonly target?: readonly string[];
85
+ }
86
+
87
+ /** A kind's own tools, by the names the kind gives them. */
88
+ export type ToolTable = Readonly<Record<string, ToolEntry>>;
89
+
90
+ /**
91
+ * The shape of a call by a kind's table: a tool the table does not name is `mcp` when the kind
92
+ * says the name is one of an MCP server's, else `other`.
93
+ */
94
+ export function shapeOf(
95
+ table: ToolTable,
96
+ name: string,
97
+ input: unknown,
98
+ isMcp: (name: string) => boolean = (tool) => tool.startsWith("mcp__"),
99
+ ): ToolShape {
100
+ const entry = Object.hasOwn(table, name) ? table[name] : undefined;
101
+ if (entry === undefined) return { category: isMcp(name) ? "mcp" : "other" };
102
+ // What a read or an edit points at is a path.
103
+ const exact = entry.category === "read" || entry.category === "edit";
104
+ const target = entry.target === undefined ? undefined : targetOf(input, entry.target, exact);
105
+ return target === undefined ? { category: entry.category } : { category: entry.category, target };
106
+ }