@evomap/evolver-cli 2.0.54 → 2.0.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lifecycle.js CHANGED
@@ -191,18 +191,25 @@ async function runLifecycleCommandInner(argv, deps) {
191
191
  case 'start': {
192
192
  const result = await startLifecycle(paths, env);
193
193
  stdout(`${JSON.stringify(result)}\n`);
194
- return 0;
194
+ if (!isUnmanagedProxy(result))
195
+ return 0;
196
+ stderr(unmanagedProxyHint(result));
197
+ return 1;
195
198
  }
196
199
  case 'stop': {
197
200
  const result = stopLifecycle(paths);
198
201
  stdout(`${JSON.stringify(result)}\n`);
202
+ if (isUnmanagedProxy(result))
203
+ stderr(unmanagedProxyHint(result));
199
204
  return 0;
200
205
  }
201
206
  case 'restart': {
202
- stopLifecycle(paths);
203
- const result = await startLifecycle(paths, env);
207
+ const result = await restartLifecycle(paths, env);
204
208
  stdout(`${JSON.stringify({ ...result, status: result.status === 'started' ? 'restarted' : result.status })}\n`);
205
- return 0;
209
+ if (!isUnmanagedProxy(result))
210
+ return 0;
211
+ stderr(unmanagedProxyHint(result));
212
+ return 1;
206
213
  }
207
214
  case 'status': {
208
215
  const status = await lifecycleStatus(paths, env);
@@ -214,9 +221,12 @@ async function runLifecycleCommandInner(argv, deps) {
214
221
  stdout(`${JSON.stringify(status, null, 2)}\n`);
215
222
  if (!status.healthy) {
216
223
  stderr(`[Lifecycle] unhealthy reason=${status.reason ?? 'unknown'}; restarting\n`);
217
- stopLifecycle(paths);
218
- const result = await startLifecycle(paths, env);
224
+ const result = await restartLifecycle(paths, env);
219
225
  stdout(`${JSON.stringify(result)}\n`);
226
+ if (isUnmanagedProxy(result)) {
227
+ stderr(unmanagedProxyHint(result));
228
+ return 1;
229
+ }
220
230
  const next = await lifecycleStatus(paths, env);
221
231
  stdout(`${JSON.stringify({ after_restart: lifecycleStatusForOperator(next), log: 'inspect EVOLVER_LIFECYCLE_LOG_FILE or EVOLVER_LIFECYCLE_LOG_DIR' }, null, 2)}\n`);
222
232
  if (!next.healthy) {
@@ -482,6 +492,9 @@ export async function startLifecycle(paths, env = process.env) {
482
492
  stopLifecycle(paths);
483
493
  else
484
494
  rmSync(paths.pidFile, { force: true });
495
+ const unmanaged = unmanagedProxyResult(paths.settingsFile);
496
+ if (unmanaged)
497
+ return unmanaged;
485
498
  const command = resolveDaemonCommand(env);
486
499
  const cwd = env['EVOLVER_LIFECYCLE_CWD'] || process.cwd();
487
500
  const out = openSync(paths.logFile, 'a');
@@ -515,12 +528,36 @@ function oneShotChildEnv(env) {
515
528
  delete childEnv['EVOLVER_SELF_UPDATE_SUPERVISOR'];
516
529
  return childEnv;
517
530
  }
531
+ const PROXY_NOT_STARTED_BY_LIFECYCLE = 'proxy_not_started_by_lifecycle';
532
+ function isUnmanagedProxy(result) {
533
+ return result.reason === PROXY_NOT_STARTED_BY_LIFECYCLE;
534
+ }
535
+ function unmanagedProxyHint(result) {
536
+ return `[Lifecycle] proxy pid ${result.pid} was not started by \`evolver lifecycle start\`, so lifecycle will neither stop nor replace it; it is owned by the installed service or a foreground \`evolver proxy\`. Remove the service with \`evolver lifecycle remove-service\`, or stop its owner directly.\n`;
537
+ }
538
+ function unmanagedProxyResult(settingsFile) {
539
+ const pid = livePublishingProxyPid(readProxySettings(settingsFile, { quietReadError: true }));
540
+ return pid ? { status: 'not_owned', pid, reason: PROXY_NOT_STARTED_BY_LIFECYCLE } : undefined;
541
+ }
542
+ function livePublishingProxyPid({ pid, startedAt }) {
543
+ if (!pid || !startedAt || !isPidRunning(pid))
544
+ return undefined;
545
+ const processStartedAt = processStartedAtMs(pid);
546
+ // A reused pid belongs to a process born after the proxy that published started_at.
547
+ return processStartedAt !== undefined && processStartedAt <= Date.parse(startedAt) ? pid : undefined;
548
+ }
549
+ async function restartLifecycle(paths, env) {
550
+ const stopped = stopLifecycle(paths);
551
+ if (isUnmanagedProxy(stopped))
552
+ return stopped;
553
+ return startLifecycle(paths, env);
554
+ }
518
555
  export function stopLifecycle(paths, deps = {}) {
519
556
  const pidFile = readPidFile(paths.pidFile);
520
557
  const pid = pidFile.pid;
521
558
  if (!pid || !isPidRunning(pid)) {
522
559
  rmSync(paths.pidFile, { force: true });
523
- return { status: 'not_running' };
560
+ return unmanagedProxyResult(paths.settingsFile) ?? { status: 'not_running' };
524
561
  }
525
562
  if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity, deps.platform ?? process.platform)) {
526
563
  return { status: 'not_owned', pid, reason: 'pidfile_owner_unconfirmed' };
@@ -5158,8 +5195,7 @@ async function runWatch(paths, env, flags, stdout, stderr) {
5158
5195
  }
5159
5196
  else {
5160
5197
  stdout(`[Watch] ${new Date().toISOString()} unhealthy reason=${status.reason ?? 'unknown'} restarting...\n`);
5161
- stopLifecycle(paths);
5162
- const result = await startLifecycle(paths, env);
5198
+ const result = await restartLifecycle(paths, env);
5163
5199
  stdout(`[Watch] restart result: ${JSON.stringify(result)}\n`);
5164
5200
  skippedLastTick = false;
5165
5201
  }
@@ -5413,6 +5449,21 @@ function processIdentity(pid) {
5413
5449
  }
5414
5450
  return undefined;
5415
5451
  }
5452
+ function processStartedAtMs(pid) {
5453
+ if (process.platform === 'win32')
5454
+ return processIdentity(pid)?.startedAt;
5455
+ try {
5456
+ const startedAt = Date.parse(execFileSync(PS_PATH, ['-p', String(pid), '-o', 'lstart='], {
5457
+ encoding: 'utf8',
5458
+ env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
5459
+ stdio: ['ignore', 'pipe', 'ignore'],
5460
+ }).trim());
5461
+ return Number.isFinite(startedAt) ? startedAt : undefined;
5462
+ }
5463
+ catch {
5464
+ return undefined;
5465
+ }
5466
+ }
5416
5467
  function processIdentityMatchesRecord(record, identity) {
5417
5468
  if (!identity?.executable || !identity.parentPid || !identity.startedAt)
5418
5469
  return false;
package/dist/recipe.js CHANGED
@@ -16,6 +16,8 @@ const MAX_RECIPE_STEPS = 20;
16
16
  const MAX_RECIPE_VALIDATION_COMMANDS = 5;
17
17
  const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
18
18
  const MAX_ID_LENGTH = 200;
19
+ /** The running proxy's Hub auth state in the shared store (`proxyDaemon` HUB_AUTH_STATUS_STATE_KEY). */
20
+ const PROXY_HUB_AUTH_STATUS = 'hub:auth_status';
19
21
  const SENSITIVE_ERROR_KEYS = new Set(['authorization', 'node_secret', 'nodesecret', 'token', 'access_token', 'refresh_token', 'secret']);
20
22
  const STALE_NODE_SECRET_ERRORS = new Set(['node_secret_invalid', 'node_secret_not_set']);
21
23
  const RECIPE_SEARCH_VALUE_OPTIONS = new Set(['--q', '--query', '--limit']);
@@ -1427,12 +1429,19 @@ function persistRotatedNodeSecret(secret, version, nodeId, env, legacyDir) {
1427
1429
  const storePath = recipeProxyStorePath(env);
1428
1430
  const store = new mailbox.MailboxStore({ path: storePath });
1429
1431
  try {
1432
+ const proxyNodeId = store.getState('node_id')?.trim();
1430
1433
  store.setState('node_secret_source', 'pending_rotate');
1431
1434
  if (nodeId)
1432
1435
  store.setState('node_id', nodeId);
1433
1436
  store.setState('node_secret', secret);
1434
1437
  setOptionalStoreState(store, 'node_secret_version', version !== undefined ? String(version) : undefined);
1435
1438
  store.setState('node_secret_source', 'hub_rotate');
1439
+ // A running proxy refuses Hub calls while it records an auth failure; the new secret is what that failure
1440
+ // waited for, so lift it and let the proxy's next request present the secret it now reloads from this store.
1441
+ // The proxy reloads only its own node's secret, so a rotation of another node leaves its failure standing.
1442
+ const sameNode = !nodeId || !proxyNodeId || nodeId === proxyNodeId;
1443
+ if (sameNode && store.getState(PROXY_HUB_AUTH_STATUS) === 'auth_failed')
1444
+ store.setState(PROXY_HUB_AUTH_STATUS, '');
1436
1445
  }
1437
1446
  finally {
1438
1447
  store.close();
package/dist/reuse.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // 1. Print EXACTLY ONE envelope object to STDOUT on BOTH success and failure (in --json mode).
12
12
  // 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
13
13
  import { assetrepair, assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
- import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
14
+ import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubAntiAbuseBlock, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
15
15
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
17
17
  import { getCliVersion } from './version.js';
@@ -469,15 +469,6 @@ const ANTI_ABUSE_BLOCK_MESSAGE = 'hub anti-abuse temporarily blocked asset fetch
469
469
  function antiAbuseOutcome() {
470
470
  return { ok: false, status: 'rate_limited', message: ANTI_ABUSE_BLOCK_MESSAGE };
471
471
  }
472
- function isAntiAbuseFetchBlock(status, code) {
473
- return status === 403 && code !== undefined && /antibody|bulk_fetch|anti[-_]?abuse/i.test(code);
474
- }
475
- function hubErrorField(body) {
476
- if (!body || typeof body !== 'object')
477
- return undefined;
478
- const err = body['error'];
479
- return typeof err === 'string' ? err : undefined;
480
- }
481
472
  function recordValue(value) {
482
473
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
483
474
  }
@@ -492,7 +483,7 @@ function mapError(e) {
492
483
  // hubFetch raises AuthError for BOTH 401 and 403, so the hub's anti-abuse 403
493
484
  // (`bulk_fetch_blocked: IP antibody active`) used to be misreported as "log in" — it is an
494
485
  // abuse-control block on a perfectly healthy credential, not an auth failure (#555).
495
- if (isAntiAbuseFetchBlock(e.status, e.errorCode))
486
+ if (isHubAntiAbuseBlock(e))
496
487
  return antiAbuseOutcome();
497
488
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
498
489
  }
@@ -501,7 +492,7 @@ function mapError(e) {
501
492
  if (e instanceof HubClientError) {
502
493
  if (e.status === 429)
503
494
  return { ok: false, status: 'rate_limited', message: 'hub rate limited the request; retry later' };
504
- if (isAntiAbuseFetchBlock(e.status, hubErrorField(e.body)))
495
+ if (isHubAntiAbuseBlock(e))
505
496
  return antiAbuseOutcome();
506
497
  if (e.status === 401 || e.status === 403)
507
498
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
@@ -1,6 +1,7 @@
1
- import { assetstore, type hub as hubNs } from '@evomap/evolver-core';
1
+ import { assetstore, skill, type hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
- import { type RequiredSkillRef, type Result, type SkillFile } from './requiredSkills.js';
3
+ type RequiredSkillRef = skill.RequiredSkillRef;
4
+ type Result<T> = skill.Result<T>;
4
5
  export interface SkillFetchHub {
5
6
  search(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
6
7
  fetch(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
@@ -16,7 +17,8 @@ export interface SkillFetchDeps {
16
17
  hub: PublicHubCapability;
17
18
  auth: hubNs.AuthProvider;
18
19
  };
19
- /** Fetches a required skill's files from its git repository; the network boundary of an install. */
20
- fetchSkillFiles?: (ref: RequiredSkillRef) => Result<SkillFile[]>;
20
+ /** Fetches a required skill's files, and the commit they come from, from its git repository; the network boundary of an install. */
21
+ fetchSkillFiles?: (ref: RequiredSkillRef) => Result<skill.FetchedSkill> | Promise<Result<skill.FetchedSkill>>;
21
22
  }
22
- export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;
23
+ export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;
24
+ export {};
@@ -1,13 +1,12 @@
1
1
  import { lstatSync, readdirSync } from 'node:fs';
2
2
  import { join, sep } from 'node:path';
3
- import { assetstore, wire } from '@evomap/evolver-core';
3
+ import { assetstore, skill, wire } from '@evomap/evolver-core';
4
4
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
5
5
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
6
6
  import { checkWriteInsideRoot, relativePathInsideRoot, writeFileInsideRoot } from './containedWrite.js';
7
- import { fetchSkillFiles } from './gitSkillSource.js';
8
7
  import { createRecipeHubFromEnv } from './recipe.js';
9
- import { digestOfSkillFiles, requiredSkillsOf } from './requiredSkills.js';
10
8
  import { geneToSkillMd } from './skillDistill.js';
9
+ const { checkSkillTree, digestOfSkillFiles, fetchSkillFiles, requiredSkillsOf } = skill;
11
10
  const GROUP = 'skill.fetch';
12
11
  const DEFAULT_LIMIT = 5;
13
12
  const MAX_LIMIT = 20;
@@ -140,7 +139,7 @@ async function buildSkillFetchResult(hub, opts, cwd, fetchFiles) {
140
139
  if (selected.asset.asset_id !== previewed.assetId) {
141
140
  return { ok: false, reason: 'integrity_error', message: 'selected Gene asset_id changed after preview' };
142
141
  }
143
- const written = writeSkill(selected.asset, cwd, opts.outDir, opts.force, fetchFiles);
142
+ const written = await writeSkill(selected.asset, cwd, opts.outDir, opts.force, fetchFiles);
144
143
  if (!written.ok)
145
144
  return written;
146
145
  return { ok: true, value: { mode: 'write', candidates: [candidateFromGene(selected.asset, opts.outDir)], written: written.value } };
@@ -220,10 +219,10 @@ function candidateFromGene(gene, outDir) {
220
219
  candidate.requiredSkills = required.value;
221
220
  return candidate;
222
221
  }
223
- function writeSkill(gene, cwd, outDir, force, fetchFiles) {
222
+ async function writeSkill(gene, cwd, outDir, force, fetchFiles) {
224
223
  const name = skillNameForGene(gene);
225
224
  const target = relativeSkillPath(name);
226
- const required = planRequiredSkills(gene, name, fetchFiles);
225
+ const required = await planRequiredSkills(gene, name, fetchFiles);
227
226
  if (!required.ok)
228
227
  return required;
229
228
  const skillMd = geneToSkillMd(gene, {
@@ -286,21 +285,30 @@ function filesUnder(dir, target) {
286
285
  return [target];
287
286
  return readdirSync(dir).flatMap((entry) => filesUnder(`${dir}${sep}${entry}`, `${target}/${entry}`));
288
287
  }
289
- /** Fetch every skill the Gene requires and check it against the Gene's pin before a single file is written. */
290
- function planRequiredSkills(gene, geneSkillName, fetchFiles) {
288
+ /**
289
+ * Fetch every skill the Gene requires and check it before a single file is written: against the Gene's pin, or, for a
290
+ * skill that follows a branch, record the commit and digest it resolved to so the install can be reproduced.
291
+ */
292
+ async function planRequiredSkills(gene, geneSkillName, fetchFiles) {
291
293
  const declared = requiredSkillsOf(gene);
292
294
  const plans = [];
293
295
  for (const ref of declared.ok ? declared.value : []) {
294
296
  const refuse = (why) => ({ ok: false, reason: 'required_skill', message: `required skill ${ref.name} cannot be installed: ${why}. Nothing was written` });
295
297
  if (ref.name === safeSkillName(geneSkillName))
296
298
  return refuse('its directory name collides with the skill rendered from this Gene');
297
- const files = fetchFiles(ref);
298
- if (!files.ok)
299
- return refuse(files.message);
300
- if (digestOfSkillFiles(files.value) !== ref.sha256)
299
+ const fetched = await fetchFiles(ref);
300
+ if (!fetched.ok)
301
+ return refuse(fetched.message);
302
+ const { commit, files } = fetched.value;
303
+ const tree = checkSkillTree(files.map((file) => ({ mode: '100644', type: 'blob', size: file.content.length, path: file.path })));
304
+ if (!tree.ok)
305
+ return refuse(tree.message);
306
+ const sha256 = digestOfSkillFiles(files);
307
+ if ('sha256' in ref && sha256 !== ref.sha256)
301
308
  return refuse('its content does not match the sha256 the Gene pins');
302
- const planned = files.value.map((file) => ({ target: `skills/${ref.name}/${file.path}`, content: file.content }));
303
- plans.push({ skill: { ...ref, target: `skills/${ref.name}/SKILL.md`, files: planned.map((file) => file.target) }, planned });
309
+ const resolved = 'branch' in ref ? { ...ref, commit, sha256 } : ref;
310
+ const planned = files.map((file) => ({ target: `skills/${ref.name}/${file.path}`, content: file.content }));
311
+ plans.push({ skill: { ...resolved, target: `skills/${ref.name}/SKILL.md`, files: planned.map((file) => file.target) }, planned });
304
312
  }
305
313
  return { ok: true, value: plans };
306
314
  }
@@ -327,7 +335,8 @@ function emitSuccess(value, json, io) {
327
335
  io.stdout(` ${c.summary}`);
328
336
  }
329
337
  for (const skill of value.written?.requiredSkills ?? []) {
330
- io.stdout(`skill fetch: installed required skill ${skill.name} (${skill.files.length} file(s)) from ${skill.repo}@${skill.commit.slice(0, 12)}`);
338
+ const source = skill.branch ? `${skill.repo} branch ${skill.branch} at ${skill.commit} (sha256 ${skill.sha256})` : `${skill.repo}@${skill.commit.slice(0, 12)}`;
339
+ io.stdout(`skill fetch: installed required skill ${skill.name} (${skill.files.length} file(s)) from ${source}`);
331
340
  }
332
341
  if (value.written)
333
342
  io.stdout(`skill fetch: wrote ${value.written.target}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.54",
3
+ "version": "2.0.55",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -27,12 +27,12 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@evomap/evolver-core": "2.0.54",
31
- "@evomap/evolver-adapter-public": "2.0.54",
32
- "@evomap/evolver-mcp": "2.0.54",
33
- "@evomap/evolver-proxy": "2.0.54",
34
- "@evomap/evolver-runtime-adapters": "2.0.54",
35
- "@evomap/evolver-webui": "2.0.54"
30
+ "@evomap/evolver-core": "2.0.55",
31
+ "@evomap/evolver-adapter-public": "2.0.55",
32
+ "@evomap/evolver-mcp": "2.0.55",
33
+ "@evomap/evolver-proxy": "2.0.55",
34
+ "@evomap/evolver-runtime-adapters": "2.0.55",
35
+ "@evomap/evolver-webui": "2.0.55"
36
36
  },
37
37
  "repository": {
38
38
  "type": "git",
@@ -1,10 +0,0 @@
1
- import { type RequiredSkillRef, type Result, type SkillFile } from './requiredSkills.js';
2
- type SkillSource = Pick<RequiredSkillRef, 'repo' | 'commit' | 'path'>;
3
- /**
4
- * Fetch one commit of a public https repository and read a skill directory out of it. Nothing is checked out:
5
- * files are read from git objects, so repository filters, hooks, symlinks and submodules never touch the disk.
6
- */
7
- export declare function fetchSkillFiles(source: SkillSource): Result<SkillFile[]>;
8
- /** Read the regular files under `path` at `commit` from a local repository that already has the commit. */
9
- export declare function readSkillTree(repoDir: string, commit: string, path: string): Result<SkillFile[]>;
10
- export {};
@@ -1,67 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { mkdtempSync, rmSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
- import { checkSkillTree } from './requiredSkills.js';
6
- const FETCH_TIMEOUT_MS = 120_000;
7
- const MAX_BUFFER = 64 * 1024 * 1024;
8
- /**
9
- * Fetch one commit of a public https repository and read a skill directory out of it. Nothing is checked out:
10
- * files are read from git objects, so repository filters, hooks, symlinks and submodules never touch the disk.
11
- */
12
- export function fetchSkillFiles(source) {
13
- const dir = mkdtempSync(join(tmpdir(), 'evolver-skill-'));
14
- try {
15
- git(dir, ['init', '--quiet']);
16
- git(dir, ['fetch', '--quiet', '--depth', '1', '--no-tags', source.repo, source.commit]);
17
- return readSkillTree(dir, source.commit, source.path);
18
- }
19
- catch (error) {
20
- return { ok: false, message: `git could not fetch ${source.commit.slice(0, 12)} from ${source.repo} (${gitFailure(error)})` };
21
- }
22
- finally {
23
- rmSync(dir, { recursive: true, force: true });
24
- }
25
- }
26
- /** Read the regular files under `path` at `commit` from a local repository that already has the commit. */
27
- export function readSkillTree(repoDir, commit, path) {
28
- let listing;
29
- try {
30
- listing = git(repoDir, ['ls-tree', '-r', '-l', '-z', path ? `${commit}:${path}` : commit]);
31
- }
32
- catch {
33
- return { ok: false, message: `the commit has no directory ${JSON.stringify(path || '/')}` };
34
- }
35
- const rows = listing.toString('utf8').split('\0').filter(Boolean).map(parseTreeRow);
36
- const checked = checkSkillTree(rows);
37
- if (!checked.ok)
38
- return checked;
39
- return { ok: true, value: rows.map((row) => ({ path: row.path, content: git(repoDir, ['cat-file', 'blob', row.object]) })) };
40
- }
41
- function parseTreeRow(row) {
42
- const tab = row.indexOf('\t');
43
- const [mode = '', type = '', object = '', size = ''] = row.slice(0, tab).split(/ +/);
44
- return { mode, type, object, size: Number(size) || 0, path: row.slice(tab + 1) };
45
- }
46
- // https only, no prompts, and neither the user's git configuration nor a caller's GIT_* variables: a hook that
47
- // exports GIT_DIR, a url.insteadOf rewrite or a credential helper must not change what gets fetched.
48
- function git(cwd, args) {
49
- const inherited = Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'));
50
- return execFileSync('git', ['-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', ...args], {
51
- cwd,
52
- env: { ...Object.fromEntries(inherited), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' },
53
- stdio: ['ignore', 'pipe', 'pipe'],
54
- timeout: FETCH_TIMEOUT_MS,
55
- maxBuffer: MAX_BUFFER,
56
- windowsHide: true,
57
- });
58
- }
59
- function gitFailure(error) {
60
- const record = error;
61
- if (record.code === 'ENOENT')
62
- return 'git is not installed';
63
- if (record.code === 'ETIMEDOUT')
64
- return 'timed out';
65
- const stderr = Buffer.isBuffer(record.stderr) ? record.stderr.toString('utf8') : '';
66
- return stderr.trim().split('\n').pop()?.slice(0, 200) || 'git failed';
67
- }
@@ -1,50 +0,0 @@
1
- /**
2
- * A skill a Gene needs, pinned to a git commit and to the content of the skill directory. It travels as one
3
- * `preconditions` entry, so it is covered by the Gene's asset_id and needs no wire-schema field:
4
- *
5
- * skill:git+https://github.com/owner/repo@<commit>#sha256=<digest>&path=<dir inside the repo>
6
- */
7
- export interface RequiredSkillRef {
8
- /** Directory the skill is installed under: `skills/<name>/`. */
9
- name: string;
10
- repo: string;
11
- commit: string;
12
- /** Skill directory inside the repository, POSIX separators; empty for the repository root. */
13
- path: string;
14
- sha256: string;
15
- }
16
- /** One file of a skill, with its path relative to the skill directory (POSIX separators). */
17
- export interface SkillFile {
18
- path: string;
19
- content: Uint8Array;
20
- }
21
- /** One `git ls-tree -r -l` row, with its path relative to the skill directory. */
22
- export interface SkillTreeEntry {
23
- mode: string;
24
- type: string;
25
- size: number;
26
- path: string;
27
- }
28
- export type Result<T> = {
29
- ok: true;
30
- value: T;
31
- } | {
32
- ok: false;
33
- message: string;
34
- };
35
- /**
36
- * Read the skills a Gene requires from its `preconditions`. Only entries that start with `skill:git+` are
37
- * references; everything else, other `skill:` text included, stays an ordinary precondition. A reference that
38
- * cannot be honoured in full is an error, not a shorter list: installing some of what a Gene needs would hand the
39
- * agent a broken strategy.
40
- */
41
- export declare function requiredSkillsOf(gene: Record<string, unknown>): Result<RequiredSkillRef[]>;
42
- /** The `preconditions` entry that pins a skill directory with this content. */
43
- export declare function formatRequiredSkill(ref: Pick<RequiredSkillRef, 'repo' | 'commit' | 'path' | 'sha256'>): string;
44
- /**
45
- * Content digest of a skill directory: SHA-256 over one `<sha256 of the file> <path>\n` line per file, sorted by
46
- * path. It is the output of `sha256sum` over the sorted files, so an author can reproduce it without this tool.
47
- */
48
- export declare function digestOfSkillFiles(files: readonly SkillFile[]): string;
49
- /** Decide from the tree listing alone, before any file content is read, whether this directory may be installed. */
50
- export declare function checkSkillTree(entries: readonly SkillTreeEntry[]): Result<true>;
@@ -1,123 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- const GIT_PREFIX = 'skill:git+';
3
- const MAX_REQUIRED_SKILLS = 8;
4
- const MAX_FILES = 256;
5
- const MAX_FILE_BYTES = 5 * 1024 * 1024;
6
- const MAX_TOTAL_BYTES = 20 * 1024 * 1024;
7
- const MAX_DEPTH = 8;
8
- const COMMIT = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
9
- const SHA256 = /^[0-9a-f]{64}$/;
10
- const SEGMENT = /^[A-Za-z0-9._-]{1,100}$/;
11
- // Windows opens these as devices, extension or not (CON, NUL.txt, COM1.md), so they never name a plain file.
12
- const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$)/i;
13
- const REGULAR_FILE_MODES = new Set(['100644', '100755']);
14
- /**
15
- * Read the skills a Gene requires from its `preconditions`. Only entries that start with `skill:git+` are
16
- * references; everything else, other `skill:` text included, stays an ordinary precondition. A reference that
17
- * cannot be honoured in full is an error, not a shorter list: installing some of what a Gene needs would hand the
18
- * agent a broken strategy.
19
- */
20
- export function requiredSkillsOf(gene) {
21
- const preconditions = Array.isArray(gene['preconditions']) ? gene['preconditions'] : [];
22
- const declared = preconditions.filter((entry) => typeof entry === 'string' && entry.startsWith(GIT_PREFIX));
23
- if (declared.length > MAX_REQUIRED_SKILLS)
24
- return { ok: false, message: `a Gene may require at most ${MAX_REQUIRED_SKILLS} skills` };
25
- const refs = [];
26
- for (const entry of declared) {
27
- const ref = parseRequiredSkill(entry);
28
- if (!ref.ok)
29
- return ref;
30
- if (refs.some((known) => known.name === ref.value.name)) {
31
- return { ok: false, message: `two required skills would install to skills/${ref.value.name}` };
32
- }
33
- refs.push(ref.value);
34
- }
35
- return { ok: true, value: refs };
36
- }
37
- function parseRequiredSkill(entry) {
38
- const malformed = (why) => ({ ok: false, message: `required skill reference is not valid (${why})` });
39
- const [location = '', fragment = '', ...extra] = entry.slice(GIT_PREFIX.length).split('#');
40
- const at = location.lastIndexOf('@');
41
- if (extra.length > 0 || at < 0)
42
- return malformed('expected <repository>@<commit>#sha256=<digest>');
43
- const repo = httpsRepository(location.slice(0, at));
44
- const commit = location.slice(at + 1);
45
- const pin = pinOf(fragment);
46
- if (!repo)
47
- return malformed('the repository must be a plain https:// URL without credentials or query');
48
- if (!COMMIT.test(commit))
49
- return malformed('the commit must be a full lowercase hex commit id');
50
- if (!pin)
51
- return malformed('expected #sha256=<64 lowercase hex>, optionally &path=<plain relative directory>');
52
- const { sha256, path } = pin;
53
- const name = installName(path || new URL(repo).pathname);
54
- if (!name)
55
- return malformed('no usable directory name');
56
- return { ok: true, value: { name, repo, commit, path, sha256 } };
57
- }
58
- function pinOf(fragment) {
59
- const params = new URLSearchParams(fragment);
60
- const sha256 = params.get('sha256') ?? '';
61
- const path = params.get('path') ?? '';
62
- const known = [...params.keys()].every((key) => key === 'sha256' || key === 'path');
63
- return known && SHA256.test(sha256) && (path === '' || isSafeRelativePath(path)) ? { sha256, path } : null;
64
- }
65
- function httpsRepository(raw) {
66
- let url;
67
- try {
68
- url = new URL(raw);
69
- }
70
- catch {
71
- return null;
72
- }
73
- const plain = url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash && url.pathname.length > 1;
74
- return plain && url.href === raw ? raw : null;
75
- }
76
- function installName(source) {
77
- const last = source.split('/').filter(Boolean).pop() ?? '';
78
- return last.replace(/\.git$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
79
- }
80
- /** The `preconditions` entry that pins a skill directory with this content. */
81
- export function formatRequiredSkill(ref) {
82
- const params = new URLSearchParams({ sha256: ref.sha256, ...(ref.path ? { path: ref.path } : {}) });
83
- return `${GIT_PREFIX}${ref.repo}@${ref.commit}#${params.toString().replace(/%2F/g, '/')}`;
84
- }
85
- /**
86
- * Content digest of a skill directory: SHA-256 over one `<sha256 of the file> <path>\n` line per file, sorted by
87
- * path. It is the output of `sha256sum` over the sorted files, so an author can reproduce it without this tool.
88
- */
89
- export function digestOfSkillFiles(files) {
90
- const lines = [...files]
91
- .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
92
- .map((file) => `${createHash('sha256').update(file.content).digest('hex')} ${file.path}\n`);
93
- return createHash('sha256').update(lines.join('')).digest('hex');
94
- }
95
- /** Decide from the tree listing alone, before any file content is read, whether this directory may be installed. */
96
- export function checkSkillTree(entries) {
97
- if (!entries.some((entry) => entry.path === 'SKILL.md'))
98
- return { ok: false, message: 'the directory has no SKILL.md' };
99
- if (entries.length > MAX_FILES)
100
- return { ok: false, message: `it has more than ${MAX_FILES} files` };
101
- const seen = new Set();
102
- let total = 0;
103
- for (const entry of entries) {
104
- if (entry.type !== 'blob' || !REGULAR_FILE_MODES.has(entry.mode)) {
105
- return { ok: false, message: `${entry.path} is a symlink or submodule, not a regular file` };
106
- }
107
- if (!isSafeRelativePath(entry.path) || seen.has(entry.path.toLowerCase())) {
108
- return { ok: false, message: `${JSON.stringify(entry.path)} is not a plain, unique relative path` };
109
- }
110
- seen.add(entry.path.toLowerCase());
111
- total += entry.size;
112
- if (entry.size > MAX_FILE_BYTES || total > MAX_TOTAL_BYTES) {
113
- return { ok: false, message: `it is larger than ${MAX_FILE_BYTES} bytes per file or ${MAX_TOTAL_BYTES} bytes in total` };
114
- }
115
- }
116
- return { ok: true, value: true };
117
- }
118
- function isSafeRelativePath(path) {
119
- const segments = path.split('/');
120
- return segments.length <= MAX_DEPTH
121
- && segments.every((segment) => SEGMENT.test(segment) && !/^\.+$/.test(segment) && segment.toLowerCase() !== '.git' && !segment.endsWith('.')
122
- && !WINDOWS_DEVICE.test(segment));
123
- }