@uppercut-labs/skills 0.0.0-stage → 1.0.4

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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +25 -0
  3. package/README.md +86 -2
  4. package/bin/grokbot-postinstall.js +12 -0
  5. package/bin/uppercut-skills.js +4 -0
  6. package/dist/agent-native/index.d.ts +21 -0
  7. package/dist/agent-native/index.d.ts.map +1 -0
  8. package/dist/agent-native/index.js +119 -0
  9. package/dist/agent-native/index.js.map +1 -0
  10. package/dist/catalog/github.d.ts +9 -0
  11. package/dist/catalog/github.d.ts.map +1 -0
  12. package/dist/catalog/github.js +256 -0
  13. package/dist/catalog/github.js.map +1 -0
  14. package/dist/catalog/index.d.ts +8 -0
  15. package/dist/catalog/index.d.ts.map +1 -0
  16. package/dist/catalog/index.js +172 -0
  17. package/dist/catalog/index.js.map +1 -0
  18. package/dist/catalog/types.d.ts +70 -0
  19. package/dist/catalog/types.d.ts.map +1 -0
  20. package/dist/catalog/types.js +2 -0
  21. package/dist/catalog/types.js.map +1 -0
  22. package/dist/cli/args.d.ts +24 -0
  23. package/dist/cli/args.d.ts.map +1 -0
  24. package/dist/cli/args.js +97 -0
  25. package/dist/cli/args.js.map +1 -0
  26. package/dist/cli/grokbot-postinstall.d.ts +30 -0
  27. package/dist/cli/grokbot-postinstall.d.ts.map +1 -0
  28. package/dist/cli/grokbot-postinstall.js +114 -0
  29. package/dist/cli/grokbot-postinstall.js.map +1 -0
  30. package/dist/cli/help.d.ts +2 -0
  31. package/dist/cli/help.d.ts.map +1 -0
  32. package/dist/cli/help.js +28 -0
  33. package/dist/cli/help.js.map +1 -0
  34. package/dist/cli/main.d.ts +2 -0
  35. package/dist/cli/main.d.ts.map +1 -0
  36. package/dist/cli/main.js +40 -0
  37. package/dist/cli/main.js.map +1 -0
  38. package/dist/cli/node-runtime.d.ts +13 -0
  39. package/dist/cli/node-runtime.d.ts.map +1 -0
  40. package/dist/cli/node-runtime.js +759 -0
  41. package/dist/cli/node-runtime.js.map +1 -0
  42. package/dist/cli/output.d.ts +26 -0
  43. package/dist/cli/output.d.ts.map +1 -0
  44. package/dist/cli/output.js +41 -0
  45. package/dist/cli/output.js.map +1 -0
  46. package/dist/engine/index.d.ts +6 -0
  47. package/dist/engine/index.d.ts.map +1 -0
  48. package/dist/engine/index.js +454 -0
  49. package/dist/engine/index.js.map +1 -0
  50. package/dist/engine/types.d.ts +91 -0
  51. package/dist/engine/types.d.ts.map +1 -0
  52. package/dist/engine/types.js +2 -0
  53. package/dist/engine/types.js.map +1 -0
  54. package/dist/generated/bundle.d.ts +3 -0
  55. package/dist/generated/bundle.d.ts.map +1 -0
  56. package/dist/generated/bundle.js +1205 -0
  57. package/dist/generated/bundle.js.map +1 -0
  58. package/dist/hosts/index.d.ts +24 -0
  59. package/dist/hosts/index.d.ts.map +1 -0
  60. package/dist/hosts/index.js +150 -0
  61. package/dist/hosts/index.js.map +1 -0
  62. package/dist/hosts/types.d.ts +41 -0
  63. package/dist/hosts/types.d.ts.map +1 -0
  64. package/dist/hosts/types.js +13 -0
  65. package/dist/hosts/types.js.map +1 -0
  66. package/dist/index.d.ts +8 -0
  67. package/dist/index.d.ts.map +1 -0
  68. package/dist/index.js +5 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/mcp/index.d.ts +12 -0
  71. package/dist/mcp/index.d.ts.map +1 -0
  72. package/dist/mcp/index.js +135 -0
  73. package/dist/mcp/index.js.map +1 -0
  74. package/package.json +76 -4
