peaks-loop-mut 0.1.53 → 0.1.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.
Files changed (34) hide show
  1. package/dist/index.d.ts +3 -3
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +3 -3
  4. package/dist/services/agent/ecc-materialize.d.ts +24 -27
  5. package/dist/services/agent/ecc-materialize.d.ts.map +1 -1
  6. package/dist/services/agent/ecc-materialize.js +43 -77
  7. package/dist/services/agent/ecc-materialized-readers.d.ts +23 -5
  8. package/dist/services/agent/ecc-materialized-readers.d.ts.map +1 -1
  9. package/dist/services/agent/ecc-materialized-readers.js +80 -18
  10. package/dist/services/agent/ecc-package-service.d.ts +38 -0
  11. package/dist/services/agent/ecc-package-service.d.ts.map +1 -0
  12. package/dist/services/agent/ecc-package-service.js +41 -0
  13. package/dist/services/agent/ecc-package-source.d.ts +97 -0
  14. package/dist/services/agent/ecc-package-source.d.ts.map +1 -0
  15. package/dist/services/agent/ecc-package-source.js +130 -0
  16. package/package.json +2 -1
  17. package/dist/services/agent/ecc-archive-safety.d.ts +0 -25
  18. package/dist/services/agent/ecc-archive-safety.d.ts.map +0 -1
  19. package/dist/services/agent/ecc-archive-safety.js +0 -131
  20. package/dist/services/agent/ecc-cache-cleanup.d.ts +0 -26
  21. package/dist/services/agent/ecc-cache-cleanup.d.ts.map +0 -1
  22. package/dist/services/agent/ecc-cache-cleanup.js +0 -90
  23. package/dist/services/agent/ecc-cache-config.d.ts +0 -66
  24. package/dist/services/agent/ecc-cache-config.d.ts.map +0 -1
  25. package/dist/services/agent/ecc-cache-config.js +0 -72
  26. package/dist/services/agent/ecc-cache-manifest.d.ts +0 -22
  27. package/dist/services/agent/ecc-cache-manifest.d.ts.map +0 -1
  28. package/dist/services/agent/ecc-cache-manifest.js +0 -136
  29. package/dist/services/agent/ecc-cache-service.d.ts +0 -65
  30. package/dist/services/agent/ecc-cache-service.d.ts.map +0 -1
  31. package/dist/services/agent/ecc-cache-service.js +0 -118
  32. package/dist/services/agent/ecc-fetch.d.ts +0 -31
  33. package/dist/services/agent/ecc-fetch.d.ts.map +0 -1
  34. package/dist/services/agent/ecc-fetch.js +0 -95
