@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,90 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { signalGroupSparingDevices } from './orphans.js';
3
+ const stopped = new Set();
4
+ const groups = new Map();
5
+ export const STOP_GRACE_MS = 3_000;
6
+ export function trackRunGroup(runId, pgid) {
7
+ if (pgid <= 1)
8
+ return;
9
+ let set = groups.get(runId);
10
+ if (!set) {
11
+ set = new Set();
12
+ groups.set(runId, set);
13
+ }
14
+ set.add(pgid);
15
+ }
16
+ export function untrackRunGroup(runId, pgid) {
17
+ const set = groups.get(runId);
18
+ if (!set)
19
+ return;
20
+ set.delete(pgid);
21
+ if (set.size === 0)
22
+ groups.delete(runId);
23
+ }
24
+ export function isStopped(runId) {
25
+ return stopped.has(runId);
26
+ }
27
+ export function forgetRun(runId) {
28
+ stopped.delete(runId);
29
+ groups.delete(runId);
30
+ }
31
+ export function readStopList(body) {
32
+ const raw = body?.stop;
33
+ if (!Array.isArray(raw))
34
+ return [];
35
+ return [...new Set(raw.filter((x) => typeof x === 'string' && x.length > 0))];
36
+ }
37
+ export function windowsStopArgs(pid) {
38
+ return ['/pid', String(pid), '/T', '/F'];
39
+ }
40
+ const defaultSignal = (pgid, sig) => {
41
+ if (process.platform === 'win32') {
42
+ if (sig !== 'SIGTERM')
43
+ return;
44
+ try {
45
+ spawn('taskkill', windowsStopArgs(pgid), { stdio: 'ignore', windowsHide: true }).on('error', () => { });
46
+ }
47
+ catch {
48
+ }
49
+ return;
50
+ }
51
+ signalGroupSparingDevices(pgid, sig);
52
+ };
53
+ export function stopRun(runId, deps = {}) {
54
+ const first = !stopped.has(runId);
55
+ stopped.add(runId);
56
+ const signal = deps.signal ?? defaultSignal;
57
+ const later = deps.later ??
58
+ ((fn, ms) => {
59
+ setTimeout(fn, ms).unref();
60
+ });
61
+ const pgids = [...(groups.get(runId) ?? [])];
62
+ for (const g of pgids)
63
+ signal(g, 'SIGTERM');
64
+ if (pgids.length > 0) {
65
+ later(() => {
66
+ for (const g of groups.get(runId) ?? [])
67
+ signal(g, 'SIGKILL');
68
+ }, STOP_GRACE_MS);
69
+ }
70
+ if (first) {
71
+ deps.log?.(`a person stopped ${runId} in FireFunc — ` +
72
+ (pgids.length > 0
73
+ ? `ending its engine session now; nothing from it is pushed`
74
+ : `it pushes nothing, and its engine is not started`));
75
+ }
76
+ return pgids.length;
77
+ }
78
+ export function stoppedByPersonSentence(engineName, at) {
79
+ const rerun = 'Re-run the task when it should run again.';
80
+ if (at === 'push')
81
+ return `A person stopped this run in FireFunc before it pushed, so nothing was pushed and no pull request was opened. ${rerun}`;
82
+ if (at === 'pr')
83
+ return `A person stopped this run in FireFunc after its branch was pushed, so no pull request was opened. ${rerun}`;
84
+ return `A person stopped this run in FireFunc, so the runner ended the ${engineName} session; nothing was pushed. ${rerun}`;
85
+ }
86
+ export function resetRunStops() {
87
+ stopped.clear();
88
+ groups.clear();
89
+ }
90
+ //# sourceMappingURL=run-stops.js.map
@@ -0,0 +1,12 @@
1
+ export declare function runTempPath(runId: string, root?: string): string;
2
+ export declare function tempRoot(): string;
3
+ export declare function makeRunTemp(runId: string, root?: string): {
4
+ dir: string;
5
+ env: {
6
+ TMPDIR: string;
7
+ TEMP: string;
8
+ TMP: string;
9
+ };
10
+ } | null;
11
+ export declare function removeRunTemp(dir: string | null): void;
12
+ export declare function staleRunTemps(roots: readonly string[], spare: ReadonlySet<string>, now?: number, minAgeMs?: number): string[];
@@ -0,0 +1,57 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { workRoot, workTempEnv } from './work-dir.js';
4
+ export function runTempPath(runId, root = tempRoot()) {
5
+ const id = runId.replace(/[^A-Za-z0-9]/g, '').slice(0, 12) || 'run';
6
+ return join(root, `fft-${id}`);
7
+ }
8
+ export function tempRoot() {
9
+ return workTempEnv().TMPDIR ?? workRoot();
10
+ }
11
+ export function makeRunTemp(runId, root) {
12
+ const dir = runTempPath(runId, root);
13
+ try {
14
+ mkdirSync(dir, { recursive: true });
15
+ return { dir, env: { TMPDIR: dir, TEMP: dir, TMP: dir } };
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ export function removeRunTemp(dir) {
22
+ if (!dir)
23
+ return;
24
+ try {
25
+ rmSync(dir, { recursive: true, force: true });
26
+ }
27
+ catch {
28
+ }
29
+ }
30
+ export function staleRunTemps(roots, spare, now = Date.now(), minAgeMs = 6 * 60 * 60_000) {
31
+ const out = [];
32
+ for (const root of new Set(roots)) {
33
+ let names;
34
+ try {
35
+ names = readdirSync(root);
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ for (const n of names) {
41
+ if (!/^fft-[A-Za-z0-9]{1,12}$/.test(n))
42
+ continue;
43
+ const p = join(root, n);
44
+ if (spare.has(p))
45
+ continue;
46
+ try {
47
+ const st = statSync(p);
48
+ if (st.isDirectory() && now - st.mtimeMs >= minAgeMs)
49
+ out.push(p);
50
+ }
51
+ catch {
52
+ }
53
+ }
54
+ }
55
+ return out;
56
+ }
57
+ //# sourceMappingURL=run-temp.js.map
@@ -1,4 +1,4 @@
1
- export type SecretKind = 'aws_access_key_id' | 'aws_secret_access_key' | 'github_token' | 'slack_token' | 'google_api_key' | 'stripe_secret_key' | 'private_key_block' | 'jwt' | 'generic_assignment';
1
+ export type SecretKind = 'aws_access_key_id' | 'aws_secret_access_key' | 'github_token' | 'slack_token' | 'google_api_key' | 'stripe_secret_key' | 'private_key_block' | 'jwt' | 'generic_assignment' | 'agent_secret';
2
2
  export type SecretHit = {
3
3
  path: string;
4
4
  kind: SecretKind;
@@ -17,3 +17,8 @@ export declare function changeReads(from: string, branch: string, tip?: string):
17
17
  export declare function uniqueHits(hits: SecretHit[]): SecretHit[];
18
18
  export declare function hardFirst(hits: SecretHit[]): SecretHit[];
19
19
  export declare function secretRefusal(hits: SecretHit[], branch?: string): string;
20
+ export declare function secretFixRead(from: string): {
21
+ args: string[];
22
+ env: Record<string, string>;
23
+ };
24
+ export declare function secretFixBrief(hits: SecretHit[], from: string, committed: boolean): string;
@@ -1,4 +1,5 @@
1
1
  import { devNull } from 'node:os';
2
+ import { heldSecretValues } from './secret-values.js';
2
3
  export const SOFT_KINDS = new Set(['generic_assignment']);
3
4
  export function refusesPush(hit) {
4
5
  return !SOFT_KINDS.has(hit.kind);
@@ -36,6 +37,8 @@ export function secretKindsIn(line) {
36
37
  break;
37
38
  }
38
39
  }
40
+ if (heldSecretValues().some((s) => line.includes(s.value)))
41
+ found.push('agent_secret');
39
42
  return found;
40
43
  }
41
44
  function pathOf(header) {
@@ -158,4 +161,34 @@ export function secretRefusal(hits, branch) {
158
161
  'like a live key. Then run the task again. A value a later commit took out still counts: the push ' +
159
162
  'would publish the commit that added it (git log -p shows which).');
160
163
  }
164
+ export function secretFixRead(from) {
165
+ return {
166
+ args: [
167
+ '--no-replace-objects',
168
+ '-c',
169
+ 'core.quotepath=off',
170
+ '-c',
171
+ 'advice.graftFileDeprecated=false',
172
+ 'diff',
173
+ '--cached',
174
+ ...PATCH_FLAGS,
175
+ from,
176
+ ],
177
+ env: { GIT_GRAFT_FILE: devNull },
178
+ };
179
+ }
180
+ export function secretFixBrief(hits, from, committed) {
181
+ const shown = hits
182
+ .slice(0, 10)
183
+ .map((h) => `- ${h.kind} at ${h.path}:${h.line}`)
184
+ .join('\n');
185
+ const more = hits.length > 10 ? `\n- and ${hits.length - 10} more` : '';
186
+ return ("Before your change is pushed, the machine's secret scan read every line it adds, and it would refuse the whole push over these lines, which look like credentials:\n" +
187
+ `${shown}${more}\n\n` +
188
+ 'Rewrite each one so no credential-shaped value is written literally. In a test or a fixture, build the value when the test runs — join its parts, sign a JWT or generate a key in the test’s setup, or read it from an environment variable the test sets. A real credential is never written into the change: read it from the environment. ' +
189
+ (committed
190
+ ? `A value inside a commit is pushed with that commit, so first undo your own commits with \`git reset --soft ${from}\` (your work stays, staged; the runner commits it for you). `
191
+ : '') +
192
+ 'Change nothing else, run the tests these files belong to again, and end with the same summary of the task you gave before. Do not commit.');
193
+ }
161
194
  //# sourceMappingURL=secret-scan.js.map
@@ -0,0 +1,17 @@
1
+ export declare function registerSecretValues(runId: string, secrets: ReadonlyArray<{
2
+ name: string;
3
+ value: string;
4
+ }>): void;
5
+ export declare function releaseSecretValues(runId: string): void;
6
+ export declare function heldSecretCount(): number;
7
+ export declare function blankSecrets(text: string): string;
8
+ export declare function blankSecretsDeep<T>(value: T): T;
9
+ export declare function heldSecretValues(): ReadonlyArray<{
10
+ name: string;
11
+ value: string;
12
+ }>;
13
+ export declare function blankingApi<T extends {
14
+ event(runId: string, event: never, detail?: Record<string, unknown>): Promise<void>;
15
+ activity(runId: string, steps: never): Promise<void>;
16
+ result(runId: string, payload: never): Promise<void>;
17
+ }>(api: T): T;
@@ -0,0 +1,81 @@
1
+ const MIN_LENGTH = 8;
2
+ const byRun = new Map();
3
+ let held = [];
4
+ function rebuild() {
5
+ const all = [...byRun.values()].flat();
6
+ const seen = new Set();
7
+ held = all
8
+ .filter((s) => s.value.length >= MIN_LENGTH && !seen.has(s.value) && seen.add(s.value))
9
+ .sort((a, b) => b.value.length - a.value.length);
10
+ }
11
+ export function registerSecretValues(runId, secrets) {
12
+ const kept = secrets.filter((s) => typeof s.value === 'string' && s.value.length >= MIN_LENGTH);
13
+ if (kept.length === 0)
14
+ return;
15
+ byRun.set(runId, [...(byRun.get(runId) ?? []), ...kept]);
16
+ rebuild();
17
+ }
18
+ export function releaseSecretValues(runId) {
19
+ if (byRun.delete(runId))
20
+ rebuild();
21
+ }
22
+ export function heldSecretCount() {
23
+ return held.length;
24
+ }
25
+ function formsOf(value) {
26
+ const forms = new Set([value]);
27
+ const json = JSON.stringify(value).slice(1, -1);
28
+ if (json !== value)
29
+ forms.add(json);
30
+ try {
31
+ const enc = encodeURIComponent(value);
32
+ if (enc !== value)
33
+ forms.add(enc);
34
+ }
35
+ catch {
36
+ }
37
+ return [...forms];
38
+ }
39
+ export function blankSecrets(text) {
40
+ if (held.length === 0 || !text)
41
+ return text;
42
+ let out = text;
43
+ for (const s of held) {
44
+ for (const form of formsOf(s.value)) {
45
+ if (out.includes(form))
46
+ out = out.split(form).join(`[secret ${s.name}]`);
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+ export function blankSecretsDeep(value) {
52
+ if (held.length === 0)
53
+ return value;
54
+ const walk = (v, depth) => {
55
+ if (typeof v === 'string')
56
+ return blankSecrets(v);
57
+ if (depth > 12 || v === null || typeof v !== 'object')
58
+ return v;
59
+ if (Array.isArray(v))
60
+ return v.map((x) => walk(x, depth + 1));
61
+ const out = {};
62
+ for (const [k, x] of Object.entries(v))
63
+ out[k] = walk(x, depth + 1);
64
+ return out;
65
+ };
66
+ return walk(value, 0);
67
+ }
68
+ export function heldSecretValues() {
69
+ return held;
70
+ }
71
+ export function blankingApi(api) {
72
+ const wrapped = Object.create(api);
73
+ const loose = api;
74
+ Object.assign(wrapped, {
75
+ event: (runId, event, detail) => loose.event.call(api, runId, event, blankSecretsDeep(detail)),
76
+ activity: (runId, steps) => loose.activity.call(api, runId, blankSecretsDeep(steps)),
77
+ result: (runId, payload) => loose.result.call(api, runId, blankSecretsDeep(payload)),
78
+ });
79
+ return wrapped;
80
+ }
81
+ //# sourceMappingURL=secret-values.js.map
@@ -0,0 +1,36 @@
1
+ export declare const UPGRADE_EXIT_CODE = 75;
2
+ export declare const UPGRADE_INSTALL_TIMEOUT_MS: number;
3
+ export type UpgradeCommand = {
4
+ version: string;
5
+ requestedAt: string;
6
+ };
7
+ export type UpgradeReport = {
8
+ state: 'started' | 'refused' | 'failed';
9
+ target: string;
10
+ code?: string;
11
+ reason?: string;
12
+ };
13
+ export type SelfUpgradeDeps = {
14
+ held: () => number;
15
+ setDrain: (on: boolean) => boolean;
16
+ install: (spec: string) => Promise<{
17
+ code: number;
18
+ output: string;
19
+ }>;
20
+ exit: (code: number) => void;
21
+ log: (line: string) => void;
22
+ env?: NodeJS.ProcessEnv;
23
+ scriptPath?: string;
24
+ pollMs?: number;
25
+ settleMs?: number;
26
+ now?: () => number;
27
+ sleep?: (ms: number) => Promise<void>;
28
+ };
29
+ export declare function upgradeRefusal(env: NodeJS.ProcessEnv, scriptPath: string): {
30
+ code: string;
31
+ reason: string;
32
+ } | null;
33
+ export declare function createSelfUpgrade(d: SelfUpgradeDeps): {
34
+ report: () => UpgradeReport | null;
35
+ onCommand(cmd: UpgradeCommand): void;
36
+ };
@@ -0,0 +1,78 @@
1
+ import { RUNNER_PACKAGE } from './fleet-words.js';
2
+ export const UPGRADE_EXIT_CODE = 75;
3
+ export const UPGRADE_INSTALL_TIMEOUT_MS = 10 * 60_000;
4
+ export function upgradeRefusal(env, scriptPath) {
5
+ if (/[\\/]_npx[\\/]/.test(scriptPath)) {
6
+ return {
7
+ code: 'npx_install',
8
+ reason: 'This runner runs from npx’s temporary cache, so there is no installed copy to upgrade. Install it with npm install -g @firefunc-agent/runner, then firefunc-runner install.',
9
+ };
10
+ }
11
+ if (env.FIREFUNC_RUNNER_SERVICE !== '1') {
12
+ return {
13
+ code: 'not_a_service',
14
+ reason: 'This runner was started by hand, not as the installed service, so nothing would start the new version after it. Upgrade it where it runs (npm install -g @firefunc-agent/runner@latest), or run it as a service (firefunc-runner install).',
15
+ };
16
+ }
17
+ return null;
18
+ }
19
+ export function createSelfUpgrade(d) {
20
+ let current = null;
21
+ let report = null;
22
+ const env = d.env ?? process.env;
23
+ const scriptPath = d.scriptPath ?? process.argv[1] ?? '';
24
+ const sleep = d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
25
+ const now = d.now ?? (() => Date.now());
26
+ async function carryOut(target) {
27
+ const drainedBefore = d.setDrain(true);
28
+ const lift = () => {
29
+ if (!drainedBefore)
30
+ d.setDrain(false);
31
+ };
32
+ d.log(`FireFunc asked this machine to upgrade to ${target} when idle — finishing the runs it holds, taking nothing new`);
33
+ const started = now();
34
+ const settle = d.settleMs ?? 70_000;
35
+ for (;;) {
36
+ if (d.held() === 0 && now() - started >= settle)
37
+ break;
38
+ await sleep(d.pollMs ?? 10_000);
39
+ }
40
+ const spec = `${RUNNER_PACKAGE}@${target}`;
41
+ d.log(`idle — installing ${spec}`);
42
+ const res = await d.install(spec).catch((err) => ({
43
+ code: -1,
44
+ output: err instanceof Error ? err.message : String(err),
45
+ }));
46
+ lift();
47
+ if (res.code !== 0) {
48
+ const tail = res.output.trim().split('\n').slice(-4).join(' ').slice(0, 400);
49
+ report = {
50
+ state: 'failed',
51
+ target,
52
+ code: 'install_failed',
53
+ reason: `npm install -g ${spec} failed (exit ${res.code})${tail ? `: ${tail}` : ''}. The runner keeps running its current version.`,
54
+ };
55
+ d.log(`upgrade failed — ${report.reason}`);
56
+ return;
57
+ }
58
+ d.log(`installed ${spec} — restarting into it`);
59
+ d.exit(UPGRADE_EXIT_CODE);
60
+ }
61
+ return {
62
+ report: () => report,
63
+ onCommand(cmd) {
64
+ if (current && current.target === cmd.version && current.requestedAt === cmd.requestedAt)
65
+ return;
66
+ current = { target: cmd.version, requestedAt: cmd.requestedAt };
67
+ const refused = upgradeRefusal(env, scriptPath);
68
+ if (refused) {
69
+ report = { state: 'refused', target: cmd.version, ...refused };
70
+ d.log(`cannot upgrade to ${cmd.version}: ${refused.reason}`);
71
+ return;
72
+ }
73
+ report = { state: 'started', target: cmd.version };
74
+ void carryOut(cmd.version);
75
+ },
76
+ };
77
+ }
78
+ //# sourceMappingURL=self-upgrade.js.map
package/dist/service.d.ts CHANGED
@@ -4,6 +4,7 @@ export declare const WINDOWS_TASK_NAME = "FireFuncRunner";
4
4
  export type ServicePaths = {
5
5
  unit: string;
6
6
  log: string;
7
+ launcher?: string;
7
8
  };
8
9
  export declare function servicePaths(os: ServicePlatform, home?: string): ServicePaths;
9
10
  export type UnitInput = {
@@ -15,8 +16,11 @@ export type UnitInput = {
15
16
  };
16
17
  export declare function renderLaunchdPlist(i: UnitInput): string;
17
18
  export declare function renderSystemdUnit(i: UnitInput): string;
19
+ export declare function windowsServiceCommand(i: UnitInput): string;
20
+ export declare function renderWindowsLauncher(i: UnitInput): string;
18
21
  export declare function renderWindowsTaskXml(i: UnitInput & {
19
22
  userId: string;
23
+ launcherPath: string;
20
24
  }): string;
21
25
  export declare function isEphemeralInstall(scriptPath: string): boolean;
22
26
  export declare const EPHEMERAL_INSTALL_MESSAGE: string;
@@ -29,6 +33,7 @@ export type ServiceDeps = {
29
33
  os: ServicePlatform | null;
30
34
  paths: ServicePaths;
31
35
  unitBody: string;
36
+ launcherBody?: string;
32
37
  exec: (cmd: string, args: string[]) => Promise<{
33
38
  code: number;
34
39
  out: string;
@@ -39,7 +44,7 @@ export type ServiceDeps = {
39
44
  removeFile: (path: string) => void;
40
45
  fileExists: (path: string) => boolean;
41
46
  };
42
- export declare function defaultServiceDeps(unitBody: string, os?: ServicePlatform | null): ServiceDeps;
47
+ export declare function defaultServiceDeps(unitBody: string, os?: ServicePlatform | null, launcherBody?: string): ServiceDeps;
43
48
  export declare function installService(d: ServiceDeps): Promise<ServiceResult>;
44
49
  export declare function uninstallService(d: ServiceDeps): Promise<ServiceResult>;
45
50
  export declare function stopService(d: ServiceDeps): Promise<ServiceResult>;
@@ -52,4 +57,5 @@ export type ServiceStatus = {
52
57
  detail?: string;
53
58
  };
54
59
  export declare function serviceStatus(d: ServiceDeps): Promise<ServiceStatus>;
60
+ export declare function serviceWords(svc: ServiceStatus, os: ServicePlatform | null, runnerRunning: boolean): string;
55
61
  export declare function readLogTail(logPath: string, lines?: number): string;
package/dist/service.js CHANGED
@@ -12,7 +12,11 @@ export function servicePaths(os, home = homedir()) {
12
12
  return { unit: join(home, 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`), log };
13
13
  }
14
14
  if (os === 'win32') {
15
- return { unit: join(home, '.firefunc-runner', 'firefunc-runner-task.xml'), log };
15
+ return {
16
+ unit: join(home, '.firefunc-runner', 'firefunc-runner-task.xml'),
17
+ log,
18
+ launcher: join(home, '.firefunc-runner', 'firefunc-runner-service.vbs'),
19
+ };
16
20
  }
17
21
  return { unit: join(home, '.config', 'systemd', 'user', 'firefunc-runner.service'), log };
18
22
  }
@@ -83,12 +87,26 @@ StandardError=append:${i.logPath}
83
87
  WantedBy=default.target
84
88
  `;
85
89
  }
86
- export function renderWindowsTaskXml(i) {
87
- const command = [
90
+ export function windowsServiceCommand(i) {
91
+ return [
88
92
  `set "PATH=${i.pathEnv}"`,
89
93
  `set "FIREFUNC_RUNNER_SERVICE=1"`,
94
+ `set "FIREFUNC_RUNNER_WINDOWLESS=1"`,
90
95
  `"${i.nodePath}" "${i.scriptPath}" start >> "${i.logPath}" 2>&1`,
91
96
  ].join(' && ');
97
+ }
98
+ export function renderWindowsLauncher(i) {
99
+ const line = `cmd.exe /c "${windowsServiceCommand(i)}"`.replace(/"/g, '""');
100
+ return [
101
+ `' FireFunc runner service launcher - written by "firefunc-runner install".`,
102
+ `' Runs the runner with no window; its output goes to ${i.logPath.replace(/[\r\n]/g, ' ')}.`,
103
+ `Set shell = CreateObject("WScript.Shell")`,
104
+ `code = shell.Run("${line}", 0, True)`,
105
+ `WScript.Quit code`,
106
+ ``,
107
+ ].join('\r\n');
108
+ }
109
+ export function renderWindowsTaskXml(i) {
92
110
  return `<?xml version="1.0" encoding="UTF-16"?>
93
111
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
94
112
  <RegistrationInfo>
@@ -133,8 +151,8 @@ export function renderWindowsTaskXml(i) {
133
151
  </Settings>
134
152
  <Actions Context="Author">
135
153
  <Exec>
136
- <Command>cmd.exe</Command>
137
- <Arguments>/c "${xmlEscape(command)}"</Arguments>
154
+ <Command>wscript.exe</Command>
155
+ <Arguments>//B //Nologo &quot;${xmlEscape(i.launcherPath)}&quot;</Arguments>
138
156
  </Exec>
139
157
  </Actions>
140
158
  </Task>
@@ -166,11 +184,12 @@ async function exec(cmd, args) {
166
184
  return { code: typeof e.code === 'number' ? e.code : 1, out: e.stderr ?? e.message ?? '' };
167
185
  }
168
186
  }
169
- export function defaultServiceDeps(unitBody, os = currentPlatform()) {
187
+ export function defaultServiceDeps(unitBody, os = currentPlatform(), launcherBody) {
170
188
  return {
171
189
  os,
172
190
  paths: servicePaths(os ?? 'linux'),
173
191
  unitBody,
192
+ ...(launcherBody ? { launcherBody } : {}),
174
193
  exec,
175
194
  ensureDir: (path) => mkdirSync(path, { recursive: true }),
176
195
  unitEncoding: os === 'win32' ? 'utf16le' : 'utf8',
@@ -206,6 +225,9 @@ export async function installService(d) {
206
225
  };
207
226
  }
208
227
  if (d.os === 'win32') {
228
+ if (d.paths.launcher && d.launcherBody) {
229
+ d.writeFile(d.paths.launcher, d.launcherBody, 'utf16le');
230
+ }
209
231
  const create = await d.exec('schtasks', [
210
232
  '/Create',
211
233
  '/TN',
@@ -223,7 +245,7 @@ export async function installService(d) {
223
245
  : `\nNOTE: registered, but could not start it right now — it will start at your next sign-in.\n${run.out.trim()}`;
224
246
  return {
225
247
  ok: true,
226
- message: `Installed. The runner starts when you sign in and restarts if it crashes.\n` +
248
+ message: `Installed. The runner starts when you sign in, runs with no window, and restarts if it crashes.\n` +
227
249
  ` task: ${WINDOWS_TASK_NAME} (Task Scheduler)\n logs: ${d.paths.log}\n\n` +
228
250
  ` firefunc-runner logs watch it work\n` +
229
251
  ` firefunc-runner stop stop it (stays stopped until you start it)\n` +
@@ -269,6 +291,8 @@ export async function uninstallService(d) {
269
291
  await d.exec('systemctl', ['--user', 'daemon-reload']);
270
292
  }
271
293
  d.removeFile(d.paths.unit);
294
+ if (d.paths.launcher)
295
+ d.removeFile(d.paths.launcher);
272
296
  return { ok: true, message: `Removed. ${d.paths.unit} deleted; the runner will not restart.` };
273
297
  }
274
298
  export async function stopService(d) {
@@ -354,6 +378,25 @@ export async function serviceStatus(d) {
354
378
  const r = await d.exec('systemctl', ['--user', 'is-active', 'firefunc-runner']);
355
379
  return { ...base, installed: true, running: r.out.trim() === 'active' };
356
380
  }
381
+ export function serviceWords(svc, os, runnerRunning) {
382
+ if (!os) {
383
+ return `\nservice: not supported on this platform — keep "firefunc-runner start" running\n`;
384
+ }
385
+ if (!svc.installed) {
386
+ return (`\nservice: NOT INSTALLED — ${runnerRunning ? 'this runner stops' : 'the runner stops'} when you close the terminal\n` +
387
+ ` and does not come back after a reboot.\n` +
388
+ ` Fix: firefunc-runner install\n`);
389
+ }
390
+ const manager = os === 'win32' ? 'Task Scheduler' : os === 'darwin' ? 'launchd' : 'systemd';
391
+ const state = svc.running
392
+ ? 'RUNNING'
393
+ : runnerRunning
394
+ ? `installed; ${manager} reports the task as ${svc.detail === 'task not found' ? 'missing' : (svc.detail ?? 'not running')}, but the runner above is running`
395
+ : 'STOPPED';
396
+ return (`\nservice: ${svc.running ? 'installed, RUNNING' : runnerRunning ? state : `installed, ${state}`}\n` +
397
+ ` unit: ${svc.unit}\n` +
398
+ (svc.running || runnerRunning ? '' : ` Start it: firefunc-runner start-service\n`));
399
+ }
357
400
  export function readLogTail(logPath, lines = 80) {
358
401
  if (!existsSync(logPath))
359
402
  return '(no log yet — has the service been started?)';
@@ -0,0 +1,41 @@
1
+ import type { RunnerConfig } from './config.js';
2
+ import { type LoginProbe } from './engine-login.js';
3
+ import type { EngineId } from './engines/types.js';
4
+ export type PlanState = 'signed_in' | 'not' | 'none' | 'unknown';
5
+ export type KeyState = 'found' | 'missing' | 'none';
6
+ export type EngineSignIn = {
7
+ plan: PlanState;
8
+ key: KeyState;
9
+ keySource?: string;
10
+ uses?: 'plan' | 'key';
11
+ };
12
+ export type SignInReport = Partial<Record<EngineId, EngineSignIn>>;
13
+ export type SignInPref = {
14
+ use?: 'plan' | 'key';
15
+ planToKey?: boolean;
16
+ keyToPlan?: boolean;
17
+ };
18
+ export type SignInPrefs = Partial<Record<string, SignInPref>>;
19
+ export declare const ENGINE_KEY_VARS: Record<EngineId, readonly string[]>;
20
+ export declare function keySourceOf(engine: EngineId, cfg: Pick<RunnerConfig, 'claudeEnv' | 'claudeApiKeyFile'>, env?: NodeJS.ProcessEnv, dir?: string): string | null;
21
+ export declare function planStateOf(engine: EngineId, cfg: Pick<RunnerConfig, 'claudeBin' | 'codexBin' | 'claudeCodeOAuthToken'>, probe?: LoginProbe, env?: NodeJS.ProcessEnv, home?: string): PlanState;
22
+ export declare function signInReport(engines: readonly EngineId[], cfg: RunnerConfig, opts?: {
23
+ probe?: LoginProbe;
24
+ env?: NodeJS.ProcessEnv;
25
+ home?: string;
26
+ dir?: string;
27
+ }): SignInReport;
28
+ export declare function parseSignInPrefs(raw: unknown): SignInPrefs | null;
29
+ export type SignInFields = Pick<RunnerConfig, 'claudeUseApiKey' | 'claudeApiKeyFallback' | 'claudeKeyToPlan' | 'codexUseApiKey'>;
30
+ export declare function signInFieldsOf(cfg: RunnerConfig): SignInFields;
31
+ export declare function applySignInPrefs(local: SignInFields, prefs: SignInPrefs | null): SignInFields;
32
+ export type JobSignIn = {
33
+ ok: true;
34
+ cfg: RunnerConfig;
35
+ note: string | null;
36
+ } | {
37
+ ok: false;
38
+ reason: string;
39
+ fix: string;
40
+ };
41
+ export declare function jobSignIn(engine: EngineId, want: unknown, cfg: RunnerConfig, machine: string, report: EngineSignIn | undefined): JobSignIn;