@@ -0,0 +1,759 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { chmod, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
7
+ import { readBundledCatalog, resolveSkill, resolveClosure } from '../catalog/index.js';
8
+ import { loadGitHubBundle, loadGitHubCatalog } from '../catalog/github.js';
9
+ import { installSkills, removeSkills, updateSkills } from '../engine/index.js';
10
+ import { resolveHostTarget } from '../hosts/index.js';
11
+ import { createSkillsCapabilityRegistry } from '../agent-native/index.js';
12
+ import { resultEnvelope } from './output.js';
13
+ const supportedHosts = ['codex', 'claude', 'cursor', 'antigravity', 'grokbot', 'grokcli'];
14
+ const processLocks = new Map();
15
+ export async function runCli(invocation, bundleModule, cwd = process.cwd(), homeDir = homedir()) {
16
+ let bundle = bundleModule.catalogBundle;
17
+ let catalog = readBundledCatalog(bundle);
18
+ const githubSelected = invocation.options.latest || invocation.options.channel === 'github';
19
+ if (githubSelected && invocation.command === 'list') {
20
+ try {
21
+ catalog = await loadGitHubCatalog();
22
+ }
23
+ catch (error) {
24
+ return failed(invocation, 'source-failure', error instanceof Error ? error.message : String(error), 4);
25
+ }
26
+ }
27
+ else if (githubSelected && invocation.command === 'show') {
28
+ try {
29
+ bundle = await loadGitHubBundle(invocation.ids);
30
+ catalog = structuredClone(bundle.manifest);
31
+ }
32
+ catch (error) {
33
+ return failed(invocation, 'source-failure', error instanceof Error ? error.message : String(error), 4);
34
+ }
35
+ }
36
+ const publicNames = ['catalog.list', 'catalog.show'];
37
+ const publicContext = {
38
+ scope: { host: 'catalog', kind: 'project' },
39
+ caller: { kind: 'anonymous' },
40
+ authorization: { authorize: (request) => request.risk === 'read' && request.access.kind === 'public' },
41
+ sourcePolicy: { channel: 'bundled' },
42
+ nativeRegistration: {},
43
+ operations: {
44
+ 'catalog.list': () => catalog.skills.map(({ id, title, summary, category }) => ({ id, title, summary, category, installed: 'unknown' })),
45
+ 'catalog.show': (input) => {
46
+ const id = readIds(input)[0];
47
+ const entry = resolveSkill(catalog, id);
48
+ const content = bundle.skills[id];
49
+ return {
50
+ id: entry.id, title: entry.title, summary: entry.summary, category: entry.category,
51
+ prerequisites: entry.prerequisites.flatMap((edge) => edge.skillId ? [edge.skillId] : []),
52
+ source: { repository: entry.sourceRepo, path: entry.sourcePath, revision: entry.sourceRevision },
53
+ resources: content?.files.map(({ path }) => path) ?? [], attribution: content?.attribution,
54
+ };
55
+ },
56
+ },
57
+ };
58
+ if (invocation.command === 'list') {
59
+ const execution = await createSkillsCapabilityRegistry(publicContext, publicNames).execute('catalog.list', {});
60
+ if (execution.kind === 'failure')
61
+ return failed(invocation, execution.reason, 'Catalog listing failed.', 1);
62
+ return complete(invocation, { requestedIds: [], resolvedIds: [], outcome: 'complete', data: execution.value });
63
+ }
64
+ if (invocation.command === 'show') {
65
+ const handle = createSkillsCapabilityRegistry(publicContext, publicNames);
66
+ const shown = [];
67
+ for (const id of invocation.ids) {
68
+ const execution = await handle.execute('catalog.show', { id });
69
+ if (execution.kind === 'failure')
70
+ return failed(invocation, execution.reason, 'Catalog lookup failed.', execution.reason === 'invalid-input' ? 2 : 1);
71
+ shown.push(execution.value);
72
+ }
73
+ return complete(invocation, { requestedIds: invocation.ids, resolvedIds: invocation.ids, outcome: 'complete', data: shown });
74
+ }
75
+ if (invocation.command === 'serve-mcp' || invocation.command === 'help') {
76
+ return failed(invocation, 'invalid-command', 'This command is handled by the package entrypoint.', 2);
77
+ }
78
+ const scope = invocation.options.global ? 'global' : 'project';
79
+ let projectRoot;
80
+ let physicalHomeDir;
81
+ try {
82
+ projectRoot = await realpath(invocation.options.project ? resolve(invocation.options.project) : scope === 'global' ? resolve(cwd) : projectRootFromGit(cwd));
83
+ physicalHomeDir = await realpath(homeDir);
84
+ }
85
+ catch (error) {
86
+ return failed(invocation, 'invalid-scope', error instanceof Error ? error.message : String(error), 2);
87
+ }
88
+ const host = await selectHost(invocation.options.host, invocation.options.json, scope, projectRoot, physicalHomeDir);
89
+ if (!host)
90
+ return failed(invocation, 'host-required', 'Select a host with --host. Supported hosts: codex, claude, cursor, antigravity, grokbot, grokcli.', 2, { candidates: supportedHosts });
91
+ const targetOptions = {
92
+ scope, projectRoot, homeDir: physicalHomeDir,
93
+ ...(invocation.options.surface ? { surface: invocation.options.surface } : {}),
94
+ };
95
+ let target;
96
+ try {
97
+ target = resolveHostTarget(host, targetOptions);
98
+ }
99
+ catch (error) {
100
+ return failed(invocation, error instanceof Error && 'code' in error ? String(error.code) : 'host-target-error', error instanceof Error ? error.message : String(error), 2, { target: { host, scope } });
101
+ }
102
+ const statePath = statePathFor(target, physicalHomeDir);
103
+ const ports = createNodePorts(statePath, target.installDir, target.scope === 'project');
104
+ const stateKey = statePath;
105
+ const bundledBundle = bundle;
106
+ const bundledCatalog = catalog;
107
+ const overrideChannel = invocation.options.latest ? 'github' : invocation.options.channel;
108
+ const channel = invocation.command === 'update' ? overrideChannel : overrideChannel ?? 'bundled';
109
+ const currentState = invocation.command === 'add' || invocation.command === 'update' ? await ports.state.load(stateKey) : undefined;
110
+ const sources = {
111
+ bundled: { snapshot: bundledCatalog, bundle: bundledBundle },
112
+ };
113
+ if (invocation.command === 'add' || invocation.command === 'update') {
114
+ const roots = [...new Set([...(currentState?.roots ?? []), ...invocation.ids])];
115
+ const rootChannels = { ...currentState?.rootChannels };
116
+ const selectedRoots = invocation.command === 'update' && !invocation.ids.length ? roots : invocation.ids;
117
+ for (const id of selectedRoots) {
118
+ if (channel)
119
+ rootChannels[id] = channel;
120
+ else
121
+ rootChannels[id] ??= 'bundled';
122
+ }
123
+ const githubRoots = roots.filter((id) => rootChannels[id] === 'github');
124
+ if (githubRoots.length) {
125
+ try {
126
+ const githubBundle = await loadGitHubBundle(githubRoots);
127
+ sources.github = { snapshot: structuredClone(githubBundle.manifest), bundle: githubBundle };
128
+ }
129
+ catch (error) {
130
+ return failed(invocation, 'source-failure', error instanceof Error ? error.message : String(error), 4, { host, scope });
131
+ }
132
+ }
133
+ if (channel === 'github' && sources.github) {
134
+ bundle = sources.github.bundle;
135
+ catalog = sources.github.snapshot;
136
+ }
137
+ }
138
+ try {
139
+ const capByCommand = {
140
+ add: 'installation.add', update: 'installation.update', remove: 'installation.remove', doctor: 'installation.doctor',
141
+ };
142
+ const selected = invocation.options.dryRun ? 'installation.plan' : capByCommand[invocation.command];
143
+ const allowedCapability = selected;
144
+ const capabilityContext = {
145
+ scope: { host, kind: scope, rootPath: target.rootPath },
146
+ caller: { kind: 'authenticated', subject: 'local-cli', scopes: ['skills:read', 'skills:write', 'skills:remove'] },
147
+ authorization: { authorize: (request) => request.identity.name === allowedCapability && request.access.kind === 'protected' },
148
+ sourcePolicy: { ...(channel ? { channel } : { channels: Object.keys(sources) }), bundleSchema: bundle.schemaVersion },
149
+ nativeRegistration: { evidence: 'unverified' },
150
+ operations: {
151
+ 'installation.plan': async (input) => {
152
+ const ids = readOptionalIds(input);
153
+ const state = await ports.state.load(stateKey);
154
+ const roots = invocation.command === 'update' ? (ids.length ? ids : [...(state?.roots ?? [])])
155
+ : invocation.command === 'add' ? [...new Set([...(state?.roots ?? []), ...ids])]
156
+ : invocation.command === 'remove' ? (state?.roots ?? []).filter((id) => !ids.includes(id))
157
+ : [...ids];
158
+ const prior = new Set(Object.keys(state?.skills ?? {}));
159
+ const desiredChannels = { ...state?.rootChannels };
160
+ if (invocation.command === 'add' || invocation.command === 'update') {
161
+ for (const id of invocation.command === 'update' && !ids.length ? roots : ids) {
162
+ if (channel)
163
+ desiredChannels[id] = channel;
164
+ else
165
+ desiredChannels[id] ??= 'bundled';
166
+ }
167
+ }
168
+ const assignments = new Map();
169
+ for (const root of roots) {
170
+ const rootChannel = desiredChannels[root] ?? 'bundled';
171
+ const source = sources[rootChannel];
172
+ if (!source)
173
+ throw new Error(`Missing content source for ${rootChannel} root ${root}`);
174
+ for (const entry of resolveClosure(source.snapshot, [root])) {
175
+ const priorChannel = assignments.get(entry.id);
176
+ if (priorChannel && priorChannel !== rootChannel)
177
+ throw new Error(`Conflicting content channels for shared skill ${entry.id}: ${priorChannel} and ${rootChannel}`);
178
+ assignments.set(entry.id, rootChannel);
179
+ }
180
+ }
181
+ const closure = [...assignments.keys()];
182
+ const resolvedIds = invocation.command === 'add' && invocation.options.noDependencies
183
+ ? [...new Set([...roots, ...prior])]
184
+ : closure;
185
+ return { requestedIds: ids, resolvedIds, target, ...(channel ? { channel } : {}), changes: [], dryRun: true };
186
+ },
187
+ 'installation.inspect': async () => diagnose(catalog, target, stateKey, ports),
188
+ 'installation.doctor': async () => diagnose(catalog, target, stateKey, ports),
189
+ 'installation.add': (input) => captureOperation(() => installSkills({ requestedIds: readIds(input), snapshot: catalog, bundle, sources, target, stateKey, ...(channel ? { channel } : {}), includeDependencies: !invocation.options.noDependencies }, ports)),
190
+ 'installation.update': (input) => captureOperation(() => updateSkills({ requestedIds: readIds(input), snapshot: catalog, bundle, sources, target, stateKey, ...(channel ? { channel } : {}) }, ports)),
191
+ 'installation.remove': (input) => captureOperation(() => removeSkills({ requestedIds: readIds(input), snapshot: catalog, bundle, target, stateKey }, ports)),
192
+ },
193
+ };
194
+ const handle = createSkillsCapabilityRegistry(capabilityContext, [selected]);
195
+ const input = { ids: invocation.ids };
196
+ const execution = await handle.execute(selected, input);
197
+ if (execution.kind === 'failure') {
198
+ const code = execution.reason;
199
+ const exit = code === 'unauthorized' ? 3 : code === 'invalid-input' ? 2 : 1;
200
+ return failed(invocation, code, `Operation failed: ${code}.`, exit, { host, scope });
201
+ }
202
+ const operationFailure = readOperationFailure(execution.value);
203
+ if (operationFailure) {
204
+ return failed(invocation, operationFailure.code, operationFailure.message, operationExitCode(operationFailure.code), { host, scope });
205
+ }
206
+ const operation = execution.value;
207
+ if (invocation.options.dryRun) {
208
+ return complete(invocation, {
209
+ requestedIds: operation.requestedIds, resolvedIds: operation.resolvedIds, host, scope,
210
+ ...(channel ? { channel } : {}), outcome: 'complete', data: operation, discovery: { status: 'unverified' },
211
+ });
212
+ }
213
+ return complete(invocation, {
214
+ command: invocation.command, requestedIds: operation.requestedIds ?? invocation.ids,
215
+ resolvedIds: operation.resolvedIds ?? [], host, scope, ...(operation.channel ? { channel: operation.channel } : {}),
216
+ outcome: 'healthy' in operation && operation.healthy === false ? 'degraded' : operation.outcome ?? 'complete', data: operation,
217
+ discovery: { status: 'unverified' },
218
+ });
219
+ }
220
+ catch (error) {
221
+ return failed(invocation, 'operation-failed', error instanceof Error ? error.message : String(error), 1, { host, scope });
222
+ }
223
+ }
224
+ function projectRootFromGit(cwd) {
225
+ try {
226
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
227
+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000,
228
+ }).trim();
229
+ }
230
+ catch (error) {
231
+ if (error && typeof error === 'object' && 'status' in error && error.status === 128)
232
+ return cwd;
233
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
234
+ return cwd;
235
+ throw error;
236
+ }
237
+ }
238
+ async function captureOperation(action) {
239
+ try {
240
+ return await action();
241
+ }
242
+ catch (error) {
243
+ const message = error instanceof Error ? error.message : String(error);
244
+ return { failure: { code: classifyOperationError(message), message } };
245
+ }
246
+ }
247
+ function readOperationFailure(value) {
248
+ if (typeof value !== 'object' || value === null || !('failure' in value))
249
+ return undefined;
250
+ const failure = value.failure;
251
+ if (typeof failure !== 'object' || failure === null || !('code' in failure) || !('message' in failure))
252
+ return undefined;
253
+ if (typeof failure.code !== 'string' || typeof failure.message !== 'string')
254
+ return undefined;
255
+ return { code: failure.code, message: failure.message };
256
+ }
257
+ function classifyOperationError(message) {
258
+ if (/source|github|catalog|manifest|revision|integrity/i.test(message))
259
+ return 'source-failure';
260
+ if (/modified|not owned|unmanaged|existing skill files?|symlink|non-regular|conflicting content channels|lock|manual recovery/i.test(message))
261
+ return 'local-conflict';
262
+ if (/registration/i.test(message))
263
+ return 'registration-required';
264
+ if (/unknown skill|prerequisite|skill ID is required|no managed roots/i.test(message))
265
+ return 'invalid-skill';
266
+ return 'operation-failed';
267
+ }
268
+ function operationExitCode(code) {
269
+ if (code === 'invalid-skill')
270
+ return 2;
271
+ if (code === 'source-failure')
272
+ return 4;
273
+ if (code === 'local-conflict')
274
+ return 5;
275
+ if (code === 'registration-required')
276
+ return 6;
277
+ return 1;
278
+ }
279
+ function readIds(input) {
280
+ if (typeof input !== 'object' || input === null || Array.isArray(input))
281
+ throw new TypeError('Expected an input object');
282
+ const record = input;
283
+ if (typeof record.id === 'string')
284
+ return [record.id];
285
+ const value = record.ids;
286
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string'))
287
+ throw new TypeError('Expected an ids array');
288
+ return [...value];
289
+ }
290
+ async function diagnose(catalog, target, stateKey, ports) {
291
+ const state = await ports.state.load(stateKey);
292
+ if (!state)
293
+ return { healthy: true, installed: [], target, discovery: { status: 'unverified' } };
294
+ const problems = [];
295
+ for (const id of state.roots) {
296
+ try {
297
+ resolveSkill(catalog, id);
298
+ }
299
+ catch (error) {
300
+ problems.push(error instanceof Error ? error.message : String(error));
301
+ }
302
+ }
303
+ const required = new Set();
304
+ try {
305
+ for (const entry of resolveClosure(catalog, state.roots))
306
+ required.add(entry.id);
307
+ }
308
+ catch (error) {
309
+ problems.push(error instanceof Error ? error.message : String(error));
310
+ }
311
+ for (const id of required)
312
+ if (!state.skills[id])
313
+ problems.push(`Required managed skill is missing: ${id}`);
314
+ for (const [id, skill] of Object.entries(state.skills)) {
315
+ for (const [path, receipt] of Object.entries(skill.files)) {
316
+ const bytes = await ports.fs.readFile(path);
317
+ if (!bytes)
318
+ problems.push(`Missing managed file: ${path}`);
319
+ else if (createHash('sha256').update(bytes).digest('hex') !== receipt.sha256)
320
+ problems.push(`Modified managed file: ${path}`);
321
+ }
322
+ if (!catalog.skills.some((entry) => entry.id === id))
323
+ problems.push(`Unknown installed skill: ${id}`);
324
+ }
325
+ return { healthy: problems.length === 0, installed: Object.keys(state.skills), roots: state.roots, problems, target, discovery: { status: 'unverified' } };
326
+ }
327
+ async function selectHost(explicit, json, scope, projectRoot, homeDir) {
328
+ if (explicit)
329
+ return explicit;
330
+ const selectionRoot = process.env.APPDATA || process.env.XDG_STATE_HOME || join(homeDir, '.local', 'state');
331
+ const targetIdentity = scope === 'global' ? 'global' : projectRoot;
332
+ const key = createHash('sha256').update(`${scope}\0${targetIdentity}`).digest('hex').slice(0, 24);
333
+ const selectionPath = join(selectionRoot, 'uppercut-skills', 'selections', `${key}.json`);
334
+ await assertNoSymlinkComponents(dirname(selectionPath));
335
+ try {
336
+ const saved = JSON.parse(await readFile(selectionPath, 'utf8'));
337
+ if (typeof saved === 'object' && saved !== null && 'host' in saved && supportedHosts.includes(saved.host))
338
+ return saved.host;
339
+ }
340
+ catch (error) {
341
+ if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'))
342
+ throw error;
343
+ }
344
+ if (json || !process.stdin.isTTY || !process.stdout.isTTY)
345
+ return undefined;
346
+ process.stdout.write('Choose a host for this target:\n');
347
+ supportedHosts.forEach((candidate, index) => process.stdout.write(` ${index + 1}. ${candidate}\n`));
348
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
349
+ let answer;
350
+ try {
351
+ answer = await terminal.question('Host [1-6]: ');
352
+ }
353
+ finally {
354
+ terminal.close();
355
+ }
356
+ const selected = supportedHosts[Number(answer) - 1];
357
+ if (!selected)
358
+ return undefined;
359
+ await mkdir(dirname(selectionPath), { recursive: true });
360
+ await assertNoSymlinkComponents(dirname(selectionPath));
361
+ await atomicJsonWrite(selectionPath, { host: selected });
362
+ return selected;
363
+ }
364
+ function readOptionalIds(input) {
365
+ if (typeof input !== 'object' || input === null || Array.isArray(input))
366
+ throw new TypeError('Expected an input object');
367
+ const value = input.ids;
368
+ if (value === undefined)
369
+ return [];
370
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string'))
371
+ throw new TypeError('Expected an IDs array');
372
+ return [...value];
373
+ }
374
+ function complete(invocation, value) {
375
+ const result = resultEnvelope({
376
+ command: value.command ?? invocation.command, outcome: value.outcome,
377
+ requestedIds: value.requestedIds, resolvedIds: value.resolvedIds,
378
+ ...(value.host ? { host: value.host } : {}), ...(value.scope ? { scope: value.scope } : {}),
379
+ ...(value.channel ? { channel: value.channel } : {}),
380
+ ...(value.discovery ? { discovery: value.discovery } : {}),
381
+ ...(value.data === undefined ? {} : { data: value.data }),
382
+ });
383
+ return { result, exitCode: result.outcome === 'complete' || result.outcome === 'unchanged' ? 0 : result.outcome === 'degraded' ? 7 : 1 };
384
+ }
385
+ function failed(invocation, code, message, exitCode, extra = {}) {
386
+ const result = resultEnvelope({
387
+ command: invocation.command, outcome: 'failed', requestedIds: invocation.ids, resolvedIds: [],
388
+ ...(extra.host ? { host: extra.host } : {}), ...(extra.scope ? { scope: extra.scope } : {}),
389
+ error: { code, message }, warnings: extra.candidates ? [`Candidates: ${extra.candidates.join(', ')}`] : [],
390
+ });
391
+ return { result, exitCode };
392
+ }
393
+ function statePathFor(target, homeDir) {
394
+ const physicalTarget = resolve(target.installDir);
395
+ const normalizedTarget = process.platform === 'win32' ? physicalTarget.toLocaleLowerCase('en-US') : physicalTarget;
396
+ const targetKey = createHash('sha256').update(normalizedTarget).digest('hex').slice(0, 32);
397
+ return target.scope === 'project'
398
+ ? join(target.rootPath, '.uppercut-skills', 'targets', targetKey, 'state.json')
399
+ : join(process.env.APPDATA || process.env.XDG_STATE_HOME || join(homeDir, '.local', 'state'), 'uppercut-skills', 'targets', targetKey, 'state.json');
400
+ }
401
+ function createNodePorts(statePath, installDir, projectScoped) {
402
+ const stateRoot = dirname(statePath);
403
+ const allowedRoots = [resolve(installDir), resolve(stateRoot)];
404
+ const rememberedModes = new Map();
405
+ const assertSafePath = async (path) => {
406
+ const absolute = resolve(path);
407
+ if (!allowedRoots.some((root) => isWithin(root, absolute)))
408
+ throw new Error(`Filesystem operation is outside managed scope: ${absolute}`);
409
+ await assertNoSymlinkComponents(absolute);
410
+ return absolute;
411
+ };
412
+ const fsPort = {
413
+ async listFiles(directory) {
414
+ const root = await assertSafePath(directory);
415
+ let rootMetadata;
416
+ try {
417
+ rootMetadata = await lstat(root);
418
+ }
419
+ catch (error) {
420
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
421
+ return [];
422
+ throw error;
423
+ }
424
+ if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink()) {
425
+ throw new Error(`Managed skill directory is not a regular directory: ${root}`);
426
+ }
427
+ const files = [];
428
+ const walk = async (directoryPath) => {
429
+ for (const entry of await readdir(directoryPath, { withFileTypes: true })) {
430
+ const child = await assertSafePath(join(directoryPath, entry.name));
431
+ const metadata = await lstat(child);
432
+ if (metadata.isSymbolicLink())
433
+ throw new Error(`Managed skill contains a symlink: ${child}`);
434
+ if (metadata.isDirectory())
435
+ await walk(child);
436
+ else if (metadata.isFile())
437
+ files.push(child);
438
+ else
439
+ throw new Error(`Managed skill contains a non-regular entry: ${child}`);
440
+ }
441
+ };
442
+ await walk(root);
443
+ return files;
444
+ },
445
+ async readFile(path) {
446
+ const absolute = await assertSafePath(path);
447
+ try {
448
+ const metadata = await lstat(absolute);
449
+ if (metadata.isSymbolicLink())
450
+ throw new Error(`Managed path is a symlink: ${absolute}`);
451
+ if (!metadata.isFile())
452
+ throw new Error(`Managed path is not a regular file: ${absolute}`);
453
+ rememberedModes.set(absolute, metadata.mode & 0o777);
454
+ return Uint8Array.from(await readFile(absolute));
455
+ }
456
+ catch (error) {
457
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
458
+ return undefined;
459
+ throw error;
460
+ }
461
+ },
462
+ async writeFile(path, bytes, options) {
463
+ const absolute = await assertSafePath(path);
464
+ await mkdir(dirname(absolute), { recursive: true });
465
+ await assertNoSymlinkComponents(dirname(absolute));
466
+ const mode = options?.executable === true ? 0o755 : options?.executable === false ? 0o644 : rememberedModes.get(absolute) ?? 0o644;
467
+ const temporary = join(dirname(absolute), `.${randomUUID()}.tmp`);
468
+ const handle = await open(temporary, 'wx', mode);
469
+ try {
470
+ await handle.writeFile(bytes);
471
+ await handle.close();
472
+ await chmod(temporary, mode);
473
+ await assertSafePath(absolute);
474
+ await rename(temporary, absolute);
475
+ }
476
+ catch (error) {
477
+ await handle.close().catch(() => undefined);
478
+ await rm(temporary, { force: true });
479
+ throw error;
480
+ }
481
+ rememberedModes.set(absolute, mode);
482
+ },
483
+ async mkdir(path) {
484
+ const absolute = await assertSafePath(path);
485
+ await mkdir(absolute, { recursive: true });
486
+ await assertNoSymlinkComponents(absolute);
487
+ },
488
+ async remove(path) {
489
+ const absolute = await assertSafePath(path);
490
+ try {
491
+ const metadata = await lstat(absolute);
492
+ if (metadata.isSymbolicLink() || !metadata.isFile())
493
+ throw new Error(`Refusing to remove non-regular managed path: ${absolute}`);
494
+ }
495
+ catch (error) {
496
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
497
+ return;
498
+ throw error;
499
+ }
500
+ await rm(absolute, { force: true });
501
+ },
502
+ async assertSafePath(path, boundary) {
503
+ const absolute = resolve(path);
504
+ const root = resolve(boundary);
505
+ if (!allowedRoots.some((allowed) => isWithin(allowed, root)))
506
+ throw new Error(`Filesystem boundary is outside managed scope: ${root}`);
507
+ if (!isWithin(root, absolute))
508
+ throw new Error(`Filesystem operation escapes its boundary: ${absolute}`);
509
+ await assertNoSymlinkComponents(absolute);
510
+ },
511
+ };
512
+ return {
513
+ fs: fsPort,
514
+ state: {
515
+ async load(key) {
516
+ const bytes = await fsPort.readFile(key);
517
+ if (!bytes)
518
+ return undefined;
519
+ const parsed = JSON.parse(Buffer.from(bytes).toString('utf8'));
520
+ if (!isInstallState(parsed))
521
+ throw new Error(`Managed state file is invalid: ${key}`);
522
+ return parsed;
523
+ },
524
+ async save(key, state) {
525
+ const absolute = await assertSafePath(key);
526
+ await mkdir(dirname(absolute), { recursive: true });
527
+ await assertNoSymlinkComponents(dirname(absolute));
528
+ if (projectScoped)
529
+ await ensureStateIgnored(statePath);
530
+ await atomicJsonWrite(absolute, state);
531
+ },
532
+ },
533
+ journal: {
534
+ async load(key) {
535
+ const journalPath = await assertSafePath(`${key}.transaction.json`);
536
+ const bytes = await fsPort.readFile(journalPath);
537
+ if (!bytes)
538
+ return undefined;
539
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
540
+ if (!isTransactionJournal(parsed, installDir))
541
+ throw new Error(`Transaction journal is invalid or out of scope: ${journalPath}`);
542
+ return parsed;
543
+ },
544
+ async save(key, journal) {
545
+ const journalPath = await assertSafePath(`${key}.transaction.json`);
546
+ if (projectScoped)
547
+ await ensureStateIgnored(statePath);
548
+ await atomicJsonWrite(journalPath, journal);
549
+ },
550
+ async clear(key) {
551
+ const journalPath = await assertSafePath(`${key}.transaction.json`);
552
+ await fsPort.remove(journalPath);
553
+ },
554
+ },
555
+ lock: {
556
+ withLock: (key, action) => withProcessLock(`${statePath}:${key}`, () => {
557
+ const lockPath = `${key}.lock`;
558
+ return withFileLock(lockPath, action, () => assertSafePath(lockPath));
559
+ }),
560
+ },
561
+ };
562
+ }
563
+ async function withProcessLock(key, action) {
564
+ const prior = processLocks.get(key) ?? Promise.resolve();
565
+ let release;
566
+ const next = new Promise((resolveLock) => { release = resolveLock; });
567
+ const queued = prior.then(() => next);
568
+ processLocks.set(key, queued);
569
+ await prior;
570
+ try {
571
+ return await action();
572
+ }
573
+ finally {
574
+ release();
575
+ if (processLocks.get(key) === queued)
576
+ processLocks.delete(key);
577
+ }
578
+ }
579
+ async function withFileLock(lockPath, action, assertSafe) {
580
+ await assertSafe();
581
+ await mkdir(dirname(lockPath), { recursive: true });
582
+ await assertSafe();
583
+ let handle;
584
+ try {
585
+ await assertSafe();
586
+ handle = await open(lockPath, 'wx', 0o600);
587
+ await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
588
+ }
589
+ catch (error) {
590
+ if (handle) {
591
+ await handle.close();
592
+ await rm(lockPath, { force: true });
593
+ }
594
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
595
+ if (await reclaimStaleLock(lockPath, assertSafe))
596
+ return withFileLock(lockPath, action, assertSafe);
597
+ throw new Error(`Another Uppercut Skills operation holds ${lockPath}; inspect or preserve the lock before retrying.`);
598
+ }
599
+ throw error;
600
+ }
601
+ try {
602
+ return await action();
603
+ }
604
+ finally {
605
+ await handle.close();
606
+ await rm(lockPath, { force: true });
607
+ }
608
+ }
609
+ async function reclaimStaleLock(lockPath, assertSafe) {
610
+ let owner;
611
+ let initialMetadata;
612
+ let initialContent;
613
+ try {
614
+ await assertSafe();
615
+ initialMetadata = await lstat(lockPath);
616
+ if (!initialMetadata.isFile() || initialMetadata.isSymbolicLink())
617
+ return false;
618
+ initialContent = await readFile(lockPath, 'utf8');
619
+ owner = JSON.parse(initialContent);
620
+ }
621
+ catch (error) {
622
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
623
+ return false;
624
+ return false;
625
+ }
626
+ if (!Number.isSafeInteger(owner.pid) || typeof owner.createdAt !== 'string')
627
+ return false;
628
+ const createdAt = Date.parse(owner.createdAt);
629
+ if (!Number.isFinite(createdAt) || createdAt > Date.now() + 60_000)
630
+ return false;
631
+ try {
632
+ process.kill(owner.pid, 0);
633
+ return false;
634
+ }
635
+ catch (error) {
636
+ if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ESRCH'))
637
+ return false;
638
+ }
639
+ const stalePath = `${lockPath}.stale-${randomUUID()}`;
640
+ try {
641
+ await assertSafe();
642
+ await rename(lockPath, stalePath);
643
+ await assertSafe();
644
+ const moved = await lstat(stalePath);
645
+ const movedContent = await readFile(stalePath, 'utf8');
646
+ if (!moved.isFile() || moved.isSymbolicLink() || moved.dev !== initialMetadata.dev || moved.ino !== initialMetadata.ino || movedContent !== initialContent) {
647
+ try {
648
+ const restored = await open(lockPath, 'wx', 0o600);
649
+ try {
650
+ await restored.writeFile(movedContent);
651
+ }
652
+ finally {
653
+ await restored.close();
654
+ }
655
+ }
656
+ catch (restoreError) {
657
+ if (!(restoreError && typeof restoreError === 'object' && 'code' in restoreError && restoreError.code === 'EEXIST'))
658
+ throw restoreError;
659
+ }
660
+ return false;
661
+ }
662
+ await rm(stalePath);
663
+ return true;
664
+ }
665
+ catch (error) {
666
+ if (error && typeof error === 'object' && 'code' in error && (error.code === 'ENOENT' || error.code === 'EEXIST'))
667
+ return false;
668
+ throw error;
669
+ }
670
+ }
671
+ function isInstallState(value) {
672
+ if (typeof value !== 'object' || value === null)
673
+ return false;
674
+ const state = value;
675
+ return state.version === 1 && Array.isArray(state.roots) && typeof state.rootChannels === 'object' && state.rootChannels !== null && typeof state.skills === 'object' && state.skills !== null;
676
+ }
677
+ function isTransactionJournal(value, installDir) {
678
+ if (typeof value !== 'object' || value === null)
679
+ return false;
680
+ const journal = value;
681
+ if (journal.version !== 1 || !isInstallState(journal.stateBefore) || !Array.isArray(journal.files))
682
+ return false;
683
+ return journal.files.every((file) => {
684
+ if (typeof file !== 'object' || file === null || typeof file.path !== 'string' || typeof file.existed !== 'boolean')
685
+ return false;
686
+ if (!isWithin(resolve(installDir), resolve(file.path)))
687
+ return false;
688
+ if (!file.existed)
689
+ return file.bytesBase64 === undefined;
690
+ if (typeof file.bytesBase64 !== 'string' || typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256))
691
+ return false;
692
+ const bytes = Buffer.from(file.bytesBase64, 'base64');
693
+ return bytes.toString('base64') === file.bytesBase64 && createHash('sha256').update(bytes).digest('hex') === file.sha256;
694
+ });
695
+ }
696
+ async function atomicJsonWrite(path, value) {
697
+ const temporary = join(dirname(path), `.${randomUUID()}.tmp`);
698
+ const handle = await open(temporary, 'wx', 0o600);
699
+ try {
700
+ await handle.writeFile(JSON.stringify(value, null, 2));
701
+ await handle.close();
702
+ await rename(temporary, path);
703
+ }
704
+ catch (error) {
705
+ await handle.close().catch(() => undefined);
706
+ await rm(temporary, { force: true });
707
+ throw error;
708
+ }
709
+ }
710
+ async function ensureStateIgnored(statePath) {
711
+ const stateRoot = dirname(dirname(dirname(statePath)));
712
+ const ignorePath = join(stateRoot, '.gitignore');
713
+ await assertNoSymlinkComponents(stateRoot);
714
+ await mkdir(stateRoot, { recursive: true });
715
+ await assertNoSymlinkComponents(stateRoot);
716
+ try {
717
+ const handle = await open(ignorePath, 'wx', 0o644);
718
+ try {
719
+ await handle.writeFile('*\n!.gitignore\n');
720
+ }
721
+ finally {
722
+ await handle.close();
723
+ }
724
+ return;
725
+ }
726
+ catch (error) {
727
+ if (!(error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST'))
728
+ throw error;
729
+ }
730
+ await assertNoSymlinkComponents(ignorePath);
731
+ const existing = await readFile(ignorePath, 'utf8');
732
+ const patterns = existing.split(/\r?\n/).map((line) => line.trim());
733
+ if (!patterns.includes('*') && !patterns.includes('targets/') && !patterns.includes('/targets/')) {
734
+ throw new Error(`Refusing to write local state because ${ignorePath} does not ignore the targets directory; add a targets/ rule and retry.`);
735
+ }
736
+ }
737
+ function isWithin(root, path) {
738
+ const relativePath = relative(root, path);
739
+ return relativePath === '' || (!relativePath.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) && relativePath !== '..' && !isAbsolute(relativePath));
740
+ }
741
+ async function assertNoSymlinkComponents(absolutePath) {
742
+ const parsed = parse(absolutePath);
743
+ let current = parsed.root;
744
+ for (const part of absolutePath.slice(parsed.root.length).split(/[\\/]+/).filter(Boolean)) {
745
+ current = join(current, part);
746
+ try {
747
+ if ((await lstat(current)).isSymbolicLink())
748
+ throw new Error(`Filesystem path contains a symlink/reparse point: ${current}`);
749
+ }
750
+ catch (error) {
751
+ if (error instanceof Error && error.message.includes('symlink/reparse point'))
752
+ throw error;
753
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
754
+ return;
755
+ throw error;
756
+ }
757
+ }
758
+ }
759
+ //# sourceMappingURL=node-runtime.js.map