@osdlc/wayfinder 0.7.3 → 0.8.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.
Files changed (121) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/CONTRIBUTING.md +6 -0
  3. package/README.md +295 -150
  4. package/SECURITY.md +19 -5
  5. package/dist/actions.d.ts +23 -0
  6. package/dist/actions.js +97 -0
  7. package/dist/app.d.ts +1 -13
  8. package/dist/app.js +1 -13
  9. package/dist/args.d.ts +11 -6
  10. package/dist/args.js +25 -7
  11. package/dist/cache.d.ts +2 -4
  12. package/dist/cache.js +5 -10
  13. package/dist/catalog.d.ts +30 -3
  14. package/dist/catalog.js +87 -11
  15. package/dist/clean-command.d.ts +65 -36
  16. package/dist/clean-command.js +372 -226
  17. package/dist/cli.d.ts +24 -57
  18. package/dist/cli.js +139 -568
  19. package/dist/commands/browse.d.ts +128 -0
  20. package/dist/commands/browse.js +151 -0
  21. package/dist/commands/index.d.ts +25 -0
  22. package/dist/commands/index.js +71 -0
  23. package/dist/commands/list.d.ts +208 -0
  24. package/dist/commands/list.js +127 -0
  25. package/dist/commands/query.d.ts +166 -0
  26. package/dist/commands/query.js +73 -0
  27. package/dist/commands/run.d.ts +114 -0
  28. package/dist/commands/run.js +139 -0
  29. package/dist/commands/shared.d.ts +152 -0
  30. package/dist/commands/shared.js +209 -0
  31. package/dist/config-command.d.ts +27 -43
  32. package/dist/config-command.js +129 -330
  33. package/dist/config-keys.d.ts +25 -0
  34. package/dist/config-keys.js +29 -0
  35. package/dist/config.d.ts +271 -257
  36. package/dist/config.js +610 -460
  37. package/dist/core/copy-text.d.ts +30 -0
  38. package/dist/core/copy-text.js +50 -0
  39. package/dist/core/filter.d.ts +55 -0
  40. package/dist/core/filter.js +59 -0
  41. package/dist/core/run.d.ts +22 -0
  42. package/dist/core/run.js +59 -0
  43. package/dist/core/saved-view.d.ts +59 -0
  44. package/dist/core/saved-view.js +119 -0
  45. package/dist/core/session.d.ts +262 -0
  46. package/dist/core/session.js +589 -0
  47. package/dist/core/skills.d.ts +53 -0
  48. package/dist/core/skills.js +54 -0
  49. package/dist/core/unknowns.d.ts +72 -0
  50. package/dist/core/unknowns.js +68 -0
  51. package/dist/devlink.d.ts +3 -0
  52. package/dist/devlink.js +5 -2
  53. package/dist/document-schemas.generated.d.ts +22 -0
  54. package/dist/document-schemas.generated.js +916 -0
  55. package/dist/documents.d.ts +432 -0
  56. package/dist/documents.js +163 -0
  57. package/dist/groups.d.ts +22 -26
  58. package/dist/groups.js +13 -29
  59. package/dist/guide.d.ts +26 -13
  60. package/dist/guide.js +119 -103
  61. package/dist/index.d.ts +112 -0
  62. package/dist/index.js +58 -0
  63. package/dist/keys.d.ts +51 -0
  64. package/dist/keys.js +273 -0
  65. package/dist/page.d.ts +18 -8
  66. package/dist/page.js +28 -17
  67. package/dist/providers-command.d.ts +81 -20
  68. package/dist/providers-command.js +33 -75
  69. package/dist/schema.d.ts +48 -0
  70. package/dist/schema.js +61 -0
  71. package/dist/serve/auth.d.ts +46 -0
  72. package/dist/serve/auth.js +82 -0
  73. package/dist/serve/catalog-share.d.ts +51 -0
  74. package/dist/serve/catalog-share.js +116 -0
  75. package/dist/serve/index.d.ts +98 -0
  76. package/dist/serve/index.js +251 -0
  77. package/dist/serve/routes.d.ts +60 -0
  78. package/dist/serve/routes.js +186 -0
  79. package/dist/serve/terminal-input.d.ts +50 -0
  80. package/dist/serve/terminal-input.js +108 -0
  81. package/dist/skills.d.ts +19 -0
  82. package/dist/skills.js +54 -0
  83. package/dist/terminal-text.d.ts +8 -0
  84. package/dist/terminal-text.js +19 -6
  85. package/dist/tool-info.d.ts +24 -0
  86. package/dist/tool-info.js +17 -0
  87. package/dist/trust-command.d.ts +15 -27
  88. package/dist/trust-command.js +110 -208
  89. package/dist/trust-store.d.ts +5 -10
  90. package/dist/trust-store.js +9 -42
  91. package/dist/tui/app.d.ts +180 -0
  92. package/dist/tui/app.js +1278 -0
  93. package/dist/tui/copy.d.ts +29 -0
  94. package/dist/tui/copy.js +39 -0
  95. package/dist/tui/index.d.ts +33 -0
  96. package/dist/tui/index.js +97 -0
  97. package/dist/tui/keys-input.d.ts +27 -0
  98. package/dist/tui/keys-input.js +87 -0
  99. package/dist/tui/settings.d.ts +94 -0
  100. package/dist/tui/settings.js +198 -0
  101. package/dist/tui/style.d.ts +62 -0
  102. package/dist/tui/style.js +77 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +7 -0
  105. package/dist/vocabulary.d.ts +89 -0
  106. package/dist/vocabulary.js +153 -0
  107. package/dist/web/main.js +1965 -568
  108. package/dist/web/page.html +39 -33
  109. package/dist/web/styles.css +457 -329
  110. package/dist/xdg.d.ts +76 -4
  111. package/dist/xdg.js +77 -5
  112. package/package.json +28 -9
  113. package/schema/config.json +133 -0
  114. package/dist/http.d.ts +0 -22
  115. package/dist/http.js +0 -149
  116. package/dist/origin-owner.d.ts +0 -19
  117. package/dist/origin-owner.js +0 -85
  118. package/dist/serve.d.ts +0 -98
  119. package/dist/serve.js +0 -671
  120. package/dist/tui.d.ts +0 -177
  121. package/dist/tui.js +0 -840
