jig-console 0.0.0-stage → 0.1.1

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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -2
  3. package/dist/commands/config.d.ts +8 -0
  4. package/dist/commands/config.d.ts.map +1 -0
  5. package/dist/commands/config.js +224 -0
  6. package/dist/commands/config.js.map +1 -0
  7. package/dist/commands/convert.d.ts +10 -0
  8. package/dist/commands/convert.d.ts.map +1 -0
  9. package/dist/commands/convert.js +40 -0
  10. package/dist/commands/convert.js.map +1 -0
  11. package/dist/commands/history.d.ts +8 -0
  12. package/dist/commands/history.d.ts.map +1 -0
  13. package/dist/commands/history.js +112 -0
  14. package/dist/commands/history.js.map +1 -0
  15. package/dist/commands/init.d.ts +7 -0
  16. package/dist/commands/init.d.ts.map +1 -0
  17. package/dist/commands/init.js +225 -0
  18. package/dist/commands/init.js.map +1 -0
  19. package/dist/commands/pipeline.d.ts +17 -0
  20. package/dist/commands/pipeline.d.ts.map +1 -0
  21. package/dist/commands/pipeline.js +137 -0
  22. package/dist/commands/pipeline.js.map +1 -0
  23. package/dist/commands/play.d.ts +13 -0
  24. package/dist/commands/play.d.ts.map +1 -0
  25. package/dist/commands/play.js +109 -0
  26. package/dist/commands/play.js.map +1 -0
  27. package/dist/commands/providers.d.ts +17 -0
  28. package/dist/commands/providers.d.ts.map +1 -0
  29. package/dist/commands/providers.js +161 -0
  30. package/dist/commands/providers.js.map +1 -0
  31. package/dist/commands/recipes.d.ts +16 -0
  32. package/dist/commands/recipes.d.ts.map +1 -0
  33. package/dist/commands/recipes.js +135 -0
  34. package/dist/commands/recipes.js.map +1 -0
  35. package/dist/commands/replay.d.ts +40 -0
  36. package/dist/commands/replay.d.ts.map +1 -0
  37. package/dist/commands/replay.js +206 -0
  38. package/dist/commands/replay.js.map +1 -0
  39. package/dist/commands/run.d.ts +3 -0
  40. package/dist/commands/run.d.ts.map +1 -0
  41. package/dist/commands/run.js +14 -0
  42. package/dist/commands/run.js.map +1 -0
  43. package/dist/commands/show.d.ts +15 -0
  44. package/dist/commands/show.d.ts.map +1 -0
  45. package/dist/commands/show.js +39 -0
  46. package/dist/commands/show.js.map +1 -0
  47. package/dist/commands/status.d.ts +6 -0
  48. package/dist/commands/status.d.ts.map +1 -0
  49. package/dist/commands/status.js +77 -0
  50. package/dist/commands/status.js.map +1 -0
  51. package/dist/commands/validate.d.ts +6 -0
  52. package/dist/commands/validate.d.ts.map +1 -0
  53. package/dist/commands/validate.js +36 -0
  54. package/dist/commands/validate.js.map +1 -0
  55. package/dist/help/jig-help.d.ts +25 -0
  56. package/dist/help/jig-help.d.ts.map +1 -0
  57. package/dist/help/jig-help.js +147 -0
  58. package/dist/help/jig-help.js.map +1 -0
  59. package/dist/index.d.ts +3 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +216 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/keys.d.ts +14 -0
  64. package/dist/keys.d.ts.map +1 -0
  65. package/dist/keys.js +68 -0
  66. package/dist/keys.js.map +1 -0
  67. package/dist/live-view.d.ts +90 -0
  68. package/dist/live-view.d.ts.map +1 -0
  69. package/dist/live-view.js +239 -0
  70. package/dist/live-view.js.map +1 -0
  71. package/dist/permissions.d.ts +40 -0
  72. package/dist/permissions.d.ts.map +1 -0
  73. package/dist/permissions.js +88 -0
  74. package/dist/permissions.js.map +1 -0
  75. package/dist/providers.d.ts +68 -0
  76. package/dist/providers.d.ts.map +1 -0
  77. package/dist/providers.js +230 -0
  78. package/dist/providers.js.map +1 -0
  79. package/dist/session/app.d.ts +28 -0
  80. package/dist/session/app.d.ts.map +1 -0
  81. package/dist/session/app.js +458 -0
  82. package/dist/session/app.js.map +1 -0
  83. package/dist/session/ascii.d.ts +5 -0
  84. package/dist/session/ascii.d.ts.map +1 -0
  85. package/dist/session/ascii.js +39 -0
  86. package/dist/session/ascii.js.map +1 -0
  87. package/dist/session/commands.d.ts +26 -0
  88. package/dist/session/commands.d.ts.map +1 -0
  89. package/dist/session/commands.js +828 -0
  90. package/dist/session/commands.js.map +1 -0
  91. package/dist/session/controller.d.ts +291 -0
  92. package/dist/session/controller.d.ts.map +1 -0
  93. package/dist/session/controller.js +779 -0
  94. package/dist/session/controller.js.map +1 -0
  95. package/dist/session/editor.d.ts +60 -0
  96. package/dist/session/editor.d.ts.map +1 -0
  97. package/dist/session/editor.js +128 -0
  98. package/dist/session/editor.js.map +1 -0
  99. package/dist/session/jig-theme.json +1 -0
  100. package/dist/session/keys.d.ts +26 -0
  101. package/dist/session/keys.d.ts.map +1 -0
  102. package/dist/session/keys.js +95 -0
  103. package/dist/session/keys.js.map +1 -0
  104. package/dist/session/lines.d.ts +65 -0
  105. package/dist/session/lines.d.ts.map +1 -0
  106. package/dist/session/lines.js +370 -0
  107. package/dist/session/lines.js.map +1 -0
  108. package/dist/session/markdown.d.ts +13 -0
  109. package/dist/session/markdown.d.ts.map +1 -0
  110. package/dist/session/markdown.js +188 -0
  111. package/dist/session/markdown.js.map +1 -0
  112. package/dist/session/models.d.ts +24 -0
  113. package/dist/session/models.d.ts.map +1 -0
  114. package/dist/session/models.js +17 -0
  115. package/dist/session/models.js.map +1 -0
  116. package/dist/session/start.d.ts +27 -0
  117. package/dist/session/start.d.ts.map +1 -0
  118. package/dist/session/start.js +140 -0
  119. package/dist/session/start.js.map +1 -0
  120. package/dist/session/theme.d.ts +137 -0
  121. package/dist/session/theme.d.ts.map +1 -0
  122. package/dist/session/theme.js +129 -0
  123. package/dist/session/theme.js.map +1 -0
  124. package/dist/session-runner.d.ts +107 -0
  125. package/dist/session-runner.d.ts.map +1 -0
  126. package/dist/session-runner.js +463 -0
  127. package/dist/session-runner.js.map +1 -0
  128. package/dist/terminal-width.d.ts +7 -0
  129. package/dist/terminal-width.d.ts.map +1 -0
  130. package/dist/terminal-width.js +45 -0
  131. package/dist/terminal-width.js.map +1 -0
  132. package/dist/topology-arg.d.ts +12 -0
  133. package/dist/topology-arg.d.ts.map +1 -0
  134. package/dist/topology-arg.js +26 -0
  135. package/dist/topology-arg.js.map +1 -0
  136. package/docs/jig-help.md +70 -0
  137. package/package.json +73 -4
