@lunchbox-labs/opencode-tool-inspector 0.2.0 → 0.2.2

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/README.md CHANGED
@@ -14,14 +14,12 @@ Add the package to `plugin` in `tui.jsonc`:
14
14
 
15
15
  ## Browse tools
16
16
 
17
- Run `/tools`, or **Browse tools** from the command palette, to list the tools OpenCode offers a model: the one the current session's latest message used, otherwise your configured `model`, otherwise the first connected provider's default. The dialog's title names the model and where it came from. If you switch models before your next prompt, the tools offered may differ.
17
+ Run `/tools`, or **Browse tools** from the command palette, to list the tools OpenCode offers a model; the dialog's title names which one. Type to filter the list, press Enter to see a tool's input schema, the agents that can use it and its full description, and press Escape to return to the list.
18
18
 
19
- Type to filter the list, and press Enter to see a tool's input schema, the agents that can use it and its full description. The input shows each field's type, whether it's required, its allowed values, default and limits, with nested objects shown under their parent and each option of a union listed with its own fields. Escape returns to the list.
19
+ ## Documentation
20
20
 
21
- The list includes built-in and plugin tools. MCP server tools aren't listed, because OpenCode only adds them when it runs a prompt; a toast says so when an MCP server is connected. If OpenCode can't resolve tools for a model, the list shows tool names only.
21
+ The [wiki](https://github.com/lunchbox-labs/opencode-tool-inspector/wiki) has the full guides:
22
22
 
23
- ## Agent access
24
-
25
- The list isn't filtered by agent. Instead, a tool's detail lists each agent and whether it's allowed to use the tool, asks first, is denied, or isn't offered the tool at all, following each agent's merged `permission` rules and the rules of the current top-level session. Input patterns with different access, such as `read` asking first for `*.env` files, are listed under the agent. Agents with mode `all` also show their access when they run as a subagent, where that differs, since OpenCode always denies subagents any `experimental.primary_tools`, and denies `todowrite` and `task` unless the agent's own rules name them.
26
-
27
- OpenCode's own hidden agents, such as `compaction` and `title`, are left out. If OpenCode's agents can't be read, details open without this section and a toast says why.
23
+ - [Usage](https://github.com/lunchbox-labs/opencode-tool-inspector/wiki/Usage): which model's tools are listed, what the list leaves out and how input schemas are shown.
24
+ - [Agent access](https://github.com/lunchbox-labs/opencode-tool-inspector/wiki/Agent-access): how a tool's detail shows each agent's access.
25
+ - [Developer](https://github.com/lunchbox-labs/opencode-tool-inspector/wiki/Developer): development, compatibility testing and publishing.
@@ -5,6 +5,9 @@ export interface TextSegment {
5
5
  }
6
6
  /** A line of rendered text, split into toned segments so the viewer can colour names and types. */
7
7
  export type TextLine = TextSegment[];
8
- /** Renders a tool's input JSON schema as indented, readable lines. */
8
+ /**
9
+ * Renders a tool's input JSON schema as indented, readable lines. A shared definition's fields
10
+ * are listed once, and a schema too large to show is cut short with a note.
11
+ */
9
12
  export declare function schemaLines(schema: unknown): TextLine[];
10
13
  export declare function linesText(lines: readonly TextLine[]): string;
@@ -1,27 +1,109 @@
1
1
  const indentWidth = 2;
2
2
  const maximumDepth = 8;
3
3
  const maximumLines = 400;
4
+ const maximumLineLength = 400;
5
+ const maximumCharacters = 100_000;
6
+ const maximumTypeLength = 200;
7
+ const maximumDescriptionLength = 4_000;
8
+ /** Enum values, tuple elements and union options named in a type before the rest are counted. */
9
+ const maximumNamedValues = 10;
10
+ /** How deep array items, unions and `allOf` members are followed when looking for fields. */
11
+ const maximumNesting = 64;
12
+ /**
13
+ * Caps the reference lookups behind one schema, so schemas whose references fan out are cut
14
+ * short instead of stalling the TUI.
15
+ */
16
+ const maximumReferenceLookups = 50_000;
17
+ /** Thrown when a schema would take more lines, text or lookups than a detail view shows. */
18
+ class SchemaTooLarge extends Error {
19
+ }
20
+ function shortened(text, maximumLength) {
21
+ return text.length > maximumLength
22
+ ? `${text.slice(0, maximumLength - 1)}…`
23
+ : text;
24
+ }
25
+ /** Keeps a line within the line length, ending a cut line with "…". */
26
+ function fittedLine(line) {
27
+ let remaining = maximumLineLength;
28
+ const fitted = [];
29
+ for (const segment of line) {
30
+ if (segment.text.length < remaining) {
31
+ fitted.push(segment);
32
+ remaining -= segment.text.length;
33
+ continue;
34
+ }
35
+ fitted.push({ ...segment, text: shortened(segment.text, remaining) });
36
+ break;
37
+ }
38
+ return fitted;
39
+ }
40
+ function write(rendering, line) {
41
+ if (rendering.lines.length >= maximumLines) {
42
+ throw new SchemaTooLarge();
43
+ }
44
+ const fitted = fittedLine(line);
45
+ rendering.remainingCharacters -= fitted.reduce((length, segment) => length + segment.text.length, 0);
46
+ if (rendering.remainingCharacters < 0) {
47
+ throw new SchemaTooLarge();
48
+ }
49
+ rendering.lines.push(fitted);
50
+ }
4
51
  function isObject(value) {
5
52
  return typeof value === "object" && value !== null && !Array.isArray(value);
6
53
  }
54
+ const literalTexts = new WeakMap();
55
+ /** A value as JSON, shortened; large strings are cut before encoding and objects encoded once. */
7
56
  function literal(value) {
8
- const json = JSON.stringify(value);
9
- return json ?? String(value);
57
+ if (typeof value === "string") {
58
+ const encoded = JSON.stringify(value.slice(0, maximumTypeLength));
59
+ return value.length > maximumTypeLength ? `${encoded}…` : encoded;
60
+ }
61
+ if (typeof value !== "object" || value === null) {
62
+ const json = JSON.stringify(value);
63
+ return shortened(json ?? String(value), maximumTypeLength);
64
+ }
65
+ let text = literalTexts.get(value);
66
+ if (text === undefined) {
67
+ text = shortened(JSON.stringify(value), maximumTypeLength);
68
+ literalTexts.set(value, text);
69
+ }
70
+ return text;
71
+ }
72
+ /** Names the first few values, leaving out repeated names, then counts the rest. */
73
+ function namedValues(values, name, separator, { distinct = false } = {}) {
74
+ const names = [];
75
+ let length = 0;
76
+ let named = 0;
77
+ while (named < values.length &&
78
+ names.length < maximumNamedValues &&
79
+ length < maximumTypeLength / 2) {
80
+ const valueName = name(values[named]);
81
+ named++;
82
+ if (!distinct || !names.includes(valueName)) {
83
+ names.push(valueName);
84
+ length += valueName.length + separator.length;
85
+ }
86
+ }
87
+ const rest = values.length - named;
88
+ return [...names, ...(rest > 0 ? [`… ${rest} more`] : [])].join(separator);
10
89
  }
11
90
  function plain(text) {
12
91
  return { text, tone: "plain" };
13
92
  }
93
+ function muted(text) {
94
+ return { text, tone: "muted" };
95
+ }
14
96
  function indentText(depth) {
15
97
  return " ".repeat(depth * indentWidth);
16
98
  }
17
- function descriptionLines(description, depth) {
99
+ function writeDescription(rendering, description, depth) {
18
100
  if (typeof description !== "string" || description.trim() === "") {
19
- return [];
101
+ return;
102
+ }
103
+ const text = shortened(description.trim(), maximumDescriptionLength);
104
+ for (const line of text.split(/\r?\n/)) {
105
+ write(rendering, [plain(`${indentText(depth)}${line}`)]);
20
106
  }
21
- return description
22
- .trim()
23
- .split(/\r?\n/)
24
- .map((line) => [plain(`${indentText(depth)}${line}`)]);
25
107
  }
26
108
  function withoutReference(node) {
27
109
  const { $ref: _reference, ...rest } = node;
@@ -35,15 +117,19 @@ function decodedPointerKey(rawKey) {
35
117
  return rawKey;
36
118
  }
37
119
  }
38
- /** Resolves local `$ref`s, as zod and MCP servers emit for shared definitions. */
39
- function resolveReference(node, root, visiting) {
40
- const reference = node.$ref;
41
- if (typeof reference !== "string" || !reference.startsWith("#")) {
42
- return { node, recursive: false };
43
- }
44
- if (visiting.has(reference)) {
45
- return { node, reference, recursive: true };
46
- }
120
+ /** Keys beside a `$ref` that change its target's shape, so it no longer reads as that definition. */
121
+ const shapeKeys = new Set([
122
+ "properties",
123
+ "required",
124
+ "items",
125
+ "prefixItems",
126
+ "additionalProperties",
127
+ "allOf",
128
+ "anyOf",
129
+ "oneOf",
130
+ ]);
131
+ /** The value a local JSON pointer such as `#/$defs/Address` names, if any. */
132
+ function pointerTarget(root, reference) {
47
133
  let target = root;
48
134
  for (const rawKey of reference.slice(1).split("/").filter(Boolean)) {
49
135
  const key = decodedPointerKey(rawKey)
@@ -51,13 +137,78 @@ function resolveReference(node, root, visiting) {
51
137
  .replaceAll("~0", "~");
52
138
  target = isObject(target) ? target[key] : undefined;
53
139
  }
54
- return isObject(target)
55
- ? {
56
- node: { ...target, ...withoutReference(node) },
57
- reference,
58
- recursive: false,
140
+ return target;
141
+ }
142
+ const definitionSections = ["#/$defs/", "#/definitions/"];
143
+ /**
144
+ * The schema a local reference names, and the reference as the schema spells it. OpenCode 1.19
145
+ * renames zod's `$defs` to `definitions` without rewriting the references to them, so a miss
146
+ * under either name is retried under the other.
147
+ */
148
+ function referenceTarget(root, reference) {
149
+ const target = pointerTarget(root, reference);
150
+ if (isObject(target)) {
151
+ return { schema: target, reference };
152
+ }
153
+ const section = definitionSections.find((prefix) => reference.startsWith(prefix));
154
+ const otherSection = definitionSections.find((prefix) => prefix !== section);
155
+ if (section === undefined || otherSection === undefined) {
156
+ return undefined;
157
+ }
158
+ const alias = `${otherSection}${reference.slice(section.length)}`;
159
+ const aliasTarget = pointerTarget(root, alias);
160
+ return isObject(aliasTarget)
161
+ ? { schema: aliasTarget, reference: alias }
162
+ : undefined;
163
+ }
164
+ function countLookup(rendering) {
165
+ rendering.remainingLookups--;
166
+ if (rendering.remainingLookups < 0) {
167
+ throw new SchemaTooLarge();
168
+ }
169
+ }
170
+ /** How many definitions that only refer to another are followed before giving up. */
171
+ const maximumReferenceHops = 64;
172
+ /**
173
+ * Resolves local `$ref`s, as zod and MCP servers emit for shared definitions, following a
174
+ * definition that is itself a reference to another.
175
+ */
176
+ function resolveReference(node, rendering, visiting) {
177
+ countLookup(rendering);
178
+ if (typeof node.$ref !== "string") {
179
+ return { node, visiting };
180
+ }
181
+ const chain = new Set(visiting);
182
+ let current = node;
183
+ let definition;
184
+ let reshaped = false;
185
+ let hops = 0;
186
+ for (let reference = node.$ref; typeof reference === "string"; reference = current.$ref) {
187
+ if (hops === maximumReferenceHops) {
188
+ return { node: current, visiting: chain, chainTooLong: true };
59
189
  }
60
- : { node, reference, recursive: false };
190
+ const target = reference.startsWith("#")
191
+ ? referenceTarget(rendering.root, reference)
192
+ : undefined;
193
+ if (target === undefined) {
194
+ return { node: current, visiting: chain, unresolvedReference: reference };
195
+ }
196
+ if (chain.has(target.reference)) {
197
+ return {
198
+ node: current,
199
+ visiting: chain,
200
+ recursiveReference: target.reference,
201
+ };
202
+ }
203
+ hops++;
204
+ countLookup(rendering);
205
+ const siblings = withoutReference(current);
206
+ reshaped ||= Object.keys(siblings).some((key) => shapeKeys.has(key));
207
+ current = { ...target.schema, ...siblings };
208
+ chain.add(target.reference);
209
+ definition = reshaped ? undefined : target.reference;
210
+ }
211
+ return { node: current, visiting: chain, definition };
61
212
  }
62
213
  function referenceName(reference) {
63
214
  const name = reference.split("/").at(-1) ?? "";
@@ -77,26 +228,33 @@ function hasCombinators(node) {
77
228
  return variants(node) !== undefined || nonEmptyList(node.allOf) !== undefined;
78
229
  }
79
230
  /** Folds `allOf` members' properties and required names into one object schema. */
80
- function mergedAllOf(node, root, visiting) {
231
+ function mergedAllOf(node, rendering, visiting, nesting = 0) {
81
232
  const members = nonEmptyList(node.allOf);
82
233
  if (members === undefined) {
83
234
  return node;
84
235
  }
236
+ if (nesting > maximumNesting) {
237
+ rendering.depthCutoffs++;
238
+ const { allOf: _allOf, ...rest } = node;
239
+ rendering.cutMerges.add(rest);
240
+ return rest;
241
+ }
242
+ let cut = false;
85
243
  const properties = {};
86
244
  const required = new Set();
87
245
  for (const member of [...members, node]) {
88
246
  if (!isObject(member)) {
89
247
  continue;
90
248
  }
91
- const resolved = resolveReference(member, root, visiting);
92
- const memberVisiting = resolved.reference === undefined
93
- ? visiting
94
- : new Set([...visiting, resolved.reference]);
95
- const memberNode = member === node
96
- ? member
97
- : resolved.recursive
98
- ? {}
99
- : mergedAllOf(resolved.node, root, memberVisiting);
249
+ let memberNode = member;
250
+ if (member !== node) {
251
+ const resolved = resolveReference(member, rendering, visiting);
252
+ memberNode =
253
+ resolved.recursiveReference === undefined
254
+ ? mergedAllOf(resolved.node, rendering, resolved.visiting, nesting + 1)
255
+ : {};
256
+ cut ||= rendering.cutMerges.has(memberNode);
257
+ }
100
258
  if (isObject(memberNode.properties)) {
101
259
  Object.assign(properties, memberNode.properties);
102
260
  }
@@ -108,20 +266,54 @@ function mergedAllOf(node, root, visiting) {
108
266
  }
109
267
  }
110
268
  const { allOf: _allOf, ...rest } = node;
111
- return Object.keys(properties).length === 0
269
+ const merged = Object.keys(properties).length === 0
112
270
  ? rest
113
271
  : { ...rest, properties, required: [...required] };
272
+ if (cut) {
273
+ rendering.cutMerges.add(merged);
274
+ }
275
+ return merged;
276
+ }
277
+ /** The one JSON type a schema or all of its union's options have, if any. */
278
+ function ownType(schema) {
279
+ if (typeof schema.type === "string") {
280
+ return schema.type;
281
+ }
282
+ const types = new Set((variants(schema) ?? []).map((variant) => isObject(variant) && typeof variant.type === "string"
283
+ ? variant.type
284
+ : undefined));
285
+ const [only] = types;
286
+ return types.size === 1 ? only : undefined;
287
+ }
288
+ /** Names a reference back into a definition being expanded. */
289
+ function recursiveTypeName(reference, rendering) {
290
+ const name = referenceName(reference);
291
+ // Generated names, such as zod's `__schema0` for a recursive schema, mean nothing to users.
292
+ if (!name.startsWith("__")) {
293
+ return name;
294
+ }
295
+ const target = referenceTarget(rendering.root, reference);
296
+ const type = target === undefined ? undefined : ownType(target.schema);
297
+ if (type !== undefined) {
298
+ return type;
299
+ }
300
+ const path = rendering.typedFields.get(reference) ??
301
+ rendering.listedDefinitions.get(reference)?.path;
302
+ return path === undefined ? "recursive value" : `same type as ${path}`;
114
303
  }
115
304
  function pluralType(type) {
116
305
  if (type === "any") {
117
306
  return "values";
118
307
  }
308
+ if (type === "…") {
309
+ return type;
310
+ }
119
311
  if (type.startsWith('"') || type.includes(" ")) {
120
312
  return `items of ${type}`;
121
313
  }
122
314
  return type.endsWith("s") ? type : `${type}s`;
123
315
  }
124
- function typeName(schema, root, visiting, depth) {
316
+ function typeName(schema, rendering, visiting, depth) {
125
317
  if (schema === true ||
126
318
  (isObject(schema) && Object.keys(schema).length === 0)) {
127
319
  return "any";
@@ -133,43 +325,60 @@ function typeName(schema, root, visiting, depth) {
133
325
  return "unknown";
134
326
  }
135
327
  if (depth > maximumDepth) {
328
+ rendering.depthCutoffs++;
136
329
  return "…";
137
330
  }
138
- const resolved = resolveReference(schema, root, visiting);
139
- if (resolved.recursive && resolved.reference !== undefined) {
140
- return referenceName(resolved.reference);
141
- }
142
- const nextVisiting = resolved.reference === undefined
143
- ? visiting
144
- : new Set([...visiting, resolved.reference]);
145
- const node = mergedAllOf(resolved.node, root, nextVisiting);
146
- const nestedName = (nested) => typeName(nested, root, nextVisiting, depth + 1);
331
+ const resolved = resolveReference(schema, rendering, visiting);
332
+ if (resolved.recursiveReference !== undefined) {
333
+ return recursiveTypeName(resolved.recursiveReference, rendering);
334
+ }
335
+ if (resolved.unresolvedReference !== undefined ||
336
+ resolved.chainTooLong === true) {
337
+ const known = typeName(withoutReference(resolved.node), rendering, resolved.visiting, depth);
338
+ return known === "any"
339
+ ? resolved.unresolvedReference === undefined
340
+ ? "reference chain too long"
341
+ : `unresolved reference ${referenceName(resolved.unresolvedReference)}`
342
+ : known;
343
+ }
344
+ const node = mergedAllOf(resolved.node, rendering, resolved.visiting);
345
+ const nestedName = (nested) => shortened(typeName(nested, rendering, resolved.visiting, depth + 1), maximumTypeLength);
147
346
  const arrayName = () => {
148
- if (node.items === undefined) {
149
- return "array";
347
+ // Draft 2020-12 tuples, as zod emits, list their elements in `prefixItems` and any further
348
+ // elements in `items`; earlier drafts use an `items` list and `additionalItems`.
349
+ const prefixItems = nonEmptyList(node.prefixItems);
350
+ const elements = prefixItems ?? nonEmptyList(node.items);
351
+ if (elements !== undefined) {
352
+ const tuple = `tuple of ${namedValues(elements, nestedName, ", ")}`;
353
+ const rest = prefixItems === undefined ? node.additionalItems : node.items;
354
+ return isObject(rest) && Object.keys(rest).length > 0
355
+ ? `${tuple}, then ${pluralType(nestedName(rest))}`
356
+ : tuple;
150
357
  }
151
- if (Array.isArray(node.items)) {
152
- const items = node.items;
153
- return `tuple of ${items.map(nestedName).join(", ")}`;
154
- }
155
- return `array of ${pluralType(nestedName(node.items))}`;
358
+ return node.items === undefined || Array.isArray(node.items)
359
+ ? "array"
360
+ : `array of ${pluralType(nestedName(node.items))}`;
156
361
  };
157
362
  if (Object.hasOwn(node, "const")) {
158
363
  return literal(node.const);
159
364
  }
160
365
  if (Array.isArray(node.enum) && node.enum.length > 0) {
161
- return node.enum.map(literal).join(" | ");
366
+ const values = node.enum;
367
+ return namedValues(values, literal, " | ");
162
368
  }
163
369
  const alternatives = variants(node);
164
370
  if (alternatives !== undefined) {
165
- return [...new Set(alternatives.map(nestedName))].join(" | ");
371
+ return namedValues(alternatives, nestedName, " | ", { distinct: true });
166
372
  }
167
373
  const type = node.type;
168
374
  if (Array.isArray(type)) {
169
- const names = type
170
- .filter((item) => typeof item === "string")
171
- .map((item) => (item === "array" ? arrayName() : item));
172
- return names.length === 0 ? "any" : names.join(" | ");
375
+ const typeNames = [
376
+ ...new Set(type.filter((item) => typeof item === "string")),
377
+ ];
378
+ let array;
379
+ return typeNames.length === 0
380
+ ? "any"
381
+ : namedValues(typeNames, (item) => (item === "array" ? (array ??= arrayName()) : String(item)), " | ");
173
382
  }
174
383
  if (type === "array") {
175
384
  return arrayName();
@@ -225,148 +434,226 @@ function constraintNotes(node) {
225
434
  return notes;
226
435
  }
227
436
  /** The object schema whose properties appear nested under a property, if any. */
228
- function nestedObject(node, root, visiting) {
229
- const resolved = resolveReference(node, root, visiting);
230
- if (resolved.recursive) {
437
+ function nestedObject(node, rendering, visiting, nesting = 0) {
438
+ if (nesting > maximumNesting) {
231
439
  return undefined;
232
440
  }
233
- const nextVisiting = resolved.reference === undefined
234
- ? visiting
235
- : new Set([...visiting, resolved.reference]);
236
- const merged = mergedAllOf(resolved.node, root, nextVisiting);
441
+ const resolved = resolveReference(node, rendering, visiting);
442
+ if (resolved.recursiveReference !== undefined) {
443
+ return undefined;
444
+ }
445
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
237
446
  // An empty `properties` beside a union, as some schema generators emit, defers to the union.
238
447
  if (isObject(merged.properties) &&
239
448
  (Object.keys(merged.properties).length > 0 ||
240
449
  variants(merged) === undefined)) {
241
- return { node: merged, visiting: nextVisiting };
450
+ return {
451
+ node: merged,
452
+ visiting: resolved.visiting,
453
+ definition: resolved.definition,
454
+ };
242
455
  }
243
456
  const items = merged.items;
244
457
  if (isObject(items)) {
245
- return nestedObject(items, root, nextVisiting);
458
+ return nestedObject(items, rendering, resolved.visiting, nesting + 1);
246
459
  }
247
460
  const alternatives = variants(merged);
248
461
  if (alternatives !== undefined) {
249
462
  const objects = alternatives
250
463
  .filter(isObject)
251
- .map((variant) => nestedObject(variant, root, nextVisiting))
464
+ .map((variant) => nestedObject(variant, rendering, resolved.visiting, nesting + 1))
252
465
  .filter((variant) => variant !== undefined);
253
466
  return objects.length === 1 ? objects[0] : undefined;
254
467
  }
255
468
  return undefined;
256
469
  }
257
- function muted(text) {
258
- return { text, tone: "muted" };
470
+ function listedObjectVariants(node, rendering, visiting) {
471
+ return (variants(node) ?? []).filter((variant) => isObject(variant) &&
472
+ nestedObject(variant, rendering, visiting) !== undefined).length;
259
473
  }
260
- function listedObjectVariants(node, root, visiting) {
261
- return (variants(node) ?? []).filter((variant) => isObject(variant) && nestedObject(variant, root, visiting) !== undefined).length;
474
+ /** The definition a property refers back into while it is being listed, following array items. */
475
+ function recursiveDefinition(node, rendering, visiting, nesting = 0) {
476
+ if (nesting > maximumNesting) {
477
+ return undefined;
478
+ }
479
+ const resolved = resolveReference(node, rendering, visiting);
480
+ if (resolved.recursiveReference !== undefined) {
481
+ return resolved.recursiveReference;
482
+ }
483
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
484
+ const present = (variants(merged) ?? []).filter((variant) => !(isObject(variant) && variant.type === "null"));
485
+ const inner = isObject(merged.items)
486
+ ? merged.items
487
+ : present.length === 1 && isObject(present[0])
488
+ ? present[0]
489
+ : undefined;
490
+ return inner === undefined
491
+ ? undefined
492
+ : recursiveDefinition(inner, rendering, resolved.visiting, nesting + 1);
262
493
  }
263
494
  /** Whether listing a union option says more than "object". */
264
- function informativeVariant(variant, root, visiting) {
265
- const type = typeName(variant, root, visiting, 0);
495
+ function informativeVariant(variant, rendering, visiting) {
496
+ const type = typeName(variant, rendering, visiting, 0);
266
497
  return ((type !== "object" && type !== "any") ||
267
- (isObject(variant) && nestedObject(variant, root, visiting) !== undefined));
498
+ (isObject(variant) &&
499
+ nestedObject(variant, rendering, visiting) !== undefined));
268
500
  }
269
501
  /** The union of several object options under a property, following array items, if any. */
270
- function objectUnion(node, root, visiting) {
271
- const resolved = resolveReference(node, root, visiting);
272
- if (resolved.recursive) {
502
+ function objectUnion(node, rendering, visiting, nesting = 0) {
503
+ if (nesting > maximumNesting) {
273
504
  return undefined;
274
505
  }
275
- const nextVisiting = resolved.reference === undefined
276
- ? visiting
277
- : new Set([...visiting, resolved.reference]);
278
- const merged = mergedAllOf(resolved.node, root, nextVisiting);
279
- if (listedObjectVariants(merged, root, nextVisiting) > 1) {
280
- return { node: merged, visiting: nextVisiting };
506
+ const resolved = resolveReference(node, rendering, visiting);
507
+ if (resolved.recursiveReference !== undefined) {
508
+ return undefined;
509
+ }
510
+ const merged = mergedAllOf(resolved.node, rendering, resolved.visiting);
511
+ if (listedObjectVariants(merged, rendering, resolved.visiting) > 1) {
512
+ return {
513
+ node: merged,
514
+ visiting: resolved.visiting,
515
+ definition: resolved.definition,
516
+ };
281
517
  }
282
518
  // A nullable union wraps the union beside a null option.
283
519
  const present = (variants(merged) ?? []).filter((variant) => !(isObject(variant) && variant.type === "null"));
284
520
  if (present.length === 1 && isObject(present[0])) {
285
- return objectUnion(present[0], root, nextVisiting);
521
+ return objectUnion(present[0], rendering, resolved.visiting, nesting + 1);
286
522
  }
287
523
  return isObject(merged.items)
288
- ? objectUnion(merged.items, root, nextVisiting)
524
+ ? objectUnion(merged.items, rendering, resolved.visiting, nesting + 1)
289
525
  : undefined;
290
526
  }
291
527
  /**
292
528
  * Lists an object schema's properties, then each option of a union beside them, indented by
293
529
  * depth.
294
530
  */
295
- function propertyLines(objectSchema, root, visiting, depth) {
531
+ function writeProperties(rendering, objectSchema, visiting, depth, path) {
296
532
  if (depth > maximumDepth) {
297
- return [[plain(`${indentText(depth)}…`)]];
298
- }
299
- /** Lists each option of a union, or nothing when no option says more than "object". */
300
- const optionLines = (schema) => {
301
- const alternatives = variants(schema);
302
- if (alternatives?.some((variant) => informativeVariant(variant, root, visiting)) !== true) {
303
- return [];
533
+ rendering.depthCutoffs++;
534
+ write(rendering, [plain(`${indentText(depth)}…`)]);
535
+ return;
536
+ }
537
+ /**
538
+ * Lists a field's or option's own fields one level deeper, or, for a shared definition already
539
+ * listed, where its fields are.
540
+ */
541
+ const writeListedAt = (listing) => {
542
+ if (listing === undefined) {
543
+ return false;
304
544
  }
305
- return alternatives.flatMap((variant, index) => {
306
- const heading = [
307
- plain(indentText(depth)),
308
- { text: `Option ${index + 1}`, tone: "name" },
309
- ];
310
- const nested = isObject(variant)
311
- ? nestedObject(variant, root, visiting)
312
- : undefined;
313
- const lines = nested === undefined
314
- ? []
315
- : propertyLines(nested.node, root, nested.visiting, depth + 1);
316
- return lines.length > 0
317
- ? [heading, ...lines]
318
- : [
319
- [
320
- ...heading,
321
- muted(` ${typeName(variant, root, visiting, depth)}`),
322
- ],
323
- ];
324
- });
545
+ write(rendering, [
546
+ plain(indentText(depth + 1)),
547
+ muted(`Same fields as ${listing.path}.`),
548
+ ]);
549
+ return true;
325
550
  };
551
+ const listingOf = (definition) => definition === undefined
552
+ ? undefined
553
+ : rendering.listedDefinitions.get(definition);
554
+ const writeFields = (source, sourcePath) => {
555
+ const { definition } = source;
556
+ const earlier = listingOf(definition);
557
+ if (earlier !== undefined &&
558
+ (!earlier.cut || depth + 1 >= earlier.depth) &&
559
+ writeListedAt(earlier)) {
560
+ return;
561
+ }
562
+ // Recorded before listing, so references back into it from inside say where it is.
563
+ const listing = {
564
+ path: sourcePath,
565
+ depth: depth + 1,
566
+ cut: false,
567
+ };
568
+ if (definition !== undefined) {
569
+ rendering.listedDefinitions.set(definition, listing);
570
+ }
571
+ const linesBefore = rendering.lines.length;
572
+ const cutoffsBefore = rendering.depthCutoffs;
573
+ writeProperties(rendering, source.node, source.visiting, depth + 1, sourcePath);
574
+ listing.cut = rendering.depthCutoffs > cutoffsBefore;
575
+ if (definition !== undefined && rendering.lines.length === linesBefore) {
576
+ if (earlier === undefined) {
577
+ rendering.listedDefinitions.delete(definition);
578
+ }
579
+ else {
580
+ rendering.listedDefinitions.set(definition, earlier);
581
+ }
582
+ }
583
+ };
584
+ const alternatives = variants(objectSchema);
585
+ // Options are listed only when at least one says more than "object".
586
+ const listedOptions = alternatives?.some((variant) => informativeVariant(variant, rendering, visiting)) === true
587
+ ? alternatives
588
+ : [];
326
589
  const properties = isObject(objectSchema.properties)
327
590
  ? Object.entries(objectSchema.properties)
328
591
  : [];
329
- const options = optionLines(objectSchema);
330
- if (properties.length === 0) {
331
- return options;
332
- }
333
- const required = new Set(Array.isArray(objectSchema.required)
334
- ? objectSchema.required.filter((name) => typeof name === "string")
335
- : []);
336
- const fields = properties.flatMap(([name, property]) => {
337
- const resolved = isObject(property)
338
- ? mergedAllOf(resolveReference(property, root, visiting).node, root, visiting)
339
- : {};
340
- const details = [
341
- typeName(property, root, visiting, depth),
342
- ...(required.has(name) ? ["required"] : []),
343
- ...constraintNotes(resolved),
344
- ];
592
+ if (properties.length > 0) {
593
+ const required = new Set(Array.isArray(objectSchema.required)
594
+ ? objectSchema.required.filter((name) => typeof name === "string")
595
+ : []);
596
+ for (const [name, property] of properties) {
597
+ const fieldPath = path === "" ? name : `${path}.${name}`;
598
+ const fieldReference = isObject(property) && typeof property.$ref === "string"
599
+ ? referenceTarget(rendering.root, property.$ref)?.reference
600
+ : undefined;
601
+ if (fieldReference !== undefined &&
602
+ !rendering.typedFields.has(fieldReference)) {
603
+ rendering.typedFields.set(fieldReference, fieldPath);
604
+ }
605
+ const resolved = isObject(property)
606
+ ? mergedAllOf(resolveReference(property, rendering, visiting).node, rendering, visiting)
607
+ : {};
608
+ const details = [
609
+ typeName(property, rendering, visiting, depth),
610
+ ...(required.has(name) ? ["required"] : []),
611
+ ...constraintNotes(resolved),
612
+ ];
613
+ write(rendering, [
614
+ plain(indentText(depth)),
615
+ { text: name, tone: "name" },
616
+ muted(` ${details.join(", ")}`),
617
+ ]);
618
+ writeDescription(rendering, resolved.description, depth + 1);
619
+ const fields = isObject(property)
620
+ ? (nestedObject(property, rendering, visiting) ??
621
+ objectUnion(property, rendering, visiting))
622
+ : undefined;
623
+ if (fields !== undefined) {
624
+ writeFields(fields, fieldPath);
625
+ }
626
+ else if (isObject(property)) {
627
+ writeListedAt(listingOf(recursiveDefinition(property, rendering, visiting)));
628
+ }
629
+ }
630
+ }
631
+ if (rendering.cutMerges.has(objectSchema)) {
632
+ write(rendering, [plain(`${indentText(depth)}…`)]);
633
+ }
634
+ if (properties.length > 0 && listedOptions.length > 0) {
635
+ write(rendering, [plain(indentText(depth)), muted("And one of:")]);
636
+ }
637
+ listedOptions.forEach((variant, index) => {
345
638
  const heading = [
346
639
  plain(indentText(depth)),
347
- { text: name, tone: "name" },
348
- { text: ` ${details.join(", ")}`, tone: "muted" },
640
+ { text: `Option ${index + 1}`, tone: "name" },
349
641
  ];
350
- const nested = isObject(property)
351
- ? nestedObject(property, root, visiting)
352
- : undefined;
353
- const union = nested === undefined && isObject(property)
354
- ? objectUnion(property, root, visiting)
642
+ write(rendering, heading);
643
+ const linesAfterHeading = rendering.lines.length;
644
+ const fields = isObject(variant)
645
+ ? nestedObject(variant, rendering, visiting)
355
646
  : undefined;
356
- const childLines = nested !== undefined
357
- ? propertyLines(nested.node, root, nested.visiting, depth + 1)
358
- : union !== undefined
359
- ? propertyLines(union.node, root, union.visiting, depth + 1)
360
- : [];
361
- return [
362
- heading,
363
- ...descriptionLines(resolved.description, depth + 1),
364
- ...childLines,
365
- ];
647
+ if (fields !== undefined) {
648
+ writeFields(fields, `${path === "" ? "" : `${path} `}option ${index + 1}`);
649
+ }
650
+ if (rendering.lines.length === linesAfterHeading) {
651
+ rendering.lines[linesAfterHeading - 1] = [
652
+ ...heading,
653
+ muted(` ${typeName(variant, rendering, visiting, depth)}`),
654
+ ];
655
+ }
366
656
  });
367
- return options.length === 0
368
- ? fields
369
- : [...fields, [plain(indentText(depth)), muted("And one of:")], ...options];
370
657
  }
371
658
  function rawSchemaLines(schema) {
372
659
  return [
@@ -385,40 +672,59 @@ function capped(lines) {
385
672
  [muted(`… ${lines.length - maximumLines} more lines not shown.`)],
386
673
  ];
387
674
  }
388
- function rootLines(schema) {
389
- const nested = nestedObject(schema, schema, new Set());
675
+ function rootLines(rendering, schema) {
676
+ const noneVisiting = new Set();
677
+ const nested = nestedObject(schema, rendering, noneVisiting);
390
678
  if (nested !== undefined) {
391
- const lines = propertyLines(nested.node, schema, nested.visiting, 0);
392
- if (lines.length > 0) {
393
- return lines;
679
+ writeProperties(rendering, nested.node, nested.visiting, 0, "");
680
+ if (rendering.lines.length > 0) {
681
+ return rendering.lines;
394
682
  }
395
683
  }
396
- const resolved = resolveReference(schema, schema, new Set()).node;
397
- const alternatives = variants(mergedAllOf(resolved, schema, new Set()));
398
- const informative = alternatives?.some((variant) => informativeVariant(variant, schema, new Set()));
399
- if (alternatives !== undefined && informative === true) {
400
- return [
401
- [muted("Takes one of these inputs:")],
402
- ...propertyLines(mergedAllOf(resolved, schema, new Set()), schema, new Set(), 0),
403
- ];
684
+ const resolved = resolveReference(schema, rendering, noneVisiting).node;
685
+ const merged = mergedAllOf(resolved, rendering, noneVisiting);
686
+ const informative = variants(merged)?.some((variant) => informativeVariant(variant, rendering, noneVisiting));
687
+ if (informative === true) {
688
+ write(rendering, [muted("Takes one of these inputs:")]);
689
+ writeProperties(rendering, merged, noneVisiting, 0, "");
690
+ return rendering.lines;
404
691
  }
405
- const type = typeName(schema, schema, new Set(), 0);
692
+ const type = typeName(schema, rendering, noneVisiting, 0);
406
693
  if (type === "object" || type === "any") {
407
694
  return hasCombinators(resolved)
408
- ? rawSchemaLines(schema)
695
+ ? capped(rawSchemaLines(schema))
409
696
  : [[muted("Takes no input.")]];
410
697
  }
411
698
  return [[plain("Input is "), { text: type, tone: "name" }]];
412
699
  }
413
- /** Renders a tool's input JSON schema as indented, readable lines. */
700
+ /**
701
+ * Renders a tool's input JSON schema as indented, readable lines. A shared definition's fields
702
+ * are listed once, and a schema too large to show is cut short with a note.
703
+ */
414
704
  export function schemaLines(schema) {
415
705
  if (!isObject(schema)) {
416
706
  return [[muted("OpenCode did not report an input schema.")]];
417
707
  }
708
+ const rendering = {
709
+ root: schema,
710
+ lines: [],
711
+ remainingLookups: maximumReferenceLookups,
712
+ remainingCharacters: maximumCharacters,
713
+ listedDefinitions: new Map(),
714
+ depthCutoffs: 0,
715
+ typedFields: new Map(),
716
+ cutMerges: new WeakSet(),
717
+ };
418
718
  try {
419
- return capped(rootLines(schema));
719
+ return rootLines(rendering, schema);
420
720
  }
421
- catch {
721
+ catch (error) {
722
+ if (error instanceof SchemaTooLarge && rendering.lines.length > 0) {
723
+ return [
724
+ ...rendering.lines,
725
+ [muted("… Schema too large to show in full.")],
726
+ ];
727
+ }
422
728
  return capped(rawSchemaLines(schema));
423
729
  }
424
730
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunchbox-labs/opencode-tool-inspector",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Inspect the tools available to OpenCode agents from the TUI",
5
5
  "license": "MIT",
6
6
  "type": "module",