@lunchbox-labs/opencode-tool-inspector 0.3.3 → 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(-.5, "viewport")
284
- },
285
- {
286
- key: "pagedown",
287
- cmd: () => scroll.scrollBy(.5, "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);
@@ -733,7 +541,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
733
541
  */
734
542
  const writeListedAt = (listing) => {
735
543
  if (listing === void 0) return false;
736
- 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}.`)]);
737
545
  return true;
738
546
  };
739
547
  const listingOf = (definition) => definition === void 0 ? void 0 : rendering.listedDefinitions.get(definition);
@@ -777,7 +585,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
777
585
  text: name,
778
586
  tone: "name"
779
587
  },
780
- muted$2(` ${details.join(", ")}`)
588
+ muted$1(` ${details.join(", ")}`)
781
589
  ]);
782
590
  writeDescription(rendering, resolved.description, depth + 1);
783
591
  const fields = isObject(property) ? nestedObject(property, rendering, visiting) ?? objectUnion(property, rendering, visiting) : void 0;
@@ -786,7 +594,7 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
786
594
  }
787
595
  }
788
596
  if (rendering.cutMerges.has(objectSchema)) write(rendering, [plain(`${indentText(depth)}…`)]);
789
- 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:")]);
790
598
  listedOptions.forEach((variant, index) => {
791
599
  const heading = [plain(indentText(depth)), {
792
600
  text: `Option ${index + 1}`,
@@ -796,15 +604,15 @@ function writeProperties(rendering, objectSchema, visiting, depth, path) {
796
604
  const linesAfterHeading = rendering.lines.length;
797
605
  const fields = isObject(variant) ? nestedObject(variant, rendering, visiting) : void 0;
798
606
  if (fields !== void 0) writeFields(fields, `${path === "" ? "" : `${path} `}option ${index + 1}`);
799
- 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)}`)];
800
608
  });
801
609
  }
802
610
  function rawSchemaLines(hostName, schema) {
803
- 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)])];
804
612
  }
