@lunchbox-labs/opencode-tool-inspector 0.3.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tui.js CHANGED
@@ -1,14 +1,7 @@
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
- ]);
1
+ import { t as errorText } from "./chunks/errors.js";
2
+ import { listedTools, toolInspectorRpc } from "./rpc.js";
3
+
4
+ // ../core/src/access.ts
12
5
  const unknownDecision = {
13
6
  access: "unknown",
14
7
  exceptions: [],
@@ -21,56 +14,6 @@ function field(value, key) {
21
14
  function isPermissionAction(value) {
22
15
  return value === "allow" || value === "ask" || value === "deny";
23
16
  }
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
17
  function readMode(mode) {
75
18
  return mode === "primary" || mode === "subagent" || mode === "all" ? mode : "unknown";
76
19
  }
@@ -95,7 +38,11 @@ function matchesWildcard(input, pattern) {
95
38
  function isCatchAllPattern(pattern) {
96
39
  return /^\*+(?: \*)?$/.test(pattern);
97
40
  }
98
- function decide(permission, rules) {
41
+ /**
42
+ * The general access and pattern exceptions the rules give one permission. `offered` receives the
43
+ * rules that name the permission, in order, and says whether the host still offers the tool.
44
+ */
45
+ function decide(permission, rules, offered) {
99
46
  const matching = rules.filter((rule) => matchesWildcard(permission, rule.permission));
100
47
  const lastCatchAll = matching.findLastIndex((rule) => isCatchAllPattern(rule.pattern));
101
48
  const access = matching[lastCatchAll]?.action ?? "ask";
@@ -110,205 +57,66 @@ function decide(permission, rules) {
110
57
  });
111
58
  }
112
59
  const firstChange = exceptions.findIndex((exception) => exception.access !== access);
113
- const lastRule = matching.at(-1);
114
60
  return {
115
61
  access,
116
62
  exceptions: firstChange === -1 ? [] : exceptions.slice(firstChange),
117
- offeredToModel: !(lastRule?.pattern === "*" && lastRule.action === "deny")
63
+ offeredToModel: offered(matching)
118
64
  };
119
65
  }
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) {
66
+
67
+ // ../core/src/agent-text.ts
68
+ function muted$2(text) {
124
69
  return {
125
- permission,
126
- pattern: "*",
127
- action: "deny"
70
+ text,
71
+ tone: "muted"
128
72
  };
129
73
  }
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))];
74
+ function decisionSummary(decision, actionLabels) {
75
+ if (decision.access === "unknown") return "Unknown";
76
+ if (decision.offeredToModel === false) return actionLabels.deny;
77
+ return actionLabels[decision.access];
135
78
  }
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
- }
79
+ function exceptionLines(decision, actionLabels) {
80
+ if (decision.offeredToModel === false) return [];
81
+ return decision.exceptions.map((exception) => [{
82
+ text: ` ${exception.pattern}`,
83
+ tone: "name"
84
+ }, muted$2(`: ${actionLabels[exception.access]}`)]);
174
85
  }
175
- function permissionForTool(toolId) {
176
- if (editTools.has(toolId)) return "edit";
177
- if (mcpResourceReadTools.has(toolId)) return "read";
178
- return toolId;
86
+ function agentLines(agent, actionLabels) {
87
+ return [[{
88
+ text: agent.agent,
89
+ tone: "name"
90
+ }, muted$2(` ${decisionSummary(agent, actionLabels)}`)], ...exceptionLines(agent, actionLabels)];
179
91
  }
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
- });
92
+ /** The host's own hidden agents, such as `compaction` and `title`, never take tool calls. */
93
+ function listed(agent) {
94
+ return !(agent.native && agent.hidden);
192
95
  }
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
- };
96
+ function primaryFirst(left, right) {
97
+ const rank = (agent) => agent.mode === "subagent" ? 1 : 0;
98
+ return rank(left) - rank(right);
99
+ }
100
+ function notesFor(notes, key) {
101
+ return notes !== void 0 && Object.hasOwn(notes, key) ? notes[key] : [];
102
+ }
103
+ function accessNoteLines(notes, access) {
104
+ return [
105
+ ...notes.always ?? [],
106
+ ...notesFor(notes.permission, access.permission),
107
+ ...notesFor(notes.tool, access.tool)
108
+ ].map((note) => [muted$2(note)]);
109
+ }
110
+ /** Renders which agents can use a tool, primary agents first. */
111
+ function agentAccessLines(access, host) {
112
+ const { actionLabels } = host;
113
+ const agents = access.agents.filter(listed).sort(primaryFirst);
114
+ if (agents.length === 0) return [[muted$2(`${host.name} reported no agents that use tools.`)]];
115
+ return [
116
+ ...access.permission === access.tool ? [] : [[muted$2(`Checked as the ${access.permission} permission.`)]],
117
+ ...accessNoteLines(host.accessNotes, access),
118
+ ...agents.flatMap((agent) => agentLines(agent, actionLabels))
119
+ ];
312
120
  }
313
121
 
314
122
  // ../core/src/schema-text.ts
@@ -398,7 +206,7 @@ function plain(text) {
398
206
  tone: "plain"
399
207
  };
400
208
  }
401
- function muted$2(text) {
209
+ function muted$1(text) {
402
210
  return {
403
211
  text,
404
212
  tone: "muted"
@@ -445,9 +253,9 @@ function pointerTarget(root, reference) {
445
253
  }
446
254
  const definitionSections = ["#/$defs/", "#/definitions/"];
447
255
  /**
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.
256
+ * The schema a local reference names, and the reference as the schema spells it. Hosts with the
257
+ * OpenCode 1 plugin API, such as Kilo 7.8, rename zod's `$defs` to `definitions` without
258
+ * rewriting the references to them, so a miss under either name is retried under the other.
451
259
  */
452
260
  function referenceTarget(root, reference) {
453
261
  const target = pointerTarget(root, reference);
@@ -619,10 +427,7 @@ function typeName(schema, rendering, visiting, depth) {
619
427
  return node.items === void 0 || Array.isArray(node.items) ? "array" : `array of ${pluralType(nestedName(node.items))}`;
620
428
  };
621
429
  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
- }
430
+ if (Array.isArray(node.enum) && node.enum.length > 0) return namedValues(node.enum, literal, " | ");
626
431
  const alternatives = variants(node);
627
432
  if (alternatives !== void 0) return namedValues(alternatives, nestedName, " | ", { distinct: true });
628
433
  const type = node.type;
@@ -736,7 +541,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
736
541
  */
737
542
  const writeListedAt = (listing) => {
738
543
  if (listing === void 0) return false;
739
- write(rendering, [plain(indentText(depth + 1)), muted$2(`Same fields as ${listing.path}.`)]);
544
+ write(rendering, [plain(indentText(depth + 1)), muted$1(`Same fields as ${listing.path}.`)]);
740
545
  return true;
741
546
  };
742
547
  const listingOf = (definition) => definition === void 0 ? void 0 : rendering.listedDefinitions.get(definition);
@@ -780,7 +585,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
780
585
  text: name,
781
586
  tone: "name"
782
587
  },
783
- muted$2(` ${details.join(", ")}`)
588
+ muted$1(` ${details.join(", ")}`)
784
589
  ]);
785
590
  writeDescription(rendering, resolved.description, depth + 1);
786
591
  const fields = isObject(property) ? nestedObject(property, rendering, visiting) ?? objectUnion(property, rendering, visiting) : void 0;
