@capagents/forgeqe 2.6.1 → 2.6.3

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 (98) hide show
  1. package/HOW_TO_USE.md +311 -15
  2. package/README.md +5 -25
  3. package/THIRD_PARTY_NOTICES.md +9 -0
  4. package/bin/activate-web.d.ts +16 -0
  5. package/bin/activate-web.js +117 -0
  6. package/bin/bundle.d.ts +27 -0
  7. package/bin/bundle.js +173 -0
  8. package/bin/forgeqe.js +109 -2
  9. package/bin/license.d.ts +25 -0
  10. package/bin/license.js +178 -0
  11. package/dist/docs-site/docs/architecture/index.html +2 -1
  12. package/dist/docs-site/docs/index.html +291 -11
  13. package/dist/docs-site/docs/search.js +1 -1
  14. package/dist/docs-site/docs/web-app/index.html +35 -6
  15. package/dist/forgeqe.js +1513 -1291
  16. package/dist/template.html +64 -64
  17. package/dist/web/assets/Agent-yd1DyMzR.js +4 -0
  18. package/dist/web/assets/ApiTests-BwOGta9J.js +10 -0
  19. package/dist/web/assets/Chat-P8GH_6gl.js +3 -0
  20. package/dist/web/assets/Data-D2iCqk3t.js +3 -0
  21. package/dist/web/assets/Features-Bu38clxs.js +1 -0
  22. package/dist/web/assets/Jobs-DymuaGeN.js +5 -0
  23. package/dist/web/assets/KindPage-zl6TBkEl.js +6 -0
  24. package/dist/web/assets/Migration-Cg_FUqS_.js +2 -0
  25. package/dist/web/assets/Quality-D3bSHP_B.js +1 -0
  26. package/dist/web/assets/Record-DkCLJos6.js +2 -0
  27. package/dist/web/assets/Regression-B2qMKjAE.js +5 -0
  28. package/dist/web/assets/Reports-D_G9yfDa.js +2 -0
  29. package/dist/web/assets/Response-BnPAefP-.js +4 -0
  30. package/dist/web/assets/Runs-DsDj9-LT.js +2 -0
  31. package/dist/web/assets/Shell-DlZHZN0d.js +3 -0
  32. package/dist/web/assets/TestData-qI1R5Q9v.js +2 -0
  33. package/dist/web/assets/WhatsNew-CoCHqSDm.js +1 -0
  34. package/dist/web/assets/accessibility-CH8EpEAV.svg +1 -0
  35. package/dist/web/assets/{arrow-down-BqARSDDZ.js → arrow-down-BWCXlJU0.js} +1 -1
  36. package/dist/web/assets/arrow-right-CdxkQBV7.js +1 -0
  37. package/dist/web/assets/{bot-BtKTIZEs.js → bot-D8486kSA.js} +1 -1
  38. package/dist/web/assets/capgemini-mark-D6aZFnD3.png +0 -0
  39. package/dist/web/assets/chevron-up-CQz_ZmIK.js +1 -0
  40. package/dist/web/assets/circle-BqXBUsQS.js +1 -0
  41. package/dist/web/assets/{circle-dashed-DwIAhHPq.js → circle-dashed-DlOiCbWD.js} +1 -1
  42. package/dist/web/assets/dataParts-bwNleJYd.js +3 -0
  43. package/dist/web/assets/forgeqe-logo-D3CwM2Jl.png +0 -0
  44. package/dist/web/assets/forgeqe-logo-white-CoE-hF2l.png +0 -0
  45. package/dist/web/assets/forgeqe-mark-ZLd4S3hw.png +0 -0
  46. package/dist/web/assets/index-Bh4NBbEU.js +37 -0
  47. package/dist/web/assets/index-DkgUrjyL.css +2 -0
  48. package/dist/web/assets/keyboard-wpCM6HMa.js +1 -0
  49. package/dist/web/assets/qualityParts-iy-mouSI.js +1 -0
  50. package/dist/web/assets/{thread-iCgQPYwX.js → thread-BfW2V-2U.js} +1 -1
  51. package/dist/web/assets/upload-CwExsxOd.js +1 -0
  52. package/dist/web/assets/usePageChat-CzWbP_sa.js +1 -0
  53. package/dist/web/index.html +3 -3
  54. package/docs/ARCHITECTURE.md +2 -1
  55. package/docs/CUSTOM_AGENTS_FIRST_RUN.md +107 -0
  56. package/docs/WEB_APP.md +36 -6
  57. package/docs/security-data-flow.html +3 -3
  58. package/docs/user-guide.html +291 -11
  59. package/docs/walkthrough/hotfix-narration.md +443 -297
  60. package/forgeqe.example.yaml +13 -2
  61. package/package.json +6 -3
  62. package/prompts/README.md +1 -0
  63. package/prompts/agent-builder.md +69 -0
  64. package/prompts/api-tests.md +1 -1
  65. package/prompts/brain.md +22 -2
  66. package/prompts/browser-persona.md +14 -0
  67. package/prompts/db-agent.md +73 -0
  68. package/prompts/heal.md +1 -1
  69. package/prompts/migrate.md +54 -0
  70. package/prompts/test-agent.md +1 -0
  71. package/py/forgeqe_engine/cli.py +9 -1
  72. package/py/forgeqe_engine/copilot_gateway.py +162 -9
  73. package/py/forgeqe_engine/persona.py +435 -0
  74. package/py/forgeqe_engine/proceed.py +67 -0
  75. package/py/forgeqe_engine/service.py +93 -11
  76. package/skills/test-data/SKILL.md +4 -0
  77. package/dist/web/assets/Agent-jYaYLJO8.js +0 -1
  78. package/dist/web/assets/ApiTests-BYQ0VYx3.js +0 -10
  79. package/dist/web/assets/Chat-DOcK3ngF.js +0 -3
  80. package/dist/web/assets/Data-KFQ0-EbI.js +0 -4
  81. package/dist/web/assets/Features-9rw1s5Vs.js +0 -1
  82. package/dist/web/assets/Jobs-MRHq6isA.js +0 -5
  83. package/dist/web/assets/Quality-CGrki-iI.js +0 -1
  84. package/dist/web/assets/Record-Bamcsz1Y.js +0 -2
  85. package/dist/web/assets/Regression-D0yEt-3X.js +0 -5
  86. package/dist/web/assets/Reports-BwvQNDFa.js +0 -2
  87. package/dist/web/assets/Response-XIaBzLD_.js +0 -4
  88. package/dist/web/assets/Runs-DtgNqxHd.js +0 -2
  89. package/dist/web/assets/Shell-E3JKoPtx.js +0 -3
  90. package/dist/web/assets/accessibility-BSaq_4Me.svg +0 -1
  91. package/dist/web/assets/capgemini-BO8ajcbd.svg +0 -21
  92. package/dist/web/assets/capgemini-white-ByjwPW8N.svg +0 -21
  93. package/dist/web/assets/circle-C_9D6W14.js +0 -1
  94. package/dist/web/assets/index-CVa5dAjG.js +0 -26
  95. package/dist/web/assets/index-DF-gVa3Q.css +0 -2
  96. package/dist/web/assets/markdown-OsvJ-mly.js +0 -10
  97. package/dist/web/assets/trending-up-fRykocOw.js +0 -1
  98. package/dist/web/assets/usePageChat-B5pKShGC.js +0 -1
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The built-in activation page for `forgeqe web` (design/forgeqe-gated-distribution-rfc.md §4): when the machine is not
3
+ * yet activated, the launcher serves this tiny page BEFORE the real web app exists (the real app is still inside the
4
+ * undownloaded bundle). The customer pastes their licence key, it activates, and the launcher proceeds to download and
5
+ * start the real app. Plain Node http, self-contained HTML (no external resources), bound to 127.0.0.1.
6
+ */
7
+ import { createServer } from "node:http"
8
+
9
+ const PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8">
10
+ <meta name="viewport" content="width=device-width, initial-scale=1">
11
+ <title>Activate ForgeQE</title><style>
12
+ /* ForgeQE design tokens (web/src/index.css): light by default, same tokens for dark. */
13
+ :root{color-scheme:light dark;
14
+ --bg:#ffffff;--surface:#f9fafb;--field:#f4f5f7;--line:#e5e7eb;--line-strong:#d1d5db;
15
+ --ink:#111928;--ink-2:#374151;--muted:#6b7280;--accent:#3758f9;--accent-hover:#1b44c8;--accent-ink:#fff;
16
+ --pass:#047857;--fail:#be123c;--radius:.75rem;--shadow:0 18px 44px -22px rgba(17,25,40,.22);
17
+ --font-sans:"DM Sans",system-ui,sans-serif}
18
+ @media (prefers-color-scheme:dark){:root{
19
+ --bg:#111318;--surface:#171a21;--field:#1a1d25;--line:#2b303b;--line-strong:#3a404d;
20
+ --ink:#e9ebf0;--ink-2:#c3c8d2;--muted:#8d95a5;--pass:#34d399;--fail:#fb7185;--shadow:0 18px 44px -22px rgba(0,0,0,.7)}}
21
+ *{box-sizing:border-box}
22
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font-family:var(--font-sans);font-size:15px}
23
+ .card{width:min(92vw,440px);padding:32px;border:1px solid var(--line);border-radius:var(--radius);background:var(--surface);box-shadow:var(--shadow)}
24
+ h1{font-size:1.2rem;font-weight:600;margin:0 0 6px}p{margin:.3rem 0 1.2rem;color:var(--muted);font-size:.92rem;line-height:1.5}
25
+ input,button{width:100%;font-size:1rem;border-radius:.6rem}
26
+ input{padding:11px 13px;border:1px solid var(--line);background:var(--field);color:inherit;margin-bottom:12px;font-family:var(--font-sans)}
27
+ input:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-color:var(--accent)}
28
+ button{padding:11px;border:0;background:var(--accent);color:var(--accent-ink);font-weight:600;cursor:pointer}
29
+ button:hover{background:var(--accent-hover)}button:disabled{opacity:.55;cursor:default}
30
+ .msg{min-height:1.2em;margin-top:12px;font-size:.9rem}.err{color:var(--fail)}.ok{color:var(--pass)}
31
+ </style></head><body><div class="card">
32
+ <h1>Activate ForgeQE</h1><p>Paste the licence key from your ForgeQE representative. This activates one seat on this machine.</p>
33
+ <input id="k" placeholder="FQK1…" autocomplete="off" autofocus>
34
+ <button id="go">Activate</button><div id="m" class="msg"></div></div>
35
+ <script>
36
+ const k=document.getElementById('k'),go=document.getElementById('go'),m=document.getElementById('m');
37
+ async function submit(){go.disabled=true;m.className='msg';m.textContent='Activating…';
38
+ try{const r=await fetch('/activate',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({key:k.value})});
39
+ const d=await r.json();
40
+ if(r.ok&&d.ok){m.className='msg ok';m.textContent='Activated. Starting ForgeQE…';setTimeout(()=>location.reload(),1200);}
41
+ else{m.className='msg err';m.textContent=d.message||'Activation failed.';go.disabled=false;}
42
+ }catch(e){m.className='msg err';m.textContent='Could not reach the licence service.';go.disabled=false;}}
43
+ go.onclick=submit;k.addEventListener('keydown',e=>{if(e.key==='Enter')submit();});
44
+ </script></body></html>`
45
+
46
+ /**
47
+ * Handle one request of the activation page. Pure-ish: `activate(key)` resolves to a token or throws a message;
48
+ * `onActivated(token)` is called once activation succeeds. Returns nothing; writes the response. Exported for tests.
49
+ */
50
+ export async function handleActivationRequest(req, res, { activate, onActivated, readBody }) {
51
+ const url = req.url || "/"
52
+ if (req.method === "GET" && (url === "/" || url.startsWith("/?"))) {
53
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" })
54
+ res.end(PAGE)
55
+ return
56
+ }
57
+ if (req.method === "POST" && url === "/activate") {
58
+ let key = ""
59
+ try {
60
+ const body = await (readBody ? readBody(req) : readRequestBody(req))
61
+ key = (JSON.parse(body || "{}").key || "").trim()
62
+ } catch {}
63
+ try {
64
+ const token = await activate(key)
65
+ res.writeHead(200, { "content-type": "application/json" })
66
+ res.end(JSON.stringify({ ok: true }))
67
+ onActivated?.(token)
68
+ } catch (err) {
69
+ res.writeHead(400, { "content-type": "application/json" })
70
+ res.end(JSON.stringify({ ok: false, message: err instanceof Error ? err.message : String(err) }))
71
+ }
72
+ return
73
+ }
74
+ res.writeHead(404, { "content-type": "text/plain" })
75
+ res.end("not found")
76
+ }
77
+
78
+ function readRequestBody(req) {
79
+ return new Promise((resolve, reject) => {
80
+ let data = ""
81
+ req.on("data", (c) => {
82
+ data += c
83
+ if (data.length > 8192) reject(new Error("too large"))
84
+ })
85
+ req.on("end", () => resolve(data))
86
+ req.on("error", reject)
87
+ })
88
+ }
89
+
90
+ /**
91
+ * Serve the activation page on 127.0.0.1:`port` and resolve with the activation token once the customer activates
92
+ * successfully, then close the server. `activate(key)` performs the real activation (activateWithKey, bound by the
93
+ * launcher). The launcher opens the browser at the returned-from address.
94
+ */
95
+ export function serveActivation({ port = 0, host = "127.0.0.1", activate, onListening, log = () => {} }) {
96
+ return new Promise((resolve, reject) => {
97
+ let settled = false
98
+ const server = createServer((req, res) => {
99
+ handleActivationRequest(req, res, {
100
+ activate,
101
+ onActivated: (token) => {
102
+ if (settled) return
103
+ settled = true
104
+ // Let the success response flush before we close and continue.
105
+ setTimeout(() => server.close(() => resolve(token)), 300)
106
+ },
107
+ }).catch((err) => log(`activation page error: ${err instanceof Error ? err.message : err}`))
108
+ })
109
+ server.on("error", reject)
110
+ server.listen(port, host, () => {
111
+ const addr = server.address()
112
+ const url = typeof addr === "object" && addr ? `http://${host}:${addr.port}/` : `http://${host}:${port}/`
113
+ log(`forgeqe: open ${url} to activate ForgeQE.`)
114
+ onListening?.(url)
115
+ })
116
+ })
117
+ }
@@ -0,0 +1,27 @@
1
+ /** Phase 1 gated-distribution bundle resolver (design/forgeqe-gated-distribution-rfc.md). Types for bin/bundle.js. */
2
+
3
+ export const BUNDLE_MARKERS: string[]
4
+ export function bundlePresent(root: string, markers?: string[]): boolean
5
+ export function bundleDir(home: string, version: string): string
6
+ export function bundleAsset(version: string): string
7
+
8
+ export type TarEntry = { name: string; mode: number; data?: Buffer; dir?: boolean }
9
+ export function readTar(input: Uint8Array | ArrayBufferView): TarEntry[]
10
+ export function extractBundle(tarGz: Uint8Array, dest: string): number
11
+ export function sha256(buf: Uint8Array): string
12
+ export function bundleUrl(repo: string, tag: string, version: string, env?: Record<string, string | undefined>): string
13
+
14
+ export type ResolveBundleOptions = {
15
+ packageRoot: string
16
+ home: string
17
+ version: string
18
+ env?: Record<string, string | undefined>
19
+ log?: (message: string) => void
20
+ repo?: string
21
+ tag?: string
22
+ url?: string
23
+ sha256Url?: string
24
+ fetchUrl?: (url: string) => Promise<Buffer>
25
+ }
26
+ export function resolveBundleRoot(opts: ResolveBundleOptions): Promise<string>
27
+ export function packageVersion(root: string): string
package/bin/bundle.js ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Phase 1 of the gated distribution (design/forgeqe-gated-distribution-rfc.md): the bundle resolver.
3
+ *
4
+ * The public npm/PyPI package is meant to become a thin launcher that carries no prompts, skills, engine, or real
5
+ * `dist/`. Those live in a signed bundle downloaded once per version into `~/.forgeqe/pkg/<version>/` and run from
6
+ * there. This module is that download-verify-extract-cache step, written in plain Node with no dependencies (like
7
+ * bin/forgeqe.js), so the launcher stays tiny.
8
+ *
9
+ * It is backward-compatible: `resolveBundleRoot` returns the package's own folder unchanged whenever the bundle is
10
+ * already there (a checkout of the source, or today's package that still ships everything), and only downloads when it
11
+ * is not. No auth yet — Phase 3 adds the license header and the gated host; the `fetchUrl` hook is where that goes.
12
+ */
13
+
14
+ import { createHash } from "node:crypto"
15
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
16
+ import path from "node:path"
17
+ import { gunzipSync } from "node:zlib"
18
+
19
+ /** The files a present bundle (or checkout) must have for ForgeQE to run, so a half-written download is never used. */
20
+ export const BUNDLE_MARKERS = ["prompts", "skills"]
21
+
22
+ /** True when `root` already holds the bundle's files (a checkout, or a package that still ships them): no download. */
23
+ export function bundlePresent(root, markers = BUNDLE_MARKERS) {
24
+ // A checkout runs from src/; a shipped bundle runs from dist/. Either proves the code is here.
25
+ if (!existsSync(path.join(root, "src", "index.ts")) && !existsSync(path.join(root, "dist", "forgeqe.js"))) return false
26
+ return markers.every((m) => existsSync(path.join(root, m)))
27
+ }
28
+
29
+ /** `~/.forgeqe/pkg/<version>/`, where a downloaded bundle for this version is cached and run from. */
30
+ export function bundleDir(home, version) {
31
+ if (!version || /[\\/]/.test(version)) throw new Error(`a bundle version cannot be empty or hold a path separator: ${version}`)
32
+ return path.join(home, "pkg", version)
33
+ }
34
+
35
+ /** The gated bundle's asset name for a release, e.g. forgeqe-bundle-2.4.0.tar.gz. */
36
+ export function bundleAsset(version) {
37
+ return `forgeqe-bundle-${version}.tar.gz`
38
+ }
39
+
40
+ /**
41
+ * A minimal POSIX ustar reader (the format `scripts/bundle.ts` writes): regular files and directories only, no GNU long
42
+ * names, no sparse files. Returns [{ name, mode, data }]. Hand-rolled to keep the launcher dependency-free, like
43
+ * bin/forgeqe.js's unzip.
44
+ */
45
+ export function readTar(input) {
46
+ const buf = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer || input, input.byteOffset || 0, input.byteLength)
47
+ const out = []
48
+ for (let off = 0; off + 512 <= buf.length; ) {
49
+ const block = buf.subarray(off, off + 512)
50
+ if (block.every((b) => b === 0)) break // the two zero blocks that end the archive
51
+ const name = cStr(block, 0, 100)
52
+ const prefix = cStr(block, 345, 155)
53
+ const full = prefix ? `${prefix}/${name}` : name
54
+ const mode = parseInt(cStr(block, 100, 8).trim() || "0", 8) || 0
55
+ const size = parseInt(cStr(block, 124, 12).trim() || "0", 8) || 0
56
+ const type = String.fromCharCode(block[156] || 0)
57
+ const start = off + 512
58
+ const data = buf.subarray(start, start + size)
59
+ if (full.includes("..") || path.isAbsolute(full)) throw new Error(`unsafe path in bundle: ${full}`)
60
+ if (type === "0" || type === "\0" || type === "") out.push({ name: full, mode, data: Buffer.from(data) })
61
+ else if (type === "5") out.push({ name: full.replace(/\/$/, ""), mode, dir: true })
62
+ off = start + Math.ceil(size / 512) * 512
63
+ }
64
+ return out
65
+ }
66
+
67
+ function cStr(block, start, len) {
68
+ const slice = block.subarray(start, start + len)
69
+ const end = slice.indexOf(0)
70
+ return slice.toString("utf8", 0, end === -1 ? len : end)
71
+ }
72
+
73
+ /** Extract a gzipped ustar tarball into `dest` (created). Regular files get their mode; nothing escapes `dest`. */
74
+ export function extractBundle(tarGz, dest) {
75
+ const entries = readTar(gunzipSync(tarGz))
76
+ const root = path.resolve(dest)
77
+ for (const e of entries) {
78
+ const target = path.resolve(root, e.name)
79
+ if (target !== root && !target.startsWith(root + path.sep)) throw new Error(`bundle entry escapes its folder: ${e.name}`)
80
+ if (e.dir) {
81
+ mkdirSync(target, { recursive: true })
82
+ continue
83
+ }
84
+ mkdirSync(path.dirname(target), { recursive: true })
85
+ writeFileSync(target, e.data)
86
+ if (process.platform !== "win32" && e.mode & 0o111) chmodSync(target, 0o755)
87
+ }
88
+ return entries.length
89
+ }
90
+
91
+ /** The hex SHA-256 of a buffer. */
92
+ export function sha256(buf) {
93
+ return createHash("sha256").update(buf).digest("hex")
94
+ }
95
+
96
+ /**
97
+ * A GitHub-release download URL for the bundle, honouring FORGEQE_GITHUB_MIRROR exactly as bin/forgeqe.js and
98
+ * py/forgeqe_cli/launcher.py do. `repo` and `tag` identify the (private, in production) release the bundle is an asset
99
+ * of. Phase 3 may replace this with a signed object-storage URL from the license service.
100
+ */
101
+ export function bundleUrl(repo, tag, version, env = process.env) {
102
+ const mirror = (env.FORGEQE_GITHUB_MIRROR || "").trim().replace(/\/+$/, "")
103
+ const base = /^https:\/\//i.test(mirror) ? mirror : "https://github.com"
104
+ return `${base}/${repo}/releases/download/${tag}/${bundleAsset(version)}`
105
+ }
106
+
107
+ async function defaultFetch(url) {
108
+ const res = await fetch(url, { redirect: "follow" })
109
+ if (!res.ok) throw new Error(`${url} returned ${res.status}`)
110
+ return Buffer.from(await res.arrayBuffer())
111
+ }
112
+
113
+ /**
114
+ * Where ForgeQE runs its code from for this version. Returns, in order:
115
+ * 1. `packageRoot` itself when the bundle is already there (checkout or today's full package) — no network.
116
+ * 2. `FORGEQE_BUNDLE_DIR` when set and it holds the bundle (air-gapped / pre-seeded, RFC §6).
117
+ * 3. `~/.forgeqe/pkg/<version>/` when already downloaded.
118
+ * 4. a fresh download: fetch the tarball + its .sha256, verify, extract atomically into (3), then use it.
119
+ *
120
+ * `opts.fetchUrl(url)` returns a Buffer (the auth header for the gated host goes here in Phase 3); `opts.url` /
121
+ * `opts.sha256Url` override the computed GitHub-release URLs (e.g. a signed object-storage URL). Throws with an
122
+ * actionable message when there is no bundle and no way to get one.
123
+ */
124
+ export async function resolveBundleRoot(opts) {
125
+ const { packageRoot, home, version, env = process.env, log = () => {} } = opts
126
+ if (bundlePresent(packageRoot)) return packageRoot
127
+
128
+ const seeded = (env.FORGEQE_BUNDLE_DIR || "").trim()
129
+ if (seeded) {
130
+ const dir = path.resolve(seeded)
131
+ if (bundlePresent(dir)) return dir
132
+ throw new Error(`FORGEQE_BUNDLE_DIR=${seeded} does not hold a ForgeQE bundle (expected ${BUNDLE_MARKERS.join(", ")}).`)
133
+ }
134
+
135
+ const dir = bundleDir(home, version)
136
+ if (bundlePresent(dir)) return dir
137
+
138
+ const fetchUrl = opts.fetchUrl || defaultFetch
139
+ const url = opts.url || (opts.repo && opts.tag ? bundleUrl(opts.repo, opts.tag, version, env) : null)
140
+ if (!url) throw new Error("No ForgeQE bundle is installed and no download source is configured. Set FORGEQE_BUNDLE_DIR to a pre-fetched bundle, or configure the bundle host.")
141
+ const sha256Url = opts.sha256Url || `${url}.sha256`
142
+
143
+ log(`forgeqe: downloading the ForgeQE ${version} bundle into ${dir} (one time)...`)
144
+ const [tarGz, sumsRaw] = await Promise.all([fetchUrl(url), fetchUrl(sha256Url)])
145
+ const expected = String(sumsRaw).trim().split(/\s+/)[0]?.toLowerCase()
146
+ const actual = sha256(tarGz)
147
+ if (!expected || !/^[0-9a-f]{64}$/.test(expected)) throw new Error(`the bundle checksum from ${sha256Url} is not a sha256.`)
148
+ if (expected !== actual) throw new Error(`bundle checksum mismatch: expected ${expected}, got ${actual}. The download was refused.`)
149
+
150
+ const tmp = `${dir}.${process.pid}.tmp`
151
+ rmSync(tmp, { recursive: true, force: true })
152
+ mkdirSync(tmp, { recursive: true })
153
+ extractBundle(tarGz, tmp)
154
+ if (!bundlePresent(tmp)) throw new Error(`the downloaded bundle is incomplete (missing ${BUNDLE_MARKERS.join(", ")}).`)
155
+ mkdirSync(path.dirname(dir), { recursive: true })
156
+ rmSync(dir, { recursive: true, force: true })
157
+ renameSync(tmp, dir)
158
+
159
+ // A new version is in place: drop older cached bundles so ~/.forgeqe/pkg does not grow without bound.
160
+ const pkgRoot = path.dirname(dir)
161
+ for (const old of readdirSync(pkgRoot)) {
162
+ const p = path.join(pkgRoot, old)
163
+ try {
164
+ if (p !== dir && statSync(p).isDirectory()) rmSync(p, { recursive: true, force: true })
165
+ } catch {}
166
+ }
167
+ return dir
168
+ }
169
+
170
+ /** The version to resolve a bundle for: a package.json's version at `root`. */
171
+ export function packageVersion(root) {
172
+ return JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version
173
+ }
package/bin/forgeqe.js CHANGED
@@ -8,13 +8,17 @@
8
8
 