805
613
  function capped(lines) {
806
614
  if (lines.length <= maximumLines) return lines;
807
- 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.`)]];
808
616
  }
809
617
  function rootLines(rendering, schema) {
810
618
  const noneVisiting = /* @__PURE__ */ new Set();
@@ -816,12 +624,12 @@ function rootLines(rendering, schema) {
816
624
  const resolved = resolveReference(schema, rendering, noneVisiting).node;
817
625
  const merged = mergedAllOf(resolved, rendering, noneVisiting);
818
626
  if (variants(merged)?.some((variant) => informativeVariant(variant, rendering, noneVisiting)) === true) {
819
- write(rendering, [muted$2("Takes one of these inputs:")]);
627
+ write(rendering, [muted$1("Takes one of these inputs:")]);
820
628
  writeProperties(rendering, merged, noneVisiting, 0, "");
821
629
  return rendering.lines;
822
630
  }
823
631
  const type = typeName(schema, rendering, noneVisiting, 0);
824
- 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.")]];
825
633
  return [[plain("Input is "), {
826
634
  text: type,
827
635
  tone: "name"
@@ -833,7 +641,7 @@ function rootLines(rendering, schema) {
833
641
  * host in notes about what it reported.
834
642
  */
835
643
  function schemaLines(schema, hostName) {
836
- 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.`)]];
837
645
  const rendering = {
838
646
  hostName,
839
647
  root: schema,
@@ -848,7 +656,7 @@ function schemaLines(schema, hostName) {
848
656
  try {
849
657
  return rootLines(rendering, schema);
850
658
  } catch (error) {
851
- 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.")]];
852
660
  return capped(rawSchemaLines(rendering.hostName, schema));
853
661
  }
854
662
  }
@@ -856,61 +664,6 @@ function linesText(lines) {
856
664
  return lines.map((line) => line.map((segment) => segment.text).join("")).join("\n");
857
665
  }
858
666
 
859
- // ../core/src/agent-text.ts
860
- function muted$1(text) {
861
- return {
862
- text,
863
- tone: "muted"
864
- };
865
- }
866
- function decisionSummary(decision, actionLabels) {
867
- if (decision.access === "unknown") return "Unknown";
868
- if (decision.offeredToModel === false) return actionLabels.deny;
869
- return actionLabels[decision.access];
870
- }
871
- function exceptionLines(decision, actionLabels) {
872
- if (decision.offeredToModel === false) return [];
873
- return decision.exceptions.map((exception) => [{
874
- text: ` ${exception.pattern}`,
875
- tone: "name"
876
- }, muted$1(`: ${actionLabels[exception.access]}`)]);
877
- }
878
- function agentLines(agent, actionLabels) {
879
- return [[{
880
- text: agent.agent,
881
- tone: "name"
882
- }, muted$1(` ${decisionSummary(agent, actionLabels)}`)], ...exceptionLines(agent, actionLabels)];
883
- }
884
- /** The host's own hidden agents, such as `compaction` and `title`, never take tool calls. */
885
- function listed(agent) {
886
- return !(agent.native && agent.hidden);
887
- }
888
- function primaryFirst(left, right) {
889
- const rank = (agent) => agent.mode === "subagent" ? 1 : 0;
890
- return rank(left) - rank(right);
891
- }
892
- function notesFor(notes, key) {
893
- return notes !== void 0 && Object.hasOwn(notes, key) ? notes[key] : [];
894
- }
895
- function accessNoteLines(notes, access) {
896
- return [
897
- ...notes.always ?? [],
898
- ...notesFor(notes.permission, access.permission),
899
- ...notesFor(notes.tool, access.tool)
900
- ].map((note) => [muted$1(note)]);
901
- }
902
- /** Renders which agents can use a tool, primary agents first. */
903
- function agentAccessLines(access, host) {
904
- const { actionLabels } = host;
905
- const agents = access.agents.filter(listed).sort(primaryFirst);
906
- if (agents.length === 0) return [[muted$1(`${host.name} reported no agents that use tools.`)]];
907
- return [
908
- ...access.permission === access.tool ? [] : [[muted$1(`Checked as the ${access.permission} permission.`)]],
909
- ...accessNoteLines(host.accessNotes, access),
910
- ...agents.flatMap((agent) => agentLines(agent, actionLabels))
911
- ];
912
- }
913
-
914
667
  // ../core/src/tool-detail.ts
915
668
  function muted(text) {
916
669
  return [[{
@@ -918,6 +671,7 @@ function muted(text) {
918
671
  tone: "muted"
919
672
  }]];
920
673
  }
674
+ /** A text as plain lines, without the whitespace around it. */
921
675
  function textLines(text) {
922
676
  return text.trim().split(/\r?\n/).map((line) => [{
923
677
  text: line,
@@ -926,17 +680,17 @@ function textLines(text) {
926
680
  }
927
681
  /**
928
682
  * The detail view's content. The Agents section is left out when the host's agents couldn't be
929
- * read.
683
+ * read, and `inputNotice` replaces the input's fields when the host couldn't describe them.
930
684
  */
931
- function toolDetail(host, tool, modelLabel, access) {
685
+ function toolDetail(host, tool, subtitle, access, inputNotice) {
932
686
  const detailsMissing = `${host.name} reported only this tool's name.`;
933
687
  return {
934
688
  title: tool.id,
935
- subtitle: modelLabel === void 0 ? void 0 : `As offered to ${modelLabel}`,
689
+ subtitle,
936
690
  sections: [
937
691
  {
938
692
  heading: "Input",
939
- 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)
940
694
  },
941
695
  ...access === void 0 ? [] : [{
942
696
  heading: "Agents",
@@ -949,82 +703,17 @@ function toolDetail(host, tool, modelLabel, access) {
949
703
  ]
950
704
  };
951
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
+ }
952
712
 
953
713
  // ../core/src/tools.ts
954
- const sourceLabels = {
955
- session: "this session's model",
956
- configured: "configured model",
957
- "provider default": "provider default"
958
- };
959
- /** The host's placeholder for unknown tool calls, never offered to agents as a real tool. */
960
- const internalToolIds = /* @__PURE__ */ new Set(["invalid"]);
961
714
  function isRecord(value) {
962
715
  return typeof value === "object" && value !== null;
963
716
  }
964
- function modelLabel(model) {
965
- return `${model.providerID}/${model.modelID}`;
966
- }
967
- function chosenModelLabel(model) {
968
- return `${modelLabel(model)} (${sourceLabels[model.source]})`;
969
- }
970
- /** The model of the session's latest user message, which the host resolves tools for on the next prompt. */
971
- function sessionModel(messages) {
972
- for (const message of [...messages].reverse()) {
973
- if (!isRecord(message) || message.role !== "user") continue;
974
- const model = message.model;
975
- if (isRecord(model) && typeof model.providerID === "string" && typeof model.modelID === "string" && model.providerID !== "" && model.modelID !== "") return {
976
- providerID: model.providerID,
977
- modelID: model.modelID
978
- };
979
- }
980
- }
981
- /** Parses the `provider/model` form used by the `model` setting. */
982
- function configuredModel(model) {
983
- if (typeof model !== "string") return;
984
- const separator = model.indexOf("/");
985
- if (separator <= 0 || separator === model.length - 1) return;
986
- return {
987
- providerID: model.slice(0, separator),
988
- modelID: model.slice(separator + 1)
989
- };
990
- }
991
- /** The first connected provider's default model, which the host falls back to when none is configured. */
992
- function providerDefaultModel(connectedProviderIds, defaults) {
993
- if (!isRecord(defaults)) return;
994
- for (const providerID of connectedProviderIds) {
995
- const modelID = defaults[providerID];
996
- if (typeof modelID === "string" && modelID !== "") return {
997
- providerID,
998
- modelID
999
- };
1000
- }
1001
- }
1002
- function byId(left, right) {
1003
- return left.id.localeCompare(right.id);
1004
- }
1005
- /** Keeps well-formed entries from the host's tool list, sorted by id. */
1006
- function toolsFromList(response) {
1007
- if (!Array.isArray(response)) return;
1008
- const tools = /* @__PURE__ */ new Map();
1009
- for (const item of response) {
1010
- if (!isRecord(item) || typeof item.id !== "string" || item.id === "" || internalToolIds.has(item.id)) continue;
1011
- tools.set(item.id, {
1012
- id: item.id,
1013
- description: typeof item.description === "string" ? item.description : void 0,
1014
- parameters: item.parameters
1015
- });
1016
- }
1017
- return [...tools.values()].sort(byId);
1018
- }
1019
- /** Tool ids without details, for when the host can't resolve tools for a model. */
1020
- function toolsFromIds(response) {
1021
- if (!Array.isArray(response)) return;
1022
- return [...new Set(response.filter((id) => typeof id === "string" && id !== "" && !internalToolIds.has(id)))].map((id) => ({
1023
- id,
1024
- description: void 0,
1025
- parameters: void 0
1026
- })).sort(byId);
1027
- }
1028
717
  const summaryLength = 100;
1029
718
  /** The first line of a description without its list marker, short enough for one list row. */
1030
719
  function descriptionSummary(description) {
@@ -1040,179 +729,444 @@ function inputCount(parameters) {
1040
729
  const count = Object.keys(parameters.properties).length;
1041
730
  return count === 0 && (parameters.anyOf !== void 0 || parameters.oneOf !== void 0) ? void 0 : count;
1042
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
+ }
1043
738
 
1044
- // ../core/src/tui.ts
1045
- const toastTitle = "Tool Inspector";
1046
- /** The plain-text fallback can't scroll, so long sections are cut short. */
1047
- const plainTextSectionLines = 20;
1048
- function errorText(error) {
1049
- if (error instanceof Error) return error.message;
1050
- if (typeof error === "object" && error !== null) {
1051
- const record = error;
1052
- if (typeof record.message === "string") return record.message;
1053
- if (typeof record.data?.message === "string") return record.data.message;
1054
- return JSON.stringify(error);
1055
- }
1056
- 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
+ };
1057
763
  }
1058
- /** Names of connected MCP servers, whose tools the host's tool list leaves out. */
1059
- function connectedMcpServers(api) {
1060
- try {
1061
- return api.state.mcp().filter((server) => server.status === "connected").map((server) => server.name);
1062
- } catch {
1063
- 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);
1064
771
  }
772
+ return rules;
1065
773
  }
1066
- function mcpNotice(host, servers) {
1067
- if (servers.length === 0) return;
1068
- return `Tools from MCP servers (${servers.join(", ")}) aren't listed, because ${host.name} only adds them when it runs a prompt.`;
1069
- }
1070
- function currentSessionId(api) {
1071
- const route = api.route.current;
1072
- 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"));
1073
786
  }
1074
- async function chooseModel(api, signal) {
1075
- const sessionId = currentSessionId(api);
1076
- const fromSession = sessionId === void 0 ? void 0 : sessionModel(api.state.session.messages(sessionId));
1077
- if (fromSession !== void 0) return {
1078
- ...fromSession,
1079
- 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)
1080
795
  };
1081
- const connectedProviderIds = api.state.provider.map((provider) => provider.id);
1082
- const configured = configuredModel(api.state.config.model);
1083
- if (configured !== void 0 && (connectedProviderIds.length === 0 || connectedProviderIds.includes(configured.providerID))) return {
1084
- ...configured,
1085
- source: "configured"
796
+ const agentRules = readRuleset(field(agent, "permissions"));
797
+ if (agentRules === void 0 || sessionRules === void 0) return {
798
+ ...summary,
799
+ ...unknownDecision
1086
800
  };
1087
- const response = await api.client.config.providers({ directory: api.state.path.directory }, { signal });
1088
- if (response.error !== void 0) throw new Error(errorText(response.error));
1089
- const fallback = providerDefaultModel(connectedProviderIds, response.data.default);
1090
- return fallback === void 0 ? void 0 : {
1091
- ...fallback,
1092
- source: "provider default"
801
+ return {
802
+ ...summary,
803
+ ...decide(permission, [...agentRules, ...sessionRules], offered)
1093
804
  };
1094
805
  }
1095
- async function readAgents(host, api, signal) {
1096
- if (typeof api.client.app?.agents !== "function") throw new Error(`this ${host.name} doesn't list agents`);
1097
- const response = await api.client.app.agents({ directory: api.state.path.directory }, { signal });
1098
- if (response.error !== void 0) throw new Error(errorText(response.error));
1099
- const agents = response.data;
1100
- if (!Array.isArray(agents)) throw new Error("the response wasn't an agent list");
1101
- 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
+ }));
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
+ };
1102
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."];
1103
956
  /**
1104
- * The permission rules of the current session's top-level session, which the host applies after
1105
- * each agent's own rules. Sessions usually have none. When a parent isn't loaded, the topmost
1106
- * 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.
1107
959
  */
1108
- function sessionPermission(api) {
1109
- const sessionId = currentSessionId(api);
1110
- if (sessionId === void 0) return [];
1111
- try {
1112
- let session = api.state.session.get(sessionId);
1113
- const seen = /* @__PURE__ */ new Set();
1114
- while (session?.parentID !== void 0 && !seen.has(session.id)) {
1115
- seen.add(session.id);
1116
- const parent = api.state.session.get(session.parentID);
1117
- if (parent === void 0) break;
1118
- 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."]
1119
976
  }
1120
- return session?.permission ?? [];
1121
- } catch {
1122
- return [];
1123
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 };
1124
1029
  }
1125
- function primaryTools(api) {
1030
+ async function readTools(context, location, signal) {
1031
+ let output;
1126
1032
  try {
1127
- return api.state.config.experimental?.primary_tools;
1128
- } catch {
1129
- 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;
1130
1043
  }
1131
- }
1132
- function accessByTool(api, tools, agents) {
1133
- const resolved = resolveToolAgentAccess(tools.map((tool) => tool.id), agents, {
1134
- primaryTools: primaryTools(api),
1135
- 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
1136
1057
  });
1137
- return new Map(resolved.map((access) => [access.tool, access]));
1058
+ return [...byId.values()].sort((left, right) => left.id.localeCompare(right.id));
1138
1059
  }
1139
- async function readToolList(host, api, signal) {
1140
- const directory = api.state.path.directory;
1141
- let modelFailure;
1142
- const model = await chooseModel(api, signal).catch((error) => {
1143
- modelFailure = errorText(error);
1144
- });
1145
- let listFailure;
1146
- if (model !== void 0) try {
1147
- const response = await api.client.tool.list({
1148
- directory,
1149
- provider: model.providerID,
1150
- model: model.modelID
1151
- }, { signal });
1152
- if (response.error === void 0) {
1153
- const tools = toolsFromList(response.data);
1154
- if (tools !== void 0) return {
1155
- tools,
1156
- model,
1157
- notice: void 0
1158
- };
1159
- listFailure = "the response wasn't a tool list";
1160
- } else listFailure = errorText(response.error);
1161
- } catch (error) {
1162
- 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;
1163
1083
  }
1164
- const response = await api.client.tool.ids({ directory }, { signal });
1165
- const tools = response.error === void 0 ? toolsFromIds(response.data) : void 0;
1166
- 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)));
1167
- return {
1168
- tools,
1169
- model: void 0,
1170
- 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.`
1171
- };
1172
1084
  }
1173
- 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);
1174
1123
  let agentsFailure;
1175
- const agentsRead = readAgents(host, api, signal).catch((error) => {
1124
+ const agentsRead = readAgents(context, location, signal).catch((error) => {
1176
1125
  agentsFailure = errorText(error);
1177
1126
  });
1178
- const list = await readToolList(host, api, signal);
1127
+ const tools = await readTools(context, location, signal);
1179
1128
  const agents = await agentsRead;
1180
1129
  let access;
1130
+ let deniedExecute;
1181
1131
  if (agents !== void 0) try {
1182
- 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);
1183
1138
  } catch (error) {
1184
1139
  agentsFailure = errorText(error);
1185
1140
  }
1186
1141
  return {
1187
- ...list,
1142
+ tools,
1188
1143
  access,
1189
- 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
1190
1146
  };
1191
1147
  }
1192
- function inputCountLabel(tool) {
1193
- const count = inputCount(tool.parameters);
1194
- if (count === void 0) return;
1195
- return count === 1 ? "1 input" : `${count} inputs`;
1196
- }
1197
- function registerToolBrowser(host, api) {
1148
+ function registerToolBrowser(context) {
1198
1149
  const toast = (variant, message) => {
1199
- api.ui.toast({
1150
+ context.ui.toast.show({
1200
1151
  variant,
1201
1152
  title: toastTitle,
1202
1153
  message,
1203
1154
  duration: variant === "warning" ? 1e4 : 5e3
1204
1155
  });
1205
1156
  };
1206
- let viewer;
1207
- const detailViewer = () => {
1208
- viewer ??= createDetailViewer(api).catch((error) => {
1157
+ let disposed = false;
1158
+ let view;
1159
+ const detailView = () => {
1160
+ view ??= createDetailView(context).catch((error) => {
1209
1161
  toast("warning", `Showing tool details as plain text: ${errorText(error)}`);
1210
1162
  });
1211
- return viewer;
1163
+ return view;
1212
1164
  };
1213
- /** 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. */
1214
1166
  let revision = 0;
1215
1167
  let showing = false;
1168
+ /** The revision a chosen tool is waiting under, while no dialog is shown for it yet. */
1169
+ let opening;
1216
1170
  /** The read behind the loading dialog, aborted once anything replaces that dialog. */
1217
1171
  let activeRead;
1218
1172
  const close = () => {
@@ -1220,51 +1174,99 @@ function registerToolBrowser(host, api) {
1220
1174
  showing = false;
1221
1175
  activeRead?.abort();
1222
1176
  activeRead = void 0;
1223
- api.ui.dialog.clear();
1224
- };
1225
- const viewContext = () => {
1226
- const directory = api.state.path.directory;
1227
- const sessionId = currentSessionId(api);
1228
- const routeName = api.route.current.name;
1229
- return () => !api.lifecycle.signal.aborted && directory === api.state.path.directory && routeName === api.route.current.name && sessionId === currentSessionId(api);
1177
+ context.ui.dialog.clear();
1230
1178
  };
1231
- 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) => {
1232
1184
  const active = ++revision;
1233
1185
  showing = true;
1234
1186
  activeRead?.abort();
1235
1187
  activeRead = void 0;
1236
- api.ui.dialog.replace(render, () => {
1237
- if (active !== revision) return;
1238
- revision++;
1239
- showing = false;
1240
- onClosed?.();
1241
- });
1242
- api.ui.dialog.setSize(size);
1243
- 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
+ }
1244
1228
  };
1245
1229
  const views = {
1246
1230
  async detail(catalog, tool) {
1247
- const listRevision = revision;
1231
+ const opened = revision;
1248
1232
  const sameView = viewContext();
1249
- const detail = toolDetail(host, tool, catalog.model === void 0 ? void 0 : chosenModelLabel(catalog.model), catalog.access?.get(tool.id));
1250
- const render = await detailViewer();
1251
- if (listRevision !== revision || !sameView()) return;
1252
- display(render === void 0 ? () => api.ui.DialogAlert({
1253
- title: detail.title,
1254
- message: detail.sections.map((section) => `${section.heading}\n${linesText(section.lines.slice(0, plainTextSectionLines))}${section.lines.length > plainTextSectionLines ? "\n…" : ""}`).join("\n\n")
1255
- }) : () => 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(() => {
1256
1246
  const closedRevision = revision;
1257
1247
  queueMicrotask(() => {
1258
- if (closedRevision === revision && !api.ui.dialog.open && sameView()) views.list(catalog, tool.id);
1248
+ if (closedRevision === revision && !dialogOpen() && sameView()) views.list(catalog, tool.id);
1259
1249
  });
1260
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
+ }
1261
1262
  },
1262
1263
  list(catalog, current) {
1263
1264
  const sameView = viewContext();
1264
- display(() => api.ui.DialogSelect({
1265
- 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",
1266
1268
  placeholder: "Search tools",
1267
- current,
1269
+ ...current === void 0 ? {} : { current },
1268
1270
  options: catalog.tools.map((tool) => {
1269
1271
  const summary = descriptionSummary(tool.description);
1270
1272
  const footer = inputCountLabel(tool);
@@ -1274,102 +1276,93 @@ function registerToolBrowser(host, api) {
1274
1276
  ...summary === "" ? {} : { description: summary },
1275
1277
  ...footer === void 0 ? {} : { footer }
1276
1278
  };
1277
- }),
1278
- onSelect: (option) => {
1279
- const tool = catalog.tools.find((item) => item.id === option.value);
1280
- if (!sameView()) {
1281
- close();
1282
- toast("info", "The session changed, so run /tools again.");
1283
- return;
1284
- }
1285
- if (tool !== void 0) views.detail(catalog, tool).catch((error) => {
1286
- toast("warning", `Could not show ${tool.id}: ${errorText(error)}`);
1287
- });
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;
1288
1290
  }
1289
- }), "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));
1290
1297
  }
1291
1298
  };
1292
1299
  const open = async () => {
1293
1300
  const sameView = viewContext();
1294
1301
  const controller = new AbortController();
1295
- const abort = () => controller.abort();
1296
- api.lifecycle.signal.addEventListener("abort", abort, { once: true });
1297
- const loading = display(() => api.ui.DialogAlert({
1298
- title: "Loading tools",
1299
- message: `Reading the tools ${host.name} offers…`
1300
- }), "medium", abort);
1302
+ const loading = display(() => controller.abort());
1301
1303
  activeRead = controller;
1302
- detailViewer().catch(() => void 0);
1303
1304
  try {
1304
- const catalog = await readCatalog(host, api, controller.signal);
1305
- 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;
1306
1319
  if (!sameView()) {
1307
1320
  close();
1308
1321
  return;
1309
1322
  }
1310
1323
  if (catalog.tools.length === 0) {
1311
1324
  close();
1312
- toast("info", `${host.name} reported no tools.`);
1325
+ toast("info", `${opencodeHost.name} reported no tools.`);
1313
1326
  return;
1314
1327
  }
1315
- const notices = [
1316
- catalog.notice,
1317
- catalog.agentsNotice,
1318
- mcpNotice(host, connectedMcpServers(api))
1319
- ].filter((notice) => notice !== void 0);
1320
- 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);
1321
1329
  views.list(catalog, void 0);
1322
1330
  } catch (error) {
1323
- if (loading === revision) {
1331
+ if (loading.active === revision) {
1324
1332
  close();
1325
- 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)}`);
1326
1334
  }
1327
- } finally {
1328
- api.lifecycle.signal.removeEventListener("abort", abort);
1329
1335
  }
1330
1336
  };
1331
- const unregister = api.keymap.registerLayer({ commands: [{
1332
- name: "tool-inspector.browse",
1333
- title: "Browse tools",
1334
- category: "Tools",
1335
- namespace: "palette",
1336
- slashName: "tools",
1337
- run: () => Promise.resolve().then(open).catch((error) => {
1338
- toast("warning", `Could not open tools: ${errorText(error)}`);
1339
- })
1340
- }] });
1341
- const stopWatching = api.event.on("server.instance.disposed", (event) => {
1342
- 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
+ }
1343
1355
  });
1344
- api.lifecycle.onDispose(() => {
1345
- unregister();
1356
+ return () => {
1357
+ disposed = true;
1346
1358
  stopWatching();
1347
- });
1348
- }
1349
- /** The Tool Inspector TUI plugin for one host, typed as the OpenCode package has always exported it. */
1350
- function createToolInspectorTui(host) {
1351
- const tui = (api) => {
1352
- registerToolBrowser(host, api);
1353
- return Promise.resolve();
1354
- };
1355
- return {
1356
- id: "tool-inspector",
1357
- tui
1359
+ invalidate();
1358
1360
  };
1359
1361
  }
1360
-
1361
- // src/host.ts
1362
- const opencodeHost = {
1363
- name: "OpenCode",
1364
- actionLabels: {
1365
- allow: "Allow",
1366
- ask: "Ask",
1367
- deny: "Deny"
1368
- },
1369
- 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
1370
1366
  };
1371
1367
 
1372
- // src/tui.ts
1373
- const plugin = createToolInspectorTui(opencodeHost);
1374
-
1375
- export { plugin as default };
1368
+ export { tui as default };