@@ -0,0 +1,589 @@
1
+ /**
2
+ * The session core: what one run of wayfinder knows about one repository,
3
+ * and the operations every surface shares. See `README.md` beside this file
4
+ * for how the CLI, the terminal UI and the web view use it.
5
+ */
6
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
7
+ import { commandString } from '@osdlc/command-seam/quote';
8
+ import { closestMatches } from '@osdlc/config-layers/did-you-mean';
9
+ import { homeDir, parseTrustScope, policyExecGate, withheldHint, } from '@osdlc/trust-repo';
10
+ import { BIN, PROJECT_CONFIG_FILENAME } from "../app.js";
11
+ import { cacheDir } from "../cache.js";
12
+ import { settingLayer } from "../config-keys.js";
13
+ import { collectAndCache, fromStore, makeProject, orderedCatalog, projectRootFor, readCachedCatalog, runnerIds, } from "../catalog.js";
14
+ import { ConfigError, collectOptionsFromConfig, readSettings, trustPolicyFromConfig, writeSetting, trustPolicyOptions, } from "../config.js";
15
+ import { readSkills } from "../skills.js";
16
+ import { toolSummary } from "../tool-info.js";
17
+ import { VERSION } from "../version.js";
18
+ import { loadTools, ToolModuleError } from "../tools.js";
19
+ import { appTrustStore } from "../trust-store.js";
20
+ import { EDITOR_VARIABLE_LABEL } from "../vocabulary.js";
21
+ import { taskCopyText } from "./copy-text.js";
22
+ import { filterTasks } from "./filter.js";
23
+ import { readView, viewKey, writeView } from "./saved-view.js";
24
+ import { filterSkills } from "./skills.js";
25
+ import { execOffSource, unknownsOf } from "./unknowns.js";
26
+ /**
27
+ * Why a session could not start, or an operation was refused. `code` is
28
+ * stable, for an error document.
29
+ */
30
+ export class SessionError extends Error {
31
+ code;
32
+ /** A sentence on what to do, when there is one. */
33
+ hint;
34
+ constructor(code, message, hint) {
35
+ super(message);
36
+ this.name = 'SessionError';
37
+ this.code = code;
38
+ this.hint = hint;
39
+ }
40
+ }
41
+ /**
42
+ * Load the tool modules this run names and build the project over them.
43
+ * Throws {@link SessionError} `tool-module` when a module cannot be used.
44
+ */
45
+ async function projectFor(toolModules, cfg, cwd, home, projectAllowed) {
46
+ let loaded;
47
+ try {
48
+ loaded = await loadTools({ flag: toolModules, cwd, config: cfg, home, projectAllowed });
49
+ }
50
+ catch (err) {
51
+ if (err instanceof ToolModuleError)
52
+ throw new SessionError('tool-module', err.message);
53
+ throw err;
54
+ }
55
+ try {
56
+ return { project: makeProject(loaded.tools.map((t) => t.def)), ...loaded };
57
+ }
58
+ catch (err) {
59
+ // Every tool here passed loadTools, so a registry refusal (such as an
60
+ // ecosystem id a built-in already uses) comes from the modules.
61
+ const modules = [...new Set(loaded.tools.map((t) => t.module))].join(', ');
62
+ const message = err instanceof Error ? err.message : String(err);
63
+ throw new SessionError('tool-module', `${message} (from a tool module: ${modules})`);
64
+ }
65
+ }
66
+ /**
67
+ * Every scope a tool grant can name for `project`: each runner's id, and
68
+ * each tool manager that wraps commands (`mise exec`), since a runner it
69
+ * wraps needs it trusted too.
70
+ */
71
+ function toolTrustScopes(project) {
72
+ const wrappers = project.tools.filter((t) => t.roles.toolManager?.exec !== undefined);
73
+ return [...new Set([...runnerIds(project), ...wrappers.map((t) => t.id)])];
74
+ }
75
+ /** `opts` with an `ownerOf` that runs git at most once per root. */
76
+ function onceOwner(opts) {
77
+ const ownerOf = opts.ownerOf;
78
+ if (ownerOf === undefined)
79
+ return opts;
80
+ const seen = new Map();
81
+ return {
82
+ ...opts,
83
+ ownerOf: (root) => {
84
+ let owner = seen.get(root);
85
+ if (owner === undefined) {
86
+ owner = ownerOf(root);
87
+ seen.set(root, owner);
88
+ }
89
+ return owner;
90
+ },
91
+ };
92
+ }
93
+ /** A scope a person typed, checked as `way trust --scope` checks it. */
94
+ function parseScope(scope) {
95
+ try {
96
+ return parseTrustScope(scope);
97
+ }
98
+ catch (err) {
99
+ throw new SessionError('bad-arguments', err instanceof Error ? err.message : String(err));
100
+ }
101
+ }
102
+ /** The collect option a flag sets, for each setting a settings screen saves. */
103
+ const FLAG_OF_SETTING = {
104
+ 'runners.disabled': 'exclude',
105
+ discovery: 'discovery',
106
+ excludePaths: 'excludePaths',
107
+ };
108
+ /** A config error as a session error; anything else unchanged. */
109
+ function asSessionError(err, prefix = '') {
110
+ if (err instanceof ConfigError)
111
+ return new SessionError('config', prefix + err.message);
112
+ return err;
113
+ }
114
+ /** Fresh states for a catalog probed just now, with each runner's measured time. */
115
+ function probedStates(catalog, times) {
116
+ return catalog.reports.map((r) => {
117
+ const probeMs = times.get(r.runner);
118
+ return {
119
+ runner: r.runner,
120
+ state: 'fresh',
121
+ ageMs: 0,
122
+ estimateMs: probeMs ?? null,
123
+ slow: false,
124
+ ...(probeMs !== undefined ? { probeMs } : {}),
125
+ };
126
+ });
127
+ }
128
+ /**
129
+ * Start a session: find the root, load config, decide execution against the
130
+ * trust store, and load tool modules. Throws {@link SessionError} for a start
131
+ * directory that does not exist, a config file that cannot be used, or a tool
132
+ * module that cannot be loaded.
133
+ */
134
+ export async function createSession(opts) {
135
+ const env = opts.env;
136
+ const home = opts.home ?? homeDir();
137
+ const flags = opts.flags ?? {};
138
+ const start = isAbsolute(opts.dir) ? opts.dir : resolve(opts.cwd, opts.dir);
139
+ const root = await projectRootFor(start);
140
+ if (root === null) {
141
+ throw new SessionError('no-such-directory', `${opts.dir}: no such directory`);
142
+ }
143
+ let settings;
144
+ try {
145
+ settings = await readSettings(root, env, home);
146
+ }
147
+ catch (err) {
148
+ throw asSessionError(err);
149
+ }
150
+ const config = settings.loaded;
151
+ // Precedence for allowExec, highest first: --exec / --no-exec, then
152
+ // allowExec in the project file (false only), then the user file, then
153
+ // the built-in default (true). Trust is decided here; collection never
154
+ // reads the trust store.
155
+ const configured = settings.allowExec.value;
156
+ const trustStore = appTrustStore({ env, home });
157
+ const policy = trustPolicyFromConfig(config.effective);
158
+ const policyOptions = onceOwner(trustPolicyOptions(home));
159
+ let gate = await policyExecGate(trustStore, policy, { root, configured, flag: flags.allowExec }, policyOptions);
160
+ // A project module runs code on import, so it needs execution allowed as
161
+ // well as trust.
162
+ const projectAllowed = gate.trusted && gate.allowExec;
163
+ const built = await projectFor(flags.toolModules ?? [], config, opts.cwd, home, projectAllowed);
164
+ const projectToolsPending = !projectAllowed && (config.layers.project?.tools?.length ?? 0) > 0;
165
+ // The config's own allowExec was consumed by the gate.
166
+ const { allowExec: _consumed, ...configOptions } = collectOptionsFromConfig(config.effective);
167
+ // Config first, flags second. --exclude REPLACES runners.disabled.
168
+ const options = {
169
+ ...configOptions,
170
+ allowExec: gate.allowExec,
171
+ // Only when trust is what is missing: when a file turned execution off,
172
+ // trusting the repository would change nothing.
173
+ ...(gate.reason === 'untrusted' ? { execWithheldHint: withheldHint(BIN) } : {}),
174
+ ...(flags.only ? { only: flags.only } : {}),
175
+ ...(flags.exclude ? { exclude: flags.exclude } : {}),
176
+ ...(flags.excludePaths ? { excludePaths: flags.excludePaths } : {}),
177
+ ...(flags.discovery !== undefined ? { discovery: flags.discovery } : {}),
178
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
179
+ };
180
+ const pinnedByFlag = [
181
+ ...(flags.exclude ? ['exclude'] : []),
182
+ ...(flags.excludePaths ? ['excludePaths'] : []),
183
+ ...(flags.discovery !== undefined ? ['discovery'] : []),
184
+ ];
185
+ // Per-tool trust applies only when the repository's own trust is what
186
+ // withholds execution. The set is read on every probe, so a tool grant in
187
+ // this session applies to the next one.
188
+ const toolTrusted = new Set();
189
+ let scopesByRunner = new Map();
190
+ const toolScopes = gate.reason === 'untrusted' ? toolTrustScopes(built.project) : [];
191
+ const decideTools = async () => {
192
+ toolTrusted.clear();
193
+ if (toolScopes.length === 0)
194
+ return;
195
+ const decided = await policyExecGate(trustStore, policy, { root, configured: true, scopes: toolScopes }, policyOptions);
196
+ for (const [scope, d] of Object.entries(decided.decisions))
197
+ if (d.trusted)
198
+ toolTrusted.add(scope);
199
+ };
200
+ await decideTools();
201
+ if (toolScopes.length > 0) {
202
+ options.toolTrust = {
203
+ trusted: toolTrusted,
204
+ onScopes: (scopes) => {
205
+ scopesByRunner = scopes;
206
+ },
207
+ };
208
+ }
209
+ const skills = () => readSkills(root, { setting: settings.skills.value, home, env, signal: opts.signal });
210
+ const store = cacheDir(env, home);
211
+ const runnerOrder = () => settings.loaded.effective.runners?.order;
212
+ /** Take `next` as the settings: the collect options follow, except where a flag decided. */
213
+ const adopt = (next) => {
214
+ settings = next;
215
+ const derived = collectOptionsFromConfig(next.loaded.effective);
216
+ const target = options;
217
+ for (const key of ['exclude', 'discovery', 'excludePaths']) {
218
+ if (pinnedByFlag.includes(key))
219
+ continue;
220
+ if (derived[key] === undefined)
221
+ delete target[key];
222
+ else
223
+ target[key] = derived[key];
224
+ }
225
+ };
226
+ const reread = async (prefix = '') => {
227
+ try {
228
+ adopt(await readSettings(root, env, home));
229
+ }
230
+ catch (err) {
231
+ throw asSessionError(err, prefix);
232
+ }
233
+ };
234
+ const trustable = () => options.execWithheldHint !== undefined;
235
+ /** The options, stopped by this call's `signal` as well as the session's. */
236
+ const withSignal = (signal) => {
237
+ const signals = [options.signal, signal].filter((s) => s !== undefined);
238
+ return signals.length > 0 ? { ...options, signal: AbortSignal.any(signals) } : options;
239
+ };
240
+ /** Probe the runners `only` names (all when absent), timing each. */
241
+ const probe = async (only, signal) => {
242
+ const times = new Map();
243
+ const catalog = await collectAndCache(project, root, {
244
+ ...withSignal(signal),
245
+ ...(only !== undefined ? { only } : {}),
246
+ onProbe: ({ runner, durationMs }) => times.set(runner, durationMs),
247
+ }, store);
248
+ return { catalog, times };
249
+ };
250
+ const { project, tools } = built;
251
+ /** What decides which rows a probe returns; a saved view is used only under the same key. */
252
+ const currentViewKey = () => viewKey({
253
+ version: VERSION,
254
+ root,
255
+ allowExec: options.allowExec ?? false,
256
+ withheldHint: options.execWithheldHint !== undefined,
257
+ toolTrusted: [...toolTrusted].sort(),
258
+ only: options.only ?? null,
259
+ exclude: options.exclude ?? null,
260
+ discovery: options.discovery ?? null,
261
+ excludePaths: options.excludePaths ?? null,
262
+ skills: settings.skills.value,
263
+ tools: project.tools.map((t) => t.id),
264
+ });
265
+ /** Save `snapshot` as the view a first paint draws, without waiting, and return it. */
266
+ const saved = (snapshot) => {
267
+ void writeView(store, {
268
+ key: currentViewKey(),
269
+ savedAt: Date.now(),
270
+ catalog: snapshot.catalog,
271
+ cache: snapshot.cache.map(({ probeMs: _probeMs, ...rest }) => rest),
272
+ skills: snapshot.skills,
273
+ scopes: Object.fromEntries([...scopesByRunner].map(([r, s]) => [r, [...s]])),
274
+ });
275
+ return snapshot;
276
+ };
277
+ const session = {
278
+ root,
279
+ get config() {
280
+ return settings.loaded;
281
+ },
282
+ warnings: [...config.warnings, ...built.warnings],
283
+ get gate() {
284
+ return gate;
285
+ },
286
+ project,
287
+ tools,
288
+ options,
289
+ projectToolsPending,
290
+ pinnedByFlag,
291
+ store,
292
+ env,
293
+ home,
294
+ runnerOrder,
295
+ withheldReason() {
296
+ if (gate.allowExec)
297
+ return null;
298
+ return gate.reason === 'untrusted' ? 'untrusted' : 'exec-off';
299
+ },
300
+ async catalog(opts = {}) {
301
+ if (opts.cached !== true) {
302
+ const { catalog, times } = await probe(undefined, opts.signal);
303
+ return saved({
304
+ catalog: orderedCatalog(catalog, runnerOrder()),
305
+ cache: probedStates(catalog, times),
306
+ skills: await skills(),
307
+ origin: 'probe',
308
+ });
309
+ }
310
+ const view = await session.savedCatalog();
311
+ if (view !== null)
312
+ return view;
313
+ // The call's signal too: a closed tab stops hashing the store.
314
+ const stored = await readCachedCatalog(project, root, withSignal(opts.signal), store);
315
+ if (stored.catalog === null || !fromStore(stored)) {
316
+ const { catalog, times } = await probe(undefined, opts.signal);
317
+ return saved({
318
+ catalog: orderedCatalog(catalog, runnerOrder()),
319
+ cache: probedStates(catalog, times),
320
+ skills: await skills(),
321
+ origin: 'empty-store',
322
+ });
323
+ }
324
+ // A miss is a runner with nothing stored. Only the missing runners are probed.
325
+ const missing = stored.runners.filter((r) => r.state === 'miss').map((r) => r.runner);
326
+ if (missing.length === 0) {
327
+ return saved({
328
+ catalog: orderedCatalog(stored.catalog, runnerOrder()),
329
+ cache: stored.runners,
330
+ skills: await skills(),
331
+ origin: 'store',
332
+ });
333
+ }
334
+ const { catalog: probed, times } = await probe(missing, opts.signal);
335
+ const fresh = new Map(probedStates(probed, times).map((s) => [s.runner, s]));
336
+ return saved({
337
+ catalog: orderedCatalog({ ...stored.catalog, reports: [...stored.catalog.reports, ...probed.reports] }, runnerOrder()),
338
+ cache: stored.runners.map((r) => fresh.get(r.runner) ?? r),
339
+ skills: await skills(),
340
+ origin: 'store',
341
+ });
342
+ },
343
+ async storedCatalog() {
344
+ const stored = await readCachedCatalog(project, root, options, store);
345
+ if (stored.catalog === null || !fromStore(stored))
346
+ return null;
347
+ return {
348
+ catalog: orderedCatalog(stored.catalog, runnerOrder()),
349
+ cache: stored.runners,
350
+ skills: await skills(),
351
+ origin: 'store',
352
+ };
353
+ },
354
+ viewKey: currentViewKey,
355
+ async savedCatalog() {
356
+ try {
357
+ const view = await readView(store, root, currentViewKey());
358
+ if (view === null)
359
+ return null;
360
+ // The withheld unknowns name the scopes each runner needs, which a
361
+ // probe would have reported. Only runner ids this session knows.
362
+ if (toolScopes.length > 0) {
363
+ const known = new Set(toolScopes);
364
+ scopesByRunner = new Map(Object.entries(view.scopes)
365
+ .filter(([runner]) => known.has(runner))
366
+ .map(([runner, scopes]) => [runner, scopes.filter((s) => known.has(s))]));
367
+ }
368
+ const since = Math.max(0, Date.now() - view.savedAt);
369
+ return {
370
+ catalog: orderedCatalog(view.catalog, runnerOrder()),
371
+ cache: view.cache.map((r) => r.state === 'miss' ? r : { ...r, ageMs: (r.ageMs ?? 0) + since }),
372
+ skills: view.skills,
373
+ origin: 'saved',
374
+ };
375
+ }
376
+ catch {
377
+ return null;
378
+ }
379
+ },
380
+ async confirmRun(plan, args = [], signal) {
381
+ const { catalog } = await probe([plan.task.runner], signal);
382
+ const shown = plan.task.display;
383
+ const report = catalog.reports.find((r) => r.runner === plan.task.runner);
384
+ const now = report?.tasks.filter((t) => t.id === plan.task.id) ?? [];
385
+ // A runner that failed, was withheld, or lost the task with a complaint
386
+ // (an unparseable file) did not read the task's file cleanly.
387
+ const complaint = report?.diagnostics.find((d) => d.severity !== 'info');
388
+ const failed = report === undefined ||
389
+ report.status === 'error' ||
390
+ report.skippedForExec ||
391
+ (now.length !== 1 && complaint !== undefined);
392
+ if (failed) {
393
+ const why = complaint === undefined ? '' : ` (${complaint.message})`;
394
+ throw new SessionError('task-changed', `${shown}: not run; ${plan.task.runner} could not be read again${why}`, `"${BIN} list" shows what it reports now`);
395
+ }
396
+ if (now.length !== 1) {
397
+ throw new SessionError('task-changed', `${shown}: not found when ${plan.task.runner} was read again; ` +
398
+ 'the listing it came from is out of date', `"${BIN} list" shows the tasks now`);
399
+ }
400
+ const task = now[0];
401
+ const same = task.cwd === plan.task.cwd &&
402
+ task.argv.length === plan.task.argv.length &&
403
+ task.argv.every((a, i) => a === plan.task.argv[i]);
404
+ if (!same) {
405
+ const line = taskCopyText(task, process.platform) ?? commandString(task.argv);
406
+ throw new SessionError('task-changed', `${shown}: changed since the listing it came from; it now runs: ${line}`, 'nothing ran; run it again to run the new command');
407
+ }
408
+ return resolveRun(project, root, catalog, task.id, args);
409
+ },
410
+ search(catalog, filter) {
411
+ return filterTasks(catalog.reports, filter);
412
+ },
413
+ searchSkills(list, filter) {
414
+ return filterSkills(list, filter);
415
+ },
416
+ unknowns(snapshot) {
417
+ let withheld = session.withheldReason() ?? 'untrusted';
418
+ // Once any tool is trusted here, a withheld runner is one whose own
419
+ // tools are not.
420
+ if (withheld === 'untrusted' && toolTrusted.size > 0)
421
+ withheld = 'tool-untrusted';
422
+ return unknownsOf({
423
+ reports: snapshot.catalog.reports,
424
+ cache: snapshot.cache,
425
+ withheld,
426
+ ...(withheld === 'exec-off' ? { execOff: execOffSource(settings) } : {}),
427
+ missingScopes: (runner) => session.missingScopes(runner),
428
+ });
429
+ },
430
+ missingScopes(runner) {
431
+ if (gate.allowExec || toolScopes.length === 0)
432
+ return undefined;
433
+ const needs = scopesByRunner.get(runner) ?? [runner];
434
+ return needs.filter((s) => !toolTrusted.has(s));
435
+ },
436
+ trustable,
437
+ async grantTrust(scope) {
438
+ if (!trustable()) {
439
+ throw new SessionError('not-trustable', "a trust grant would not change this run's execution gate");
440
+ }
441
+ if (scope !== undefined) {
442
+ const parsed = parseScope(scope);
443
+ const result = await trustStore.trust(root, parsed);
444
+ toolTrusted.add(parsed);
445
+ return { changed: !result.alreadyTrusted };
446
+ }
447
+ const result = await trustStore.trust(root);
448
+ options.allowExec = true;
449
+ // The hint told the user to trust this repository, which they just did.
450
+ delete options.execWithheldHint;
451
+ gate = { ...gate, allowExec: true, trusted: true, reason: 'allowed', missing: [] };
452
+ // Tool modules are code; a grant does not import them.
453
+ const note = projectToolsPending
454
+ ? `the tools ${PROJECT_CONFIG_FILENAME} names load the next time ${BIN} starts with execution allowed`
455
+ : undefined;
456
+ return { changed: !result.alreadyTrusted, ...(note !== undefined ? { note } : {}) };
457
+ },
458
+ async revokeTrust(scope) {
459
+ if (scope !== undefined) {
460
+ const removed = await trustStore.untrust(root, parseScope(scope));
461
+ // The user config's trust.tools may still trust it.
462
+ await decideTools();
463
+ return { changed: removed };
464
+ }
465
+ const removed = await trustStore.untrust(root);
466
+ return { changed: removed };
467
+ },
468
+ settings() {
469
+ return {
470
+ root,
471
+ settings,
472
+ allowExec: gate.allowExec,
473
+ reason: gate.reason,
474
+ trusted: gate.trusted,
475
+ trustable: trustable(),
476
+ tools: project.tools.map(toolSummary),
477
+ trustedTools: gate.allowExec ? [] : [...toolTrusted],
478
+ };
479
+ },
480
+ async reloadSettings() {
481
+ await reread();
482
+ return session.settings();
483
+ },
484
+ async saveSetting(key, value) {
485
+ const source = settings.settings.find((s) => s.key === key)?.source ?? 'default';
486
+ const layer = settingLayer(key, source);
487
+ let file;
488
+ try {
489
+ ;
490
+ ({ file } = await writeSetting({ layer, root, env, home }, key, value));
491
+ }
492
+ catch (err) {
493
+ const message = err instanceof Error ? err.message : String(err);
494
+ throw new SessionError('config', `not saved: ${message}`);
495
+ }
496
+ await reread(`saved to ${file}, but it cannot be read back: `);
497
+ const flag = FLAG_OF_SETTING[key];
498
+ return {
499
+ key,
500
+ file,
501
+ layer,
502
+ pinned: flag !== undefined && pinnedByFlag.includes(flag),
503
+ snapshot: session.settings(),
504
+ };
505
+ },
506
+ resolveRun(catalog, id, args = []) {
507
+ return resolveRun(project, root, catalog, id, args);
508
+ },
509
+ };
510
+ return session;
511
+ }
512
+ /**
513
+ * The task `id` names: by id, else by the line `list` prints for it (the
514
+ * copied form, with its `cd` and quoting), else by its `display`. A line or
515
+ * a display names a task only when no other task has it.
516
+ */
517
+ function findTask(catalog, id) {
518
+ const all = catalog.reports.flatMap((r) => r.tasks);
519
+ const only = (tasks) => (tasks.length === 1 ? tasks[0] : undefined);
520
+ const lineOf = (t) => taskCopyText(t, process.platform);
521
+ const byId = all.filter((t) => t.id === id);
522
+ if (byId.length === 1)
523
+ return byId[0];
524
+ const byLine = only(all.filter((t) => lineOf(t) === id));
525
+ if (byLine !== undefined)
526
+ return byLine;
527
+ // Ids are `runner:source:name`, and a name may hold a `:`, so two tasks can
528
+ // share one. Running the first would run a task the caller did not pick.
529
+ if (byId.length > 1) {
530
+ const lines = byId.map(lineOf);
531
+ const usable = lines.every((line) => line !== null && all.filter((t) => lineOf(t) === line).length === 1);
532
+ throw new SessionError('ambiguous-task', `'${id}' is the id of ${byId.length} tasks`, usable
533
+ ? `run one by its line from "${BIN} list": ` +
534
+ lines.map((line) => commandString([BIN, 'run', line])).join(' or ')
535
+ : `they have the same line in "${BIN} list", so ${BIN} cannot tell them apart; ` +
536
+ 'run the command yourself');
537
+ }
538
+ return only(all.filter((t) => t.display === id));
539
+ }
540
+ /** See {@link Session.resolveRun}. */
541
+ export function resolveRun(project, root, catalog, id, args = []) {
542
+ const task = findTask(catalog, id);
543
+ if (task === undefined) {
544
+ const all = catalog.reports.flatMap((r) => r.tasks);
545
+ // A task that contains `id` first; else one whose name is a near miss of
546
+ // it. Not a fuzzy match: letters in order find unrelated tasks.
547
+ let close = filterTasks(catalog.reports, { query: id, mode: 'exact' })
548
+ .slice(0, 3)
549
+ .map((h) => h.task.id);
550
+ if (close.length === 0) {
551
+ const names = closestMatches(id, [...new Set(all.map((t) => t.path.at(-1) ?? t.id))]);
552
+ close = all
553
+ .filter((t) => names.includes(t.path.at(-1) ?? t.id))
554
+ .map((t) => t.id)
555
+ .slice(0, 3);
556
+ }
557
+ throw new SessionError('task-not-found', `no task '${id}'`, close.length > 0
558
+ ? `did you mean ${close.join(', ')}?`
559
+ : `"${BIN} list --json" lists every task id`);
560
+ }
561
+ if (task.parametersUnknown === 'editor-variable') {
562
+ throw new SessionError('not-runnable', `${task.display}: ${EDITOR_VARIABLE_LABEL}`);
563
+ }
564
+ let invocation;
565
+ try {
566
+ invocation =
567
+ args.length === 0
568
+ ? { argv: [...task.argv], env: {} }
569
+ : project.runners.invocation(task, [...args]);
570
+ }
571
+ catch (err) {
572
+ throw new SessionError('bad-arguments', err instanceof Error ? err.message : String(err));
573
+ }
574
+ // The binary is always the task's own: invoke may not change it.
575
+ if (invocation.argv[0] !== task.argv[0]) {
576
+ throw new SessionError('bad-arguments', `${task.runner}: invoke changed the binary from ${task.argv[0]} to ${invocation.argv[0]}`);
577
+ }
578
+ // A catalog can come from a file (the saved view, the store), so its cwd
579
+ // is checked here, whatever the catalog's source.
580
+ const cwd = task.cwd === '.' ? root : resolve(root, task.cwd);
581
+ const inside = relative(root, cwd);
582
+ if (isAbsolute(task.cwd) ||
583
+ inside === '..' ||
584
+ inside.startsWith(`..${sep}`) ||
585
+ isAbsolute(inside)) {
586
+ throw new SessionError('not-runnable', `${task.display}: its directory is outside ${root}`);
587
+ }
588
+ return { task, argv: invocation.argv, env: invocation.env, cwd };
589
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Agent skills as catalog rows: the Skills group. A skill is not a task. It
3
+ * has no command line; an agent runs it when a person types `/<name>`. So
4
+ * the run action copies {@link SkillRow.invoke} and nothing is spawned.
5
+ *
6
+ * Skill names, descriptions and hints come from files in the repository or
7
+ * the user's config. Filter them like any repository text before printing.
8
+ *
9
+ * Browser-safe: it imports only the matcher, so the page can use it.
10
+ */
11
+ import type { TaskFilter } from './filter.ts';
12
+ /** Which skills a catalog lists: the `skills` setting. */
13
+ export declare const SKILLS_SETTING_VALUES: readonly ["project", "all", "off"];
14
+ /**
15
+ * `project`: the skills the repository ships (the default). `all`: those and
16
+ * the user's and plugins' skills, read from the home folder. `off`: none.
17
+ */
18
+ export type SkillsSetting = (typeof SKILLS_SETTING_VALUES)[number];
19
+ /** One agent skill. */
20
+ export interface SkillRow {
21
+ /** Stable: `skill:` and the skill file's path. */
22
+ id: string;
23
+ name: string;
24
+ description: string | null;
25
+ /** What to type after `/<name>`, such as `[pr-number]`. Null when the file sets none. */
26
+ argumentHint: string | null;
27
+ /** The `SKILL.md` file: relative to the root inside it, else absolute. */
28
+ path: string;
29
+ /** The config scope it was found in: `project`, `local`, `user` and so on. */
30
+ scope: string;
31
+ /** `project`, `user`, `local`, `managed`, or `plugin:<id>`. */
32
+ origin: string;
33
+ /** The agents that read this skill file: `claude`, `codex`, `cursor`. */
34
+ harnesses: string[];
35
+ /** What the run action copies: `/<name>`. */
36
+ invoke: string;
37
+ }
38
+ /** One kept skill, with its score and the offsets its name matched at. */
39
+ export interface SkillHit {
40
+ skill: SkillRow;
41
+ /** 0 when there is no query. */
42
+ score: number;
43
+ /** Offsets into `skill.name`, when the name is what matched. */
44
+ labelHits: number[] | null;
45
+ }
46
+ /** The text a surface shows for a skill: `/review [pr-number]`. */
47
+ export declare function skillLine(skill: Pick<SkillRow, 'invoke' | 'argumentHint'>): string;
48
+ /**
49
+ * The skills that pass `filter`, matched like tasks: by name, then the
50
+ * `/<name>` line, the description and the origin. With a query they are
51
+ * ranked best first; without one they keep their order.
52
+ */
53
+ export declare function filterSkills(skills: readonly SkillRow[], filter?: TaskFilter): SkillHit[];