@firefunc-agent/runner 0.9.7 → 0.9.34

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 (178) hide show
  1. package/README.md +169 -10
  2. package/dist/activity.d.ts +1 -0
  3. package/dist/activity.js +1 -1
  4. package/dist/alive.d.ts +40 -0
  5. package/dist/alive.js +138 -0
  6. package/dist/api-fallback.d.ts +11 -0
  7. package/dist/api-fallback.js +80 -0
  8. package/dist/api.d.ts +186 -3
  9. package/dist/api.js +311 -6
  10. package/dist/ask/index.d.ts +20 -0
  11. package/dist/ask/index.js +64 -0
  12. package/dist/ask-first.d.ts +8 -0
  13. package/dist/brief-file.d.ts +15 -0
  14. package/dist/brief-file.js +36 -0
  15. package/dist/brief.d.ts +5 -0
  16. package/dist/brief.js +19 -3
  17. package/dist/build-caches.d.ts +7 -0
  18. package/dist/build-caches.js +63 -0
  19. package/dist/build-info.json +2 -2
  20. package/dist/checkpoint.d.ts +40 -0
  21. package/dist/checkpoint.js +98 -0
  22. package/dist/cli.js +184 -18
  23. package/dist/cloud-boot.d.ts +41 -0
  24. package/dist/cloud-boot.js +239 -0
  25. package/dist/command-activity.d.ts +23 -0
  26. package/dist/command-activity.js +89 -0
  27. package/dist/command-step.d.ts +58 -0
  28. package/dist/command-step.js +248 -0
  29. package/dist/config.d.ts +40 -0
  30. package/dist/config.js +23 -0
  31. package/dist/cut.d.ts +2 -1
  32. package/dist/cut.js +19 -5
  33. package/dist/daemon.js +375 -14
  34. package/dist/device-lease.d.ts +15 -0
  35. package/dist/device-lease.js +608 -0
  36. package/dist/editor/fs-server.d.ts +31 -0
  37. package/dist/editor/fs-server.js +159 -0
  38. package/dist/editor/relay-crypto.d.ts +68 -0
  39. package/dist/editor/relay-crypto.js +191 -0
  40. package/dist/editor/sessions.d.ts +50 -0
  41. package/dist/editor/sessions.js +279 -0
  42. package/dist/editor/worktree-of.d.ts +1 -0
  43. package/dist/editor/worktree-of.js +23 -0
  44. package/dist/editor/ws-client.d.ts +26 -0
  45. package/dist/editor/ws-client.js +227 -0
  46. package/dist/engine-account.d.ts +24 -0
  47. package/dist/engine-account.js +118 -0
  48. package/dist/engine-login.d.ts +12 -0
  49. package/dist/engine-login.js +88 -0
  50. package/dist/engine-models.d.ts +13 -0
  51. package/dist/engine-models.js +71 -0
  52. package/dist/engine-watch.d.ts +1 -0
  53. package/dist/engine-watch.js +22 -6
  54. package/dist/engines/antigravity.js +19 -4
  55. package/dist/engines/claude.js +15 -8
  56. package/dist/engines/codex.js +16 -2
  57. package/dist/engines/copilot.js +12 -0
  58. package/dist/engines/crush.d.ts +2 -0
  59. package/dist/engines/crush.js +58 -0
  60. package/dist/engines/cursor.js +12 -0
  61. package/dist/engines/gemini.js +14 -9
  62. package/dist/engines/index.d.ts +8 -0
  63. package/dist/engines/index.js +73 -1
  64. package/dist/engines/kilo.d.ts +2 -0
  65. package/dist/engines/kilo.js +63 -0
  66. package/dist/engines/opencode.d.ts +9 -0
  67. package/dist/engines/opencode.js +234 -0
  68. package/dist/engines/openhands.d.ts +10 -0
  69. package/dist/engines/openhands.js +271 -0
  70. package/dist/engines/pi.d.ts +10 -0
  71. package/dist/engines/pi.js +248 -0
  72. package/dist/engines/qwen.d.ts +8 -0
  73. package/dist/engines/qwen.js +153 -0
  74. package/dist/engines/sessions.d.ts +6 -0
  75. package/dist/engines/sessions.js +68 -0
  76. package/dist/engines/types.d.ts +3 -3
  77. package/dist/exec.d.ts +1 -0
  78. package/dist/exec.js +10 -4
  79. package/dist/firefunc/agents.d.ts +8 -1
  80. package/dist/firefunc/agents.js +53 -3
  81. package/dist/firefunc/auth.js +72 -19
  82. package/dist/firefunc/cli.js +25 -0
  83. package/dist/firefunc/client.d.ts +5 -1
  84. package/dist/firefunc/client.js +12 -2
  85. package/dist/firefunc/config.d.ts +11 -1
  86. package/dist/firefunc/config.js +6 -4
  87. package/dist/firefunc/io.d.ts +1 -0
  88. package/dist/firefunc/main.js +8 -1
  89. package/dist/firefunc/oauth-login.d.ts +23 -0
  90. package/dist/firefunc/oauth-login.js +304 -0
  91. package/dist/firefunc/tasks.d.ts +4 -0
  92. package/dist/firefunc/tasks.js +89 -2
  93. package/dist/fleet-words.d.ts +2 -0
  94. package/dist/fleet-words.js +7 -0
  95. package/dist/git-auth.d.ts +16 -0
  96. package/dist/git-auth.js +48 -2
  97. package/dist/held.d.ts +3 -0
  98. package/dist/job.d.ts +26 -3
  99. package/dist/job.js +1109 -132
  100. package/dist/keep-awake.d.ts +17 -0
  101. package/dist/keep-awake.js +90 -0
  102. package/dist/keep-local.d.ts +2 -1
  103. package/dist/keep-local.js +8 -3
  104. package/dist/limit.d.ts +10 -1
  105. package/dist/limit.js +264 -4
  106. package/dist/local-checks.d.ts +19 -0
  107. package/dist/local-checks.js +79 -0
  108. package/dist/locks.d.ts +21 -1
  109. package/dist/locks.js +279 -66
  110. package/dist/machine-commands.d.ts +21 -0
  111. package/dist/machine-commands.js +107 -0
  112. package/dist/machine-profile.d.ts +18 -0
  113. package/dist/machine-profile.js +69 -0
  114. package/dist/mcp-init.d.ts +2 -0
  115. package/dist/mcp-init.js +28 -0
  116. package/dist/mcp.d.ts +13 -1
  117. package/dist/mcp.js +23 -2
  118. package/dist/network.js +3 -2
  119. package/dist/orphans.d.ts +4 -0
  120. package/dist/orphans.js +96 -4
  121. package/dist/plan-phase/index.d.ts +11 -0
  122. package/dist/plan-phase/index.js +46 -0
  123. package/dist/pool.d.ts +1 -0
  124. package/dist/pool.js +29 -4
  125. package/dist/pr-title.d.ts +15 -0
  126. package/dist/pr-title.js +33 -0
  127. package/dist/recover.d.ts +3 -1
  128. package/dist/recover.js +27 -7
  129. package/dist/reference-files.d.ts +27 -0
  130. package/dist/reference-files.js +202 -0
  131. package/dist/release-draft.d.ts +79 -0
  132. package/dist/release-draft.js +301 -0
  133. package/dist/resources.d.ts +86 -0
  134. package/dist/resources.js +217 -0
  135. package/dist/restart-idle.d.ts +23 -0
  136. package/dist/restart-idle.js +67 -0
  137. package/dist/run-attachments.d.ts +84 -0
  138. package/dist/run-attachments.js +281 -0
  139. package/dist/run-stops.d.ts +15 -0
  140. package/dist/run-stops.js +90 -0
  141. package/dist/run-temp.d.ts +12 -0
  142. package/dist/run-temp.js +57 -0
  143. package/dist/secret-scan.d.ts +6 -1
  144. package/dist/secret-scan.js +33 -0
  145. package/dist/secret-values.d.ts +17 -0
  146. package/dist/secret-values.js +81 -0
  147. package/dist/self-upgrade.d.ts +36 -0
  148. package/dist/self-upgrade.js +78 -0
  149. package/dist/service.d.ts +7 -1
  150. package/dist/service.js +50 -7
  151. package/dist/sign-in.d.ts +41 -0
  152. package/dist/sign-in.js +239 -0
  153. package/dist/tool-call.d.ts +59 -0
  154. package/dist/tool-call.js +375 -0
  155. package/dist/trail/chain.d.ts +12 -0
  156. package/dist/trail/chain.js +89 -0
  157. package/dist/trail/deltas.d.ts +34 -0
  158. package/dist/trail/deltas.js +206 -0
  159. package/dist/trail/index.d.ts +27 -0
  160. package/dist/trail/index.js +128 -0
  161. package/dist/trail/keys.d.ts +14 -0
  162. package/dist/trail/keys.js +61 -0
  163. package/dist/trail/recorder.d.ts +118 -0
  164. package/dist/trail/recorder.js +697 -0
  165. package/dist/trail/rules.d.ts +30 -0
  166. package/dist/trail/rules.js +158 -0
  167. package/dist/trail/stream.d.ts +41 -0
  168. package/dist/trail/stream.js +86 -0
  169. package/dist/transport.d.ts +26 -0
  170. package/dist/transport.js +118 -0
  171. package/dist/work-dir.d.ts +11 -0
  172. package/dist/work-dir.js +69 -0
  173. package/dist/worktree-report.d.ts +10 -0
  174. package/dist/worktree-report.js +17 -0
  175. package/dist/worktrees.d.ts +16 -1
  176. package/dist/worktrees.js +62 -17
  177. package/package.json +4 -4
  178. package/skill/firefunc/SKILL.md +4 -3