@@ -1,136 +0,0 @@
1
- /**
2
- * ECC cache manifest + cache reads (writeManifest / readManifestAt /
3
- * listCachedAgents / readAgentSkill and the D-009 `fallbackMetadata`).
4
- *
5
- * The warn-once latch `warnedAboutFallback` lives HERE with its only
6
- * reader `fallbackMetadata` — they move as one unit, so the D-009
7
- * warning stays single-fire across repeated calls.
8
- *
9
- * Split verbatim out of `ecc-cache-service.ts` (wave 11 slice A,
10
- * 2026-10-03); no behaviour changed.
11
- */
12
- import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
13
- import { join } from 'node:path';
14
- import { parseFrontmatter } from '../../shared/frontmatter.js';
15
- import { resolveManifestPath, resolveAgentsDir } from './ecc-cache-config.js';
16
- import { isSafeAgentName } from './ecc-archive-safety.js';
17
- function writeManifest(manifest) {
18
- const path = resolveManifestPath();
19
- writeFileSync(path, JSON.stringify(manifest, null, 2));
20
- }
21
- export function readCacheManifest() {
22
- return readManifestAt();
23
- }
24
- function readManifestAt(dirOverride) {
25
- const path = resolveManifestPath(dirOverride);
26
- if (!existsSync(path))
27
- return null;
28
- try {
29
- const raw = readFileSync(path, 'utf8');
30
- const parsed = JSON.parse(raw);
31
- if (typeof parsed.version === 'string' &&
32
- typeof parsed.sha === 'string' &&
33
- typeof parsed.fetchedAt === 'string' &&
34
- Array.isArray(parsed.agents)) {
35
- return parsed;
36
- }
37
- return null;
38
- }
39
- catch {
40
- return null;
41
- }
42
- }
43
- let warnedAboutFallback = false;
44
- function fallbackMetadata(fileName) {
45
- const base = fileName.replace(/\.md$/i, '');
46
- let description = '';
47
- try {
48
- const body = readFileSync(join(resolveManifestDirForAgents(), fileName), 'utf8');
49
- const lines = body.split(/\r?\n/);
50
- let inFrontmatter = false;
51
- let seenClosing = false;
52
- for (const raw of lines) {
53
- const line = raw.trim();
54
- if (!seenClosing) {
55
- if (!inFrontmatter && line === '---') {
56
- inFrontmatter = true;
57
- continue;
58
- }
59
- if (inFrontmatter && line === '---') {
60
- seenClosing = true;
61
- continue;
62
- }
63
- continue;
64
- }
65
- if (line.length === 0)
66
- continue;
67
- description = line;
68
- break;
69
- }
70
- }
71
- catch {
72
- /* best-effort */
73
- }
74
- if (description.length > 80)
75
- description = `${description.slice(0, 77)}...`;
76
- if (!warnedAboutFallback) {
77
- try {
78
- process.stderr.write(`warning: cached agent "${base}" has malformed frontmatter; falling back to filename + first body line\n`);
79
- }
80
- catch {
81
- /* best-effort */
82
- }
83
- warnedAboutFallback = true;
84
- }
85
- return { name: base, description };
86
- }
87
- function resolveManifestDirForAgents() {
88
- const manifest = readCacheManifest();
89
- if (manifest === null)
90
- return '';
91
- return resolveAgentsDir(manifest.sha);
92
- }
93
- export function listCachedAgents() {
94
- const manifest = readCacheManifest();
95
- if (manifest === null)
96
- return [];
97
- const agentsDir = resolveAgentsDir(manifest.sha);
98
- if (!existsSync(agentsDir))
99
- return [];
100
- const out = [];
101
- for (const file of readdirSync(agentsDir).sort()) {
102
- if (!file.endsWith('.md'))
103
- continue;
104
- const fullPath = join(agentsDir, file);
105
- let meta;
106
- try {
107
- const raw = readFileSync(fullPath, 'utf8');
108
- const fm = parseFrontmatter(raw);
109
- meta = { name: fm.name, description: fm.description };
110
- }
111
- catch {
112
- // D-009 fallback — name from filename, description from first body line.
113
- meta = fallbackMetadata(file);
114
- }
115
- out.push(meta);
116
- }
117
- return out;
118
- }
119
- export function readAgentSkill(name) {
120
- if (!isSafeAgentName(name))
121
- return null;
122
- const manifest = readCacheManifest();
123
- if (manifest === null)
124
- return null;
125
- const file = join(resolveAgentsDir(manifest.sha), `${name}.md`);
126
- if (!existsSync(file))
127
- return null;
128
- try {
129
- return readFileSync(file, 'utf8');
130
- }
131
- catch {
132
- return null;
133
- }
134
- }
135
- // Cross-module glue: private inside ecc-cache-service.ts before the split.
136
- export { writeManifest, readManifestAt };
@@ -1,65 +0,0 @@
1
- /**
2
- * ECC cache service — Slice 3 of 4.0.0-beta.11.
3
- *
4
- * Drop-in replacement for the deleted `ecc-agent-service.ts`. The
5
- * pre-Slice-3 implementation shelled out to `npx ecc agent run ...`,
6
- * but the upstream `affaan-m/everything-claude-code` v2.0.0 release
7
- * has NO `ecc` binary — the repo is `agents/*.md` flat files plus
8
- * SKILL.md descriptors. The peaks-loop path is therefore download
9
- * + cache only; the LLM consumes cached `agents/*.md` directly
10
- * through `peaks ecc show <name>`.
11
- *
12
- * Six cache exports per RD §2:
13
- * - setCacheDirPermissions
14
- * - downloadToCache
15
- * - readCacheManifest
16
- * - listCachedAgents
17
- * - readAgentSkill
18
- * - cleanupStaleCache
19
- *
20
- * Slice A of 2026-09-09-ecc-dynamic adds the plugin-free materialize
21
- * layer (`materializeEccAgents` + readers) that copies the active sha's
22
- * `agents/*.md` into `~/.peaks/agents/ecc/` so the RD fan-out works on a
23
- * machine with no ECC Claude Code plugin.
24
- *
25
- * The cache layout is `~/.peaks/cache/ecc-installed.json` (manifest)
26
- * + `~/.peaks/cache/ecc-<sha>/agents/<name>.md`. The manifest is
27
- * the active-cache pointer; cleanupStaleCache iterates the on-disk
28
- * sha directories and decides based on the manifest's `fetchedAt`
29
- * (active) vs `mtimeMs` (orphan).
30
- *
31
- * Hard contracts (Karpathy #2 Simplicity First):
32
- * - No subprocess plumbing. Network is `fetch()` only.
33
- * - No factory; one module, six functions, six dependencies.
34
- * - Strict selective extract: agents/*.md only, no symlinks, no
35
- * `..`, no absolute paths, no devices.
36
- * - D-009 fallback: parseFrontmatter throws on malformed input —
37
- * wrap it in try/catch and synthesize `{name, description}`
38
- * from the file name + first non-empty body line.
39
- * - D-010 fallback order (2026-09-09, leads with what actually works):
40
- * 1. `tarball_url` from `releases/tags/<ref>` — the only path that
41
- * serves a tarball on upstream v2.2.0. Must be fetched with
42
- * `accept: application/vnd.github+json`; GitHub's API tarball
43
- * endpoint answers 415 to `application/octet-stream`.
44
- * 2. release asset named `ecc.tar.gz` or any `.tgz` / `.tar.gz`.
45
- * 3. PRD's `ecc.tar.gz` asset URL — dead today (v2.2.0 ships only
46
- * `.png` assets) but kept as last resort in case a future
47
- * release ships the asset again.
48
- */
49
- import { type DownloadResult } from './ecc-cache-config.js';
50
- /**
51
- * Download ECC into `~/.peaks/cache/ecc-<sha>/agents/`. Returns
52
- * the resolved SHA + the number of agents extracted.
53
- *
54
- * Throws `Error('fetch-failed')` on network failure so the CLI
55
- * layer can render the manual-install instructions.
56
- */
57
- export declare function downloadToCache({ ref }?: {
58
- ref?: string;
59
- }): Promise<DownloadResult>;
60
- export { ECC_REPO_OWNER, ECC_REPO_NAME, type CacheManifest, type DownloadResult, type EccMaterializeManifest, resolveEccCacheDir, resolveManifestPath, resolveShaDir, resolveAgentsDir, resolveEccMaterializedDir, resolveEccMaterializedManifestPath, setCacheDirPermissions } from './ecc-cache-config.js';
61
- export { readCacheManifest, listCachedAgents, readAgentSkill } from './ecc-cache-manifest.js';
62
- export { readEccMaterializeManifest, listMaterializedAgents, hasMaterializedEccAgents, resolveMaterializedAgentName, readMaterializedAgent } from './ecc-materialized-readers.js';
63
- export { materializeEccAgents } from './ecc-materialize.js';
64
- export { cleanupStaleCache } from './ecc-cache-cleanup.js';
65
- //# sourceMappingURL=ecc-cache-service.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ecc-cache-service.d.ts","sourceRoot":"","sources":["../../../src/services/agent/ecc-cache-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAaH,OAAO,EASL,KAAK,cAAc,EACpB,MAAM,uBAAuB,CAAC;AAK/B;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,EAAE,GAAG,EAAE,GAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,OAAO,CAAC,cAAc,CAAC,CAkD7F;AAGD,OAAO,EACL,cAAc,EACd,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,sBAAsB,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,yBAAyB,EACzB,kCAAkC,EAClC,sBAAsB,EACvB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAE9F,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,wBAAwB,EACxB,4BAA4B,EAC5B,qBAAqB,EACtB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC"}
@@ -1,118 +0,0 @@
1
- /**
2
- * ECC cache service — Slice 3 of 4.0.0-beta.11.
3
- *
4
- * Drop-in replacement for the deleted `ecc-agent-service.ts`. The
5
- * pre-Slice-3 implementation shelled out to `npx ecc agent run ...`,
6
- * but the upstream `affaan-m/everything-claude-code` v2.0.0 release
7
- * has NO `ecc` binary — the repo is `agents/*.md` flat files plus
8
- * SKILL.md descriptors. The peaks-loop path is therefore download
9
- * + cache only; the LLM consumes cached `agents/*.md` directly
10
- * through `peaks ecc show <name>`.
11
- *
12
- * Six cache exports per RD §2:
13
- * - setCacheDirPermissions
14
- * - downloadToCache
15
- * - readCacheManifest
16
- * - listCachedAgents
17
- * - readAgentSkill
18
- * - cleanupStaleCache
19
- *
20
- * Slice A of 2026-09-09-ecc-dynamic adds the plugin-free materialize
21
- * layer (`materializeEccAgents` + readers) that copies the active sha's
22
- * `agents/*.md` into `~/.peaks/agents/ecc/` so the RD fan-out works on a
23
- * machine with no ECC Claude Code plugin.
24
- *
25
- * The cache layout is `~/.peaks/cache/ecc-installed.json` (manifest)
26
- * + `~/.peaks/cache/ecc-<sha>/agents/<name>.md`. The manifest is
27
- * the active-cache pointer; cleanupStaleCache iterates the on-disk
28
- * sha directories and decides based on the manifest's `fetchedAt`
29
- * (active) vs `mtimeMs` (orphan).
30
- *
31
- * Hard contracts (Karpathy #2 Simplicity First):
32
- * - No subprocess plumbing. Network is `fetch()` only.
33
- * - No factory; one module, six functions, six dependencies.
34
- * - Strict selective extract: agents/*.md only, no symlinks, no
35
- * `..`, no absolute paths, no devices.
36
- * - D-009 fallback: parseFrontmatter throws on malformed input —
37
- * wrap it in try/catch and synthesize `{name, description}`
38
- * from the file name + first non-empty body line.
39
- * - D-010 fallback order (2026-09-09, leads with what actually works):
40
- * 1. `tarball_url` from `releases/tags/<ref>` — the only path that
41
- * serves a tarball on upstream v2.2.0. Must be fetched with
42
- * `accept: application/vnd.github+json`; GitHub's API tarball
43
- * endpoint answers 415 to `application/octet-stream`.
44
- * 2. release asset named `ecc.tar.gz` or any `.tgz` / `.tar.gz`.
45
- * 3. PRD's `ecc.tar.gz` asset URL — dead today (v2.2.0 ships only
46
- * `.png` assets) but kept as last resort in case a future
47
- * release ships the asset again.
48
- */
49
- // ---------------------------------------------------------------------
50
- // 2026-10-03 wave 11 slice A: this file is the facade for the split. The
51
- // implementation lives in the sibling modules beside it; this module keeps
52
- // the download orchestration plus the FULL original export surface, because
53
- // `tests/unit/services/ecc/*` import this exact path after mocking
54
- // `node:os` (T2) and `src/index.ts` re-exports it. Do not move these files
55
- // without reading `.peaks/docs/lint-gate.md` §4e/§4r first.
56
- // ---------------------------------------------------------------------
57
- import { existsSync, mkdirSync, readdirSync } from 'node:fs';
58
- import { ECC_CACHE_VERSION, ECC_REPO_OWNER, ECC_REPO_NAME, resolveEccCacheDir, resolveAgentsDir, setCacheDirPermissions, asSha } from './ecc-cache-config.js';
59
- import { fetchReleaseJson, resolveCommitSha, downloadTarball } from './ecc-fetch.js';
60
- import { writeManifest } from './ecc-cache-manifest.js';
61
- import { materializeBestEffort } from './ecc-materialize.js';
62
- /**
63
- * Download ECC into `~/.peaks/cache/ecc-<sha>/agents/`. Returns
64
- * the resolved SHA + the number of agents extracted.
65
- *
66
- * Throws `Error('fetch-failed')` on network failure so the CLI
67
- * layer can render the manual-install instructions.
68
- */
69
- export async function downloadToCache({ ref } = {}) {
70
- const requestedRef = ref ?? 'latest';
71
- let resolvedSha;
72
- if (requestedRef === 'latest') {
73
- const release = await fetchReleaseJson(`https://api.github.com/repos/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/latest`);
74
- const tag = release?.tag_name;
75
- if (typeof tag !== 'string' || tag.length === 0) {
76
- throw new Error('fetch-failed');
77
- }
78
- resolvedSha = asSha((await resolveCommitSha(tag)) ?? tag);
79
- }
80
- else {
81
- resolvedSha = asSha((await resolveCommitSha(requestedRef)) ?? requestedRef);
82
- }
83
- const cacheDir = resolveEccCacheDir();
84
- if (!existsSync(cacheDir))
85
- mkdirSync(cacheDir, { recursive: true });
86
- setCacheDirPermissions(cacheDir);
87
- const agentsDir = resolveAgentsDir(resolvedSha, cacheDir);
88
- if (existsSync(agentsDir) && readdirSync(agentsDir).length > 0) {
89
- // Already populated; emit manifest + return.
90
- const agents = readdirSync(agentsDir)
91
- .filter((f) => f.endsWith('.md'))
92
- .map((f) => f.replace(/\.md$/i, ''));
93
- writeManifest({
94
- version: ECC_CACHE_VERSION,
95
- sha: resolvedSha,
96
- fetchedAt: new Date().toISOString(),
97
- agents
98
- });
99
- materializeBestEffort(cacheDir);
100
- return { sha: resolvedSha, agents: agents.length };
101
- }
102
- const extracted = await downloadTarball(requestedRef === 'latest' ? resolvedSha : requestedRef, resolvedSha, agentsDir);
103
- const manifest = {
104
- version: ECC_CACHE_VERSION,
105
- sha: resolvedSha,
106
- fetchedAt: new Date().toISOString(),
107
- agents: extracted
108
- };
109
- writeManifest(manifest);
110
- materializeBestEffort(cacheDir);
111
- return { sha: resolvedSha, agents: extracted.length };
112
- }
113
- // Re-exports — the exact public surface of the pre-split module.
114
- export { ECC_REPO_OWNER, ECC_REPO_NAME, resolveEccCacheDir, resolveManifestPath, resolveShaDir, resolveAgentsDir, resolveEccMaterializedDir, resolveEccMaterializedManifestPath, setCacheDirPermissions } from './ecc-cache-config.js';
115
- export { readCacheManifest, listCachedAgents, readAgentSkill } from './ecc-cache-manifest.js';
116
- export { readEccMaterializeManifest, listMaterializedAgents, hasMaterializedEccAgents, resolveMaterializedAgentName, readMaterializedAgent } from './ecc-materialized-readers.js';
117
- export { materializeEccAgents } from './ecc-materialize.js';
118
- export { cleanupStaleCache } from './ecc-cache-cleanup.js';
@@ -1,31 +0,0 @@
1
- /**
2
- * ECC network layer — release JSON fetch, SHA resolution and the D-010
3
- * tarball download chain (tarball_url -> release asset -> PRD asset URL),
4
- * including the accept-header rules that keep the API tarball alive.
5
- *
6
- * Split verbatim out of `ecc-cache-service.ts` (wave 11 slice A,
7
- * 2026-10-03); no behaviour changed.
8
- */
9
- /**
10
- * Best-effort fetch of the upstream release JSON. Returns the
11
- * parsed body, or null on any network/parse error. Used as the
12
- * D-010 fallback path.
13
- */
14
- declare function fetchReleaseJson(apiBase: string): Promise<{
15
- tag_name?: string;
16
- tarball_url?: string;
17
- assets?: {
18
- name: string;
19
- browser_download_url: string;
20
- }[];
21
- } | null>;
22
- /**
23
- * Resolve a 40-char commit SHA for `tag`. Prefers the GitHub
24
- * releases API (which dereferences annotated tags to commit SHA
25
- * via `target_commitish`). Falls back to the tag name if the
26
- * upstream returns a non-SHA-shaped identifier (older tags).
27
- */
28
- declare function resolveCommitSha(ref: string): Promise<string | null>;
29
- declare function downloadTarball(ref: string, sha: string, outDir: string): Promise<string[]>;
30
- export { fetchReleaseJson, resolveCommitSha, downloadTarball };
31
- //# sourceMappingURL=ecc-fetch.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ecc-fetch.d.ts","sourceRoot":"","sources":["../../../src/services/agent/ecc-fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAUH;;;;GAIG;AACH,iBAAe,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,oBAAoB,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC3D,GAAG,IAAI,CAAC,CAcR;AAED;;;;;GAKG;AACH,iBAAe,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAMnE;AAuBD,iBAAe,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAmC1F;AAGD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,CAAC"}
@@ -1,95 +0,0 @@
1
- /**
2
- * ECC network layer — release JSON fetch, SHA resolution and the D-010
3
- * tarball download chain (tarball_url -> release asset -> PRD asset URL),
4
- * including the accept-header rules that keep the API tarball alive.
5
- *
6
- * Split verbatim out of `ecc-cache-service.ts` (wave 11 slice A,
7
- * 2026-10-03); no behaviour changed.
8
- */
9
- import { ECC_REPO_OWNER, ECC_REPO_NAME, ECC_TARBALL_BASENAME, GITHUB_API_ACCEPT } from './ecc-cache-config.js';
10
- import { extractAgentsFromTarGz } from './ecc-archive-safety.js';
11
- /**
12
- * Best-effort fetch of the upstream release JSON. Returns the
13
- * parsed body, or null on any network/parse error. Used as the
14
- * D-010 fallback path.
15
- */
16
- async function fetchReleaseJson(apiBase) {
17
- try {
18
- const res = await fetch(apiBase, {
19
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'peaks-loop' }
20
- });
21
- if (!res.ok)
22
- return null;
23
- return (await res.json());
24
- }
25
- catch {
26
- return null;
27
- }
28
- }
29
- /**
30
- * Resolve a 40-char commit SHA for `tag`. Prefers the GitHub
31
- * releases API (which dereferences annotated tags to commit SHA
32
- * via `target_commitish`). Falls back to the tag name if the
33
- * upstream returns a non-SHA-shaped identifier (older tags).
34
- */
35
- async function resolveCommitSha(ref) {
36
- const apiBase = `https://api.github.com/repos/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/tags/${encodeURIComponent(ref)}`;
37
- const release = await fetchReleaseJson(apiBase);
38
- const tagName = release?.tag_name ?? ref;
39
- if (/^[0-9a-f]{40}$/.test(tagName))
40
- return tagName;
41
- return tagName;
42
- }
43
- /**
44
- * Binary fetch with an explicit, overridable `accept`.
45
- *
46
- * Do NOT default to `application/octet-stream`: GitHub's
47
- * `api.github.com/.../tarball/<ref>` endpoint rejects it with 415.
48
- * Omitting `accept` entirely is fine for release-asset / codeload
49
- * URLs, which always serve the bytes.
50
- */
51
- async function fetchBuffer(url, accept) {
52
- try {
53
- const headers = { 'user-agent': 'peaks-loop' };
54
- if (accept !== undefined)
55
- headers.accept = accept;
56
- const res = await fetch(url, { headers });
57
- if (!res.ok)
58
- return null;
59
- const ab = await res.arrayBuffer();
60
- return new Uint8Array(ab);
61
- }
62
- catch {
63
- return null;
64
- }
65
- }
66
- async function downloadTarball(ref, sha, outDir) {
67
- // D-010 order (2026-09-09): tarball_url -> release asset -> PRD URL.
68
- // See the module header for why each step exists and which one works.
69
- let buffer = null;
70
- const release = await fetchReleaseJson(`https://api.github.com/repos/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/tags/${encodeURIComponent(ref)}`);
71
- // 1. API tarball. Requires the GitHub JSON accept header (octet-stream 415s).
72
- const tarballUrl = release?.tarball_url;
73
- if (typeof tarballUrl === 'string' && tarballUrl.length > 0) {
74
- buffer = await fetchBuffer(tarballUrl, GITHUB_API_ACCEPT);
75
- }
76
- // 2. Release asset, if this release happens to ship one.
77
- if (buffer === null && Array.isArray(release?.assets)) {
78
- const asset = release.assets.find((a) => a.name === ECC_TARBALL_BASENAME) ??
79
- release.assets.find((a) => a.name === `${ECC_REPO_NAME}-universal-${ref}.tgz`) ??
80
- release.assets.find((a) => a.name.endsWith('.tgz') || a.name.endsWith('.tar.gz'));
81
- if (asset)
82
- buffer = await fetchBuffer(asset.browser_download_url);
83
- }
84
- // 3. PRD asset URL — last resort, dead upstream today.
85
- if (buffer === null) {
86
- const prdUrl = `https://github.com/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/download/${encodeURIComponent(ref)}/${ECC_TARBALL_BASENAME}`;
87
- buffer = await fetchBuffer(prdUrl);
88
- }
89
- if (buffer === null) {
90
- throw new Error('fetch-failed');
91
- }
92
- return extractAgentsFromTarGz(buffer, outDir);
93
- }
94
- // Cross-module glue: private inside ecc-cache-service.ts before the split.
95
- export { fetchReleaseJson, resolveCommitSha, downloadTarball };