@@ -0,0 +1,828 @@
1
+ // ============================================
2
+ // The session's slash commands
3
+ // ============================================
4
+ // Each command names itself, says what it does, completes its arguments, and
5
+ // writes what it has to say into the conversation. Settings a command
6
+ // changes take effect on the next task and are kept with the session.
7
+ import { existsSync, readdirSync, statSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import * as path from "node:path";
10
+ import { CONSULT_SIGHTS, createDefaultToolkit, draw, drawingOf, initialRunState, layoutFor, listRecipes, measureSight, shortTokens, toText, len, padCells, parseRule, } from "jig-core";
11
+ import { ENTRY_KINDS, PRESETS, needsKey } from "jig-core";
12
+ import { removeEntry, resolveNow, saveBrain, saveEntry, storeInKeychain, testOne } from "../providers.js";
13
+ import { MODE_LABEL, ruleSources, saveLocalRules } from "../permissions.js";
14
+ const line = (...parts) => parts;
15
+ const plain = (text, k = "ink") => [[text, k]];
16
+ const MEMORY_SCOPES = ["off", "session", "task", "shared", "run"];
17
+ /** Topology files in the working directory, for completion. */
18
+ function topologyFiles(dir) {
19
+ try {
20
+ return readdirSync(dir).filter((f) => /\.(ya?ml|json)$/i.test(f));
21
+ }
22
+ catch {
23
+ return [];
24
+ }
25
+ }
26
+ function roleIds(ctrl) {
27
+ const t = ctrl.topology;
28
+ return t ? [...t.nodes.map((n) => n.id), ...t.consults.map((c) => c.role.id)] : [];
29
+ }
30
+ function roleTable(ctrl) {
31
+ const t = ctrl.topology;
32
+ if (!t)
33
+ return [plain("no topology", "fail")];
34
+ // The cells of each row first, so every column is padded to its widest, in display cells.
35
+ const cells = [];
36
+ for (const n of t.nodes) {
37
+ const face = t.faces[n.id];
38
+ const own = ctrl.settings.roleModels[n.id];
39
+ const brain = !own && !ctrl.settings.defaultModel ? n.config.brain?.brain : undefined;
40
+ const first = brain ? ctrl.models.chain?.(brain)[0] : undefined;
41
+ cells.push({ name: `${face?.icon ?? "◦"} ${face?.label ?? n.id}`, id: n.id, model: brain ? brain : ctrl.modelOf(n.id), modelK: own || brain ? "ink" : "dim", note: own ? "" : brain ? `(its brain: ${first ?? "no model"} first)` : "(the default)" });
42
+ }
43
+ for (const c of t.consults) {
44
+ const model = ctrl.settings.advisor.model ?? ctrl.settings.roleModels[c.role.id] ?? (c.role.brain?.model ? `${c.role.brain.provider ?? ""}/${c.role.brain.model}` : ctrl.modelOf(""));
45
+ cells.push({ name: `${c.role.face.icon} ${c.role.face.label}`, id: c.role.id, model, modelK: "ink", note: `consulted by ${c.from}` });
46
+ }
47
+ const w = (k) => Math.max(...cells.map((c) => len(c[k])));
48
+ return cells.map((c) => line([` ${padCells(c.name, w("name"))} `, "b"], [`${padCells(c.id, w("id"))} `, "faint"], [`${padCells(c.model, w("model"))} `, c.modelK], [c.note, "faint"]));
49
+ }
50
+ /** Brains first, then every model each provider has now, as picker items, the one in effect marked. */
51
+ async function modelItems(ctrl, current) {
52
+ const brains = ctrl.models.brainsNow ?? {};
53
+ const lists = await ctrl.models.list().catch(() => []);
54
+ return [
55
+ ...Object.entries(brains).map(([b, chain]) => ({ value: b, label: b, detail: `brain: ${chain.join(" ⇢ ") || "no model in it"}`, current: b === current })),
56
+ ...lists.flatMap((l) => l.models.map((m) => ({ value: `${l.entry}/${m}`, label: `${l.entry}/${m}`, current: `${l.entry}/${m}` === current }))),
57
+ ];
58
+ }
59
+ /** A role's model as the session runs it, for a picker's detail. */
60
+ function roleModelDetail(ctrl, id, brain) {
61
+ const own = ctrl.settings.roleModels[id];
62
+ if (own)
63
+ return own;
64
+ if (brain && !ctrl.settings.defaultModel)
65
+ return `brain ${brain}`;
66
+ return `${ctrl.modelOf(id)} (the default)`;
67
+ }
68
+ /** The roles of the topology, its advisor and "every other role", as picker items. */
69
+ function roleItems(ctrl, withDefault) {
70
+ const t = ctrl.topology;
71
+ return [
72
+ ...(t?.nodes ?? []).map((n) => ({ value: n.id, label: t.faces[n.id]?.label ?? n.id, detail: roleModelDetail(ctrl, n.id, n.config.brain?.brain) })),
73
+ ...(t?.consults ?? []).map((c) => ({ value: c.role.id, label: c.role.face.label, detail: `${ctrl.settings.advisor.model ?? roleModelDetail(ctrl, c.role.id, c.role.brain?.brain)} ∙ consulted by ${c.from}` })),
74
+ ...(withDefault ? [{ value: "default", label: "every other role", detail: ctrl.modelOf("") }] : []),
75
+ ];
76
+ }
77
+ /** A past run, newest first, with its outcome, time and task. */
78
+ async function pickRun(ctrl, title) {
79
+ const runs = await ctrl.pastRuns(50);
80
+ if (!runs.length) {
81
+ ctrl.info([plain(" no recorded runs here yet", "dim")], "runs");
82
+ return null;
83
+ }
84
+ const when = (at) => (at ? new Date(at).toLocaleString("en-US", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false }) : "");
85
+ return ctrl.pickOne(title, runs.map((r) => ({ value: r.runId, label: `${r.outcome === "passed" ? "✓" : r.outcome === "failed" ? "✗" : "▪"} ${when(r.at)}`, detail: `${r.outcome ?? "no outcome"} ∙ ${r.topology} ∙ ${(r.task ?? "").replace(/\s+/g, " ").slice(0, 60)}` })));
86
+ }
87
+ const MEMORY_WORDS = {
88
+ session: "this session's runs: the conversation so far, and what its runs kept",
89
+ task: "runs of the same task, in any session",
90
+ shared: "everything kept, across tasks",
91
+ run: "only what the run itself writes",
92
+ off: "nothing: each task starts with no memory, and the conversation is still its input",
93
+ };
94
+ const SIGHT_SAYS = { prompt: "sees it, in its prompt", delivered: "is given it, outside its prompt", none: "does not see it", own: "writes it" };
95
+ export const COMMANDS = [
96
+ {
97
+ name: "help",
98
+ usage: "/help",
99
+ summary: "what each command does, and the keys",
100
+ run: (_args, ctrl) => {
101
+ // A usage wider than the column takes a row of its own, and its summary starts in the column below it.
102
+ const usageW = Math.min(36, Math.max(...COMMANDS.map((c) => len(c.usage))));
103
+ const rows = COMMANDS.flatMap((c) => len(c.usage) > usageW ? [line([` ${c.usage}`, "b"]), line([` ${padCells("", usageW)} `, ""], [c.summary, "dim"])] : [line([` ${padCells(c.usage, usageW)} `, "b"], [c.summary, "dim"])]);
104
+ rows.push(plain(""));
105
+ rows.push(plain(" Enter sends ∙ Alt+Enter, Ctrl+J or \\ then Enter start a new line ∙ ⇡⇣ history ∙ Tab completes", "dim"));
106
+ rows.push(plain(" Typing while a run goes steers it (a note Do reads on its next turn) ∙ Esc stops the run", "dim"));
107
+ rows.push(plain(" Ctrl+T folds the topology to one line ∙ PgUp PgDn scroll the conversation ∙ Ctrl+D quits", "dim"));
108
+ rows.push(plain(" Shift+Tab cycles the permission mode: manual, accept edits, plan", "dim"));
109
+ ctrl.info(rows, "help");
110
+ },
111
+ },
112
+ {
113
+ name: "topology",
114
+ usage: "/topology [list|show|<id or file>]",
115
+ summary: "the topology each task runs through: pick one, list them, draw it, or switch",
116
+ complete: (args, ctrl) => (args.length <= 1 ? ["list", "show", ...listRecipes().map((r) => r.id), ...topologyFiles(ctrl.workingDir)] : []),
117
+ run: async (args, ctrl) => {
118
+ let [what] = args;
119
+ if (!what) {
120
+ const items = [
121
+ ...listRecipes().map((r) => {
122
+ const consults = r.consults ?? [];
123
+ return { value: r.id, label: r.id, detail: `${r.nodes.length} role${r.nodes.length > 1 ? "s" : ""}${consults.length ? " + advisor" : ""} ∙ ${r.name}`, current: r.id === ctrl.settings.topology };
124
+ }),
125
+ ...topologyFiles(ctrl.workingDir).map((f) => ({ value: f, label: f, detail: "a definition file here", current: f === ctrl.settings.topology })),
126
+ ];
127
+ const chosen = await ctrl.pickOne("The topology the next task runs through", items);
128
+ if (!chosen)
129
+ return;
130
+ what = chosen;
131
+ }
132
+ if (what === "list") {
133
+ const all = listRecipes();
134
+ const idW = Math.max(...all.map((r) => len(r.id))) + 2;
135
+ const roles = (r) => `${r.nodes.length} role${r.nodes.length > 1 ? "s" : ""}`;
136
+ const rolesW = Math.max(...all.map((r) => len(roles(r)))) + 2;
137
+ const rows = all.map((r) => line([r.id === ctrl.topology?.id ? " ◉ " : " ", r.id === ctrl.topology?.id ? "run" : "faint"], [padCells(r.id, idW), "b"], [padCells(roles(r), rolesW), "dim"], [r.name, "ink"]));
138
+ rows.push(plain(" /topology picks one; /topology <id> switches; a .yaml or .json file works too", "faint"));
139
+ ctrl.info(rows, "topologies");
140
+ return;
141
+ }
142
+ if (what === "show") {
143
+ if (!ctrl.topology)
144
+ return;
145
+ const d = ctrl.drawingFor(ctrl.topology);
146
+ const width = Math.max(60, process.stdout.columns || 120);
147
+ const g = draw(d, initialRunState(0), layoutFor(d, width, { sight: false }), { sight: false, width });
148
+ ctrl.info([...toText(g).split("\n").map((l) => plain(l, "ink")), ...ctrl.topology.nodes.map((n) => plain(` ${ctrl.topology.faces[n.id]?.icon ?? ""} ${ctrl.topology.faces[n.id]?.sentence ?? ""}`, "dim"))], ctrl.topology.name);
149
+ return;
150
+ }
151
+ if (await ctrl.useTopology(what))
152
+ ctrl.info([line([" the next task runs through ", "dim"], [ctrl.topology.name, "b"], [` (${ctrl.topologySource})`, "faint"])], "topology");
153
+ },
154
+ },
155
+ {
156
+ name: "models",
157
+ usage: "/models [list|table|<role> <entry/model or brain>|default ...]",
158
+ summary: "a model or a brain per role, from any configured provider",
159
+ complete: async (args, ctrl) => {
160
+ if (args.length <= 1)
161
+ return ["list", "table", "default", ...roleIds(ctrl)];
162
+ const lists = await ctrl.models.list().catch(() => []);
163
+ return [...Object.keys(ctrl.models.brainsNow ?? {}), ...lists.flatMap((l) => l.models.map((m) => `${l.entry}/${m}`))];
164
+ },
165
+ run: async (args, ctrl) => {
166
+ let [what, ref] = args;
167
+ if (!what) {
168
+ const roles = roleItems(ctrl, true);
169
+ const role = await ctrl.pickOne("Whose model", roles);
170
+ if (!role)
171
+ return;
172
+ const current = role === "default" ? ctrl.modelOf("") : (ctrl.settings.roleModels[role] ?? ctrl.modelOf(role));
173
+ const items = await modelItems(ctrl, current);
174
+ if (!items.length)
175
+ return ctrl.say("error", "no model to choose from: /providers says why");
176
+ const chosen = await ctrl.pickOne(`The model or brain for ${roles.find((r) => r.value === role)?.label ?? role}`, items);
177
+ if (!chosen)
178
+ return;
179
+ [what, ref] = [role, chosen];
180
+ }
181
+ if (what === "table") {
182
+ ctrl.info([...roleTable(ctrl), plain(" /models picks; /models list shows what each provider has; /models <role> <entry/model> sets one", "faint")], "models");
183
+ return;
184
+ }
185
+ if (what === "list") {
186
+ const lists = await ctrl.models.list();
187
+ const rows = [];
188
+ for (const l of lists) {
189
+ rows.push(line([` ${l.entry}`, "b"], [l.error ? ` ${l.error}` : ` ${l.models.length} model${l.models.length === 1 ? "" : "s"}`, l.error ? "fail" : "dim"]));
190
+ for (const m of l.models.slice(0, 30))
191
+ rows.push(plain(` ${l.entry}/${m}`, "ink"));
192
+ }
193
+ ctrl.info(rows, "models, live");
194
+ return;
195
+ }
196
+ if (!ref) {
197
+ ctrl.say("error", `/models ${what} needs a model: <entry>/<model>, such as ${ctrl.models.defaultRef}`);
198
+ return;
199
+ }
200
+ try {
201
+ ctrl.models.provider(ref);
202
+ }
203
+ catch (e) {
204
+ ctrl.say("error", e.message);
205
+ return;
206
+ }
207
+ if (what === "default")
208
+ await ctrl.update({ defaultModel: ref });
209
+ else if (roleIds(ctrl).includes(what))
210
+ await ctrl.update({ roleModels: { ...ctrl.settings.roleModels, [what]: ref } });
211
+ else {
212
+ ctrl.say("error", `no role ${what} in ${ctrl.topology?.name ?? "this topology"}: ${roleIds(ctrl).join(", ")}`);
213
+ return;
214
+ }
215
+ ctrl.info(roleTable(ctrl), "models");
216
+ },
217
+ },
218
+ {
219
+ name: "tools",
220
+ usage: "/tools [list|on|off <tool>]",
221
+ summary: "each role's tools: a checklist per role, or one tool on or off for every role, for the session",
222
+ complete: (args) => (args.length <= 1 ? ["list", "on", "off"] : createDefaultToolkit().getAll().map((t) => t.definition.name)),
223
+ run: async (args, ctrl) => {
224
+ const [what, name] = args;
225
+ const all = createDefaultToolkit().getAll().map((t) => t.definition.name);
226
+ if (!what && ctrl.topology) {
227
+ const t = ctrl.topology;
228
+ const role = await ctrl.pickOne("Whose tools", t.nodes.map((n) => ({ value: n.id, label: t.faces[n.id]?.label ?? n.id, detail: (n.config.toolPolicy?.allow ?? n.config.enabledTools ?? all).filter((x) => !ctrl.settings.toolsOff.includes(x) && !(ctrl.settings.roleToolsOff?.[n.id] ?? []).includes(x)).join(", ") || "no tools" })));
229
+ if (!role)
230
+ return;
231
+ const node = t.nodes.find((n) => n.id === role);
232
+ const own = node.config.toolPolicy?.allow ?? node.config.enabledTools ?? all;
233
+ const offHere = ctrl.settings.roleToolsOff?.[role] ?? [];
234
+ const on = await ctrl.pick(`${t.faces[role]?.label ?? role}'s tools for this session`, own.map((x) => ({ value: x, label: x, ...(ctrl.settings.toolsOff.includes(x) ? { detail: "off for every role" } : {}) })), { multi: true, checked: own.filter((x) => !ctrl.settings.toolsOff.includes(x) && !offHere.includes(x)) });
235
+ if (!on)
236
+ return;
237
+ // A tool checked here that was off for every role comes back for this role only.
238
+ const roleToolsOff = { ...(ctrl.settings.roleToolsOff ?? {}) };
239
+ const revived = ctrl.settings.toolsOff.filter((x) => on.includes(x));
240
+ if (revived.length)
241
+ for (const n of t.nodes)
242
+ if (n.id !== role)
243
+ roleToolsOff[n.id] = [...new Set([...(roleToolsOff[n.id] ?? []), ...revived])];
244
+ roleToolsOff[role] = own.filter((x) => !on.includes(x));
245
+ await ctrl.update({ roleToolsOff, toolsOff: ctrl.settings.toolsOff.filter((x) => !revived.includes(x)) });
246
+ }
247
+ if ((what === "on" || what === "off") && name) {
248
+ if (!all.includes(name)) {
249
+ ctrl.say("error", `no tool ${name}: ${all.join(", ")}`);
250
+ return;
251
+ }
252
+ const off = new Set(ctrl.settings.toolsOff);
253
+ if (what === "off")
254
+ off.add(name);
255
+ else
256
+ off.delete(name);
257
+ await ctrl.update({ toolsOff: [...off] });
258
+ }
259
+ const t = ctrl.topology;
260
+ const rows = [];
261
+ for (const n of t?.nodes ?? []) {
262
+ const policy = n.config.toolPolicy;
263
+ const allowed = (policy?.allow ?? n.config.enabledTools ?? all).filter((x) => !ctrl.settings.toolsOff.includes(x) && !(ctrl.settings.roleToolsOff?.[n.id] ?? []).includes(x));
264
+ rows.push(line([` ${padCells(`${t.faces[n.id]?.icon ?? "◦"} ${t.faces[n.id]?.label ?? n.id}`, 12)} `, "b"], [allowed.length ? allowed.join(", ") : "no tools", allowed.length ? "ink" : "faint"]));
265
+ }
266
+ if (ctrl.settings.toolsOff.length)
267
+ rows.push(plain(` off for this session: ${ctrl.settings.toolsOff.join(", ")}`, "you"));
268
+ rows.push(plain(" reads inside the working directories and read-only commands run; a write or any other command asks you first (/permissions)", "faint"));
269
+ ctrl.info(rows, "tools");
270
+ },
271
+ },
272
+ {
273
+ name: "permissions",
274
+ usage: "/permissions [list|mode <mode>|allow|ask|deny|remove <rule>]",
275
+ summary: "the mode, the working directories and every rule, with the file it is in; add or remove a rule",
276
+ complete: (args, ctrl) => {
277
+ if (args.length <= 1)
278
+ return ["list", "allow", "ask", "deny", "remove", "mode"];
279
+ if (args[0] === "mode")
280
+ return ["default", "acceptEdits", "plan"];
281
+ if (args[0] === "remove")
282
+ return [...ctrl.permissions.rules.allow, ...ctrl.permissions.rules.ask, ...ctrl.permissions.rules.deny];
283
+ return ["Shell(", "Write(", "Read("];
284
+ },
285
+ run: async (args, ctrl, rest) => {
286
+ let [what] = args;
287
+ let rule = rest.slice(what?.length ?? 0).trim();
288
+ if (!what) {
289
+ const all = [...ctrl.permissions.rules.deny, ...ctrl.permissions.rules.ask, ...ctrl.permissions.rules.allow];
290
+ const choice = await ctrl.pickOne("Permissions", [
291
+ { value: "mode", label: "mode", detail: MODE_LABEL[ctrl.permissions.mode] },
292
+ { value: "remove", label: "remove rules", detail: all.length ? `${all.length} rule${all.length > 1 ? "s" : ""}` : "no rules yet" },
293
+ { value: "list", label: "show everything", detail: "the mode, the folders and every rule with its file" },
294
+ ]);
295
+ if (!choice)
296
+ return;
297
+ if (choice === "mode") {
298
+ const m = await ctrl.pickOne("The permission mode", ["default", "acceptEdits", "plan"].map((x) => ({ value: x, label: x, detail: MODE_LABEL[x], current: x === ctrl.permissions.mode })));
299
+ if (!m)
300
+ return;
301
+ [what, rule] = ["mode", m];
302
+ }
303
+ else if (choice === "remove") {
304
+ if (!all.length)
305
+ return ctrl.info([plain(" no rules to remove: /permissions allow|ask|deny <rule> adds one", "dim")], "permissions");
306
+ const sources = ruleSources(ctrl.workingDir);
307
+ const gone = await ctrl.pick("Rules to remove", all.map((r) => ({ value: r, label: r, detail: `${["deny", "ask", "allow"].find((k) => ctrl.permissions.rules[k].includes(r))} ∙ ${sources.find((x) => [...x.rules.allow, ...x.rules.ask, ...x.rules.deny].includes(r))?.label ?? "this session"}` })), { multi: true });
308
+ if (!gone?.length)
309
+ return;
310
+ for (const r of gone)
311
+ await commandNamed("permissions").run(["remove", ...r.split(/\s+/)], ctrl, `remove ${r}`);
312
+ return;
313
+ }
314
+ else
315
+ what = "list";
316
+ }
317
+ if (what === "list")
318
+ what = undefined;
319
+ if (what === "mode") {
320
+ if (!["default", "acceptEdits", "plan"].includes(rule)) {
321
+ ctrl.say("error", rule === "bypassPermissions" ? "bypass is only ever --dangerously-skip-permissions, for one session" : "a mode is default, acceptEdits or plan");
322
+ return;
323
+ }
324
+ ctrl.permissions.mode = rule;
325
+ }
326
+ else if (what === "allow" || what === "ask" || what === "deny") {
327
+ if (!parseRule(rule)) {
328
+ ctrl.say("error", `a rule is Shell(<command>), Write(<path>) or Read(<path>), as Shell(npm test *) or Read(./.env); not ${rule || "nothing"}`);
329
+ return;
330
+ }
331
+ saveLocalRules(ctrl.workingDir, { add: { list: what, rules: [rule] } });
332
+ if (!ctrl.permissions.rules[what].includes(rule))
333
+ ctrl.permissions.rules[what].push(rule);
334
+ }
335
+ else if (what === "remove") {
336
+ const from = ruleSources(ctrl.workingDir).filter((src) => src.label !== "local" && [...src.rules.allow, ...src.rules.ask, ...src.rules.deny].includes(rule));
337
+ saveLocalRules(ctrl.workingDir, { remove: rule });
338
+ for (const k of ["allow", "ask", "deny"])
339
+ ctrl.permissions.rules[k] = ctrl.permissions.rules[k].filter((r) => r !== rule || from.length > 0);
340
+ ctrl.grants.rules.splice(0, ctrl.grants.rules.length, ...ctrl.grants.rules.filter((r) => r !== rule));
341
+ if (from.length)
342
+ ctrl.say("error", `${rule} is also in ${from.map((f) => f.file).join(" and ")}: Jig changes only .jig/settings.local.json, so edit that file to remove it`);
343
+ }
344
+ else if (what) {
345
+ ctrl.say("error", "/permissions takes allow, ask, deny or remove and a rule, or mode and a mode");
346
+ return;
347
+ }
348
+ const rows = [line([" mode ", "faint"], [MODE_LABEL[ctrl.permissions.mode], "b"], [" (shift+tab cycles default, acceptEdits, plan)", "faint"])];
349
+ rows.push(line([" working directories ", "faint"], [ctrl.permissions.workingDirs.join(", "), "ink"]));
350
+ const sources = ruleSources(ctrl.workingDir);
351
+ const ruleW = Math.max(0, ...["deny", "ask", "allow"].flatMap((k) => ctrl.permissions.rules[k].map((r) => len(r))));
352
+ for (const k of ["deny", "ask", "allow"]) {
353
+ const all = ctrl.permissions.rules[k];
354
+ rows.push(plain(` ${k}${all.length ? "" : ": none"}`, "b"));
355
+ for (const r of all) {
356
+ const src = sources.find((x) => x.rules[k].includes(r));
357
+ rows.push(line([` ${padCells(r, ruleW)} `, "ink"], [src ? src.label : "this session (--allow or --deny)", "faint"]));
358
+ }
359
+ }
360
+ if (ctrl.grants.edits || ctrl.grants.rules.length) {
361
+ rows.push(plain(` for this session: ${[ctrl.grants.edits ? "all edits" : "", ...ctrl.grants.rules].filter(Boolean).join(" ∙ ")}`, "you"));
362
+ }
363
+ rows.push(plain(" deny wins over ask, and ask over allow, whichever file a rule is in; Jig writes only .jig/settings.local.json", "faint"));
364
+ ctrl.info(rows, "permissions");
365
+ },
366
+ },
367
+ {
368
+ name: "add-dir",
369
+ usage: "/add-dir <folder> [save]",
370
+ summary: "let roles read and write in another folder, for this session or saved for the project",
371
+ complete: (args, ctrl) => {
372
+ const word = args.at(-1) ?? "";
373
+ const dir = path.resolve(ctrl.workingDir, word.endsWith("/") ? word : path.dirname(word || "."));
374
+ try {
375
+ const base = word.endsWith("/") ? word : path.dirname(word) === "." && !word.startsWith(".") ? "" : `${path.dirname(word)}/`;
376
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => `${base}${e.name}/`);
377
+ }
378
+ catch {
379
+ return [];
380
+ }
381
+ },
382
+ run: (args, ctrl) => {
383
+ const [folder, save] = args;
384
+ if (!folder) {
385
+ ctrl.info([line([" working directories ", "faint"], [ctrl.permissions.workingDirs.join(", "), "ink"])], "add-dir");
386
+ return;
387
+ }
388
+ const dir = path.resolve(ctrl.workingDir, folder.replace(/^~(?=\/|$)/, homedir()));
389
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
390
+ ctrl.say("error", `${folder} is not a folder`);
391
+ return;
392
+ }
393
+ if (!ctrl.permissions.workingDirs.includes(dir))
394
+ ctrl.permissions.workingDirs.push(dir);
395
+ if (save === "save")
396
+ saveLocalRules(ctrl.workingDir, { addDir: dir });
397
+ ctrl.info([plain(` ${dir} is a working directory ${save === "save" ? "for this project (.jig/settings.local.json)" : "for this session"}: roles read there without asking, and writes there ask as they do here`, "ink")], "add-dir");
398
+ },
399
+ },
400
+ {
401
+ name: "sight",
402
+ usage: "/sight [all|<role>]",
403
+ summary: "what each role sees, measured with a mock model (no tokens)",
404
+ complete: (args, ctrl) => (args.length <= 1 ? ["all", ...roleIds(ctrl)] : []),
405
+ run: async (args, ctrl) => {
406
+ if (!ctrl.topology)
407
+ return;
408
+ let [which] = args;
409
+ if (!which) {
410
+ const chosen = await ctrl.pickOne("Whose sight", [{ value: "all", label: "every role", detail: "the topology with its walls" }, ...roleItems(ctrl, false).map((r) => ({ ...r, detail: "what it sees, row by row" }))]);
411
+ if (!chosen)
412
+ return;
413
+ which = chosen;
414
+ }
415
+ const sight = await measureSight(ctrl.configured(ctrl.topology));
416
+ if (which !== "all") {
417
+ const role = sight.roles.find((r) => r.id === which);
418
+ if (!role)
419
+ return ctrl.say("error", `no role ${which}: ${roleIds(ctrl).join(", ")}`);
420
+ const rows = sight.rows.map((row) => {
421
+ const cell = sight.cells[row.key]?.[role.id] ?? "none";
422
+ return line([cell === "none" ? " " : " ✓ ", cell === "none" ? "faint" : "b"], [padCells(row.label, 24), cell === "none" ? "faint" : "ink"], [SIGHT_SAYS[cell] ?? cell, "dim"]);
423
+ });
424
+ rows.push(plain(` ${role.turns} turn${role.turns === 1 ? "" : "s"}, ${role.calls} model call${role.calls === 1 ? "" : "s"} in the probe; tools: ${role.tools?.join(", ") || "none"}`, "faint"));
425
+ ctrl.info(rows, `what ${role.name} sees`);
426
+ return;
427
+ }
428
+ const d = drawingOf(ctrl.configured(ctrl.topology), { sight, source: ctrl.topologySource });
429
+ const width = Math.max(60, process.stdout.columns || 120);
430
+ const g = draw(d, initialRunState(0), layoutFor(d, width, { sight: true }), { sight: true, width });
431
+ ctrl.info(toText(g).split("\n").map((l) => plain(l, "ink")), `${ctrl.topology.name}: what each role sees`);
432
+ },
433
+ },
434
+ {
435
+ name: "checks",
436
+ usage: "/checks [add <command>|file <path>|clear]",
437
+ summary: "how the next task is checked: by the lab, where no role can write",
438
+ complete: (args) => (args.length <= 1 ? ["add", "file", "clear"] : []),
439
+ run: async (args, ctrl, rest) => {
440
+ const [what] = args;
441
+ if (what === "add") {
442
+ const command = rest.replace(/^\s*add\s+/, "").trim();
443
+ if (!command)
444
+ return ctrl.say("error", "/checks add needs a command that exits 0 when the task is done");
445
+ await ctrl.update({ checks: [...ctrl.settings.checks, { name: `check ${ctrl.settings.checks.length + 1}`, kind: "command", command }] });
446
+ }
447
+ else if (what === "file") {
448
+ const file = args[1];
449
+ if (!file || !existsSync(path.resolve(ctrl.workingDir, file)))
450
+ return ctrl.say("error", `/checks file needs a file in ${ctrl.workingDir}`);
451
+ await ctrl.update({ checkFiles: [...ctrl.settings.checkFiles, file] });
452
+ }
453
+ else if (what === "clear")
454
+ await ctrl.update({ checks: [], checkFiles: [] });
455
+ const rows = ctrl.settings.checks.map((c) => line([" ▪ ", "b"], [`${c.name}: `, "dim"], [c.kind === "command" ? c.command : c.kind, "ink"]));
456
+ for (const f of ctrl.settings.checkFiles)
457
+ rows.push(line([" ▪ ", "b"], ["copied back before each check: ", "dim"], [f, "ink"]));
458
+ rows.push(plain(rows.length ? " for the next task only: the lab runs them after it, and its outcome is theirs" : " no checks for the next task: /checks add <command>", "faint"));
459
+ ctrl.info(rows, "checks");
460
+ },
461
+ },
462
+ {
463
+ name: "budget",
464
+ usage: "/budget [<tokens>|off]",
465
+ summary: "the tokens one task may spend",
466
+ run: async (args, ctrl) => {
467
+ const [what] = args;
468
+ if (what === "off")
469
+ await ctrl.update({ tokenBudget: undefined });
470
+ else if (what) {
471
+ const n = Number(what.replace(/k$/i, "000").replace(/_/g, ""));
472
+ if (!(n > 0))
473
+ return ctrl.say("error", "/budget takes a number of tokens (40000 or 40k), or off");
474
+ await ctrl.update({ tokenBudget: Math.round(n) });
475
+ }
476
+ ctrl.info([plain(ctrl.settings.tokenBudget ? ` each task may spend ${shortTokens(ctrl.settings.tokenBudget)} tokens; then it stops` : " no token budget: a task stops at its round limit", "ink")], "budget");
477
+ },
478
+ },
479
+ {
480
+ name: "memory",
481
+ usage: "/memory [session|task|shared|run|off]",
482
+ summary: "how far back a run's recall reaches",
483
+ complete: () => MEMORY_SCOPES,
484
+ run: async (args, ctrl) => {
485
+ let [what] = args;
486
+ if (!what) {
487
+ const chosen = await ctrl.pickOne("How far recall reaches", MEMORY_SCOPES.map((m) => ({ value: m, label: m, detail: MEMORY_WORDS[m], current: m === ctrl.settings.memoryScope })));
488
+ if (!chosen)
489
+ return;
490
+ what = chosen;
491
+ }
492
+ if (what) {
493
+ if (!MEMORY_SCOPES.includes(what))
494
+ return ctrl.say("error", `/memory takes ${MEMORY_SCOPES.join(", ")}`);
495
+ await ctrl.update({ memoryScope: what });
496
+ }
497
+ ctrl.info([line([" recall reaches ", "dim"], [ctrl.settings.memoryScope, "b"], [`: ${MEMORY_WORDS[ctrl.settings.memoryScope]}`, "dim"])], "memory");
498
+ },
499
+ },
500
+ {
501
+ name: "advisor",
502
+ usage: "/advisor [model <entry/model>|limit <n>|sees <a,b>]",
503
+ summary: "the consulted role: its model, its limit a turn, what it sees",
504
+ complete: (args) => (args.length <= 1 ? ["model", "limit", "sees"] : args[0] === "sees" ? [...CONSULT_SIGHTS] : []),
505
+ run: async (args, ctrl) => {
506
+ const t = ctrl.topology;
507
+ if (!t?.consults.length) {
508
+ ctrl.info([plain(` ${t?.name ?? "This topology"} has no consult edge; /topology advisor has one (Do consults an Advisor)`, "dim")], "advisor");
509
+ return;
510
+ }
511
+ let [what, value] = args;
512
+ if (!what) {
513
+ const conf = ctrl.configured(t).consults[0];
514
+ const current = ctrl.settings.advisor.model ?? (conf.role.brain?.model ? `${conf.role.brain.provider}/${conf.role.brain.model}` : ctrl.modelOf(""));
515
+ const choice = await ctrl.pickOne(`${conf.role.face.label}, consulted by ${conf.from}`, [
516
+ { value: "model", label: "model", detail: current },
517
+ { value: "sees", label: "what it sees", detail: conf.sees.join(", ") },
518
+ ], { hint: "/advisor limit <n> sets its limit a turn" });
519
+ if (!choice)
520
+ return;
521
+ if (choice === "model") {
522
+ const chosen = await ctrl.pickOne(`The model or brain for ${conf.role.face.label}`, await modelItems(ctrl, current));
523
+ if (!chosen)
524
+ return;
525
+ [what, value] = ["model", chosen];
526
+ }
527
+ else {
528
+ const sees = await ctrl.pick(`What ${conf.role.face.label} sees`, CONSULT_SIGHTS.map((x) => ({ value: x, label: x })), { multi: true, checked: conf.sees });
529
+ if (!sees)
530
+ return;
531
+ if (!sees.length)
532
+ return ctrl.say("error", `${conf.role.face.label} has to see something: nothing was changed`);
533
+ [what, value] = ["sees", sees.join(",")];
534
+ }
535
+ }
536
+ if (what === "model" && value) {
537
+ try {
538
+ ctrl.models.provider(value);
539
+ }
540
+ catch (e) {
541
+ return ctrl.say("error", e.message);
542
+ }
543
+ await ctrl.update({ advisor: { ...ctrl.settings.advisor, model: value } });
544
+ }
545
+ else if (what === "limit" && value) {
546
+ const n = parseInt(value, 10);
547
+ if (!(n > 0))
548
+ return ctrl.say("error", "/advisor limit takes a number above 0");
549
+ await ctrl.update({ advisor: { ...ctrl.settings.advisor, limit: n } });
550
+ }
551
+ else if (what === "sees" && value) {
552
+ const sees = value.split(",").map((x) => x.trim());
553
+ const bad = sees.filter((x) => !CONSULT_SIGHTS.includes(x));
554
+ if (bad.length)
555
+ return ctrl.say("error", `/advisor sees takes ${CONSULT_SIGHTS.join(", ")}`);
556
+ await ctrl.update({ advisor: { ...ctrl.settings.advisor, sees } });
557
+ }
558
+ const conf = ctrl.configured(t);
559
+ const rows = conf.consults.map((c) => line([` ${c.role.face.icon} ${c.role.face.label} `, "b"], [`consulted by ${c.from}, at most ${c.limit} a turn, sees ${c.sees.join(", ")} ∙ `, "dim"], [c.role.brain?.model ? `${c.role.brain.provider}/${c.role.brain.model}` : ctrl.modelOf(""), "ink"]));
560
+ ctrl.info(rows, "advisor");
561
+ },
562
+ },
563
+ {
564
+ name: "providers",
565
+ usage: "/providers [list|discover|keep <name>|test [name]|add <name> ...|remove <name>]",
566
+ summary: "the provider entries, and the model servers found on this machine: where each is, where its key comes from (never the key)",
567
+ complete: (args, ctrl) => (args.length <= 1 ? ["list", "discover", "keep", "test", "add", "remove"] : ctrl.models.entries()),
568
+ run: async (args, ctrl) => {
569
+ let [what = "", name, ...rest] = args;
570
+ const models = ctrl.models;
571
+ if (!what) {
572
+ const states = models.states ?? [];
573
+ if (!states.length)
574
+ what = "list";
575
+ else {
576
+ const entry = await ctrl.pickOne("Which provider entry", states.map((st) => ({ value: st.entry.name, label: st.entry.name, detail: st.discovered ? `found on this machine: ${st.discovered.label} ∙ ${st.discovered.models.length} model${st.discovered.models.length === 1 ? "" : "s"} ∙ not kept` : `${st.entry.kind} ∙ ${st.entry.baseUrl ?? "its default address"} ∙ ${st.key ? `key from ${st.source}` : needsKey(st.entry) ? "no key" : "no key needed"}${st.live ? ` ∙ up, ${st.live.length} models` : ""}` })), { hint: "/providers add <name> adds one ∙ /providers discover asks this machine again" });
577
+ if (!entry)
578
+ return;
579
+ const found = states.find((st) => st.entry.name === entry)?.discovered;
580
+ const action = await ctrl.pickOne(entry, found
581
+ ? [
582
+ { value: "keep", label: "keep", detail: `write it to your config, so it is there in every session (${found.label})` },
583
+ { value: "ignore", label: "ignore", detail: "leave it out of this session" },
584
+ { value: "test", label: "test", detail: "one real call, timed" },
585
+ ]
586
+ : [
587
+ { value: "test", label: "test", detail: "one real call, timed" },
588
+ { value: "remove", label: "remove", detail: "take it out of your config (a key in the keychain stays there)" },
589
+ ]);
590
+ if (!action)
591
+ return;
592
+ if (action === "remove") {
593
+ const sure = await ctrl.pickOne(`Remove ${entry} from your config?`, [
594
+ { value: "no", label: "No, keep it" },
595
+ { value: "yes", label: `Yes, remove ${entry}` },
596
+ ]);
597
+ if (sure !== "yes")
598
+ return;
599
+ }
600
+ [what, name] = [action, entry];
601
+ }
602
+ }
603
+ const flag = (f) => {
604
+ const i = rest.indexOf(f);
605
+ return i >= 0 ? rest[i + 1] : undefined;
606
+ };
607
+ if (what === "discover") {
608
+ ctrl.info([plain(" asking this machine's model servers (127.0.0.1 only)", "faint")]);
609
+ await ctrl.discover();
610
+ what = "list";
611
+ }
612
+ else if (what === "keep") {
613
+ const st = (models.states ?? []).find((x) => x.entry.name === name && x.discovered);
614
+ if (!st)
615
+ return ctrl.say("error", `nothing discovered named ${name ?? ""}: /providers discover asks this machine again`);
616
+ saveEntry({ name: st.entry.name, kind: st.entry.kind, ...(st.entry.baseUrl ? { baseUrl: st.entry.baseUrl } : {}), ...(st.entry.defaultModel ? { defaultModel: st.entry.defaultModel } : {}) });
617
+ await ctrl.reload();
618
+ what = "list";
619
+ }
620
+ else if (what === "ignore") {
621
+ const i = (models.states ?? []).findIndex((x) => x.entry.name === name && x.discovered);
622
+ if (i >= 0)
623
+ models.states.splice(i, 1);
624
+ what = "list";
625
+ }
626
+ if (what === "test") {
627
+ if (!models.states)
628
+ return ctrl.say("error", "these models cannot be tested here");
629
+ for (const n of name ? [name] : ctrl.models.entries()) {
630
+ ctrl.info([line([" ⋯ ", "faint"], [`testing ${n}: one real call`, "dim"])]);
631
+ const r = await testOne(models, n, flag("--model"));
632
+ ctrl.info([line([r.ok ? " ✓ " : " ✗ ", r.ok ? "pass" : "fail"], [`${n} `, "b"], [r.ok ? `${r.ms} ms ∙ ${r.detail}` : r.detail, r.ok ? "dim" : "fail"])]);
633
+ }
634
+ return;
635
+ }
636
+ if (what === "add") {
637
+ if (!name)
638
+ return ctrl.say("error", "/providers add <name> [--kind k | --preset p] [--base-url u] [--key env:NAME | --key command:<program> | --keychain] [--default-model m]");
639
+ const preset = flag("--preset");
640
+ const kind = flag("--kind") ?? (preset ? "openai-compatible" : ENTRY_KINDS.includes(name) ? name : undefined);
641
+ if (!kind || !ENTRY_KINDS.includes(kind))
642
+ return ctrl.say("error", `--kind is one of ${ENTRY_KINDS.join(", ")}, or give --preset (${Object.keys(PRESETS).join(", ")})`);
643
+ let key = flag("--key");
644
+ if (key?.startsWith("command:"))
645
+ key = rest.slice(rest.indexOf("--key") + 1).join(" ").split(/ --(?:kind|preset|base-url|default-model)/)[0];
646
+ if (rest.includes("--keychain") || (!key && ["anthropic", "openai", "gemini", "openrouter"].includes(kind) && !preset)) {
647
+ // Typed without being shown, kept in the OS keychain, never in a file.
648
+ const typed = await ctrl.askSecret(`${name}'s key: type or paste it, it is not shown`);
649
+ if (!typed)
650
+ return ctrl.say("error", "no key: nothing was saved");
651
+ try {
652
+ storeInKeychain(name, typed);
653
+ }
654
+ catch (e) {
655
+ return ctrl.say("error", e.message);
656
+ }
657
+ key = "keychain";
658
+ }
659
+ try {
660
+ saveEntry({ name, kind, ...(preset ? { preset } : {}), ...(flag("--base-url") ? { baseUrl: flag("--base-url") } : {}), ...(key ? { key } : {}), ...(flag("--default-model") ? { defaultModel: flag("--default-model") } : {}) });
661
+ }
662
+ catch (e) {
663
+ return ctrl.say("error", e.message);
664
+ }
665
+ await ctrl.reload();
666
+ }
667
+ else if (what === "remove") {
668
+ if (!name || !removeEntry(name))
669
+ return ctrl.say("error", `no entry ${name ?? ""} in your config`);
670
+ await ctrl.reload();
671
+ }
672
+ const states = ctrl.models.states ?? [];
673
+ const rows = states.map((st) => line([` ${padCells(st.entry.name, 14)}`, "b"], [`${padCells(st.entry.kind, 18)} ${padCells(st.entry.baseUrl ?? "(its default)", 36)} `, "dim"], st.discovered
674
+ ? [`found on this machine (${st.discovered.label}), ${st.discovered.models.length} model${st.discovered.models.length === 1 ? "" : "s"}, not kept: /providers keep ${st.entry.name}`, "you"]
675
+ : [`${st.key ? `key from ${st.source}` : !needsKey(st.entry) && st.source === "none" ? "no key needed" : st.source === "none" ? "no key" : `no key in ${st.source}`}${st.live ? ` ∙ up, ${st.live.length} models` : ""}`, st.key || !needsKey(st.entry) ? "faint" : "fail"]));
676
+ const d = models.discovery;
677
+ rows.push(plain(d ? ` this machine: ${d.summary} (127.0.0.1 only; a server elsewhere is added by hand)` : " this machine has not been asked yet: /providers discover", "faint"));
678
+ for (const w of ctrl.models.warnings ?? [])
679
+ rows.push(line([" ! ", "you"], [w, "you"]));
680
+ rows.push(plain(` presets: ${Object.keys(PRESETS).join(", ")} ∙ /providers test <name> makes one real call`, "faint"));
681
+ ctrl.info(rows, "providers");
682
+ },
683
+ },
684
+ {
685
+ name: "brains",
686
+ usage: "/brains [list|set <name> <entry/model>...|test [name]]",
687
+ summary: "named chains of models; a role on a brain falls back only when a provider is unavailable",
688
+ complete: (args, ctrl) => (args.length <= 1 ? ["list", "set", "test"] : Object.keys(ctrl.models.brainsNow ?? {})),
689
+ run: async (args, ctrl) => {
690
+ let [what = "", name, ...chain] = args;
691
+ const models = ctrl.models;
692
+ if (!models.brainsNow)
693
+ return ctrl.say("error", "no brains here");
694
+ if (!what) {
695
+ const chosen = await ctrl.pickOne("Which brain to test: the model that would answer now", Object.entries(models.brainsNow).map(([b, c]) => ({ value: b, label: b, detail: c.join(" ⇢ ") || "no model in it" })), { hint: "/brains list prints them; /brains set <name> <model>... sets one" });
696
+ if (!chosen)
697
+ return;
698
+ [what, name] = ["test", chosen];
699
+ }
700
+ if (what === "set") {
701
+ if (!name || !chain.length)
702
+ return ctrl.say("error", "/brains set <name> <entry/model> [<entry/model>...]");
703
+ try {
704
+ saveBrain(name, chain);
705
+ }
706
+ catch (e) {
707
+ return ctrl.say("error", e.message);
708
+ }
709
+ await ctrl.reload();
710
+ }
711
+ const brains = ctrl.models.brainsNow;
712
+ const rows = [];
713
+ const brainW = Math.max(...Object.keys(brains).map((b) => len(b)));
714
+ for (const [b, c] of Object.entries(brains)) {
715
+ if (what === "test" && name && b !== name)
716
+ continue;
717
+ const now = what === "test" ? await resolveNow(ctrl.models, b) : null;
718
+ rows.push(line([` ${padCells(b, brainW)} `, "b"], [c.join(" ⇢ "), "ink"]));
719
+ if (now)
720
+ rows.push(line([now.answers ? " ✓ " : " ✗ ", now.answers ? "pass" : "fail"], [now.answers ? `${now.answers} would answer now` : "nothing in it answers now", "dim"], [now.notes.length ? ` (${now.notes.join("; ")})` : "", "faint"]));
721
+ }
722
+ rows.push(plain(" /models <role> <brain> puts a role on one ∙ /brains test says which model would answer now", "faint"));
723
+ ctrl.info(rows, "brains");
724
+ },
725
+ },
726
+ {
727
+ name: "runs",
728
+ usage: "/runs [list]",
729
+ summary: "the runs kept in this working directory: pick one to replay, or list them",
730
+ complete: (args) => (args.length <= 1 ? ["list"] : []),
731
+ run: async (args, ctrl) => {
732
+ if (!args[0]) {
733
+ const id = await pickRun(ctrl, "A past run to replay, newest first");
734
+ if (id)
735
+ await commandNamed("replay").run([id], ctrl, id);
736
+ return;
737
+ }
738
+ const runs = await ctrl.pastRuns();
739
+ if (!runs.length)
740
+ return ctrl.info([plain(" no recorded runs here yet", "dim")], "runs");
741
+ ctrl.info([
742
+ ...runs.map((r) => {
743
+ const mark = r.outcome === "passed" ? "✓" : r.outcome === "failed" ? "✗" : "▪";
744
+ const k = r.outcome === "passed" ? "pass" : r.outcome === "failed" ? "fail" : "dim";
745
+ return line([` ${mark} `, k], [`${r.runId} `, "b"], [`${padCells(r.topology, 18)} `, "dim"], [(r.task ?? "").replace(/\s+/g, " ").slice(0, 60), "ink"]);
746
+ }),
747
+ plain(" /runs picks one to replay ∙ /replay <run-id> plays one here", "faint"),
748
+ ], "runs");
749
+ },
750
+ },
751
+ {
752
+ name: "replay",
753
+ usage: "/replay [<run-id>|last] [speed]",
754
+ summary: "play a past run on this screen, from its step records: pick one, or name it",
755
+ complete: async (_args, ctrl) => ["last", ...(await ctrl.pastRuns(30)).map((r) => r.runId)],
756
+ run: async (args, ctrl) => {
757
+ const [runId, speed] = args;
758
+ const id = !runId ? await pickRun(ctrl, "A past run to replay, newest first") : runId === "last" ? (await ctrl.pastRuns(1))[0]?.runId : runId;
759
+ if (!id)
760
+ return runId ? ctrl.say("error", "no recorded run to replay: /runs lists them") : undefined;
761
+ try {
762
+ await ctrl.openReplay(id, speed ? Math.max(0.1, Number(speed)) || 4 : 4);
763
+ }
764
+ catch (e) {
765
+ ctrl.say("error", e.message);
766
+ }
767
+ },
768
+ },
769
+ {
770
+ name: "clear",
771
+ usage: "/clear",
772
+ summary: "start the conversation again; settings stay",
773
+ run: async (_args, ctrl) => {
774
+ await ctrl.clear();
775
+ },
776
+ },
777
+ {
778
+ name: "quit",
779
+ usage: "/quit",
780
+ summary: "leave; jig --resume opens this session again",
781
+ run: (_args, ctrl) => {
782
+ ctrl.emit("exit");
783
+ },
784
+ },
785
+ ];
786
+ export const commandNamed = (name) => COMMANDS.find((c) => c.name === name || (name === "exit" && c.name === "quit"));
787
+ /** Split a slash command into its name, words and the text after the name. */
788
+ export function parseSlash(text) {
789
+ const body = text.trim().slice(1);
790
+ const name = body.split(/\s+/)[0] ?? "";
791
+ const rest = body.slice(name.length).trim();
792
+ return { name, args: rest ? rest.split(/\s+/) : [], rest };
793
+ }
794
+ /** Completions for what is typed: command names, then a command's arguments. */
795
+ export async function completions(text, ctrl) {
796
+ if (!text.startsWith("/") || text.includes("\n"))
797
+ return { items: [], word: "" };
798
+ const hasSpace = /\s/.test(text);
799
+ if (!hasSpace) {
800
+ const word = text.slice(1);
801
+ return { items: COMMANDS.map((c) => c.name).filter((n) => n.startsWith(word)), word };
802
+ }
803
+ const { name, args } = parseSlash(text);
804
+ const cmd = commandNamed(name);
805
+ if (!cmd?.complete)
806
+ return { items: [], word: "" };
807
+ const endsWithSpace = /\s$/.test(text);
808
+ const word = endsWithSpace ? "" : (args.at(-1) ?? "");
809
+ const before = endsWithSpace ? args : args.slice(0, -1);
810
+ const all = await cmd.complete([...before, word], ctrl);
811
+ return { items: [...new Set(all)].filter((x) => x.startsWith(word) && x !== word).slice(0, 40), word };
812
+ }
813
+ /** Run a slash command; an unknown one says so. */
814
+ export async function runSlash(text, ctrl) {
815
+ const { name, args, rest } = parseSlash(text);
816
+ const cmd = commandNamed(name);
817
+ if (!cmd) {
818
+ ctrl.say("error", `no command /${name}: /help lists them`);
819
+ return;
820
+ }
821
+ try {
822
+ await cmd.run(args, ctrl, rest);
823
+ }
824
+ catch (e) {
825
+ ctrl.say("error", `/${name}: ${e.message}`);
826
+ }
827
+ }
828
+ //# sourceMappingURL=commands.js.map