@lunchbox-labs/kilo-tool-inspector 0.0.0-stage → 0.3.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/tui.js ADDED
@@ -0,0 +1,1416 @@
1
+ // ../core/src/agents.ts
2
+ const editTools = /* @__PURE__ */ new Set([
3
+ "edit",
4
+ "write",
5
+ "apply_patch"
6
+ ]);
7
+ const mcpResourceReadTools = /* @__PURE__ */ new Set([
8
+ "list_mcp_resources",
9
+ "list_mcp_resource_templates",
10
+ "read_mcp_resource"
11
+ ]);
12
+ const unknownDecision = {
13
+ access: "unknown",
14
+ exceptions: [],
15
+ offeredToModel: void 0
16
+ };
17
+ const compiledWildcards = /* @__PURE__ */ new Map();
18
+ function field(value, key) {
19
+ return typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0;
20
+ }
21
+ function isPermissionAction(value) {
22
+ return value === "allow" || value === "ask" || value === "deny";
23
+ }
24
+ function readRule(value) {
25
+ const permission = field(value, "permission");
26
+ const pattern = field(value, "pattern");
27
+ const action = field(value, "action");
28
+ if (typeof permission !== "string" || typeof pattern !== "string" || !isPermissionAction(action)) return;
29
+ return {
30
+ permission,
31
+ pattern,
32
+ action
33
+ };
34
+ }
35
+ function readRuleset(value) {
36
+ if (!Array.isArray(value)) return;
37
+ const rules = [];
38
+ for (const item of value) {
39
+ const rule = readRule(item);
40
+ if (rule === void 0) return;
41
+ rules.push(rule);
42
+ }
43
+ return rules;
44
+ }
45
+ function readStringList(value) {
46
+ if (value === void 0) return [];
47
+ if (!Array.isArray(value)) return;
48
+ const strings = [];
49
+ for (const item of value) {
50
+ if (typeof item !== "string") return;
51
+ strings.push(item);
52
+ }
53
+ return strings;
54
+ }
55
+ function readItems(value) {
56
+ return Array.isArray(value) ? value : [];
57
+ }
58
+ function readAgent(value) {
59
+ const name = field(value, "name");
60
+ if (typeof name !== "string") return;
61
+ const mode = field(value, "mode");
62
+ return {
63
+ name,
64
+ mode: typeof mode === "string" ? mode : void 0,
65
+ hidden: field(value, "hidden") === true,
66
+ native: field(value, "native") === true,
67
+ permission: field(value, "permission")
68
+ };
69
+ }
70
+ function readToolId(value) {
71
+ const id = typeof value === "string" ? value : field(value, "id");
72
+ return typeof id === "string" ? id : void 0;
73
+ }
74
+ function readMode(mode) {
75
+ return mode === "primary" || mode === "subagent" || mode === "all" ? mode : "unknown";
76
+ }
77
+ function runsOnWindows() {
78
+ return typeof process !== "undefined" && process.platform === "win32";
79
+ }
80
+ function compileWildcard(pattern, flags) {
81
+ let expression = pattern.replaceAll("\\", "/").replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
82
+ if (expression.endsWith(" .*")) expression = `${expression.slice(0, -3)}( .*)?`;
83
+ return new RegExp(`^${expression}$`, flags);
84
+ }
85
+ function matchesWildcard(input, pattern) {
86
+ const flags = runsOnWindows() ? "si" : "s";
87
+ const key = `${flags}:${pattern}`;
88
+ let compiled = compiledWildcards.get(key);
89
+ if (compiled === void 0) {
90
+ compiled = compileWildcard(pattern, flags);
91
+ compiledWildcards.set(key, compiled);
92
+ }
93
+ return compiled.test(input.replaceAll("\\", "/"));
94
+ }
95
+ function isCatchAllPattern(pattern) {
96
+ return /^\*+(?: \*)?$/.test(pattern);
97
+ }
98
+ function decide(permission, rules) {
99
+ const matching = rules.filter((rule) => matchesWildcard(permission, rule.permission));
100
+ const lastCatchAll = matching.findLastIndex((rule) => isCatchAllPattern(rule.pattern));
101
+ const access = matching[lastCatchAll]?.action ?? "ask";
102
+ const exceptions = [];
103
+ for (const rule of matching.slice(lastCatchAll + 1)) {
104
+ const earlier = exceptions.findIndex((exception) => exception.pattern === rule.pattern);
105
+ if (earlier !== -1) exceptions.splice(earlier, 1);
106
+ if (exceptions.length === 0 && rule.action === access) continue;
107
+ exceptions.push({
108
+ pattern: rule.pattern,
109
+ access: rule.action
110
+ });
111
+ }
112
+ const firstChange = exceptions.findIndex((exception) => exception.access !== access);
113
+ const lastRule = matching.at(-1);
114
+ return {
115
+ access,
116
+ exceptions: firstChange === -1 ? [] : exceptions.slice(firstChange),
117
+ offeredToModel: !(lastRule?.pattern === "*" && lastRule.action === "deny")
118
+ };
119
+ }
120
+ function sameDecision(first, second) {
121
+ return first.access === second.access && first.offeredToModel === second.offeredToModel && first.exceptions.length === second.exceptions.length && first.exceptions.every((exception, index) => exception.pattern === second.exceptions[index]?.pattern && exception.access === second.exceptions[index].access);
122
+ }
123
+ function denyAll(permission) {
124
+ return {
125
+ permission,
126
+ pattern: "*",
127
+ action: "deny"
128
+ };
129
+ }
130
+ function subagentSessionRules(agentRules, parentSessionRules, primaryTools) {
131
+ const namesPermission = (permission) => agentRules.some((rule) => rule.permission === permission);
132
+ const inherited = [...parentSessionRules.filter((rule) => rule.action === "deny" || rule.permission === "external_directory"), ...["todowrite", "task"].filter((permission) => !namesPermission(permission)).map(denyAll)];
133
+ const isInherited = (deny) => inherited.some((rule) => rule.permission === deny.permission && rule.pattern === deny.pattern && rule.action === deny.action);
134
+ return [...inherited, ...primaryTools.map(denyAll).filter((deny) => !isInherited(deny))];
135
+ }
136
+ function agentAccess(agent, permission, sessionRules, primaryTools) {
137
+ const mode = readMode(agent.mode);
138
+ const summary = {
139
+ agent: agent.name,
140
+ mode,
141
+ hidden: agent.hidden === true,
142
+ native: agent.native === true
143
+ };
144
+ const agentRules = readRuleset(agent.permission);
145
+ if (agentRules === void 0) return {
146
+ ...summary,
147
+ ...unknownDecision
148
+ };
149
+ const primaryDecision = () => sessionRules === void 0 ? unknownDecision : decide(permission, [...agentRules, ...sessionRules]);
150
+ const subagentDecision = () => primaryTools === void 0 || sessionRules === void 0 ? unknownDecision : decide(permission, [...agentRules, ...subagentSessionRules(agentRules, sessionRules, primaryTools)]);
151
+ switch (mode) {
152
+ case "subagent": return {
153
+ ...summary,
154
+ ...subagentDecision()
155
+ };
156
+ case "all": {
157
+ const asPrimary = primaryDecision();
158
+ const asSubagent = subagentDecision();
159
+ return sameDecision(asPrimary, asSubagent) ? {
160
+ ...summary,
161
+ ...asPrimary
162
+ } : {
163
+ ...summary,
164
+ ...asPrimary,
165
+ whenSubagent: asSubagent
166
+ };
167
+ }
168
+ case "primary":
169
+ case "unknown": return {
170
+ ...summary,
171
+ ...primaryDecision()
172
+ };
173
+ }
174
+ }
175
+ function permissionForTool(toolId) {
176
+ if (editTools.has(toolId)) return "edit";
177
+ if (mcpResourceReadTools.has(toolId)) return "read";
178
+ return toolId;
179
+ }
180
+ function resolveToolAgentAccess(tools, agents, options = {}) {
181
+ const sessionRules = readRuleset(field(options, "sessionPermission") ?? []);
182
+ const primaryTools = readStringList(field(options, "primaryTools"));
183
+ const readableAgents = readItems(agents).map(readAgent).filter((agent) => agent !== void 0);
184
+ return readItems(tools).map(readToolId).filter((tool) => tool !== void 0).map((tool) => {
185
+ const permission = permissionForTool(tool);
186
+ return {
187
+ tool,
188
+ permission,
189
+ agents: readableAgents.map((agent) => agentAccess(agent, permission, sessionRules, primaryTools))
190
+ };
191
+ });
192
+ }
193
+
194
+ // ../core/src/detail-viewer.ts
195
+ const chromeRows = 9;
196
+ /** Renders a tool's detail sections in a keyboard-scrollable box inside the host's dialog frame. */
197
+ async function createDetailViewer(api) {
198
+ const { BoxRenderable, RenderableEvents, ScrollBoxRenderable, StyledText, TextAttributes, TextRenderable } = await import("@opentui/core");
199
+ return (detail) => {
200
+ const { renderer } = api;
201
+ const theme = api.theme.current;
202
+ const toneColours = {
203
+ plain: theme.text,
204
+ name: theme.text,
205
+ muted: theme.textMuted
206
+ };
207
+ const styled = (lines) => new StyledText(lines.flatMap((line, index) => [...index === 0 ? [] : [{
208
+ __isChunk: true,
209
+ text: "\n"
210
+ }], ...line.map((segment) => ({
211
+ __isChunk: true,
212
+ text: segment.text,
213
+ fg: toneColours[segment.tone],
214
+ ...segment.tone === "name" ? { attributes: TextAttributes.BOLD } : {}
215
+ }))]));
216
+ const rows = () => Math.max(1, renderer.height - Math.floor(renderer.height / 4) - chromeRows);
217
+ const view = new BoxRenderable(renderer, {
218
+ flexDirection: "column",
219
+ paddingX: 2,
220
+ paddingBottom: 1,
221
+ gap: 1
222
+ });
223
+ view.add(new TextRenderable(renderer, {
224
+ content: detail.title,
225
+ fg: theme.text,
226
+ attributes: TextAttributes.BOLD,
227
+ selectable: false
228
+ }));
229
+ const body = new BoxRenderable(renderer, {
230
+ flexDirection: "column",
231
+ gap: 1
232
+ });
233
+ if (detail.subtitle !== void 0) body.add(new TextRenderable(renderer, {
234
+ content: detail.subtitle,
235
+ fg: theme.textMuted,
236
+ wrapMode: "word"
237
+ }));
238
+ for (const section of detail.sections) {
239
+ const block = new BoxRenderable(renderer, { flexDirection: "column" });
240
+ block.add(new TextRenderable(renderer, {
241
+ content: section.heading,
242
+ fg: theme.accent,
243
+ attributes: TextAttributes.BOLD,
244
+ selectable: false
245
+ }));
246
+ block.add(new TextRenderable(renderer, {
247
+ content: styled(section.lines),
248
+ fg: theme.text,
249
+ wrapMode: "word"
250
+ }));
251
+ body.add(block);
252
+ }
253
+ const unwrappedRows = detail.sections.reduce((total, section) => total + section.lines.length + 2, detail.subtitle === void 0 ? 0 : 2);
254
+ const scroll = new ScrollBoxRenderable(renderer, {
255
+ height: Math.min(rows(), unwrappedRows),
256
+ flexShrink: 0,
257
+ verticalScrollbarOptions: {
258
+ paddingLeft: 1,
259
+ trackOptions: {
260
+ backgroundColor: theme.backgroundElement,
261
+ foregroundColor: theme.border
262
+ }
263
+ }
264
+ });
265
+ const fit = () => {
266
+ if (!scroll.isDestroyed) scroll.height = Math.max(1, Math.min(rows(), body.height));
267
+ };
268
+ body.onSizeChange = fit;
269
+ scroll.add(body);
270
+ view.add(scroll);
271
+ view.add(new TextRenderable(renderer, {
272
+ content: "↑/↓ scroll · pgup/pgdn page · home/end · esc back",
273
+ fg: theme.textMuted,
274
+ selectable: false
275
+ }));
276
+ renderer.on("resize", fit);
277
+ const unbind = api.keymap.registerLayer({
278
+ target: scroll,
279
+ targetMode: "focus",
280
+ bindings: [
281
+ {
282
+ key: "pageup",
283
+ cmd: () => scroll.scrollBy(-1 / 2, "viewport")
284
+ },
285
+ {
286
+ key: "pagedown",
287
+ cmd: () => scroll.scrollBy(1 / 2, "viewport")
288
+ },
289
+ {
290
+ key: "home",
291
+ cmd: () => scroll.scrollBy(-1, "content")
292
+ },
293
+ {
294
+ key: "end",
295
+ cmd: () => scroll.scrollBy(1, "content")
296
+ }
297
+ ]
298
+ });
299
+ const focus = setTimeout(() => {
300
+ if (!scroll.isDestroyed && !api.lifecycle.signal.aborted) scroll.focus();
301
+ }, 1);
302
+ const dispose = () => view.destroyRecursively();
303
+ api.lifecycle.signal.addEventListener("abort", dispose, { once: true });
304
+ view.on(RenderableEvents.DESTROYED, () => {
305
+ clearTimeout(focus);
306
+ renderer.off("resize", fit);
307
+ unbind();
308
+ api.lifecycle.signal.removeEventListener("abort", dispose);
309
+ });
310
+ return view;
311
+ };
312
+ }
313
+
314
+ // ../core/src/schema-text.ts
315
+ const indentWidth = 2;
316
+ const maximumDepth = 8;
317
+ const maximumLines = 400;
318
+ const maximumLineLength = 400;
319
+ const maximumCharacters = 1e5;
320
+ const maximumTypeLength = 200;
321
+ const maximumDescriptionLength = 4e3;
322
+ /** Enum values, tuple elements and union options named in a type before the rest are counted. */
323
+ const maximumNamedValues = 10;
324
+ /** How deep array items, unions and `allOf` members are followed when looking for fields. */
325
+ const maximumNesting = 64;
326
+ /**
327
+ * Caps the reference lookups behind one schema, so schemas whose references fan out are cut
328
+ * short instead of stalling the TUI.
329
+ */
330
+ const maximumReferenceLookups = 5e4;
331
+ /** Thrown when a schema would take more lines, text or lookups than a detail view shows. */
332
+ var SchemaTooLarge = class extends Error {};
333
+ function shortened(text, maximumLength) {
334
+ return text.length > maximumLength ? `${text.slice(0, maximumLength - 1)}…` : text;
335
+ }
336
+ /** Keeps a line within the line length, ending a cut line with "…". */
337
+ function fittedLine(line) {
338
+ let remaining = maximumLineLength;
339
+ const fitted = [];
340
+ for (const segment of line) {
341
+ if (segment.text.length < remaining) {
342
+ fitted.push(segment);
343
+ remaining -= segment.text.length;
344
+ continue;
345
+ }
346
+ fitted.push({
347
+ ...segment,
348
+ text: shortened(segment.text, remaining)
349
+ });
350
+ break;
351
+ }
352
+ return fitted;
353
+ }
354
+ function write(rendering, line) {
355
+ if (rendering.lines.length >= maximumLines) throw new SchemaTooLarge();
356
+ const fitted = fittedLine(line);
357
+ rendering.remainingCharacters -= fitted.reduce((length, segment) => length + segment.text.length, 0);
358
+ if (rendering.remainingCharacters < 0) throw new SchemaTooLarge();
359
+ rendering.lines.push(fitted);
360
+ }
361
+ function isObject(value) {
362
+ return typeof value === "object" && value !== null && !Array.isArray(value);
363
+ }
364
+ const literalTexts = /* @__PURE__ */ new WeakMap();
365
+ /** A value as JSON, shortened; large strings are cut before encoding and objects encoded once. */
366
+ function literal(value) {
367
+ if (typeof value === "string") {
368
+ const encoded = JSON.stringify(value.slice(0, maximumTypeLength));
369
+ return value.length > maximumTypeLength ? `${encoded}…` : encoded;
370
+ }
371
+ if (typeof value !== "object" || value === null) return shortened(JSON.stringify(value) ?? String(value), maximumTypeLength);
372
+ let text = literalTexts.get(value);
373
+ if (text === void 0) {
374
+ text = shortened(JSON.stringify(value), maximumTypeLength);
375
+ literalTexts.set(value, text);
376
+ }
377
+ return text;
378
+ }
379
+ /** Names the first few values, leaving out repeated names, then counts the rest. */
380
+ function namedValues(values, name, separator, { distinct = false } = {}) {
381
+ const names = [];
382
+ let length = 0;
383
+ let named = 0;
384
+ while (named < values.length && names.length < maximumNamedValues && length < maximumTypeLength / 2) {
385
+ const valueName = name(values[named]);
386
+ named++;
387
+ if (!distinct || !names.includes(valueName)) {
388
+ names.push(valueName);
389
+ length += valueName.length + separator.length;
390
+ }
391
+ }
392
+ const rest = values.length - named;
393
+ return [...names, ...rest > 0 ? [`… ${rest} more`] : []].join(separator);
394
+ }
395
+ function plain$1(text) {
396
+ return {
397
+ text,
398
+ tone: "plain"
399
+ };
400
+ }
401
+ function muted$2(text) {
402
+ return {
403
+ text,
404
+ tone: "muted"
405
+ };
406
+ }
407
+ function indentText(depth) {
408
+ return " ".repeat(depth * indentWidth);
409
+ }
410
+ function writeDescription(rendering, description, depth) {
411
+ if (typeof description !== "string" || description.trim() === "") return;
412
+ const text = shortened(description.trim(), maximumDescriptionLength);
413
+ for (const line of text.split(/\r?\n/)) write(rendering, [plain$1(`${indentText(depth)}${line}`)]);
414
+ }
415
+ function withoutReference(node) {
416
+ const { $ref: _reference, ...rest } = node;
417
+ return rest;
418
+ }
419
+ function decodedPointerKey(rawKey) {
420
+ try {
421
+ return decodeURIComponent(rawKey);
422
+ } catch {
423
+ return rawKey;
424
+ }
425
+ }
426
+ /** Keys beside a `$ref` that change its target's shape, so it no longer reads as that definition. */
427
+ const shapeKeys = /* @__PURE__ */ new Set([
428
+ "properties",
429
+ "required",
430
+ "items",
431
+ "prefixItems",
432
+ "additionalProperties",
433
+ "allOf",
434
+ "anyOf",
435
+ "oneOf"
436
+ ]);
437
+ /** The value a local JSON pointer such as `#/$defs/Address` names, if any. */
438
+ function pointerTarget(root, reference) {
439
+ let target = root;
440
+ for (const rawKey of reference.slice(1).split("/").filter(Boolean)) {
441
+ const key = decodedPointerKey(rawKey).replaceAll("~1", "/").replaceAll("~0", "~");
442
+ target = isObject(target) ? target[key] : void 0;
443
+ }
444
+ return target;
445
+ }
446
+ const definitionSections = ["#/$defs/", "#/definitions/"];
447
+ /**
448
+ * The schema a local reference names, and the reference as the schema spells it. OpenCode 1.19
449
+ * and Kilo 7.8 rename zod's `$defs` to `definitions` without rewriting the references to them,
450
+ * so a miss under either name is retried under the other.
451
+ */
452
+ function referenceTarget(root, reference) {
453
+ const target = pointerTarget(root, reference);
454
+ if (isObject(target)) return {
455
+ schema: target,
456
+ reference
457
+ };
458
+ const section = definitionSections.find((prefix) => reference.startsWith(prefix));
459
+ const otherSection = definitionSections.find((prefix) => prefix !== section);
460
+ if (section === void 0 || otherSection === void 0) return;
461
+ const alias = `${otherSection}${reference.slice(section.length)}`;
462
+ const aliasTarget = pointerTarget(root, alias);
463
+ return isObject(aliasTarget) ? {
464
+ schema: aliasTarget,
465
+ reference: alias
466
+ } : void 0;
467
+ }
468
+ function countLookup(rendering) {
469
+ rendering.remainingLookups--;
470
+ if (rendering.remainingLookups < 0) throw new SchemaTooLarge();
471
+ }
472
+ /** How many definitions that only refer to another are followed before giving up. */
473
+ const maximumReferenceHops = 64;
474
+ /**
475
+ * Resolves local `$ref`s, as zod and MCP servers emit for shared definitions, following a
476
+ * definition that is itself a reference to another.
477
+ */
478
+ function resolveReference(node, rendering, visiting) {
479
+ countLookup(rendering);
480
+ if (typeof node.$ref !== "string") return {
481
+ node,
482
+ visiting
483
+ };
484
+ const chain = new Set(visiting);
485
+ let current = node;
486
+ let definition;
487
+ let reshaped = false;
488
+ let hops = 0;
489
+ for (let reference = node.$ref; typeof reference === "string"; reference = current.$ref) {
490
+ if (hops === maximumReferenceHops) return {
491
+ node: current,
492
+ visiting: chain,
493
+ chainTooLong: true
494
+ };
495
+ const target = reference.startsWith("#") ? referenceTarget(rendering.root, reference) : void 0;
496
+ if (target === void 0) return {
497
+ node: current,
498
+ visiting: chain,
499
+ unresolvedReference: reference
500
+ };
501
+ if (chain.has(target.reference)) return {
502
+ node: current,
503
+ visiting: chain,
504
+ recursiveReference: target.reference
505
+ };
506
+ hops++;
507
+ countLookup(rendering);
508
+ const siblings = withoutReference(current);
509
+ reshaped ||= Object.keys(siblings).some((key) => shapeKeys.has(key));
510
+ current = {
511
+ ...target.schema,
512
+ ...siblings
513
+ };
514
+ chain.add(target.reference);
515
+ definition = reshaped ? void 0 : target.reference;
516
+ }
517
+ return {
518
+ node: current,
519
+ visiting: chain,
520
+ definition
521
+ };
522
+ }
523
+ function referenceName(reference) {
524
+ const name = reference.split("/").at(-1) ?? "";
525
+ return name === "" || name === "#" ? "the whole input" : name;
526
+ }
527
+ function nonEmptyList(value) {
528
+ if (Array.isArray(value) && value.length > 0) return value;
529
+ }
530
+ function variants(node) {
531
+ return nonEmptyList(node.anyOf) ?? nonEmptyList(node.oneOf);
532
+ }
533
+ function hasCombinators(node) {
534
+ return variants(node) !== void 0 || nonEmptyList(node.allOf) !== void 0;
535
+ }
536
+ /** Folds `allOf` members' properties and required names into one object schema. */
537
+ function mergedAllOf(node, rendering, visiting, nesting = 0) {
538
+ const members = nonEmptyList(node.allOf);
539
+ if (members === void 0) return node;
540
+ if (nesting > maximumNesting) {
541
+ rendering.depthCutoffs++;
542
+ const { allOf: _allOf, ...rest } = node;
543
+ rendering.cutMerges.add(rest);
544
+ return rest;
545
+ }
546
+ let cut = false;
547
+ const properties = {};
548
+ const required = /* @__PURE__ */ new Set();
549
+ for (const member of [...members, node]) {
550
+ if (!isObject(member)) continue;
551
+ let memberNode = member;
552
+ if (member !== node) {
553
+ const resolved = resolveReference(member, rendering, visiting);
554
+ memberNode = resolved.recursiveReference === void 0 ? mergedAllOf(resolved.node, rendering, resolved.visiting, nesting + 1) : {};
555
+ cut ||= rendering.cutMerges.has(memberNode);
556
+ }
557
+ if (isObject(memberNode.properties)) Object.assign(properties, memberNode.properties);
558
+ if (Array.isArray(memberNode.required)) {
559
+ const memberRequired = memberNode.required;
560
+ for (const name of memberRequired) required.add(name);
561
+ }
562
+ }
563
+ const { allOf: _allOf, ...rest } = node;
564
+ const merged = Object.keys(properties).length === 0 ? rest : {
565
+ ...rest,
566
+ properties,
567
+ required: [...required]
568
+ };
569
+ if (cut) rendering.cutMerges.add(merged);
570
+ return merged;
571
+ }
572
+ /** The one JSON type a schema or all of its union's options have, if any. */
573
+ function ownType(schema) {
574
+ if (typeof schema.type === "string") return schema.type;
575
+ const types = new Set((variants(schema) ?? []).map((variant) => isObject(variant) && typeof variant.type === "string" ? variant.type : void 0));
576
+ const [only] = types;
577
+ return types.size === 1 ? only : void 0;
578
+ }
579
+ /** Names a reference back into a definition being expanded. */
580
+ function recursiveTypeName(reference, rendering) {
581
+ const name = referenceName(reference);
582
+ if (!name.startsWith("__")) return name;
583
+ const target = referenceTarget(rendering.root, reference);
584
+ const type = target === void 0 ? void 0 : ownType(target.schema);
585
+ if (type !== void 0) return type;
586
+ const path = rendering.typedFields.get(reference) ?? rendering.listedDefinitions.get(reference)?.path;
587
+ return path === void 0 ? "recursive value" : `same type as ${path}`;
588
+ }
589
+ function pluralType(type) {
590
+ if (type === "any") return "values";
591
+ if (type === "…") return type;
592
+ if (type.startsWith("\"") || type.includes(" ")) return `items of ${type}`;
593
+ return type.endsWith("s") ? type : `${type}s`;
594
+ }
595
+ function typeName(schema, rendering, visiting, depth) {
596
+ if (schema === true || isObject(schema) && Object.keys(schema).length === 0) return "any";
597
+ if (schema === false) return "never";
598
+ if (!isObject(schema)) return "unknown";
599
+ if (depth > maximumDepth) {
600
+ rendering.depthCutoffs++;
601
+ return "…";
602
+ }
603
+ const resolved = resolveReference(schema, rendering, visiting);
604
+ if (resolved.recursiveReference !== void 0) return recursiveTypeName(resolved.recursiveReference, rendering);
605
+ if (resolved.unresolvedReference !== void 0 || resolved.chainTooLong === true) {
606
+ const known = typeName(withoutReference(resolved.node), rendering, resolved.visiting, depth);
607
+ return known === "any" ? resolved.unresolvedReference === void 0 ? "reference chain too long" : `unresolved reference ${referenceName(resolved.unresolvedReference)}` : known;
608
+ }
609
+ const node = mergedAllOf(resolved.node, rendering, resolved.visiting);
610
+ const nestedName = (nested) => shortened(typeName(nested, rendering, resolved.visiting, depth + 1), maximumTypeLength);
611
+ const arrayName = () => {
612
+ const prefixItems = nonEmptyList(node.prefixItems);
613
+ const elements = prefixItems ?? nonEmptyList(node.items);
614
+ if (elements !== void 0) {
615
+ const tuple = `tuple of ${namedValues(elements, nestedName, ", ")}`;
616
+ const rest = prefixItems === void 0 ? node.additionalItems : node.items;
617
+ return isObject(rest) && Object.keys(rest).length > 0 ? `${tuple}, then ${pluralType(nestedName(rest))}` : tuple;
618
+ }
619
+ return node.items === void 0 || Array.isArray(node.items) ? "array" : `array of ${pluralType(nestedName(node.items))}`;
620
+ };
621
+ if (Object.hasOwn(node, "const")) return literal(node.const);
622
+ if (Array.isArray(node.enum) && node.enum.length > 0) {
623
+ const values = node.enum;
624
+ return namedValues(values, literal, " | ");
625
+ }
626
+ const alternatives = variants(node);
627
+ if (alternatives !== void 0) return namedValues(alternatives, nestedName, " | ", { distinct: true });
628
+ const type = node.type;
629
+ if (Array.isArray(type)) {
630
+ const typeNames = [...new Set(type.filter((item) => typeof item === "string"))];
631
+ let array;
632
+ return typeNames.length === 0 ? "any" : namedValues(typeNames, (item) => item === "array" ? array ??= arrayName() : String(item), " | ");
633
+ }
634
+ if (type === "array") return arrayName();
635
+ if (type === "object" || isObject(node.properties)) {
636
+ if (!isObject(node.properties) && isObject(node.additionalProperties)) return `object with ${nestedName(node.additionalProperties)} values`;
637
+ return "object";
638
+ }
639
+ return typeof type === "string" ? type : "any";
640
+ }
641
+ const unboundedLimits = /* @__PURE__ */ new Set([
642
+ Number.MAX_SAFE_INTEGER,
643
+ Number.MIN_SAFE_INTEGER,
644
+ Number.MAX_VALUE,
645
+ -Number.MAX_VALUE
646
+ ]);
647
+ function constraintNotes(node) {
648
+ const notes = [];
649
+ const bound = (key, symbol) => {
650
+ const value = node[key];
651
+ if (typeof value === "number" && !unboundedLimits.has(value)) notes.push(`${symbol} ${value}`);
652
+ };
653
+ bound("minimum", "≥");
654
+ bound("exclusiveMinimum", ">");
655
+ bound("maximum", "≤");
656
+ bound("exclusiveMaximum", "<");
657
+ const count = (key, label) => {
658
+ const value = node[key];
659
+ if (typeof value === "number") notes.push(`${label} ${value}`);
660
+ };
661
+ count("minLength", "min length");
662
+ count("maxLength", "max length");
663
+ count("minItems", "min items");
664
+ count("maxItems", "max items");
665
+ if (typeof node.format === "string") notes.push(`format ${node.format}`);
666
+ if (typeof node.pattern === "string") notes.push(`pattern "${node.pattern.replaceAll("\n", "\\n")}"`);
667
+ if (Object.hasOwn(node, "default")) notes.push(`default ${literal(node.default)}`);
668
+ if (node.deprecated === true) notes.push("deprecated");
669
+ return notes;
670
+ }
671
+ /** The object schema whose properties appear nested under a property, if any. */
672
+ function nestedObject(node, rendering, visiting, nesting = 0) {
673
+ if (nesting > maximumNesting) return;
674
+ const resolved = resolveReference(node, rendering, visiting);
675
+ if (resolved.recursiveReference !== void 0) return;
676
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
677
+ if (isObject(merged.properties) && (Object.keys(merged.properties).length > 0 || variants(merged) === void 0)) return {
678
+ node: merged,
679
+ visiting: resolved.visiting,
680
+ definition: resolved.definition
681
+ };
682
+ const items = merged.items;
683
+ if (isObject(items)) return nestedObject(items, rendering, resolved.visiting, nesting + 1);
684
+ const alternatives = variants(merged);
685
+ if (alternatives !== void 0) {
686
+ const objects = alternatives.filter(isObject).map((variant) => nestedObject(variant, rendering, resolved.visiting, nesting + 1)).filter((variant) => variant !== void 0);
687
+ return objects.length === 1 ? objects[0] : void 0;
688
+ }
689
+ }
690
+ function listedObjectVariants(node, rendering, visiting) {
691
+ return (variants(node) ?? []).filter((variant) => isObject(variant) && nestedObject(variant, rendering, visiting) !== void 0).length;
692
+ }
693
+ /** The definition a property refers back into while it is being listed, following array items. */
694
+ function recursiveDefinition(node, rendering, visiting, nesting = 0) {
695
+ if (nesting > maximumNesting) return;
696
+ const resolved = resolveReference(node, rendering, visiting);
697
+ if (resolved.recursiveReference !== void 0) return resolved.recursiveReference;
698
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
699
+ const present = (variants(merged) ?? []).filter((variant) => !(isObject(variant) && variant.type === "null"));
700
+ const inner = isObject(merged.items) ? merged.items : present.length === 1 && isObject(present[0]) ? present[0] : void 0;
701
+ return inner === void 0 ? void 0 : recursiveDefinition(inner, rendering, resolved.visiting, nesting + 1);
702
+ }
703
+ /** Whether listing a union option says more than "object". */
704
+ function informativeVariant(variant, rendering, visiting) {
705
+ const type = typeName(variant, rendering, visiting, 0);
706
+ return type !== "object" && type !== "any" || isObject(variant) && nestedObject(variant, rendering, visiting) !== void 0;
707
+ }
708
+ /** The union of several object options under a property, following array items, if any. */
709
+ function objectUnion(node, rendering, visiting, nesting = 0) {
710
+ if (nesting > maximumNesting) return;
711
+ const resolved = resolveReference(node, rendering, visiting);
712
+ if (resolved.recursiveReference !== void 0) return;
713
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
714
+ if (listedObjectVariants(merged, rendering, resolved.visiting) > 1) return {
715
+ node: merged,
716
+ visiting: resolved.visiting,
717
+ definition: resolved.definition
718
+ };
719
+ const present = (variants(merged) ?? []).filter((variant) => !(isObject(variant) && variant.type === "null"));
720
+ if (present.length === 1 && isObject(present[0])) return objectUnion(present[0], rendering, resolved.visiting, nesting + 1);
721
+ return isObject(merged.items) ? objectUnion(merged.items, rendering, resolved.visiting, nesting + 1) : void 0;
722
+ }
723
+ /**
724
+ * Lists an object schema's properties, then each option of a union beside them, indented by
725
+ * depth.
726
+ */
727
+ function writeProperties(rendering, objectSchema, visiting, depth, path) {
728
+ if (depth > maximumDepth) {
729
+ rendering.depthCutoffs++;
730
+ write(rendering, [plain$1(`${indentText(depth)}…`)]);
731
+ return;
732
+ }
733
+ /**
734
+ * Lists a field's or option's own fields one level deeper, or, for a shared definition already
735
+ * listed, where its fields are.
736
+ */
737
+ const writeListedAt = (listing) => {
738
+ if (listing === void 0) return false;
739
+ write(rendering, [plain$1(indentText(depth + 1)), muted$2(`Same fields as ${listing.path}.`)]);
740
+ return true;
741
+ };
742
+ const listingOf = (definition) => definition === void 0 ? void 0 : rendering.listedDefinitions.get(definition);
743
+ const writeFields = (source, sourcePath) => {
744
+ const { definition } = source;
745
+ const earlier = listingOf(definition);
746
+ if (earlier !== void 0 && (!earlier.cut || depth + 1 >= earlier.depth) && writeListedAt(earlier)) return;
747
+ const listing = {
748
+ path: sourcePath,
749
+ depth: depth + 1,
750
+ cut: false
751
+ };
752
+ if (definition !== void 0) rendering.listedDefinitions.set(definition, listing);
753
+ const linesBefore = rendering.lines.length;
754
+ const cutoffsBefore = rendering.depthCutoffs;
755
+ writeProperties(rendering, source.node, source.visiting, depth + 1, sourcePath);
756
+ listing.cut = rendering.depthCutoffs > cutoffsBefore;
757
+ if (definition !== void 0 && rendering.lines.length === linesBefore) {
758
+ if (earlier === void 0) rendering.listedDefinitions.delete(definition);
759
+ else rendering.listedDefinitions.set(definition, earlier);
760
+ }
761
+ };
762
+ const alternatives = variants(objectSchema);
763
+ const listedOptions = alternatives?.some((variant) => informativeVariant(variant, rendering, visiting)) === true ? alternatives : [];
764
+ const properties = isObject(objectSchema.properties) ? Object.entries(objectSchema.properties) : [];
765
+ if (properties.length > 0) {
766
+ const required = new Set(Array.isArray(objectSchema.required) ? objectSchema.required.filter((name) => typeof name === "string") : []);
767
+ for (const [name, property] of properties) {
768
+ const fieldPath = path === "" ? name : `${path}.${name}`;
769
+ const fieldReference = isObject(property) && typeof property.$ref === "string" ? referenceTarget(rendering.root, property.$ref)?.reference : void 0;
770
+ if (fieldReference !== void 0 && !rendering.typedFields.has(fieldReference)) rendering.typedFields.set(fieldReference, fieldPath);
771
+ const resolved = isObject(property) ? mergedAllOf(resolveReference(property, rendering, visiting).node, rendering, visiting) : {};
772
+ const details = [
773
+ typeName(property, rendering, visiting, depth),
774
+ ...required.has(name) ? ["required"] : [],
775
+ ...constraintNotes(resolved)
776
+ ];
777
+ write(rendering, [
778
+ plain$1(indentText(depth)),
779
+ {
780
+ text: name,
781
+ tone: "name"
782
+ },
783
+ muted$2(` ${details.join(", ")}`)
784
+ ]);
785
+ writeDescription(rendering, resolved.description, depth + 1);
786
+ const fields = isObject(property) ? nestedObject(property, rendering, visiting) ?? objectUnion(property, rendering, visiting) : void 0;
787
+ if (fields !== void 0) writeFields(fields, fieldPath);
788
+ else if (isObject(property)) writeListedAt(listingOf(recursiveDefinition(property, rendering, visiting)));
789
+ }
790
+ }
791
+ if (rendering.cutMerges.has(objectSchema)) write(rendering, [plain$1(`${indentText(depth)}…`)]);
792
+ if (properties.length > 0 && listedOptions.length > 0) write(rendering, [plain$1(indentText(depth)), muted$2("And one of:")]);
793
+ listedOptions.forEach((variant, index) => {
794
+ const heading = [plain$1(indentText(depth)), {
795
+ text: `Option ${index + 1}`,
796
+ tone: "name"
797
+ }];
798
+ write(rendering, heading);
799
+ const linesAfterHeading = rendering.lines.length;
800
+ const fields = isObject(variant) ? nestedObject(variant, rendering, visiting) : void 0;
801
+ if (fields !== void 0) writeFields(fields, `${path === "" ? "" : `${path} `}option ${index + 1}`);
802
+ if (rendering.lines.length === linesAfterHeading) rendering.lines[linesAfterHeading - 1] = [...heading, muted$2(` ${typeName(variant, rendering, visiting, depth)}`)];
803
+ });
804
+ }
805
+ function rawSchemaLines(hostName, schema) {
806
+ return [[muted$2(`${hostName} reported this input schema:`)], ...JSON.stringify(schema, void 0, indentWidth).split("\n").map((line) => [muted$2(line)])];
807
+ }
808
+ function capped(lines) {
809
+ if (lines.length <= maximumLines) return lines;
810
+ return [...lines.slice(0, maximumLines), [muted$2(`… ${lines.length - maximumLines} more lines not shown.`)]];
811
+ }
812
+ function rootLines(rendering, schema) {
813
+ const noneVisiting = /* @__PURE__ */ new Set();
814
+ const nested = nestedObject(schema, rendering, noneVisiting);
815
+ if (nested !== void 0) {
816
+ writeProperties(rendering, nested.node, nested.visiting, 0, "");
817
+ if (rendering.lines.length > 0) return rendering.lines;
818
+ }
819
+ const resolved = resolveReference(schema, rendering, noneVisiting).node;
820
+ const merged = mergedAllOf(resolved, rendering, noneVisiting);
821
+ if (variants(merged)?.some((variant) => informativeVariant(variant, rendering, noneVisiting)) === true) {
822
+ write(rendering, [muted$2("Takes one of these inputs:")]);
823
+ writeProperties(rendering, merged, noneVisiting, 0, "");
824
+ return rendering.lines;
825
+ }
826
+ const type = typeName(schema, rendering, noneVisiting, 0);
827
+ if (type === "object" || type === "any") return hasCombinators(resolved) ? capped(rawSchemaLines(rendering.hostName, schema)) : [[muted$2("Takes no input.")]];
828
+ return [[plain$1("Input is "), {
829
+ text: type,
830
+ tone: "name"
831
+ }]];
832
+ }
833
+ /**
834
+ * Renders a tool's input JSON schema as indented, readable lines. A shared definition's fields
835
+ * are listed once, and a schema too large to show is cut short with a note. `hostName` names the
836
+ * host in notes about what it reported.
837
+ */
838
+ function schemaLines(schema, hostName) {
839
+ if (!isObject(schema)) return [[muted$2(`${hostName} did not report an input schema.`)]];
840
+ const rendering = {
841
+ hostName,
842
+ root: schema,
843
+ lines: [],
844
+ remainingLookups: maximumReferenceLookups,
845
+ remainingCharacters: maximumCharacters,
846
+ listedDefinitions: /* @__PURE__ */ new Map(),
847
+ depthCutoffs: 0,
848
+ typedFields: /* @__PURE__ */ new Map(),
849
+ cutMerges: /* @__PURE__ */ new WeakSet()
850
+ };
851
+ try {
852
+ return rootLines(rendering, schema);
853
+ } catch (error) {
854
+ if (error instanceof SchemaTooLarge && rendering.lines.length > 0) return [...rendering.lines, [muted$2("… Schema too large to show in full.")]];
855
+ return capped(rawSchemaLines(rendering.hostName, schema));
856
+ }
857
+ }
858
+ function linesText(lines) {
859
+ return lines.map((line) => line.map((segment) => segment.text).join("")).join("\n");
860
+ }
861
+
862
+ // ../core/src/agent-text.ts
863
+ const modeLabels = {
864
+ primary: "primary",
865
+ subagent: "subagent",
866
+ all: "primary or subagent",
867
+ unknown: void 0
868
+ };
869
+ function muted$1(text) {
870
+ return {
871
+ text,
872
+ tone: "muted"
873
+ };
874
+ }
875
+ function plain(text) {
876
+ return {
877
+ text,
878
+ tone: "plain"
879
+ };
880
+ }
881
+ function indent(depth) {
882
+ return " ".repeat(depth);
883
+ }
884
+ function decisionSummary(decision, actionLabels) {
885
+ if (decision.access === "unknown") return "unknown, permissions couldn't be read";
886
+ if (decision.offeredToModel === false) return "not offered to the model";
887
+ return actionLabels[decision.access];
888
+ }
889
+ function exceptionLines(decision, depth, actionLabels) {
890
+ if (decision.offeredToModel === false) return [];
891
+ return decision.exceptions.map((exception) => [plain(`${indent(depth)}${actionLabels[exception.access]} for `), {
892
+ text: exception.pattern,
893
+ tone: "name"
894
+ }]);
895
+ }
896
+ function agentLines(agent, actionLabels) {
897
+ const notes = [modeLabels[agent.mode], ...agent.hidden ? ["hidden"] : []].filter((note) => note !== void 0);
898
+ const lines = [[{
899
+ text: agent.agent,
900
+ tone: "name"
901
+ }, muted$1(` ${notes.length === 0 ? "" : `${notes.join(", ")}: `}${decisionSummary(agent, actionLabels)}`)], ...exceptionLines(agent, 1, actionLabels)];
902
+ if (agent.whenSubagent !== void 0) lines.push([plain(`${indent(1)}as a subagent: ${decisionSummary(agent.whenSubagent, actionLabels)}`)], ...exceptionLines(agent.whenSubagent, 2, actionLabels));
903
+ return lines;
904
+ }
905
+ /** The host's own hidden agents, such as `compaction` and `title`, never take tool calls. */
906
+ function listed(agent) {
907
+ return !(agent.native && agent.hidden);
908
+ }
909
+ function primaryFirst(left, right) {
910
+ const rank = (agent) => agent.mode === "subagent" ? 1 : 0;
911
+ return rank(left) - rank(right);
912
+ }
913
+ function notesFor(notes, key) {
914
+ return notes !== void 0 && Object.hasOwn(notes, key) ? notes[key] : [];
915
+ }
916
+ function accessNoteLines(notes, access) {
917
+ return [
918
+ ...notes.always ?? [],
919
+ ...notesFor(notes.permission, access.permission),
920
+ ...notesFor(notes.tool, access.tool)
921
+ ].map((note) => [muted$1(note)]);
922
+ }
923
+ /** Renders which agents can use a tool, primary agents first. */
924
+ function agentAccessLines(access, host) {
925
+ const { actionLabels } = host;
926
+ const agents = access.agents.filter(listed).sort(primaryFirst);
927
+ if (agents.length === 0) return [[muted$1(`${host.name} reported no agents that use tools.`)]];
928
+ const permissionNote = access.permission === access.tool ? [] : [[muted$1(`Checked as the ${access.permission} permission.`)]];
929
+ const patternNote = agents.some((agent) => exceptionLines(agent, 1, actionLabels).length > 0 || agent.whenSubagent !== void 0 && exceptionLines(agent.whenSubagent, 2, actionLabels).length > 0) ? [[muted$1("Patterns match the call's input, such as a command or path; a later line wins.")]] : [];
930
+ return [
931
+ ...permissionNote,
932
+ ...accessNoteLines(host.accessNotes, access),
933
+ ...agents.flatMap((agent) => agentLines(agent, actionLabels)),
934
+ ...patternNote
935
+ ];
936
+ }
937
+
938
+ // ../core/src/tool-detail.ts
939
+ function muted(text) {
940
+ return [[{
941
+ text,
942
+ tone: "muted"
943
+ }]];
944
+ }
945
+ function textLines(text) {
946
+ return text.trim().split(/\r?\n/).map((line) => [{
947
+ text: line,
948
+ tone: "plain"
949
+ }]);
950
+ }
951
+ /**
952
+ * The detail view's content. The Agents section is left out when the host's agents couldn't be
953
+ * read.
954
+ */
955
+ function toolDetail(host, tool, modelLabel, access) {
956
+ const detailsMissing = `${host.name} reported only this tool's name.`;
957
+ return {
958
+ title: tool.id,
959
+ subtitle: modelLabel === void 0 ? void 0 : `As offered to ${modelLabel}`,
960
+ sections: [
961
+ {
962
+ heading: "Input",
963
+ lines: tool.description === void 0 && tool.parameters === void 0 ? muted(detailsMissing) : schemaLines(tool.parameters, host.name)
964
+ },
965
+ ...access === void 0 ? [] : [{
966
+ heading: "Agents",
967
+ lines: agentAccessLines(access, host)
968
+ }],
969
+ {
970
+ heading: "Description",
971
+ lines: tool.description === void 0 ? muted(detailsMissing) : tool.description.trim() === "" ? muted("No description.") : textLines(tool.description)
972
+ }
973
+ ]
974
+ };
975
+ }
976
+
977
+ // ../core/src/tools.ts
978
+ const sourceLabels = {
979
+ session: "this session's model",
980
+ configured: "configured model",
981
+ "provider default": "provider default"
982
+ };
983
+ /** The host's placeholder for unknown tool calls, never offered to agents as a real tool. */
984
+ const internalToolIds = /* @__PURE__ */ new Set(["invalid"]);
985
+ function isRecord(value) {
986
+ return typeof value === "object" && value !== null;
987
+ }
988
+ function modelLabel(model) {
989
+ return `${model.providerID}/${model.modelID}`;
990
+ }
991
+ function chosenModelLabel(model) {
992
+ return `${modelLabel(model)} (${sourceLabels[model.source]})`;
993
+ }
994
+ /** The model of the session's latest user message, which the host resolves tools for on the next prompt. */
995
+ function sessionModel(messages) {
996
+ for (const message of [...messages].reverse()) {
997
+ if (!isRecord(message) || message.role !== "user") continue;
998
+ const model = message.model;
999
+ if (isRecord(model) && typeof model.providerID === "string" && typeof model.modelID === "string" && model.providerID !== "" && model.modelID !== "") return {
1000
+ providerID: model.providerID,
1001
+ modelID: model.modelID
1002
+ };
1003
+ }
1004
+ }
1005
+ /** Parses the `provider/model` form used by the `model` setting. */
1006
+ function configuredModel(model) {
1007
+ if (typeof model !== "string") return;
1008
+ const separator = model.indexOf("/");
1009
+ if (separator <= 0 || separator === model.length - 1) return;
1010
+ return {
1011
+ providerID: model.slice(0, separator),
1012
+ modelID: model.slice(separator + 1)
1013
+ };
1014
+ }
1015
+ /** The first connected provider's default model, which the host falls back to when none is configured. */
1016
+ function providerDefaultModel(connectedProviderIds, defaults) {
1017
+ if (!isRecord(defaults)) return;
1018
+ for (const providerID of connectedProviderIds) {
1019
+ const modelID = defaults[providerID];
1020
+ if (typeof modelID === "string" && modelID !== "") return {
1021
+ providerID,
1022
+ modelID
1023
+ };
1024
+ }
1025
+ }
1026
+ function byId(left, right) {
1027
+ return left.id.localeCompare(right.id);
1028
+ }
1029
+ /** Keeps well-formed entries from the host's tool list, sorted by id. */
1030
+ function toolsFromList(response) {
1031
+ if (!Array.isArray(response)) return;
1032
+ const tools = /* @__PURE__ */ new Map();
1033
+ for (const item of response) {
1034
+ if (!isRecord(item) || typeof item.id !== "string" || item.id === "" || internalToolIds.has(item.id)) continue;
1035
+ tools.set(item.id, {
1036
+ id: item.id,
1037
+ description: typeof item.description === "string" ? item.description : void 0,
1038
+ parameters: item.parameters
1039
+ });
1040
+ }
1041
+ return [...tools.values()].sort(byId);
1042
+ }
1043
+ /** Tool ids without details, for when the host can't resolve tools for a model. */
1044
+ function toolsFromIds(response) {
1045
+ if (!Array.isArray(response)) return;
1046
+ return [...new Set(response.filter((id) => typeof id === "string" && id !== "" && !internalToolIds.has(id)))].map((id) => ({
1047
+ id,
1048
+ description: void 0,
1049
+ parameters: void 0
1050
+ })).sort(byId);
1051
+ }
1052
+ const summaryLength = 100;
1053
+ /** The first line of a description without its list marker, short enough for one list row. */
1054
+ function descriptionSummary(description) {
1055
+ const firstLine = description?.split(/\r?\n/).map((line) => line.trim().replace(/^[-*•]\s+/, "")).find((line) => line !== "") ?? "";
1056
+ return firstLine.length > summaryLength ? `${firstLine.slice(0, 99).trimEnd()}…` : firstLine;
1057
+ }
1058
+ /**
1059
+ * The number of top-level input properties, or undefined when the schema has none to count, such
1060
+ * as a union beside empty `properties`.
1061
+ */
1062
+ function inputCount(parameters) {
1063
+ if (!isRecord(parameters) || !isRecord(parameters.properties)) return;
1064
+ const count = Object.keys(parameters.properties).length;
1065
+ return count === 0 && (parameters.anyOf !== void 0 || parameters.oneOf !== void 0) ? void 0 : count;
1066
+ }
1067
+
1068
+ // ../core/src/tui.ts
1069
+ const toastTitle = "Tool Inspector";
1070
+ /** The plain-text fallback can't scroll, so long sections are cut short. */
1071
+ const plainTextSectionLines = 20;
1072
+ function errorText(error) {
1073
+ if (error instanceof Error) return error.message;
1074
+ if (typeof error === "object" && error !== null) {
1075
+ const record = error;
1076
+ if (typeof record.message === "string") return record.message;
1077
+ if (typeof record.data?.message === "string") return record.data.message;
1078
+ return JSON.stringify(error);
1079
+ }
1080
+ return String(error);
1081
+ }
1082
+ /** Names of connected MCP servers, whose tools the host's tool list leaves out. */
1083
+ function connectedMcpServers(api) {
1084
+ try {
1085
+ return api.state.mcp().filter((server) => server.status === "connected").map((server) => server.name);
1086
+ } catch {
1087
+ return [];
1088
+ }
1089
+ }
1090
+ function mcpNotice(host, servers) {
1091
+ if (servers.length === 0) return;
1092
+ return `Tools from MCP servers (${servers.join(", ")}) aren't listed, because ${host.name} only adds them when it runs a prompt.`;
1093
+ }
1094
+ function currentSessionId(api) {
1095
+ const route = api.route.current;
1096
+ return route.name === "session" && typeof route.params?.sessionID === "string" ? route.params.sessionID : void 0;
1097
+ }
1098
+ async function chooseModel(api, signal) {
1099
+ const sessionId = currentSessionId(api);
1100
+ const fromSession = sessionId === void 0 ? void 0 : sessionModel(api.state.session.messages(sessionId));
1101
+ if (fromSession !== void 0) return {
1102
+ ...fromSession,
1103
+ source: "session"
1104
+ };
1105
+ const connectedProviderIds = api.state.provider.map((provider) => provider.id);
1106
+ const configured = configuredModel(api.state.config.model);
1107
+ if (configured !== void 0 && (connectedProviderIds.length === 0 || connectedProviderIds.includes(configured.providerID))) return {
1108
+ ...configured,
1109
+ source: "configured"
1110
+ };
1111
+ const response = await api.client.config.providers({ directory: api.state.path.directory }, { signal });
1112
+ if (response.error !== void 0) throw new Error(errorText(response.error));
1113
+ const fallback = providerDefaultModel(connectedProviderIds, response.data.default);
1114
+ return fallback === void 0 ? void 0 : {
1115
+ ...fallback,
1116
+ source: "provider default"
1117
+ };
1118
+ }
1119
+ async function readAgents(host, api, signal) {
1120
+ if (typeof api.client.app?.agents !== "function") throw new Error(`this ${host.name} doesn't list agents`);
1121
+ const response = await api.client.app.agents({ directory: api.state.path.directory }, { signal });
1122
+ if (response.error !== void 0) throw new Error(errorText(response.error));
1123
+ const agents = response.data;
1124
+ if (!Array.isArray(agents)) throw new Error("the response wasn't an agent list");
1125
+ return agents;
1126
+ }
1127
+ /**
1128
+ * The permission rules of the current session's top-level session, which the host applies after
1129
+ * each agent's own rules. Sessions usually have none. When a parent isn't loaded, the topmost
1130
+ * session found is used, since a child session carries copies of its parent's deny rules.
1131
+ */
1132
+ function sessionPermission(api) {
1133
+ const sessionId = currentSessionId(api);
1134
+ if (sessionId === void 0) return [];
1135
+ try {
1136
+ let session = api.state.session.get(sessionId);
1137
+ const seen = /* @__PURE__ */ new Set();
1138
+ while (session?.parentID !== void 0 && !seen.has(session.id)) {
1139
+ seen.add(session.id);
1140
+ const parent = api.state.session.get(session.parentID);
1141
+ if (parent === void 0) break;
1142
+ session = parent;
1143
+ }
1144
+ return session?.permission ?? [];
1145
+ } catch {
1146
+ return [];
1147
+ }
1148
+ }
1149
+ function primaryTools(api) {
1150
+ try {
1151
+ return api.state.config.experimental?.primary_tools;
1152
+ } catch {
1153
+ return;
1154
+ }
1155
+ }
1156
+ function accessByTool(api, tools, agents) {
1157
+ const resolved = resolveToolAgentAccess(tools.map((tool) => tool.id), agents, {
1158
+ primaryTools: primaryTools(api),
1159
+ sessionPermission: sessionPermission(api)
1160
+ });
1161
+ return new Map(resolved.map((access) => [access.tool, access]));
1162
+ }
1163
+ async function readToolList(host, api, signal) {
1164
+ const directory = api.state.path.directory;
1165
+ let modelFailure;
1166
+ const model = await chooseModel(api, signal).catch((error) => {
1167
+ modelFailure = errorText(error);
1168
+ });
1169
+ let listFailure;
1170
+ if (model !== void 0) try {
1171
+ const response = await api.client.tool.list({
1172
+ directory,
1173
+ provider: model.providerID,
1174
+ model: model.modelID
1175
+ }, { signal });
1176
+ if (response.error === void 0) {
1177
+ const tools = toolsFromList(response.data);
1178
+ if (tools !== void 0) return {
1179
+ tools,
1180
+ model,
1181
+ notice: void 0
1182
+ };
1183
+ listFailure = "the response wasn't a tool list";
1184
+ } else listFailure = errorText(response.error);
1185
+ } catch (error) {
1186
+ listFailure = errorText(error);
1187
+ }
1188
+ const response = await api.client.tool.ids({ directory }, { signal });
1189
+ const tools = response.error === void 0 ? toolsFromIds(response.data) : void 0;
1190
+ if (tools === void 0) throw new Error(listFailure ?? modelFailure ?? (response.error === void 0 ? `${host.name} did not return a readable tool list.` : errorText(response.error)));
1191
+ return {
1192
+ tools,
1193
+ model: void 0,
1194
+ notice: model === void 0 ? modelFailure === void 0 ? `No model is selected, so this lists every registered tool without details. Pick a model to see what ${host.name} offers it.` : `Could not work out the current model (${modelFailure}), so this lists tool names only.` : `${host.name} did not return tool details for ${chosenModelLabel(model)} (${listFailure ?? "no reason given"}), so this lists tool names only.`
1195
+ };
1196
+ }
1197
+ async function readCatalog(host, api, signal) {
1198
+ let agentsFailure;
1199
+ const agentsRead = readAgents(host, api, signal).catch((error) => {
1200
+ agentsFailure = errorText(error);
1201
+ });
1202
+ const list = await readToolList(host, api, signal);
1203
+ const agents = await agentsRead;
1204
+ let access;
1205
+ if (agents !== void 0) try {
1206
+ access = accessByTool(api, list.tools, agents);
1207
+ } catch (error) {
1208
+ agentsFailure = errorText(error);
1209
+ }
1210
+ return {
1211
+ ...list,
1212
+ access,
1213
+ agentsNotice: access === void 0 ? `Could not read ${host.name}'s agents (${agentsFailure ?? "no reason given"}), so tool details don't show which agents can use each tool.` : void 0
1214
+ };
1215
+ }
1216
+ function inputCountLabel(tool) {
1217
+ const count = inputCount(tool.parameters);
1218
+ if (count === void 0) return;
1219
+ return count === 1 ? "1 input" : `${count} inputs`;
1220
+ }
1221
+ function registerToolBrowser(host, api) {
1222
+ const toast = (variant, message) => {
1223
+ api.ui.toast({
1224
+ variant,
1225
+ title: toastTitle,
1226
+ message,
1227
+ duration: variant === "warning" ? 1e4 : 5e3
1228
+ });
1229
+ };
1230
+ let viewer;
1231
+ const detailViewer = () => {
1232
+ viewer ??= createDetailViewer(api).catch((error) => {
1233
+ toast("warning", `Showing tool details as plain text: ${errorText(error)}`);
1234
+ });
1235
+ return viewer;
1236
+ };
1237
+ /** Each displayed dialog gets a revision, so stale close callbacks and late reads are ignored. */
1238
+ let revision = 0;
1239
+ let showing = false;
1240
+ /** The read behind the loading dialog, aborted once anything replaces that dialog. */
1241
+ let activeRead;
1242
+ const close = () => {
1243
+ revision++;
1244
+ showing = false;
1245
+ activeRead?.abort();
1246
+ activeRead = void 0;
1247
+ api.ui.dialog.clear();
1248
+ };
1249
+ const viewContext = () => {
1250
+ const directory = api.state.path.directory;
1251
+ const sessionId = currentSessionId(api);
1252
+ const routeName = api.route.current.name;
1253
+ return () => !api.lifecycle.signal.aborted && directory === api.state.path.directory && routeName === api.route.current.name && sessionId === currentSessionId(api);
1254
+ };
1255
+ const display = (render, size, onClosed) => {
1256
+ const active = ++revision;
1257
+ showing = true;
1258
+ activeRead?.abort();
1259
+ activeRead = void 0;
1260
+ api.ui.dialog.replace(render, () => {
1261
+ if (active !== revision) return;
1262
+ revision++;
1263
+ showing = false;
1264
+ onClosed?.();
1265
+ });
1266
+ api.ui.dialog.setSize(size);
1267
+ return active;
1268
+ };
1269
+ const views = {
1270
+ async detail(catalog, tool) {
1271
+ const listRevision = revision;
1272
+ const sameView = viewContext();
1273
+ const detail = toolDetail(host, tool, catalog.model === void 0 ? void 0 : chosenModelLabel(catalog.model), catalog.access?.get(tool.id));
1274
+ const render = await detailViewer();
1275
+ if (listRevision !== revision || !sameView()) return;
1276
+ display(render === void 0 ? () => api.ui.DialogAlert({
1277
+ title: detail.title,
1278
+ message: detail.sections.map((section) => `${section.heading}\n${linesText(section.lines.slice(0, plainTextSectionLines))}${section.lines.length > plainTextSectionLines ? "\n…" : ""}`).join("\n\n")
1279
+ }) : () => render(detail), "xlarge", () => {
1280
+ const closedRevision = revision;
1281
+ queueMicrotask(() => {
1282
+ if (closedRevision === revision && !api.ui.dialog.open && sameView()) views.list(catalog, tool.id);
1283
+ });
1284
+ });
1285
+ },
1286
+ list(catalog, current) {
1287
+ const sameView = viewContext();
1288
+ display(() => api.ui.DialogSelect({
1289
+ title: catalog.model === void 0 ? "Tools" : `Tools for ${chosenModelLabel(catalog.model)}`,
1290
+ placeholder: "Search tools",
1291
+ current,
1292
+ options: catalog.tools.map((tool) => {
1293
+ const summary = descriptionSummary(tool.description);
1294
+ const footer = inputCountLabel(tool);
1295
+ return {
1296
+ title: tool.id,
1297
+ value: tool.id,
1298
+ ...summary === "" ? {} : { description: summary },
1299
+ ...footer === void 0 ? {} : { footer }
1300
+ };
1301
+ }),
1302
+ onSelect: (option) => {
1303
+ const tool = catalog.tools.find((item) => item.id === option.value);
1304
+ if (!sameView()) {
1305
+ close();
1306
+ toast("info", "The session changed, so run /tools again.");
1307
+ return;
1308
+ }
1309
+ if (tool !== void 0) views.detail(catalog, tool).catch((error) => {
1310
+ toast("warning", `Could not show ${tool.id}: ${errorText(error)}`);
1311
+ });
1312
+ }
1313
+ }), "large");
1314
+ }
1315
+ };
1316
+ const open = async () => {
1317
+ const sameView = viewContext();
1318
+ const controller = new AbortController();
1319
+ const abort = () => controller.abort();
1320
+ api.lifecycle.signal.addEventListener("abort", abort, { once: true });
1321
+ const loading = display(() => api.ui.DialogAlert({
1322
+ title: "Loading tools",
1323
+ message: `Reading the tools ${host.name} offers…`
1324
+ }), "medium", abort);
1325
+ activeRead = controller;
1326
+ detailViewer().catch(() => void 0);
1327
+ try {
1328
+ const catalog = await readCatalog(host, api, controller.signal);
1329
+ if (loading !== revision) return;
1330
+ if (!sameView()) {
1331
+ close();
1332
+ return;
1333
+ }
1334
+ if (catalog.tools.length === 0) {
1335
+ close();
1336
+ toast("info", `${host.name} reported no tools.`);
1337
+ return;
1338
+ }
1339
+ const notices = [
1340
+ catalog.notice,
1341
+ catalog.agentsNotice,
1342
+ mcpNotice(host, connectedMcpServers(api))
1343
+ ].filter((notice) => notice !== void 0);
1344
+ if (notices.length > 0) toast(catalog.notice === void 0 && catalog.agentsNotice === void 0 ? "info" : "warning", notices.join(" "));
1345
+ views.list(catalog, void 0);
1346
+ } catch (error) {
1347
+ if (loading === revision) {
1348
+ close();
1349
+ if (sameView()) toast("warning", `Could not read tools from ${host.name}: ${errorText(error)}`);
1350
+ }
1351
+ } finally {
1352
+ api.lifecycle.signal.removeEventListener("abort", abort);
1353
+ }
1354
+ };
1355
+ const unregister = api.keymap.registerLayer({ commands: [{
1356
+ name: "tool-inspector.browse",
1357
+ title: "Browse tools",
1358
+ category: "Tools",
1359
+ namespace: "palette",
1360
+ slashName: "tools",
1361
+ run: () => Promise.resolve().then(open).catch((error) => {
1362
+ toast("warning", `Could not open tools: ${errorText(error)}`);
1363
+ })
1364
+ }] });
1365
+ const stopWatching = api.event.on("server.instance.disposed", (event) => {
1366
+ if (event.properties.directory === api.state.path.directory && showing) close();
1367
+ });
1368
+ api.lifecycle.onDispose(() => {
1369
+ unregister();
1370
+ stopWatching();
1371
+ });
1372
+ }
1373
+ /** The Tool Inspector TUI plugin for one host, typed as the OpenCode package has always exported it. */
1374
+ function createToolInspectorTui(host) {
1375
+ const tui = (api) => {
1376
+ registerToolBrowser(host, api);
1377
+ return Promise.resolve();
1378
+ };
1379
+ return {
1380
+ id: "tool-inspector",
1381
+ tui
1382
+ };
1383
+ }
1384
+
1385
+ // src/host.ts
1386
+ const protectedConfigPaths = ["Kilo checks protected config paths separately; broad read grants do not automatically authorize sensitive .env files."];
1387
+ /**
1388
+ * Kilo applies call-time checks beyond the configured rules, so its labels and notes say that
1389
+ * the detail shows configuration rather than a final authorization decision.
1390
+ */
1391
+ const kiloHost = {
1392
+ name: "Kilo",
1393
+ actionLabels: {
1394
+ allow: "allowed by configured rules",
1395
+ ask: "asks first by configured rules",
1396
+ deny: "denied by configured rules"
1397
+ },
1398
+ accessNotes: {
1399
+ always: ["Configured rules only. Kilo can still ask or deny at call time; saved approvals, hard limits, skill commands and sandbox escalation are not resolved here."],
1400
+ permission: {
1401
+ read: protectedConfigPaths,
1402
+ edit: protectedConfigPaths
1403
+ },
1404
+ tool: { agent_manager: ["Agent manager prompt, stop, move and answer actions need exact action rules; broad grants can still ask first."] }
1405
+ }
1406
+ };
1407
+
1408
+ // src/tui.ts
1409
+ const core = createToolInspectorTui(kiloHost);
1410
+ const tui = (api, options, meta) => core.tui(api, options, meta);
1411
+ const plugin = {
1412
+ id: core.id,
1413
+ tui
1414
+ };
1415
+
1416
+ export { plugin as default };