@@ -789,7 +594,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
789
594
  }
790
595
  }
791
596
  if (rendering.cutMerges.has(objectSchema)) write(rendering, [plain(`${indentText(depth)}…`)]);
792
- if (properties.length > 0 && listedOptions.length > 0) write(rendering, [plain(indentText(depth)), muted$2("And one of:")]);
597
+ if (properties.length > 0 && listedOptions.length > 0) write(rendering, [plain(indentText(depth)), muted$1("And one of:")]);
793
598
  listedOptions.forEach((variant, index) => {
794
599
  const heading = [plain(indentText(depth)), {
795
600
  text: `Option ${index + 1}`,
@@ -799,15 +604,15 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
799
604
  const linesAfterHeading = rendering.lines.length;
800
605
  const fields = isObject(variant) ? nestedObject(variant, rendering, visiting) : void 0;
801
606
  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)}`)];
607
+ if (rendering.lines.length === linesAfterHeading) rendering.lines[linesAfterHeading - 1] = [...heading, muted$1(` ${typeName(variant, rendering, visiting, depth)}`)];
803
608
  });
804
609
  }
805
610
  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)])];
611
+ return [[muted$1(`${hostName} reported this input schema:`)], ...JSON.stringify(schema, void 0, indentWidth).split("\n").map((line) => [muted$1(line)])];
807
612
  }
808
613
  function capped(lines) {
809
614
  if (lines.length <= maximumLines) return lines;
810
- return [...lines.slice(0, maximumLines), [muted$2(`… ${lines.length - maximumLines} more lines not shown.`)]];
615
+ return [...lines.slice(0, maximumLines), [muted$1(`… ${lines.length - maximumLines} more lines not shown.`)]];
811
616
  }
812
617
  function rootLines(rendering, schema) {
813
618
  const noneVisiting = /* @__PURE__ */ new Set();
@@ -819,12 +624,12 @@ function rootLines(rendering, schema) {
819
624
  const resolved = resolveReference(schema, rendering, noneVisiting).node;
820
625
  const merged = mergedAllOf(resolved, rendering, noneVisiting);
821
626
  if (variants(merged)?.some((variant) => informativeVariant(variant, rendering, noneVisiting)) === true) {
822
- write(rendering, [muted$2("Takes one of these inputs:")]);
627
+ write(rendering, [muted$1("Takes one of these inputs:")]);
823
628
  writeProperties(rendering, merged, noneVisiting, 0, "");
824
629
  return rendering.lines;
825
630
  }
826
631
  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.")]];
632
+ if (type === "object" || type === "any") return hasCombinators(resolved) ? capped(rawSchemaLines(rendering.hostName, schema)) : [[muted$1("Takes no input.")]];
828
633
  return [[plain("Input is "), {
829
634
  text: type,
830
635
  tone: "name"
@@ -836,7 +641,7 @@ function rootLines(rendering, schema) {
836
641
  * host in notes about what it reported.
837
642
  */
838
643
  function schemaLines(schema, hostName) {
839
- if (!isObject(schema)) return [[muted$2(`${hostName} did not report an input schema.`)]];
644
+ if (!isObject(schema)) return [[muted$1(`${hostName} did not report an input schema.`)]];
840
645
  const rendering = {
841
646
  hostName,
842
647
  root: schema,
@@ -851,7 +656,7 @@ function schemaLines(schema, hostName) {
851
656
  try {
852
657
  return rootLines(rendering, schema);
853
658
  } catch (error) {
854
- if (error instanceof SchemaTooLarge && rendering.lines.length > 0) return [...rendering.lines, [muted$2("… Schema too large to show in full.")]];
659
+ if (error instanceof SchemaTooLarge && rendering.lines.length > 0) return [...rendering.lines, [muted$1("… Schema too large to show in full.")]];
855
660
  return capped(rawSchemaLines(rendering.hostName, schema));
856
661
  }
857
662
  }
@@ -859,61 +664,6 @@ function linesText(lines) {
859
664
  return lines.map((line) => line.map((segment) => segment.text).join("")).join("\n");
860
665
  }
861
666
 
862
- // ../core/src/agent-text.ts
863
- function muted$1(text) {
864
- return {
865
- text,
866
- tone: "muted"
867
- };
868
- }
869
- function decisionSummary(decision, actionLabels) {
870
- if (decision.access === "unknown") return "Unknown";
871
- if (decision.offeredToModel === false) return actionLabels.deny;
872
- return actionLabels[decision.access];
873
- }
874
- function exceptionLines(decision, actionLabels) {
875
- if (decision.offeredToModel === false) return [];
876
- return decision.exceptions.map((exception) => [{
877
- text: ` ${exception.pattern}`,
878
- tone: "name"
879
- }, muted$1(`: ${actionLabels[exception.access]}`)]);
880
- }
881
- function agentLines(agent, actionLabels) {
882
- return [[{
883
- text: agent.agent,
884
- tone: "name"
885
- }, muted$1(` ${decisionSummary(agent, actionLabels)}`)], ...exceptionLines(agent, actionLabels)];
886
- }
887
- /** The host's own hidden agents, such as `compaction` and `title`, never take tool calls. */
888
- function listed(agent) {
889
- return !(agent.native && agent.hidden);
890
- }
891
- function primaryFirst(left, right) {
892
- const rank = (agent) => agent.mode === "subagent" ? 1 : 0;
893
- return rank(left) - rank(right);
894
- }
895
- function notesFor(notes, key) {
896
- return notes !== void 0 && Object.hasOwn(notes, key) ? notes[key] : [];
897
- }
898
- function accessNoteLines(notes, access) {
899
- return [
900
- ...notes.always ?? [],
901
- ...notesFor(notes.permission, access.permission),
902
- ...notesFor(notes.tool, access.tool)
903
- ].map((note) => [muted$1(note)]);
904
- }
905
- /** Renders which agents can use a tool, primary agents first. */
906
- function agentAccessLines(access, host) {
907
- const { actionLabels } = host;
908
- const agents = access.agents.filter(listed).sort(primaryFirst);
909
- if (agents.length === 0) return [[muted$1(`${host.name} reported no agents that use tools.`)]];
910
- return [
911
- ...access.permission === access.tool ? [] : [[muted$1(`Checked as the ${access.permission} permission.`)]],
912
- ...accessNoteLines(host.accessNotes, access),
913
- ...agents.flatMap((agent) => agentLines(agent, actionLabels))
914
- ];
915
- }
916
-
917
667
  // ../core/src/tool-detail.ts
918
668
  function muted(text) {
919
669
  return [[{
@@ -921,6 +671,7 @@ function muted(text) {
921
671
  tone: "muted"
922
672
  }]];
923
673
  }
674
+ /** A text as plain lines, without the whitespace around it. */
924
675
  function textLines(text) {
925
676
  return text.trim().split(/\r?\n/).map((line) => [{
926
677
  text: line,
@@ -929,17 +680,17 @@ function textLines(text) {
929
680
  }
930
681
  /**
931
682
  * The detail view's content. The Agents section is left out when the host's agents couldn't be
932
- * read.
683
+ * read, and `inputNotice` replaces the input's fields when the host couldn't describe them.
933
684
  */
934
- function toolDetail(host, tool, modelLabel, access) {
685
+ function toolDetail(host, tool, subtitle, access, inputNotice) {
935
686
  const detailsMissing = `${host.name} reported only this tool's name.`;
936
687
  return {
937
688
  title: tool.id,
938
- subtitle: modelLabel === void 0 ? void 0 : `As offered to ${modelLabel}`,
689
+ subtitle,
939
690
  sections: [
940
691
  {
941
692
  heading: "Input",
942
- lines: tool.description === void 0 && tool.parameters === void 0 ? muted(detailsMissing) : schemaLines(tool.parameters, host.name)
693
+ lines: inputNotice !== void 0 ? muted(inputNotice) : tool.description === void 0 && tool.parameters === void 0 ? muted(detailsMissing) : schemaLines(tool.parameters, host.name)
943
694
  },
944
695
  ...access === void 0 ? [] : [{
945
696
  heading: "Agents",
@@ -952,82 +703,17 @@ function toolDetail(host, tool, modelLabel, access) {
952
703
  ]
953
704
  };
954
705
  }
706
+ /** The plain-text fallback can't scroll, so long sections are cut short. */
707
+ const plainTextSectionLines = 20;
708
+ /** A tool's detail as one message, for hosts whose OpenTUI the detail view can't load. */
709
+ function plainTextDetail(detail) {
710
+ return detail.sections.map((section) => `${section.heading}\n${linesText(section.lines.slice(0, plainTextSectionLines))}${section.lines.length > plainTextSectionLines ? "\n…" : ""}`).join("\n\n");
711
+ }
955
712
 
956
713
  // ../core/src/tools.ts
957
- const sourceLabels = {
958
- session: "this session's model",
959
- configured: "configured model",
960
- "provider default": "provider default"
961
- };
962
- /** The host's placeholder for unknown tool calls, never offered to agents as a real tool. */
963
- const internalToolIds = /* @__PURE__ */ new Set(["invalid"]);
964
714
  function isRecord(value) {
965
715
  return typeof value === "object" && value !== null;
966
716
  }
967
- function modelLabel(model) {
968
- return `${model.providerID}/${model.modelID}`;
969
- }
970
- function chosenModelLabel(model) {
971
- return `${modelLabel(model)} (${sourceLabels[model.source]})`;
972
- }
973
- /** The model of the session's latest user message, which the host resolves tools for on the next prompt. */
974
- function sessionModel(messages) {
975
- for (const message of [...messages].reverse()) {
976
- if (!isRecord(message) || message.role !== "user") continue;
977
- const model = message.model;
978
- if (isRecord(model) && typeof model.providerID === "string" && typeof model.modelID === "string" && model.providerID !== "" && model.modelID !== "") return {
979
- providerID: model.providerID,
980
- modelID: model.modelID
981
- };
982
- }
983
- }
984
- /** Parses the `provider/model` form used by the `model` setting. */
985
- function configuredModel(model) {
986
- if (typeof model !== "string") return;
987
- const separator = model.indexOf("/");
988
- if (separator <= 0 || separator === model.length - 1) return;
989
- return {
990
- providerID: model.slice(0, separator),
991
- modelID: model.slice(separator + 1)
992
- };
993
- }
994
- /** The first connected provider's default model, which the host falls back to when none is configured. */
995
- function providerDefaultModel(connectedProviderIds, defaults) {
996
- if (!isRecord(defaults)) return;
997
- for (const providerID of connectedProviderIds) {
998
- const modelID = defaults[providerID];
999
- if (typeof modelID === "string" && modelID !== "") return {
1000
- providerID,
1001
- modelID
1002
- };
1003
- }
1004
- }
1005
- function byId(left, right) {
1006
- return left.id.localeCompare(right.id);
1007
- }
1008
- /** Keeps well-formed entries from the host's tool list, sorted by id. */
1009
- function toolsFromList(response) {
1010
- if (!Array.isArray(response)) return;
1011
- const tools = /* @__PURE__ */ new Map();
1012
- for (const item of response) {
1013
- if (!isRecord(item) || typeof item.id !== "string" || item.id === "" || internalToolIds.has(item.id)) continue;
1014
- tools.set(item.id, {
1015
- id: item.id,
1016
- description: typeof item.description === "string" ? item.description : void 0,
1017
- parameters: item.parameters
1018
- });
1019
- }
1020
- return [...tools.values()].sort(byId);
1021
- }
1022
- /** Tool ids without details, for when the host can't resolve tools for a model. */
1023
- function toolsFromIds(response) {
1024
- if (!Array.isArray(response)) return;
1025
- return [...new Set(response.filter((id) => typeof id === "string" && id !== "" && !internalToolIds.has(id)))].map((id) => ({
1026
- id,
1027
- description: void 0,
1028
- parameters: void 0
1029
- })).sort(byId);
1030
- }
1031
717
  const summaryLength = 100;
1032
718
  /** The first line of a description without its list marker, short enough for one list row. */
1033
719
  function descriptionSummary(description) {
@@ -1043,179 +729,444 @@ function inputCount(parameters) {
1043
729
  const count = Object.keys(parameters.properties).length;
1044
730
  return count === 0 && (parameters.anyOf !== void 0 || parameters.oneOf !== void 0) ? void 0 : count;
1045
731
  }
732
+ /** A tool's input count for its list row, such as "2 inputs". */
733
+ function inputCountLabel(tool) {
734
+ const count = inputCount(tool.parameters);
735
+ if (count === void 0) return;
736
+ return count === 1 ? "1 input" : `${count} inputs`;
737
+ }
1046
738
 
1047
- // ../core/src/tui.ts
1048
- const toastTitle = "Tool Inspector";
1049
- /** The plain-text fallback can't scroll, so long sections are cut short. */
1050
- const plainTextSectionLines = 20;
1051
- function errorText(error) {
1052
- if (error instanceof Error) return error.message;
1053
- if (typeof error === "object" && error !== null) {
1054
- const record = error;
1055
- if (typeof record.message === "string") return record.message;
1056
- if (typeof record.data?.message === "string") return record.data.message;
1057
- return JSON.stringify(error);
1058
- }
1059
- return String(error);
739
+ // src/access.ts
740
+ /**
741
+ * Works out which agents may use each tool, following the permission rules
742
+ * OpenCode 2 applies when it offers tools to a model and when a tool asks for
743
+ * permission.
744
+ *
745
+ * Each agent's `permissions` already combine the host's defaults, the
746
+ * configured rules and the agent's own. The host applies them and then the
747
+ * session's own rules, the last matching rule winning, and a subagent's
748
+ * session starts with its parent's rules, so an agent's access is the same
749
+ * whether it runs as a primary agent or as a subagent. Only these configured
750
+ * rules are applied here: saved approvals can settle an `ask`, plugins can
751
+ * change a call's outcome, and the host withholds some tools by model.
752
+ */
753
+ function readRule(value) {
754
+ const permission = field(value, "action");
755
+ const pattern = field(value, "resource");
756
+ const action = field(value, "effect");
757
+ if (typeof permission !== "string" || typeof pattern !== "string" || !isPermissionAction(action)) return;
758
+ return {
759
+ permission,
760
+ pattern,
761
+ action
762
+ };
1060
763
  }
1061
- /** Names of connected MCP servers, whose tools the host's tool list leaves out. */
1062
- function connectedMcpServers(api) {
1063
- try {
1064
- return api.state.mcp().filter((server) => server.status === "connected").map((server) => server.name);
1065
- } catch {
1066
- return [];
764
+ function readRuleset(value) {
765
+ if (!Array.isArray(value)) return;
766
+ const rules = [];
767
+ for (const item of value) {
768
+ const rule = readRule(item);
769
+ if (rule === void 0) return;
770
+ rules.push(rule);
1067
771
  }
772
+ return rules;
1068
773
  }
1069
- function mcpNotice(host, servers) {
1070
- if (servers.length === 0) return;
1071
- return `Tools from MCP servers (${servers.join(", ")}) aren't listed, because ${host.name} only adds them when it runs a prompt.`;
1072
- }
1073
- function currentSessionId(api) {
1074
- const route = api.route.current;
1075
- return route.name === "session" && typeof route.params?.sessionID === "string" ? route.params.sessionID : void 0;
774
+ /**
775
+ * The host withholds a tool only when every input is certain to be denied: a rule for every input
776
+ * replaces what earlier rules could decide, a narrower rule adds its action, and with no rule for
777
+ * every input the host could still ask.
778
+ */
779
+ function offered(matching) {
780
+ const reachable = /* @__PURE__ */ new Set(["ask"]);
781
+ for (const rule of matching) {
782
+ if (isCatchAllPattern(rule.pattern)) reachable.clear();
783
+ reachable.add(rule.action);
784
+ }
785
+ return !(reachable.size === 1 && reachable.has("deny"));
1076
786
  }
1077
- async function chooseModel(api, signal) {
1078
- const sessionId = currentSessionId(api);
1079
- const fromSession = sessionId === void 0 ? void 0 : sessionModel(api.state.session.messages(sessionId));
1080
- if (fromSession !== void 0) return {
1081
- ...fromSession,
1082
- source: "session"
787
+ function agentAccess(agent, permission, sessionRules, nativeAgents) {
788
+ const id = field(agent, "id");
789
+ if (typeof id !== "string") return;
790
+ const summary = {
791
+ agent: id,
792
+ mode: readMode(field(agent, "mode")),
793
+ hidden: field(agent, "hidden") === true,
794
+ native: nativeAgents.includes(id)
1083
795
  };
1084
- const connectedProviderIds = api.state.provider.map((provider) => provider.id);
1085
- const configured = configuredModel(api.state.config.model);
1086
- if (configured !== void 0 && (connectedProviderIds.length === 0 || connectedProviderIds.includes(configured.providerID))) return {
1087
- ...configured,
1088
- source: "configured"
796
+ const agentRules = readRuleset(field(agent, "permissions"));
797
+ if (agentRules === void 0 || sessionRules === void 0) return {
798
+ ...summary,
799
+ ...unknownDecision
1089
800
  };
1090
- const response = await api.client.config.providers({ directory: api.state.path.directory }, { signal });
1091
- if (response.error !== void 0) throw new Error(errorText(response.error));
1092
- const fallback = providerDefaultModel(connectedProviderIds, response.data.default);
1093
- return fallback === void 0 ? void 0 : {
1094
- ...fallback,
1095
- source: "provider default"
801
+ return {
802
+ ...summary,
803
+ ...decide(permission, [...agentRules, ...sessionRules], offered)
1096
804
  };
1097
805
  }
1098
- async function readAgents(host, api, signal) {
1099
- if (typeof api.client.app?.agents !== "function") throw new Error(`this ${host.name} doesn't list agents`);
1100
- const response = await api.client.app.agents({ directory: api.state.path.directory }, { signal });
1101
- if (response.error !== void 0) throw new Error(errorText(response.error));
1102
- const agents = response.data;
1103
- if (!Array.isArray(agents)) throw new Error("the response wasn't an agent list");
1104
- return agents;
806
+ function resolveToolAgentAccess(tools, agents, options = {}) {
807
+ const sessionRules = readRuleset(options.sessionPermissions ?? []);
808
+ const nativeAgents = options.nativeAgents ?? [];
809
+ const listed = Array.isArray(agents) ? agents : [];
810
+ return tools.map((tool) => ({
811
+ tool: tool.id,
812
+ permission: tool.permission,
813
+ agents: listed.map((agent) => agentAccess(agent, tool.permission, sessionRules, nativeAgents)).filter((access) => access !== void 0)
814
+ }));
1105
815
  }
816
+
817
+ // src/detail-view.ts
818
+ const chromeRows = 9;
819
+ /** The host's own dialogs pad their content this far from each side. */
820
+ const dialogInset = 3;
821
+ /** Renders a tool's detail sections in a keyboard-scrollable box inside the host's dialog frame. */
822
+ async function createDetailView(context) {
823
+ const { BoxRenderable, RenderableEvents, ScrollBoxRenderable, StyledText, TextAttributes, TextRenderable } = await import("@opentui/core");
824
+ function buildView(detail, colours) {
825
+ const { renderer } = context;
826
+ const toneColours = {
827
+ plain: colours.text,
828
+ name: colours.text,
829
+ muted: colours.muted
830
+ };
831
+ const styled = (lines) => new StyledText(lines.flatMap((line, index) => [...index === 0 ? [] : [{
832
+ __isChunk: true,
833
+ text: "\n"
834
+ }], ...line.map((segment) => ({
835
+ __isChunk: true,
836
+ text: segment.text,
837
+ fg: toneColours[segment.tone],
838
+ ...segment.tone === "name" ? { attributes: TextAttributes.BOLD } : {}
839
+ }))]));
840
+ const rows = () => Math.max(1, renderer.height - Math.floor(renderer.height / 4) - chromeRows);
841
+ const view = new BoxRenderable(renderer, {
842
+ flexDirection: "column",
843
+ paddingX: dialogInset,
844
+ paddingBottom: 1,
845
+ gap: 1
846
+ });
847
+ view.add(new TextRenderable(renderer, {
848
+ content: detail.title,
849
+ fg: colours.text,
850
+ attributes: TextAttributes.BOLD,
851
+ selectable: false
852
+ }));
853
+ const body = new BoxRenderable(renderer, {
854
+ flexDirection: "column",
855
+ gap: 1
856
+ });
857
+ if (detail.subtitle !== void 0) body.add(new TextRenderable(renderer, {
858
+ content: detail.subtitle,
859
+ fg: colours.muted,
860
+ wrapMode: "word"
861
+ }));
862
+ for (const section of detail.sections) {
863
+ const block = new BoxRenderable(renderer, { flexDirection: "column" });
864
+ block.add(new TextRenderable(renderer, {
865
+ content: section.heading,
866
+ fg: colours.accent,
867
+ attributes: TextAttributes.BOLD,
868
+ selectable: false
869
+ }));
870
+ block.add(new TextRenderable(renderer, {
871
+ content: styled(section.lines),
872
+ fg: colours.text,
873
+ wrapMode: "word"
874
+ }));
875
+ body.add(block);
876
+ }
877
+ const unwrappedRows = detail.sections.reduce((total, section) => total + section.lines.length + 2, detail.subtitle === void 0 ? 0 : 2);
878
+ const scroll = new ScrollBoxRenderable(renderer, {
879
+ height: Math.min(rows(), unwrappedRows),
880
+ flexShrink: 0,
881
+ verticalScrollbarOptions: {
882
+ paddingLeft: 1,
883
+ trackOptions: {
884
+ backgroundColor: colours.track,
885
+ foregroundColor: colours.thumb
886
+ }
887
+ }
888
+ });
889
+ const fit = () => {
890
+ if (!scroll.isDestroyed) scroll.height = Math.max(1, Math.min(rows(), body.height));
891
+ };
892
+ body.onSizeChange = fit;
893
+ scroll.add(body);
894
+ view.add(scroll);
895
+ view.add(new TextRenderable(renderer, {
896
+ content: "↑/↓ scroll · pgup/pgdn page · home/end · esc back",
897
+ fg: colours.muted,
898
+ selectable: false
899
+ }));
900
+ renderer.on("resize", fit);
901
+ view.on(RenderableEvents.DESTROYED, () => {
902
+ renderer.off("resize", fit);
903
+ });
904
+ context.keymap.layer(() => ({
905
+ mode: "modal",
906
+ enabled: () => !scroll.isDestroyed,
907
+ commands: [
908
+ {
909
+ bind: "up",
910
+ run: () => scroll.scrollBy(-1)
911
+ },
912
+ {
913
+ bind: "down",
914
+ run: () => scroll.scrollBy(1)
915
+ },
916
+ {
917
+ bind: "pageup",
918
+ run: () => scroll.scrollBy(-.5, "viewport")
919
+ },
920
+ {
921
+ bind: "pagedown",
922
+ run: () => scroll.scrollBy(.5, "viewport")
923
+ },
924
+ {
925
+ bind: "home",
926
+ run: () => scroll.scrollBy(-1, "content")
927
+ },
928
+ {
929
+ bind: "end",
930
+ run: () => scroll.scrollBy(1, "content")
931
+ }
932
+ ]
933
+ }));
934
+ return view;
935
+ }
936
+ /**
937
+ * Prepares a detail's view. Call the result while the host renders the dialog, so the dialog
938
+ * owns the view's key bindings.
939
+ */
940
+ return (detail) => {
941
+ const surface = context.theme.surface("dialog");
942
+ const colours = {
943
+ text: surface.text.base,
944
+ muted: surface.text.muted,
945
+ accent: surface.hue.accent[500],
946
+ track: surface.background.raised.high,
947
+ thumb: surface.scrollbar.base
948
+ };
949
+ return () => buildView(detail, colours);
950
+ };
951
+ }
952
+
953
+ // src/host.ts
954
+ const editingByModel = ["OpenCode offers GPT-5 and later GPT models patch, and every other model edit and write."];
955
+ const outsideProject = ["A path outside the project is checked as external_directory first."];
1106
956
  /**
1107
- * The permission rules of the current session's top-level session, which the host applies after
1108
- * each agent's own rules. Sessions usually have none. When a parent isn't loaded, the topmost
1109
- * session found is used, since a child session carries copies of its parent's deny rules.
957
+ * OpenCode 2 settles some calls beyond the configured rules, so its notes say what a tool's
958
+ * agents section leaves out.
1110
959
  */
1111
- function sessionPermission(api) {
1112
- const sessionId = currentSessionId(api);
1113
- if (sessionId === void 0) return [];
1114
- try {
1115
- let session = api.state.session.get(sessionId);
1116
- const seen = /* @__PURE__ */ new Set();
1117
- while (session?.parentID !== void 0 && !seen.has(session.id)) {
1118
- seen.add(session.id);
1119
- const parent = api.state.session.get(session.parentID);
1120
- if (parent === void 0) break;
1121
- session = parent;
960
+ const opencodeHost = {
961
+ name: "OpenCode",
962
+ actionLabels: {
963
+ allow: "Allow",
964
+ ask: "Ask",
965
+ deny: "Deny"
966
+ },
967
+ accessNotes: {
968
+ always: ["Configured rules only. A saved approval can already allow a call shown as Ask, and a policy or plugin can still deny or change a call."],
969
+ permission: {
970
+ read: outsideProject,
971
+ edit: outsideProject,
972
+ shell: outsideProject,
973
+ glob: outsideProject,
974
+ grep: outsideProject,
975
+ cd: ["A directory outside the project and its worktrees is checked as external_directory."]
1122
976
  }
1123
- return session?.permission ?? [];
1124
- } catch {
1125
- return [];
1126
977
  }
978
+ };
979
+ /**
980
+ * Notes about a tool that hold whichever agent uses it, by tool id, shown under its name. OpenCode
981
+ * withholds a few tools by model or setup, which its tool registry doesn't show.
982
+ */
983
+ const toolNotes = {
984
+ edit: editingByModel,
985
+ write: editingByModel,
986
+ patch: editingByModel,
987
+ websearch: ["Offered only when a web search provider is set up."]
988
+ };
989
+ /**
990
+ * OpenCode's own agents, which its agent list doesn't mark. A tool's detail leaves out the hidden
991
+ * ones, such as `title`, which never take tool calls.
992
+ */
993
+ const nativeAgents = [
994
+ "build",
995
+ "plan",
996
+ "general",
997
+ "explore",
998
+ "compaction",
999
+ "title",
1000
+ "summary"
1001
+ ];
1002
+ /** What to do when the TUI part gets no answer from this plugin's server part. */
1003
+ const serverPartHint = "If the package is in cli.json, move it to \"plugins\" in opencode.jsonc; otherwise run /tools again.";
1004
+
1005
+ // src/tui.ts
1006
+ const toastTitle = "Tool Inspector";
1007
+ /** The input mode the host is in while any dialog is open. */
1008
+ const dialogMode = "modal";
1009
+ /**
1010
+ * What the host answers when nothing serves the tool list: the server part isn't loaded, or the
1011
+ * location is closing or reloading (upstream `packages/core/src/rpc.ts`).
1012
+ */
1013
+ const noAnswerErrors = /* @__PURE__ */ new Set(["rpc.unavailable", "rpc.method_not_found"]);
1014
+ /** Stands in for session rules that couldn't be read; anything but a rule list reads as unknown. */
1015
+ const unreadableRules = "unreadable";
1016
+ function currentSessionId(context) {
1017
+ const route = context.ui.router.current();
1018
+ return route.type === "session" ? route.sessionID : void 0;
1019
+ }
1020
+ function currentLocation(context) {
1021
+ return context.location ?? context.data.location.default();
1022
+ }
1023
+ /**
1024
+ * How a request names a location. The server resolves it by directory alone
1025
+ * (upstream `packages/server/src/location.ts`), for the RPC and the agent list alike.
1026
+ */
1027
+ function locationRef(location) {
1028
+ return { directory: location.directory };
1127
1029
  }
1128
- function primaryTools(api) {
1030
+ async function readTools(context, location, signal) {
1031
+ let output;
1129
1032
  try {
1130
- return api.state.config.experimental?.primary_tools;
1131
- } catch {
1132
- return;
1033
+ output = await context.client.rpc(toolInspectorRpc).tools({}, {
1034
+ location: locationRef(location),
1035
+ signal
1036
+ });
1037
+ } catch (error) {
1038
+ const type = field(error, "type");
1039
+ if (typeof type === "string" && noAnswerErrors.has(type)) throw new Error(`Tool Inspector's server part didn't answer. ${serverPartHint}`, { cause: error });
1040
+ if (type === "rpc.internal") throw new Error(`Tool Inspector's server part failed. Search ${opencodeHost.name}'s log for rpc=${toolInspectorRpc.id} to see why.`, { cause: error });
1041
+ if (type === "rpc.invalid_output") throw new Error(`${opencodeHost.name} didn't accept the tool list from Tool Inspector's server part: ${errorText(error)}`, { cause: error });
1042
+ throw error;
1133
1043
  }
1134
- }
1135
- function accessByTool(api, tools, agents) {
1136
- const resolved = resolveToolAgentAccess(tools.map((tool) => tool.id), agents, {
1137
- primaryTools: primaryTools(api),
1138
- sessionPermission: sessionPermission(api)
1044
+ const tools = listedTools(output);
1045
+ if (tools === void 0) throw new Error(`${opencodeHost.name} did not return a readable tool list.`);
1046
+ const byId = /* @__PURE__ */ new Map();
1047
+ for (const tool of tools) byId.set(tool.id, {
1048
+ id: tool.id,
1049
+ description: tool.description,
1050
+ parameters: tool.input,
1051
+ permission: tool.permission,
1052
+ codeMode: tool.codeMode,
1053
+ inputError: tool.inputError,
1054
+ codeModeInput: tool.codeModeInput,
1055
+ codeModeInputError: tool.codeModeInputError,
1056
+ codeModeDescription: tool.codeModeDescription
1139
1057
  });
1140
- return new Map(resolved.map((access) => [access.tool, access]));
1058
+ return [...byId.values()].sort((left, right) => left.id.localeCompare(right.id));
1141
1059
  }
1142
- async function readToolList(host, api, signal) {
1143
- const directory = api.state.path.directory;
1144
- let modelFailure;
1145
- const model = await chooseModel(api, signal).catch((error) => {
1146
- modelFailure = errorText(error);
1147
- });
1148
- let listFailure;
1149
- if (model !== void 0) try {
1150
- const response = await api.client.tool.list({
1151
- directory,
1152
- provider: model.providerID,
1153
- model: model.modelID
1154
- }, { signal });
1155
- if (response.error === void 0) {
1156
- const tools = toolsFromList(response.data);
1157
- if (tools !== void 0) return {
1158
- tools,
1159
- model,
1160
- notice: void 0
1161
- };
1162
- listFailure = "the response wasn't a tool list";
1163
- } else listFailure = errorText(response.error);
1164
- } catch (error) {
1165
- listFailure = errorText(error);
1060
+ async function readAgents(context, location, signal) {
1061
+ const response = await context.client.agent.list({ location: locationRef(location) }, { signal });
1062
+ const agents = field(response, "data");
1063
+ if (!Array.isArray(agents)) throw new Error("the response wasn't an agent list");
1064
+ return agents;
1065
+ }
1066
+ /**
1067
+ * The current session's own permission rules, which the host applies after each agent's. A
1068
+ * session the TUI's store doesn't hold is fetched once. One the host still can't give is not a
1069
+ * session without rules, so its rules read as unknown.
1070
+ */
1071
+ async function sessionPermissions(context) {
1072
+ const sessionId = currentSessionId(context);
1073
+ if (sessionId === void 0) return [];
1074
+ try {
1075
+ let session = context.data.session.get(sessionId);
1076
+ if (session === void 0) {
1077
+ await context.data.session.sync(sessionId);
1078
+ session = context.data.session.get(sessionId);
1079
+ }
1080
+ return session === void 0 ? unreadableRules : session.permissions ?? [];
1081
+ } catch {
1082
+ return unreadableRules;
1166
1083
  }
1167
- const response = await api.client.tool.ids({ directory }, { signal });
1168
- const tools = response.error === void 0 ? toolsFromIds(response.data) : void 0;
1169
- 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)));
1170
- return {
1171
- tools,
1172
- model: void 0,
1173
- 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.`
1174
- };
1175
1084
  }
1176
- async function readCatalog(host, api, signal) {
1085
+ /** The agents whose rules deny `execute` outright, or nothing when the rules can't be read. */
1086
+ function agentsDeniedExecute(agents, options) {
1087
+ const [execute] = resolveToolAgentAccess([{
1088
+ id: "execute",
1089
+ permission: "execute"
1090
+ }], agents, options);
1091
+ const listed = execute.agents.filter((agent) => !(agent.native && agent.hidden));
1092
+ if (listed.some((agent) => agent.offeredToModel === void 0)) return;
1093
+ return listed.filter((agent) => agent.offeredToModel === false).map((agent) => agent.agent);
1094
+ }
1095
+ function nameList(names) {
1096
+ return names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1) ?? ""}`;
1097
+ }
1098
+ /** How agents reach a tool that runs in Code Mode. */
1099
+ function codeModeNote(deniedExecute, access) {
1100
+ const how = "Agents with Code Mode call this through execute.";
1101
+ if (deniedExecute === void 0) return `${how} Agents denied execute get it as a direct tool.`;
1102
+ const withheld = new Set(access?.agents.filter((agent) => agent.offeredToModel === false).map((agent) => agent.agent));
1103
+ const direct = deniedExecute.filter((agent) => !withheld.has(agent));
1104
+ if (direct.length === 0) return `${how} No agent here gets it as a direct tool.`;
1105
+ const one = direct.length === 1;
1106
+ return `${how} ${nameList(direct)} ${one ? "is" : "are"} denied execute and ${one ? "gets" : "get"} it as a direct tool.`;
1107
+ }
1108
+ /** The input and description Code Mode presents instead of the tool's own, for a tool that declares them. */
1109
+ function codeModeSections(tool, inputNotice) {
1110
+ return [...inputNotice === void 0 && tool.codeModeInput === void 0 ? [] : [{
1111
+ heading: "Input in Code Mode",
1112
+ lines: inputNotice === void 0 ? schemaLines(tool.codeModeInput, opencodeHost.name) : [[{
1113
+ text: inputNotice,
1114
+ tone: "muted"
1115
+ }]]
1116
+ }], ...tool.codeModeDescription === void 0 || tool.codeModeDescription.trim() === "" ? [] : [{
1117
+ heading: "Description in Code Mode",
1118
+ lines: textLines(tool.codeModeDescription)
1119
+ }]];
1120
+ }
1121
+ async function readCatalog(context, signal) {
1122
+ const location = currentLocation(context);
1177
1123
  let agentsFailure;
1178
- const agentsRead = readAgents(host, api, signal).catch((error) => {
1124
+ const agentsRead = readAgents(context, location, signal).catch((error) => {
1179
1125
  agentsFailure = errorText(error);
1180
1126
  });
1181
- const list = await readToolList(host, api, signal);
1127
+ const tools = await readTools(context, location, signal);
1182
1128
  const agents = await agentsRead;
1183
1129
  let access;
1130
+ let deniedExecute;
1184
1131
  if (agents !== void 0) try {
1185
- access = accessByTool(api, list.tools, agents);
1132
+ const options = {
1133
+ sessionPermissions: await sessionPermissions(context),
1134
+ nativeAgents
1135
+ };
1136
+ access = new Map(resolveToolAgentAccess(tools, agents, options).map((item) => [item.tool, item]));
1137
+ deniedExecute = agentsDeniedExecute(agents, options);
1186
1138
  } catch (error) {
1187
1139
  agentsFailure = errorText(error);
1188
1140
  }
1189
1141
  return {
1190
- ...list,
1142
+ tools,
1191
1143
  access,
1192
- 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
1144
+ deniedExecute,
1145
+ agentsNotice: access === void 0 ? `Could not read ${opencodeHost.name}'s agents (${agentsFailure ?? "no reason given"}), so tool details don't show which agents can use each tool.` : void 0
1193
1146
  };
1194
1147
  }
1195
- function inputCountLabel(tool) {
1196
- const count = inputCount(tool.parameters);
1197
- if (count === void 0) return;
1198
- return count === 1 ? "1 input" : `${count} inputs`;
1199
- }
1200
- function registerToolBrowser(host, api) {
1148
+ function registerToolBrowser(context) {
1201
1149
  const toast = (variant, message) => {
1202
- api.ui.toast({
1150
+ context.ui.toast.show({
1203
1151
  variant,
1204
1152
  title: toastTitle,
1205
1153
  message,
1206
1154
  duration: variant === "warning" ? 1e4 : 5e3
1207
1155
  });
1208
1156
  };
1209
- let viewer;
1210
- const detailViewer = () => {
1211
- viewer ??= createDetailViewer(api).catch((error) => {
1157
+ let disposed = false;
1158
+ let view;
1159
+ const detailView = () => {
1160
+ view ??= createDetailView(context).catch((error) => {
1212
1161
  toast("warning", `Showing tool details as plain text: ${errorText(error)}`);
1213
1162
  });
1214
- return viewer;
1163
+ return view;
1215
1164
  };
1216
- /** Each displayed dialog gets a revision, so stale close callbacks and late reads are ignored. */
1165
+ /** Each displayed dialog gets a revision, so stale close notices and late reads are ignored. */
1217
1166
  let revision = 0;
1218
1167
  let showing = false;
1168
+ /** The revision a chosen tool is waiting under, while no dialog is shown for it yet. */
1169
+ let opening;
1219
1170
  /** The read behind the loading dialog, aborted once anything replaces that dialog. */
1220
1171
  let activeRead;
1221
1172
  const close = () => {
@@ -1223,51 +1174,99 @@ function registerToolBrowser(host, api) {
1223
1174
  showing = false;
1224
1175
  activeRead?.abort();
1225
1176
  activeRead = void 0;
1226
- api.ui.dialog.clear();
1227
- };
1228
- const viewContext = () => {
1229
- const directory = api.state.path.directory;
1230
- const sessionId = currentSessionId(api);
1231
- const routeName = api.route.current.name;
1232
- return () => !api.lifecycle.signal.aborted && directory === api.state.path.directory && routeName === api.route.current.name && sessionId === currentSessionId(api);
1177
+ context.ui.dialog.clear();
1233
1178
  };
1234
- const display = (render, size, onClosed) => {
1179
+ /**
1180
+ * Makes the dialog about to be shown the current one. `closed` is for the host's notice that
1181
+ * the dialog went away, which is ignored once another of this plugin's dialogs took over.
1182
+ */
1183
+ const display = (onClosed) => {
1235
1184
  const active = ++revision;
1236
1185
  showing = true;
1237
1186
  activeRead?.abort();
1238
1187
  activeRead = void 0;
1239
- api.ui.dialog.replace(render, () => {
1240
- if (active !== revision) return;
1241
- revision++;
1242
- showing = false;
1243
- onClosed?.();
1244
- });
1245
- api.ui.dialog.setSize(size);
1246
- return active;
1188
+ return {
1189
+ active,
1190
+ closed: () => {
1191
+ if (active !== revision) return;
1192
+ revision++;
1193
+ showing = false;
1194
+ onClosed?.();
1195
+ },
1196
+ /** For a dialog that failed to show: nothing is on screen, and nothing follows its close. */
1197
+ abandon: () => {
1198
+ if (active === revision) {
1199
+ revision++;
1200
+ showing = false;
1201
+ }
1202
+ }
1203
+ };
1204
+ };
1205
+ /** Closes the browser, or stops a tool that is about to open while no dialog is shown. */
1206
+ const invalidate = () => {
1207
+ if (showing) close();
1208
+ else revision++;
1209
+ };
1210
+ const viewContext = () => {
1211
+ const directory = currentLocation(context).directory;
1212
+ const sessionId = currentSessionId(context);
1213
+ const routeType = context.ui.router.current().type;
1214
+ return () => !disposed && directory === currentLocation(context).directory && routeType === context.ui.router.current().type && sessionId === currentSessionId(context);
1215
+ };
1216
+ /**
1217
+ * Whether the host shows a dialog, its own or any plugin's. The host pushes its `modal` input
1218
+ * mode for as long as its dialog stack isn't empty (upstream `packages/tui/src/ui/dialog.tsx`).
1219
+ * Its other modes (menus, autocomplete, the composer's) belong to the prompt, which a dialog
1220
+ * covers, so none is expected above `modal`; if one were, this would read as no dialog open.
1221
+ */
1222
+ const dialogOpen = () => {
1223
+ try {
1224
+ return context.keymap.mode.current() === dialogMode;
1225
+ } catch {
1226
+ return false;
1227
+ }
1247
1228
  };
1248
1229
  const views = {
1249
1230
  async detail(catalog, tool) {
1250
- const listRevision = revision;
1231
+ const opened = revision;
1251
1232
  const sameView = viewContext();
1252
- const detail = toolDetail(host, tool, catalog.model === void 0 ? void 0 : chosenModelLabel(catalog.model), catalog.access?.get(tool.id));
1253
- const render = await detailViewer();
1254
- if (listRevision !== revision || !sameView()) return;
1255
- display(render === void 0 ? () => api.ui.DialogAlert({
1256
- title: detail.title,
1257
- message: detail.sections.map((section) => `${section.heading}\n${linesText(section.lines.slice(0, plainTextSectionLines))}${section.lines.length > plainTextSectionLines ? "\n…" : ""}`).join("\n\n")
1258
- }) : () => render(detail), "xlarge", () => {
1233
+ const unread = (reason) => reason === void 0 ? void 0 : `Tool Inspector couldn't read this input: ${reason}. ${opencodeHost.name} still describes it to the model.`;
1234
+ const notes = [...Object.hasOwn(toolNotes, tool.id) ? toolNotes[tool.id] : [], ...tool.codeMode ? [codeModeNote(catalog.deniedExecute, catalog.access?.get(tool.id))] : []];
1235
+ const base = toolDetail(opencodeHost, tool, notes.length === 0 ? void 0 : notes.join("\n"), catalog.access?.get(tool.id), unread(tool.inputError));
1236
+ const detail = {
1237
+ ...base,
1238
+ sections: [...base.sections, ...codeModeSections(tool, unread(tool.codeModeInputError))]
1239
+ };
1240
+ opening = opened;
1241
+ const prepare = await detailView();
1242
+ if (opening === opened) opening = void 0;
1243
+ if (opened !== revision || !sameView() || dialogOpen()) return;
1244
+ const view = prepare?.(detail);
1245
+ const shown = display(() => {
1259
1246
  const closedRevision = revision;
1260
1247
  queueMicrotask(() => {
1261
- if (closedRevision === revision && !api.ui.dialog.open && sameView()) views.list(catalog, tool.id);
1248
+ if (closedRevision === revision && !dialogOpen() && sameView()) views.list(catalog, tool.id);
1262
1249
  });
1263
1250
  });
1251
+ try {
1252
+ if (view === void 0) context.ui.dialog.alert({
1253
+ title: detail.title,
1254
+ message: [...detail.subtitle === void 0 ? [] : [detail.subtitle], plainTextDetail(detail)].join("\n\n")
1255
+ }).then(shown.closed, shown.closed);
1256
+ else context.ui.dialog.show(view, shown.closed);
1257
+ context.ui.dialog.set({ size: "xlarge" });
1258
+ } catch (error) {
1259
+ shown.abandon();
1260
+ throw error;
1261
+ }
1264
1262
  },
1265
1263
  list(catalog, current) {
1266
1264
  const sameView = viewContext();
1267
- display(() => api.ui.DialogSelect({
1268
- title: catalog.model === void 0 ? "Tools" : `Tools for ${chosenModelLabel(catalog.model)}`,
1265
+ const shown = display();
1266
+ const selection = context.ui.dialog.select({
1267
+ title: "Tools",
1269
1268
  placeholder: "Search tools",
1270
- current,
1269
+ ...current === void 0 ? {} : { current },
1271
1270
  options: catalog.tools.map((tool) => {
1272
1271
  const summary = descriptionSummary(tool.description);
1273
1272
  const footer = inputCountLabel(tool);
@@ -1277,102 +1276,93 @@ function registerToolBrowser(host, api) {
1277
1276
  ...summary === "" ? {} : { description: summary },
1278
1277
  ...footer === void 0 ? {} : { footer }
1279
1278
  };
1280
- }),
1281
- onSelect: (option) => {
1282
- const tool = catalog.tools.find((item) => item.id === option.value);
1283
- if (!sameView()) {
1284
- close();
1285
- toast("info", "The session changed, so run /tools again.");
1286
- return;
1287
- }
1288
- if (tool !== void 0) views.detail(catalog, tool).catch((error) => {
1289
- toast("warning", `Could not show ${tool.id}: ${errorText(error)}`);
1290
- });
1279
+ })
1280
+ });
1281
+ context.ui.dialog.set({ size: "large" });
1282
+ const settled = (selected) => {
1283
+ if (shown.active !== revision) return;
1284
+ shown.closed();
1285
+ const tool = catalog.tools.find((item) => item.id === selected);
1286
+ if (tool === void 0) return;
1287
+ if (!sameView()) {
1288
+ toast("info", "The session changed, so run /tools again.");
1289
+ return;
1291
1290
  }
1292
- }), "large");
1291
+ views.detail(catalog, tool).catch((error) => {
1292
+ toast("warning", `Could not show ${tool.id}: ${errorText(error)}`);
1293
+ if (!showing && !dialogOpen() && sameView()) views.list(catalog, tool.id);
1294
+ });
1295
+ };
1296
+ selection.then(settled, () => settled(void 0));
1293
1297
  }
1294
1298
  };
1295
1299
  const open = async () => {
1296
1300
  const sameView = viewContext();
1297
1301
  const controller = new AbortController();
1298
- const abort = () => controller.abort();
1299
- api.lifecycle.signal.addEventListener("abort", abort, { once: true });
1300
- const loading = display(() => api.ui.DialogAlert({
1301
- title: "Loading tools",
1302
- message: `Reading the tools ${host.name} offers…`
1303
- }), "medium", abort);
1302
+ const loading = display(() => controller.abort());
1304
1303
  activeRead = controller;
1305
- detailViewer().catch(() => void 0);
1306
1304
  try {
1307
- const catalog = await readCatalog(host, api, controller.signal);
1308
- if (loading !== revision) return;
1305
+ context.ui.dialog.alert({
1306
+ title: "Loading tools",
1307
+ message: `Reading the tools ${opencodeHost.name} has registered. Enter or Esc cancels.`
1308
+ }).then(loading.closed, loading.closed);
1309
+ } catch (error) {
1310
+ loading.abandon();
1311
+ controller.abort();
1312
+ activeRead = void 0;
1313
+ throw error;
1314
+ }
1315
+ detailView().catch(() => void 0);
1316
+ try {
1317
+ const catalog = await readCatalog(context, controller.signal);
1318
+ if (loading.active !== revision) return;
1309
1319
  if (!sameView()) {
1310
1320
  close();
1311
1321
  return;
1312
1322
  }
1313
1323
  if (catalog.tools.length === 0) {
1314
1324
  close();
1315
- toast("info", `${host.name} reported no tools.`);
1325
+ toast("info", `${opencodeHost.name} reported no tools.`);
1316
1326
  return;
1317
1327
  }
1318
- const notices = [
1319
- catalog.notice,
1320
- catalog.agentsNotice,
1321
- mcpNotice(host, connectedMcpServers(api))
1322
- ].filter((notice) => notice !== void 0);
1323
- if (notices.length > 0) toast(catalog.notice === void 0 && catalog.agentsNotice === void 0 ? "info" : "warning", notices.join(" "));
1328
+ if (catalog.agentsNotice !== void 0) toast("warning", catalog.agentsNotice);
1324
1329
  views.list(catalog, void 0);
1325
1330
  } catch (error) {
1326
- if (loading === revision) {
1331
+ if (loading.active === revision) {
1327
1332
  close();
1328
- if (sameView()) toast("warning", `Could not read tools from ${host.name}: ${errorText(error)}`);
1333
+ if (sameView()) toast("warning", `Could not read tools from ${opencodeHost.name}: ${errorText(error)}`);
1329
1334
  }
1330
- } finally {
1331
- api.lifecycle.signal.removeEventListener("abort", abort);
1332
1335
  }
1333
1336
  };
1334
- const unregister = api.keymap.registerLayer({ commands: [{
1335
- name: "tool-inspector.browse",
1336
- title: "Browse tools",
1337
- category: "Tools",
1338
- namespace: "palette",
1339
- slashName: "tools",
1340
- run: () => Promise.resolve().then(open).catch((error) => {
1341
- toast("warning", `Could not open tools: ${errorText(error)}`);
1342
- })
1343
- }] });
1344
- const stopWatching = api.event.on("server.instance.disposed", (event) => {
1345
- if (event.properties.directory === api.state.path.directory && showing) close();
1337
+ context.keymap.layer(() => ({
1338
+ mode: "global",
1339
+ commands: [{
1340
+ id: "tool-inspector.browse",
1341
+ title: "Browse tools",
1342
+ group: "Tools",
1343
+ palette: true,
1344
+ slash: { name: "tools" },
1345
+ run: () => Promise.resolve().then(open).catch((error) => {
1346
+ toast("warning", `Could not open tools: ${errorText(error)}`);
1347
+ })
1348
+ }]
1349
+ }));
1350
+ const stopWatching = context.data.on("location.shutdown", (event) => {
1351
+ if (event.location?.directory === currentLocation(context).directory) {
1352
+ if (showing || opening === revision) toast("info", `${opencodeHost.name} unloaded this project, so run /tools again.`);
1353
+ invalidate();
1354
+ }
1346
1355
  });
1347
- api.lifecycle.onDispose(() => {
1348
- unregister();
1356
+ return () => {
1357
+ disposed = true;
1349
1358
  stopWatching();
1350
- });
1351
- }
1352
- /** The Tool Inspector TUI plugin for one host, typed as the OpenCode package has always exported it. */
1353
- function createToolInspectorTui(host) {
1354
- const tui = (api) => {
1355
- registerToolBrowser(host, api);
1356
- return Promise.resolve();
1357
- };
1358
- return {
1359
- id: "tool-inspector",
1360
- tui
1359
+ invalidate();
1361
1360
  };
1362
1361
  }
1363
-
1364
- // src/host.ts
1365
- const opencodeHost = {
1366
- name: "OpenCode",
1367
- actionLabels: {
1368
- allow: "Allow",
1369
- ask: "Ask",
1370
- deny: "Deny"
1371
- },
1372
- accessNotes: {}
1362
+ /** The TUI part: the `/tools` browser, which reads tools through the server part. */
1363
+ const tui = {
1364
+ id: toolInspectorRpc.id,
1365
+ setup: registerToolBrowser
1373
1366
  };
1374
1367
 
1375
- // src/tui.ts
1376
- const plugin = createToolInspectorTui(opencodeHost);
1377
-
1378
- export { plugin as default };
1368
+ export { tui as default };