9
9
  import { spawnSync } from "node:child_process";
10
10
  import { createHash } from "node:crypto";
11
- import { chmodSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
12
  import os from "node:os";
13
13
  import path from "node:path";
14
14
  import { createRequire } from "node:module";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { inflateRawSync } from "node:zlib";
17
17
 
18
+ import { packageVersion, resolveBundleRoot } from "./bundle.js";
19
+ import { activateWithKey, authorize, canPrompt, DEFAULT_LICENSE_URL, loadCachedToken, promptKeyTTY } from "./license.js";
20
+ import { serveActivation } from "./activate-web.js";
21
+
18
22
  export const BUN_VERSION = "1.4.2";
19
23
 
20
24
  /** The CLI's entry: the TypeScript in a checkout of the source, else the bundle the shipped package holds in dist/. */
@@ -25,7 +29,6 @@ export function cliEntry(root) {
25
29
  const MIN_BUN = [1, 3, 0];
26
30
 
27
31
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
28
- const entry = cliEntry(root);
29
32
  const windows = process.platform === "win32";
30
33
  const exe = windows ? "bun.exe" : "bun";
31
34
 
@@ -193,7 +196,111 @@ function manualHint() {
193
196
  return `Reinstall ForgeQE with npm (npm install -g @capagents/forgeqe), which brings Bun through your npm registry,\nor install Bun ${MIN_BUN.join(".")}+ yourself (${install}) and re-run forgeqe,\nor set FORGEQE_BUN to the full path of ${exe}.\nBehind a company mirror of GitHub downloads, set FORGEQE_GITHUB_MIRROR to it.`;
194
197
  }
195
198
 
199
+ /**
200
+ * The folder ForgeQE runs its code from: the package itself when it still ships the code (today, or a checkout), else
201
+ * the per-version bundle downloaded into ~/.forgeqe/pkg (design/forgeqe-gated-distribution-rfc.md). The download source,
202
+ * when the package is the thin launcher, comes from package.json's "bundle" { repo, tag } or FORGEQE_BUNDLE_REPO /
203
+ * FORGEQE_BUNDLE_TAG; with neither, resolveBundleRoot throws an actionable message unless FORGEQE_BUNDLE_DIR is set.
204
+ */
205
+ /**
206
+ * Get a valid activation token, collecting the licence key the way that suits the surface, so activation is forced
207
+ * before `start`/`web` run: a cached/env token is reused; else the FORGEQE_LICENSE_KEY env var; else `web` serves the
208
+ * activation page in the browser, an interactive terminal prompts, and a non-interactive run (CI with no key) throws.
209
+ */
210
+ async function obtainToken(command, licenseUrl, home, log) {
211
+ const cached = loadCachedToken({ home, env: process.env });
212
+ if (cached) return cached;
213
+ const envKey = (process.env.FORGEQE_LICENSE_KEY || "").trim();
214
+ if (envKey) {
215
+ log("forgeqe: activating this machine with your ForgeQE licence...");
216
+ return activateWithKey(envKey, { home, licenseUrl, log });
217
+ }
218
+ if (command === "web") {
219
+ return serveActivation({
220
+ activate: (key) => activateWithKey(key, { home, licenseUrl, log }),
221
+ onListening: (url) => openInBrowser(url),
222
+ log,
223
+ });
224
+ }
225
+ // Terminal (start/run/TUI and the rest): prompt when we can, else an actionable error (CI).
226
+ return authorize({ home, env: process.env, licenseUrl, log, getKey: canPrompt() ? () => promptKeyTTY() : undefined });
227
+ }
228
+
229
+ /** `forgeqe activate`: activate this machine now (prompt for the key, or take --license-key / FORGEQE_LICENSE_KEY). */
230
+ async function runActivate() {
231
+ let cfg = {};
232
+ try {
233
+ cfg = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).bundle || {};
234
+ } catch {}
235
+ const home = forgeqeHome();
236
+ const licenseUrl = (process.env.FORGEQE_LICENSE_URL || cfg.licenseUrl || DEFAULT_LICENSE_URL || "").replace(/\/+$/, "");
237
+ if (!licenseUrl) {
238
+ console.error("forgeqe: no licence service is configured.");
239
+ return 1;
240
+ }
241
+ const flagIdx = process.argv.indexOf("--license-key");
242
+ const key = flagIdx !== -1 ? process.argv[flagIdx + 1] : (process.env.FORGEQE_LICENSE_KEY || "").trim() || (canPrompt() ? await promptKeyTTY() : "");
243
+ try {
244
+ await activateWithKey(key, { home, licenseUrl, log: (m) => process.stderr.write(`${m}\n`) });
245
+ console.log("ForgeQE is activated on this machine.");
246
+ return 0;
247
+ } catch (err) {
248
+ console.error(`forgeqe: ${err instanceof Error ? err.message : err}`);
249
+ return 1;
250
+ }
251
+ }
252
+
253
+ async function bundleRoot() {
254
+ let cfg = {};
255
+ try {
256
+ cfg = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).bundle || {};
257
+ } catch {}
258
+ const home = forgeqeHome();
259
+ const version = packageVersion(root);
260
+ const log = (m) => process.stderr.write(`${m}\n`);
261
+
262
+ // Gated mode: when a licence service is configured, the bundle is fetched THROUGH it with an activation token
263
+ // (design/forgeqe-gated-distribution-rfc.md §3–§4). Activation happens lazily, only if a download is actually needed
264
+ // (resolveBundleRoot returns early when the bundle is already present), so a cached bundle never forces a round-trip.
265
+ const licenseUrl = (process.env.FORGEQE_LICENSE_URL || cfg.licenseUrl || DEFAULT_LICENSE_URL || "").replace(/\/+$/, "");
266
+ if (licenseUrl) {
267
+ const command = process.argv[2];
268
+ let token;
269
+ const authed = async (url) => {
270
+ // Activation is forced here, before the bundle downloads, so start/web do nothing until the machine is licensed.
271
+ if (!token) token = await obtainToken(command, licenseUrl, home, log);
272
+ const res = await fetch(url, { redirect: "follow", headers: { authorization: `Bearer ${token}` } });
273
+ if (!res.ok) throw new Error(`${url} returned ${res.status}`);
274
+ return Buffer.from(await res.arrayBuffer());
275
+ };
276
+ const base = `${licenseUrl}/bundle?version=${encodeURIComponent(version)}`;
277
+ return resolveBundleRoot({ packageRoot: root, home, version, url: base, sha256Url: `${base}&format=sha256`, fetchUrl: authed, log });
278
+ }
279
+
280
+ // Ungated fallback (checkout, today's full package, or a direct GitHub-release bundle via FORGEQE_BUNDLE_REPO/TAG).
281
+ return resolveBundleRoot({
282
+ packageRoot: root,
283
+ home,
284
+ version,
285
+ repo: process.env.FORGEQE_BUNDLE_REPO || cfg.repo,
286
+ tag: process.env.FORGEQE_BUNDLE_TAG || cfg.tag,
287
+ log,
288
+ });
289
+ }
290
+
196
291
  async function main() {
292
+ // `forgeqe activate` runs before anything else and never needs the bundle.
293
+ if (process.argv[2] === "activate") {
294
+ process.exit(await runActivate());
295
+ }
296
+ let codeRoot;
297
+ try {
298
+ codeRoot = await bundleRoot();
299
+ } catch (err) {
300
+ console.error(`forgeqe: ${err instanceof Error ? err.message : err}`);
301
+ process.exit(1);
302
+ }
303
+ const entry = cliEntry(codeRoot);
197
304
  if (!existsSync(entry)) {
198
305
  console.error(`forgeqe: CLI entry missing at ${entry}`);
199
306
  process.exit(1);
@@ -0,0 +1,25 @@
1
+ /** Client-side activation for ForgeQE's per-customer licensing. Types for bin/license.js. */
2
+
3
+ export const PUBLIC_KEY_PEM: string
4
+ export const DEFAULT_LICENSE_URL: string
5
+
6
+ export type ActivationTokenPayload = { v: number; cid: string; mid: string; kid: string; exp: number }
7
+
8
+ export function verifyToken(token: string, publicKeyObj: import("node:crypto").KeyObject | null, now?: number): ActivationTokenPayload | null
9
+ export function machineId(home: string): string
10
+ export function canPrompt(stdin?: NodeJS.ReadStream, stdout?: NodeJS.WriteStream): boolean
11
+ export function promptKeyTTY(input?: NodeJS.ReadStream, output?: NodeJS.WriteStream): Promise<string>
12
+
13
+ export type AuthorizeOptions = {
14
+ home: string
15
+ env?: Record<string, string | undefined>
16
+ licenseUrl?: string
17
+ publicKeyPem?: string
18
+ now?: number
19
+ log?: (message: string) => void
20
+ fetchImpl?: (url: string, init?: unknown) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>
21
+ getKey?: () => Promise<string> | string
22
+ }
23
+ export function loadCachedToken(opts: Pick<AuthorizeOptions, "home" | "env" | "publicKeyPem" | "now">): string | null
24
+ export function activateWithKey(key: string, opts: AuthorizeOptions): Promise<string>
25
+ export function authorize(opts: AuthorizeOptions): Promise<string>
package/bin/license.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Client side of ForgeQE's per-customer licensing (design/forgeqe-gated-distribution-rfc.md §2, §4): activate a machine
3
+ * against the Azure license service and cache the short-lived activation token, so the launcher can fetch the gated
4
+ * bundle. Plain Node, no dependencies, like the rest of bin/.
5
+ *
6
+ * Order of authority (first that works wins):
7
+ * 1. FORGEQE_ACTIVATION_TOKEN — a pre-minted token (air-gapped CI); verified offline, used as-is.
8
+ * 2. ~/.forgeqe/activation.jwt — the cached token from a previous activation; verified offline, re-used until expiry.
9
+ * 3. FORGEQE_LICENSE_KEY — the customer key; POST /activate to mint and cache a token.
10
+ *
11
+ * Verification uses only the public key shipped with the launcher (PUBLIC_KEY_PEM), so steps 1–2 are fully offline.
12
+ * This module never writes the license key to disk — only the activation token it gets back.
13
+ */
14
+
15
+ import { createPublicKey, verify as edVerify } from "node:crypto"
16
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
17
+ import path from "node:path"
18
+ import { randomUUID } from "node:crypto"
19
+ import { createInterface } from "node:readline"
20
+
21
+ const TOKEN_PREFIX = "FQT1"
22
+
23
+ /**
24
+ * The public key that verifies activation tokens, shipped with the launcher. Empty until the signing keypair is minted
25
+ * (bun license-service/src/mint.ts keygen) and pasted here for release; FORGEQE_PUBLIC_KEY overrides it (and tests
26
+ * inject their own). Phase 3 bakes the real key in.
27
+ */
28
+ export const PUBLIC_KEY_PEM = ""
29
+
30
+ /** The abstract base URL of the activation service (RFC §3); overridden by FORGEQE_LICENSE_URL. */
31
+ export const DEFAULT_LICENSE_URL = ""
32
+
33
+ function publicKey(env, publicKeyPem) {
34
+ const pem = publicKeyPem || env.FORGEQE_PUBLIC_KEY || PUBLIC_KEY_PEM
35
+ return pem ? createPublicKey(pem) : null
36
+ }
37
+
38
+ /** Verify an FQT1 activation token offline and return its payload, or null if it is malformed, unsigned, or expired. */
39
+ export function verifyToken(token, publicKeyObj, now = Math.floor(Date.now() / 1000)) {
40
+ if (!publicKeyObj) return null
41
+ const parts = String(token || "").trim().split(".")
42
+ if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null
43
+ const signed = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8")
44
+ try {
45
+ if (!edVerify(null, signed, publicKeyObj, Buffer.from(parts[2], "base64url"))) return null
46
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))
47
+ if (payload.exp && now >= payload.exp) return null
48
+ return payload
49
+ } catch {
50
+ return null
51
+ }
52
+ }
53
+
54
+ /** This machine's stable id: a random UUID created once under the ForgeQE home (RFC §2). Not hardware fingerprinting. */
55
+ export function machineId(home) {
56
+ const file = path.join(home, "machine-id")
57
+ try {
58
+ const existing = readFileSync(file, "utf8").trim()
59
+ if (existing) return existing
60
+ } catch {}
61
+ const id = randomUUID()
62
+ mkdirSync(home, { recursive: true })
63
+ writeFileSync(file, `${id}\n`)
64
+ try {
65
+ chmodSync(file, 0o600)
66
+ } catch {}
67
+ return id
68
+ }
69
+
70
+ function tokenFile(home) {
71
+ return path.join(home, "activation.jwt")
72
+ }
73
+
74
+ function storeToken(home, token) {
75
+ mkdirSync(home, { recursive: true })
76
+ const file = tokenFile(home)
77
+ writeFileSync(file, token)
78
+ try {
79
+ chmodSync(file, 0o600)
80
+ } catch {}
81
+ }
82
+
83
+ async function postActivate(url, key, mid, fetchImpl) {
84
+ const res = await fetchImpl(`${url.replace(/\/+$/, "")}/activate`, {
85
+ method: "POST",
86
+ headers: { "content-type": "application/json" },
87
+ body: JSON.stringify({ key, machine_id: mid }),
88
+ })
89
+ let data
90
+ try {
91
+ data = await res.json()
92
+ } catch {
93
+ data = null
94
+ }
95
+ if (res.ok && data?.ok && typeof data.token === "string") return data.token
96
+ const message = (data && (data.message || data.error)) || `activation failed (HTTP ${res.status})`
97
+ throw new Error(String(message))
98
+ }
99
+
100
+ /** Whether we can prompt the customer in this terminal (a real TTY, not a pipe or CI). */
101
+ export function canPrompt(stdin = process.stdin, stdout = process.stdout) {
102
+ return Boolean(stdin && stdin.isTTY && stdout && stdout.isTTY)
103
+ }
104
+
105
+ /** Ask for the licence key on the terminal and return what was typed. For `forgeqe start` and `forgeqe activate`. */
106
+ export function promptKeyTTY(input = process.stdin, output = process.stdout) {
107
+ const rl = createInterface({ input, output })
108
+ output.write("\nActivate ForgeQE.\nPaste your licence key (from your ForgeQE representative):\n")
109
+ return new Promise((resolve) => {
110
+ rl.question("Licence key: ", (answer) => {
111
+ rl.close()
112
+ resolve(String(answer || "").trim())
113
+ })
114
+ })
115
+ }
116
+
117
+ /** The cached (or env) activation token if one is present and still valid, else null. No network, no key needed. */
118
+ export function loadCachedToken(opts) {
119
+ const env = opts.env || process.env
120
+ const pub = publicKey(env, opts.publicKeyPem)
121
+ const now = opts.now ?? Math.floor(Date.now() / 1000)
122
+ const envToken = (env.FORGEQE_ACTIVATION_TOKEN || "").trim()
123
+ if (envToken) return verifyToken(envToken, pub, now) ? envToken : null
124
+ try {
125
+ const cached = readFileSync(tokenFile(opts.home), "utf8").trim()
126
+ if (cached && verifyToken(cached, pub, now)) return cached
127
+ } catch {}
128
+ return null
129
+ }
130
+
131
+ /**
132
+ * Activate this machine with a customer `key`: POST to the service, verify the returned token, cache it, and return it.
133
+ * Used by the terminal prompt, the web activation page, and `forgeqe activate`. Throws the service's message on refusal
134
+ * (e.g. seat_exhausted), so the caller can show it. The key is never written to disk — only the token it yields.
135
+ */
136
+ export async function activateWithKey(key, opts) {
137
+ const env = opts.env || process.env
138
+ const pub = publicKey(env, opts.publicKeyPem)
139
+ const now = opts.now ?? Math.floor(Date.now() / 1000)
140
+ const url = opts.licenseUrl || env.FORGEQE_LICENSE_URL || DEFAULT_LICENSE_URL
141
+ if (!url) throw new Error("No licence service is configured (FORGEQE_LICENSE_URL).")
142
+ const clean = String(key || "").trim()
143
+ if (!clean) throw new Error("a licence key is required.")
144
+ const mid = machineId(opts.home)
145
+ const token = await postActivate(url, clean, mid, opts.fetchImpl || ((u, init) => fetch(u, init)))
146
+ if (!verifyToken(token, pub, now)) throw new Error("the licence service returned a token the launcher could not verify.")
147
+ storeToken(opts.home, token)
148
+ return token
149
+ }
150
+
151
+ /**
152
+ * Return a valid activation token, activating this machine if needed, forcing activation before anything else runs.
153
+ * Order: a valid env/cached token → the FORGEQE_LICENSE_KEY env var → `opts.getKey()` (a prompt or the web page, when
154
+ * provided) → throw an actionable error (CI with no key). `opts`: { home, env, licenseUrl, publicKeyPem, fetchImpl,
155
+ * now, log, getKey }.
156
+ */
157
+ export async function authorize(opts) {
158
+ const env = opts.env || process.env
159
+ const log = opts.log || (() => {})
160
+
161
+ const cached = loadCachedToken(opts)
162
+ if (cached) return cached
163
+ if ((env.FORGEQE_ACTIVATION_TOKEN || "").trim()) throw new Error("FORGEQE_ACTIVATION_TOKEN is not a valid or current ForgeQE activation token.")
164
+
165
+ const envKey = (env.FORGEQE_LICENSE_KEY || "").trim()
166
+ if (envKey) {
167
+ log(`forgeqe: activating this machine with your ForgeQE licence...`)
168
+ return activateWithKey(envKey, opts)
169
+ }
170
+
171
+ if (opts.getKey) {
172
+ const key = (await opts.getKey()) || ""
173
+ log(`forgeqe: activating this machine with your ForgeQE licence...`)
174
+ return activateWithKey(key, opts)
175
+ }
176
+
177
+ throw new Error("ForgeQE needs a licence. Run `forgeqe activate` and enter your customer key, or set FORGEQE_LICENSE_KEY.")
178
+ }