@@ -0,0 +1,202 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, mkdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
5
+ export const REFERENCE_FOLDER = '.firefunc/reference';
6
+ const MAX_BYTES = 20 * 1024 * 1024;
7
+ const GITIGNORE = '# FireFunc: reference files for one run, never committed\n*\n';
8
+ const NONE = (skipped = []) => ({
9
+ written: [],
10
+ pathspecs: [],
11
+ names: [],
12
+ skipped,
13
+ });
14
+ function git(cwd, args) {
15
+ try {
16
+ return execFileSync('git', ['-C', cwd, ...args], {
17
+ encoding: 'utf8',
18
+ stdio: ['ignore', 'pipe', 'ignore'],
19
+ }).trim();
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ function insideTop(top, real) {
26
+ const rel = relative(top, real);
27
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
28
+ return null;
29
+ return rel.split(sep).join('/');
30
+ }
31
+ function lstatExists(p) {
32
+ try {
33
+ lstatSync(p);
34
+ return true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ export function safeReferenceName(name) {
41
+ return (typeof name === 'string' &&
42
+ name.length > 0 &&
43
+ name.length <= 120 &&
44
+ name.trim() === name &&
45
+ name !== '.' &&
46
+ name !== '..' &&
47
+ !/[\u0000-\u001f\u007f/\\]/.test(name));
48
+ }
49
+ export async function downloadReference(f, fetcher = fetch) {
50
+ if (f.size > MAX_BYTES)
51
+ return { why: `it is larger than ${MAX_BYTES} bytes` };
52
+ const ctrl = new AbortController();
53
+ const timer = setTimeout(() => ctrl.abort(), 120_000);
54
+ try {
55
+ const res = await fetcher(f.url, { signal: ctrl.signal });
56
+ if (!res.ok)
57
+ return { why: `the download answered ${res.status}` };
58
+ const bytes = Buffer.from(await res.arrayBuffer());
59
+ if (bytes.byteLength !== f.size) {
60
+ return { why: `${bytes.byteLength} bytes arrived where ${f.size} were recorded` };
61
+ }
62
+ const sha = createHash('sha256').update(bytes).digest('hex');
63
+ if (sha !== f.sha256.toLowerCase()) {
64
+ return { why: 'the bytes that arrived are not the file that was uploaded (SHA-256 differs)' };
65
+ }
66
+ return { bytes };
67
+ }
68
+ catch (e) {
69
+ return { why: `the download failed (${e.name})` };
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+ export async function writeReferenceFiles(worktree, files, log, download = (f) => downloadReference(f)) {
76
+ const wanted = [];
77
+ const skipped = [];
78
+ const seen = new Set();
79
+ for (const f of files ?? []) {
80
+ if (!f || !safeReferenceName(f.name)) {
81
+ skipped.push({ name: String(f?.name ?? ''), why: 'its name is not one file name' });
82
+ continue;
83
+ }
84
+ if (seen.has(f.name.toLowerCase()))
85
+ continue;
86
+ seen.add(f.name.toLowerCase());
87
+ wanted.push(f);
88
+ }
89
+ if (wanted.length === 0)
90
+ return NONE(skipped);
91
+ let top;
92
+ try {
93
+ top = realpathSync(worktree);
94
+ }
95
+ catch (e) {
96
+ log(`could not write reference files: ${e.message}`);
97
+ return NONE([...skipped, ...wanted.map((f) => ({ name: f.name, why: 'no worktree' }))]);
98
+ }
99
+ const allSkipped = (why) => NONE([...skipped, ...wanted.map((f) => ({ name: f.name, why }))]);
100
+ const outer = join(top, '.firefunc');
101
+ if (!lstatExists(outer)) {
102
+ try {
103
+ mkdirSync(outer);
104
+ }
105
+ catch (e) {
106
+ log(`could not write reference files: ${e.message}`);
107
+ return allSkipped('the folder could not be made');
108
+ }
109
+ }
110
+ else if (!existsSync(outer)) {
111
+ log('reference files not written: .firefunc is a link to a place that does not exist in this checkout. ' +
112
+ 'Fix: point it at a folder inside the repository, or remove the link.');
113
+ return allSkipped('.firefunc is a dangling link');
114
+ }
115
+ let outerReal;
116
+ try {
117
+ outerReal = realpathSync(outer);
118
+ }
119
+ catch (e) {
120
+ log(`could not write reference files: ${e.message}`);
121
+ return allSkipped('the folder could not be read');
122
+ }
123
+ if (insideTop(top, outerReal) === null || !statSync(outerReal).isDirectory()) {
124
+ log(`reference files not written: .firefunc leads to ${outerReal}, which is not a folder inside this checkout; ` +
125
+ 'FireFunc writes only inside the worktree. Fix: make .firefunc a folder inside the repository.');
126
+ return allSkipped('.firefunc is not a folder inside the checkout');
127
+ }
128
+ const dir = join(outerReal, 'reference');
129
+ const rel = insideTop(top, dir);
130
+ if (lstatExists(dir)) {
131
+ log(`reference files not written: ${rel} is already in the checkout, and FireFunc never writes into ` +
132
+ `the repository's own files. Fix: rename or remove ${rel} in the repository.`);
133
+ return allSkipped(`${rel} is the repository's own`);
134
+ }
135
+ const gitTop = git(top, ['rev-parse', '--show-toplevel']);
136
+ let isRepo = false;
137
+ if (gitTop) {
138
+ try {
139
+ isRepo = realpathSync(gitTop) === top;
140
+ }
141
+ catch {
142
+ isRepo = false;
143
+ }
144
+ }
145
+ const ignoreCase = isRepo && git(top, ['config', '--bool', 'core.ignorecase']) === 'true';
146
+ if (isRepo) {
147
+ const tracked = git(top, [
148
+ 'ls-files',
149
+ '-z',
150
+ '--',
151
+ `:(literal${ignoreCase ? ',icase' : ''})${rel}`,
152
+ ]);
153
+ if (tracked) {
154
+ log(`reference files not written: the repository tracks files under ${rel}, and FireFunc never ` +
155
+ `overwrites a repository's files. Fix: move them out of ${rel}.`);
156
+ return allSkipped(`${rel} is tracked by the repository`);
157
+ }
158
+ }
159
+ try {
160
+ mkdirSync(dir);
161
+ writeFileSync(join(dir, '.gitignore'), GITIGNORE);
162
+ }
163
+ catch (e) {
164
+ log(`could not write reference files: ${e.message}`);
165
+ return allSkipped('the folder could not be made');
166
+ }
167
+ const names = [];
168
+ for (const f of wanted) {
169
+ const got = await download(f);
170
+ if ('why' in got) {
171
+ skipped.push({ name: f.name, why: got.why });
172
+ log(`reference file ${f.name} not written: ${got.why}. Fix: add it again on the agent page.`);
173
+ continue;
174
+ }
175
+ try {
176
+ writeFileSync(join(dir, f.name), got.bytes, { mode: 0o600 });
177
+ names.push(f.name);
178
+ }
179
+ catch (e) {
180
+ skipped.push({ name: f.name, why: 'it could not be written' });
181
+ log(`could not write reference file ${f.name}: ${e.message}`);
182
+ }
183
+ }
184
+ if (names.length)
185
+ log(`wrote ${names.length} reference file(s) into ${rel}: ${names.join(', ')}`);
186
+ return {
187
+ written: [rel],
188
+ pathspecs: [`:(exclude,literal${ignoreCase ? ',icase' : ''})${rel}`],
189
+ ...(ignoreCase ? { ignoreCase } : {}),
190
+ names,
191
+ skipped,
192
+ };
193
+ }
194
+ export function mergeWritten(a, b) {
195
+ const ignoreCase = !!(a.ignoreCase || b.ignoreCase);
196
+ return {
197
+ written: [...a.written, ...b.written],
198
+ pathspecs: [...a.pathspecs, ...b.pathspecs],
199
+ ...(ignoreCase ? { ignoreCase } : {}),
200
+ };
201
+ }
202
+ //# sourceMappingURL=reference-files.js.map
@@ -0,0 +1,79 @@
1
+ import type { GitCredential } from './git-auth.js';
2
+ import { type PreparedAttach } from './run-attachments.js';
3
+ export declare const RELEASE_FOLDER = ".firefunc/release";
4
+ export declare const RELEASE_MANIFEST = "release.json";
5
+ export declare const MAX_RELEASE_FILES = 20;
6
+ export declare const MAX_RELEASE_FILE_BYTES: number;
7
+ export declare const MAX_RELEASE_TOTAL_BYTES: number;
8
+ export type ReleaseOffer = {
9
+ folder?: string;
10
+ manifest?: string;
11
+ tag?: string | null;
12
+ name?: string | null;
13
+ prerelease?: boolean;
14
+ maxFiles?: number;
15
+ maxFileBytes?: number;
16
+ maxTotalBytes?: number;
17
+ };
18
+ export type ReleaseReport = {
19
+ draftId: number;
20
+ tag: string;
21
+ url: string | null;
22
+ files: Array<{
23
+ name: string;
24
+ size: number;
25
+ }>;
26
+ skipped: Array<{
27
+ name: string;
28
+ why: string;
29
+ }>;
30
+ } | {
31
+ staged: false;
32
+ why: string;
33
+ tag: string | null;
34
+ };
35
+ export declare function releaseRule(offer: ReleaseOffer): string;
36
+ export declare function releaseTagProblem(tag: unknown): string | null;
37
+ export declare function prepareReleaseFolder(worktree: string, log: (m: string) => void): PreparedAttach;
38
+ type Manifest = {
39
+ tag: string | null;
40
+ name: string | null;
41
+ notes: string | null;
42
+ prerelease: boolean | null;
43
+ };
44
+ export type ReleaseScan = {
45
+ manifest: Manifest | {
46
+ problem: string;
47
+ } | null;
48
+ files: Array<{
49
+ name: string;
50
+ path: string;
51
+ size: number;
52
+ }>;
53
+ skipped: Array<{
54
+ name: string;
55
+ why: string;
56
+ }>;
57
+ };
58
+ export declare function scanReleaseFolder(dir: string, offer?: ReleaseOffer): ReleaseScan;
59
+ export type AssetUploader = (opts: {
60
+ url: string;
61
+ token: string;
62
+ path: string;
63
+ size: number;
64
+ }) => Promise<{
65
+ status: number;
66
+ }>;
67
+ export declare function assetUrl(uploadUrl: string | undefined, name: string): string | null;
68
+ export declare function stageDraftRelease(opts: {
69
+ repo: string;
70
+ base: string | null;
71
+ offer: ReleaseOffer;
72
+ dir: string;
73
+ cred: Pick<GitCredential, 'token'>;
74
+ log: (m: string) => void;
75
+ fetcher?: typeof fetch;
76
+ upload?: AssetUploader;
77
+ apiBase?: string;
78
+ }): Promise<ReleaseReport>;
79
+ export {};
@@ -0,0 +1,301 @@
1
+ import { createReadStream, lstatSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { join } from 'node:path';
4
+ import { prepareFireFuncFolder } from './run-attachments.js';
5
+ export const RELEASE_FOLDER = '.firefunc/release';
6
+ export const RELEASE_MANIFEST = 'release.json';
7
+ export const MAX_RELEASE_FILES = 20;
8
+ export const MAX_RELEASE_FILE_BYTES = 1024 * 1024 * 1024;
9
+ export const MAX_RELEASE_TOTAL_BYTES = 2 * 1024 * 1024 * 1024;
10
+ const MAX_NOTES = 125_000;
11
+ const GITIGNORE = '# FireFunc: the files a release carries, never committed\n*\n';
12
+ const SECRET_EXTENSIONS = new Set([
13
+ 'jks',
14
+ 'keystore',
15
+ 'p12',
16
+ 'pfx',
17
+ 'pem',
18
+ 'key',
19
+ 'p8',
20
+ 'mobileprovision',
21
+ 'provisionprofile',
22
+ 'gpg',
23
+ 'asc',
24
+ ]);
25
+ export function releaseRule(offer) {
26
+ const tag = offer.tag
27
+ ? ` (the line names ${offer.tag}; write your own when you bump the version)`
28
+ : '';
29
+ return `- This agent publishes a GitHub release. Put the files the release carries — the build (an .apk, .aab, .ipa, .zip …) and its checksums — in \`${RELEASE_FOLDER}/\`, and write \`${RELEASE_FOLDER}/${RELEASE_MANIFEST}\` as {"tag": "v1.2.0", "name": "…", "notes": "…"}${tag}. FireFunc stages them as a draft release when you finish and publishes it once the pull request merges. Never commit them, and never put a signing key, a keystore or a password there — those are never published.`;
30
+ }
31
+ export function releaseTagProblem(tag) {
32
+ if (typeof tag !== 'string' || !tag.trim())
33
+ return 'No tag was named for the release.';
34
+ const t = tag.trim();
35
+ if (t.length > 100)
36
+ return `The tag "${t.slice(0, 40)}…" is longer than 100 characters.`;
37
+ if (!/^[A-Za-z0-9][A-Za-z0-9._+\-/]*$/.test(t) ||
38
+ t.includes('..') ||
39
+ t.includes('//') ||
40
+ t.endsWith('.') ||
41
+ t.endsWith('/') ||
42
+ t.endsWith('.lock')) {
43
+ return `"${t}" is not a tag git takes: letters, digits, ".", "-", "_", "+" and "/" only, starting with a letter or a digit.`;
44
+ }
45
+ return null;
46
+ }
47
+ export function prepareReleaseFolder(worktree, log) {
48
+ return prepareFireFuncFolder(worktree, { sub: 'release', gitignore: GITIGNORE, what: 'the release' }, log);
49
+ }
50
+ function readManifest(path) {
51
+ let text;
52
+ try {
53
+ if (!lstatSync(path).isFile())
54
+ return { problem: `${RELEASE_MANIFEST} is not a file.` };
55
+ text = readFileSync(path, 'utf8');
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ let raw;
61
+ try {
62
+ raw = JSON.parse(text);
63
+ }
64
+ catch {
65
+ return { problem: `${RELEASE_MANIFEST} is not JSON.` };
66
+ }
67
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
68
+ return { problem: `${RELEASE_MANIFEST} is not an object such as {"tag": "v1.2.0"}.` };
69
+ }
70
+ const o = raw;
71
+ const str = (v, max) => typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null;
72
+ const tag = str(o.tag, 200);
73
+ if (tag && releaseTagProblem(tag))
74
+ return { problem: releaseTagProblem(tag) };
75
+ return {
76
+ tag,
77
+ name: str(o.name, 200),
78
+ notes: str(o.notes, MAX_NOTES),
79
+ prerelease: typeof o.prerelease === 'boolean' ? o.prerelease : null,
80
+ };
81
+ }
82
+ export function scanReleaseFolder(dir, offer = {}) {
83
+ const within = (v, cap) => typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.min(Math.floor(v), cap) : cap;
84
+ const maxFiles = within(offer.maxFiles, MAX_RELEASE_FILES);
85
+ const maxFileBytes = within(offer.maxFileBytes, MAX_RELEASE_FILE_BYTES);
86
+ const maxTotalBytes = within(offer.maxTotalBytes, MAX_RELEASE_TOTAL_BYTES);
87
+ const files = [];
88
+ const skipped = [];
89
+ let names;
90
+ try {
91
+ names = readdirSync(dir).sort((a, b) => a.localeCompare(b));
92
+ }
93
+ catch {
94
+ return { manifest: null, files, skipped };
95
+ }
96
+ const manifest = names.includes(RELEASE_MANIFEST)
97
+ ? readManifest(join(dir, RELEASE_MANIFEST))
98
+ : null;
99
+ let total = 0;
100
+ for (const name of names) {
101
+ if (name === '.gitignore' || name === RELEASE_MANIFEST)
102
+ continue;
103
+ const path = join(dir, name);
104
+ let st;
105
+ try {
106
+ st = lstatSync(path);
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ if (!st.isFile()) {
112
+ skipped.push({
113
+ name,
114
+ why: st.isSymbolicLink() ? 'it is a link, not a file' : 'it is not a file',
115
+ });
116
+ continue;
117
+ }
118
+ if (name.length > 120 || /[\u0000-\u001f\u007f\\]/.test(name) || name.trim() !== name) {
119
+ skipped.push({ name, why: 'its name is not a plain file name' });
120
+ continue;
121
+ }
122
+ const ext = /\.([A-Za-z0-9]+)$/.exec(name)?.[1]?.toLowerCase() ?? '';
123
+ if (SECRET_EXTENSIONS.has(ext) ||
124
+ /(^|[._-])(secret|password|credentials?)([._-]|$)/i.test(name)) {
125
+ skipped.push({ name, why: 'a signing key or a secret is never published' });
126
+ continue;
127
+ }
128
+ if (st.size === 0) {
129
+ skipped.push({ name, why: 'it is empty' });
130
+ continue;
131
+ }
132
+ if (st.size > maxFileBytes) {
133
+ skipped.push({ name, why: `it is larger than ${maxFileBytes} bytes` });
134
+ continue;
135
+ }
136
+ if (files.length >= maxFiles) {
137
+ skipped.push({ name, why: `a release carries at most ${maxFiles} files` });
138
+ continue;
139
+ }
140
+ if (total + st.size > maxTotalBytes) {
141
+ skipped.push({ name, why: `a release carries at most ${maxTotalBytes} bytes in all` });
142
+ continue;
143
+ }
144
+ total += st.size;
145
+ files.push({ name, path, size: st.size });
146
+ }
147
+ return { manifest, files, skipped };
148
+ }
149
+ const httpsUpload = ({ url, token, path, size }) => new Promise((resolve, reject) => {
150
+ const req = httpsRequest(url, {
151
+ method: 'POST',
152
+ headers: {
153
+ authorization: `Bearer ${token}`,
154
+ accept: 'application/vnd.github+json',
155
+ 'x-github-api-version': '2022-11-28',
156
+ 'content-type': 'application/octet-stream',
157
+ 'content-length': String(size),
158
+ 'user-agent': 'firefunc-runner',
159
+ },
160
+ timeout: 30 * 60_000,
161
+ }, (res) => {
162
+ res.resume();
163
+ res.on('end', () => resolve({ status: res.statusCode ?? 0 }));
164
+ });
165
+ req.on('timeout', () => req.destroy(new Error('the upload timed out')));
166
+ req.on('error', reject);
167
+ const stream = createReadStream(path);
168
+ stream.on('error', (e) => req.destroy(e));
169
+ stream.pipe(req);
170
+ });
171
+ export function assetUrl(uploadUrl, name) {
172
+ if (!uploadUrl)
173
+ return null;
174
+ const base = uploadUrl.replace(/\{[^}]*\}$/, '');
175
+ let u;
176
+ try {
177
+ u = new URL(base);
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ if (u.protocol !== 'https:' || !/(^|\.)github\.com$/.test(u.hostname))
183
+ return null;
184
+ u.searchParams.set('name', name);
185
+ return u.toString();
186
+ }
187
+ export async function stageDraftRelease(opts) {
188
+ const { repo, offer, dir, cred, log } = opts;
189
+ const fetcher = opts.fetcher ?? fetch;
190
+ const upload = opts.upload ?? httpsUpload;
191
+ const api = opts.apiBase ?? 'https://api.github.com';
192
+ const scan = scanReleaseFolder(dir, offer);
193
+ for (const s of scan.skipped)
194
+ log(`release file ${s.name} not staged: ${s.why}`);
195
+ if (scan.manifest && 'problem' in scan.manifest) {
196
+ log(`no draft release: ${scan.manifest.problem}`);
197
+ return { staged: false, why: scan.manifest.problem, tag: null };
198
+ }
199
+ const manifest = scan.manifest;
200
+ const tag = manifest?.tag ?? (offer.tag && !releaseTagProblem(offer.tag) ? offer.tag : null);
201
+ if (!tag) {
202
+ const why = `${RELEASE_FOLDER}/${RELEASE_MANIFEST} named no tag, and the line names none`;
203
+ log(`no draft release: ${why}`);
204
+ return { staged: false, why, tag: null };
205
+ }
206
+ if (scan.files.length === 0) {
207
+ const why = `${RELEASE_FOLDER}/ held no file to publish`;
208
+ log(`no draft release for ${tag}: ${why} (the release is published without files)`);
209
+ return { staged: false, why, tag };
210
+ }
211
+ const headers = {
212
+ authorization: `Bearer ${cred.token}`,
213
+ accept: 'application/vnd.github+json',
214
+ 'x-github-api-version': '2022-11-28',
215
+ 'content-type': 'application/json',
216
+ 'user-agent': 'firefunc-runner',
217
+ };
218
+ try {
219
+ let draft = null;
220
+ const list = await fetcher(`${api}/repos/${repo}/releases?per_page=100`, { headers });
221
+ if (list.ok) {
222
+ const rows = (await list.json());
223
+ draft = rows.find((r) => r.draft === true && r.tag_name === tag) ?? null;
224
+ }
225
+ if (!draft) {
226
+ const name = manifest?.name ?? offer.name ?? null;
227
+ const res = await fetcher(`${api}/repos/${repo}/releases`, {
228
+ method: 'POST',
229
+ headers,
230
+ body: JSON.stringify({
231
+ tag_name: tag,
232
+ ...(name ? { name } : {}),
233
+ ...(manifest?.notes ? { body: manifest.notes } : {}),
234
+ draft: true,
235
+ prerelease: manifest?.prerelease ?? offer.prerelease === true,
236
+ ...(opts.base ? { target_commitish: opts.base } : {}),
237
+ }),
238
+ });
239
+ if (!res.ok) {
240
+ const why = `GitHub refused the draft release (${res.status})${res.status === 403 || res.status === 404 ? ' — the run’s token may not create releases in this repository' : ''}`;
241
+ log(`no draft release for ${tag}: ${why}`);
242
+ return { staged: false, why, tag };
243
+ }
244
+ draft = (await res.json());
245
+ }
246
+ const draftId = Number(draft.id);
247
+ if (!Number.isSafeInteger(draftId) || draftId < 1) {
248
+ return { staged: false, why: 'GitHub answered the draft release without an id', tag };
249
+ }
250
+ const there = new Map((draft.assets ?? []).map((a) => [a.name, a]));
251
+ const staged = [];
252
+ const skipped = [...scan.skipped];
253
+ for (const f of scan.files) {
254
+ const have = there.get(f.name);
255
+ if (have && have.size === f.size) {
256
+ staged.push({ name: f.name, size: f.size });
257
+ continue;
258
+ }
259
+ if (have?.id) {
260
+ await fetcher(`${api}/repos/${repo}/releases/assets/${have.id}`, {
261
+ method: 'DELETE',
262
+ headers,
263
+ }).catch(() => undefined);
264
+ }
265
+ const url = assetUrl(draft.upload_url, f.name);
266
+ if (!url) {
267
+ skipped.push({ name: f.name, why: 'GitHub gave no address to upload it to' });
268
+ continue;
269
+ }
270
+ try {
271
+ const res = await upload({ url, token: cred.token, path: f.path, size: f.size });
272
+ if (res.status >= 200 && res.status < 300) {
273
+ staged.push({ name: f.name, size: f.size });
274
+ }
275
+ else {
276
+ skipped.push({ name: f.name, why: `the upload answered ${res.status}` });
277
+ }
278
+ }
279
+ catch (e) {
280
+ skipped.push({ name: f.name, why: `it could not be uploaded (${e.name})` });
281
+ }
282
+ }
283
+ for (const s of skipped.slice(scan.skipped.length)) {
284
+ log(`release file ${s.name} not staged: ${s.why}`);
285
+ }
286
+ log(`staged draft release ${tag} on ${repo} with ${staged.length} file(s)${staged.length ? `: ${staged.map((s) => s.name).join(', ')}` : ''}`);
287
+ return {
288
+ draftId,
289
+ tag,
290
+ url: typeof draft.html_url === 'string' ? draft.html_url : null,
291
+ files: staged,
292
+ skipped,
293
+ };
294
+ }
295
+ catch (e) {
296
+ const why = `GitHub could not be reached to stage the draft release (${e.name})`;
297
+ log(`no draft release for ${tag}: ${why}`);
298
+ return { staged: false, why, tag };
299
+ }
300
+ }
301
+ //# sourceMappingURL=release-draft.js.map
@@ -0,0 +1,86 @@
1
+ import { type DeviceReport } from './device-lease.js';
2
+ import { type MachineProfile } from './machine-profile.js';
3
+ export type ResourceReading = {
4
+ freeBytes: number;
5
+ totalBytes: number | null;
6
+ floorBytes: number;
7
+ };
8
+ export type ResourcesReport = {
9
+ disk: ResourceReading | null;
10
+ memory: ResourceReading | null;
11
+ timeLimitMinutes: number;
12
+ devices?: DeviceReport;
13
+ workDir?: WorkDirReport;
14
+ cpus?: number;
15
+ load1PerCore?: number;
16
+ maxHeavyRuns?: number;
17
+ profile?: MachineProfile;
18
+ };
19
+ export declare function heavyRunBudget(setting: unknown, memBytes?: number): number;
20
+ export declare function processorReading(os?: NodeJS.Platform, read?: {
21
+ cores?: () => number;
22
+ load?: () => number[];
23
+ }): {
24
+ cpus: number;
25
+ load1PerCore: number | null;
26
+ };
27
+ export type WorkDirReport = {
28
+ set: boolean;
29
+ usable: boolean;
30
+ };
31
+ export declare const DEFAULT_MIN_FREE_DISK_GB = 5;
32
+ export declare const DEFAULT_MIN_FREE_MEMORY_GB = 1;
33
+ export declare const DEFAULT_JOB_TIMEOUT_MINUTES = 20;
34
+ export declare function floorBytes(gb: unknown, fallbackGb: number): number;
35
+ export declare function diskOf(dir: string): {
36
+ freeBytes: number;
37
+ totalBytes: number;
38
+ } | null;
39
+ export declare function leastFreeDisk(dirs: readonly string[], read?: (dir: string) => {
40
+ freeBytes: number;
41
+ totalBytes: number;
42
+ } | null): {
43
+ freeBytes: number;
44
+ totalBytes: number;
45
+ } | null;
46
+ export declare function macAvailableFromVmStat(out: string): number | null;
47
+ export declare function linuxAvailableFromMeminfo(text: string): number | null;
48
+ export declare function availableMemory(os?: NodeJS.Platform): number;
49
+ export type ResourceCfg = {
50
+ workDir?: string;
51
+ minFreeDiskGB?: number;
52
+ minFreeMemoryGB?: number;
53
+ jobTimeoutMinutes?: number;
54
+ repos?: Record<string, string>;
55
+ devices?: string[];
56
+ maxEmulators?: number;
57
+ maxHeavyRuns?: number;
58
+ claudeEnv?: Record<string, string>;
59
+ };
60
+ export declare function hasDeviceTools(cfg: Pick<ResourceCfg, 'devices' | 'claudeEnv'>, has?: (name: string, pathVar: string) => boolean): boolean;
61
+ export declare function readResources(cfg: ResourceCfg, runnerDir: string, deps?: {
62
+ disk?: (dirs: readonly string[]) => {
63
+ freeBytes: number;
64
+ totalBytes: number;
65
+ } | null;
66
+ memory?: () => number;
67
+ totalMemory?: () => number;
68
+ workDir?: () => WorkDirReport;
69
+ devices?: () => DeviceReport;
70
+ processor?: () => {
71
+ cpus: number;
72
+ load1PerCore: number | null;
73
+ };
74
+ profile?: () => MachineProfile | null;
75
+ }): ResourcesReport;
76
+ export declare function workDirReport(): WorkDirReport;
77
+ export declare function shortOf(r: ResourcesReport): Array<'disk' | 'memory'>;
78
+ export declare function resourceWatch(deps: {
79
+ read: () => ResourcesReport;
80
+ log: (msg: string) => void;
81
+ everyMs?: number;
82
+ now?: () => number;
83
+ }): {
84
+ report: () => ResourcesReport;
85
+ short: () => boolean;
86
+ };