@firefunc-agent/runner 0.7.1 → 0.9.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 (114) hide show
  1. package/LICENSE +7 -3
  2. package/README.md +296 -4
  3. package/dist/activity.d.ts +32 -0
  4. package/dist/activity.js +295 -0
  5. package/dist/api.d.ts +69 -1
  6. package/dist/api.js +114 -3
  7. package/dist/brief.d.ts +11 -0
  8. package/dist/brief.js +278 -0
  9. package/dist/build-info.json +4 -0
  10. package/dist/cli.js +59 -2
  11. package/dist/config.d.ts +7 -0
  12. package/dist/config.js +3 -0
  13. package/dist/cut.d.ts +45 -0
  14. package/dist/cut.js +105 -0
  15. package/dist/daemon.d.ts +16 -0
  16. package/dist/daemon.js +196 -7
  17. package/dist/declined.d.ts +11 -0
  18. package/dist/declined.js +27 -0
  19. package/dist/engines/antigravity.d.ts +2 -0
  20. package/dist/engines/antigravity.js +102 -0
  21. package/dist/engines/claude-budget.d.ts +1 -1
  22. package/dist/engines/claude-budget.js +2 -72
  23. package/dist/engines/claude.js +139 -2
  24. package/dist/engines/codex.js +10 -3
  25. package/dist/engines/copilot.d.ts +2 -0
  26. package/dist/engines/copilot.js +117 -0
  27. package/dist/engines/cursor.js +4 -0
  28. package/dist/engines/gemini.js +6 -1
  29. package/dist/engines/index.d.ts +2 -0
  30. package/dist/engines/index.js +22 -4
  31. package/dist/engines/types.d.ts +12 -1
  32. package/dist/exec.d.ts +3 -0
  33. package/dist/exec.js +48 -5
  34. package/dist/firefunc/agents.d.ts +2 -0
  35. package/dist/firefunc/agents.js +343 -0
  36. package/dist/firefunc/args.d.ts +18 -0
  37. package/dist/firefunc/args.js +82 -0
  38. package/dist/firefunc/auth.d.ts +21 -0
  39. package/dist/firefunc/auth.js +129 -0
  40. package/dist/firefunc/catalog.d.ts +10 -0
  41. package/dist/firefunc/catalog.js +201 -0
  42. package/dist/firefunc/cli.d.ts +2 -0
  43. package/dist/firefunc/cli.js +24 -0
  44. package/dist/firefunc/client.d.ts +36 -0
  45. package/dist/firefunc/client.js +177 -0
  46. package/dist/firefunc/command.d.ts +28 -0
  47. package/dist/firefunc/command.js +35 -0
  48. package/dist/firefunc/config.d.ts +29 -0
  49. package/dist/firefunc/config.js +111 -0
  50. package/dist/firefunc/configure.d.ts +6 -0
  51. package/dist/firefunc/configure.js +409 -0
  52. package/dist/firefunc/io.d.ts +25 -0
  53. package/dist/firefunc/io.js +14 -0
  54. package/dist/firefunc/main.d.ts +4 -0
  55. package/dist/firefunc/main.js +259 -0
  56. package/dist/firefunc/output.d.ts +29 -0
  57. package/dist/firefunc/output.js +131 -0
  58. package/dist/firefunc/prompt.d.ts +14 -0
  59. package/dist/firefunc/prompt.js +58 -0
  60. package/dist/firefunc/skill.d.ts +3 -0
  61. package/dist/firefunc/skill.js +80 -0
  62. package/dist/firefunc/tasks.d.ts +2 -0
  63. package/dist/firefunc/tasks.js +279 -0
  64. package/dist/firefunc/version.d.ts +2 -0
  65. package/dist/firefunc/version.js +8 -0
  66. package/dist/git-auth.d.ts +4 -1
  67. package/dist/git-auth.js +6 -2
  68. package/dist/held.d.ts +18 -0
  69. package/dist/held.js +95 -0
  70. package/dist/job.d.ts +3 -0
  71. package/dist/job.js +818 -102
  72. package/dist/keep-local.d.ts +12 -0
  73. package/dist/keep-local.js +651 -0
  74. package/dist/limit.d.ts +30 -0
  75. package/dist/limit.js +258 -0
  76. package/dist/locks.d.ts +14 -0
  77. package/dist/locks.js +164 -0
  78. package/dist/machine-logins.d.ts +19 -0
  79. package/dist/machine-logins.js +187 -0
  80. package/dist/mcp-login.d.ts +24 -0
  81. package/dist/mcp-login.js +993 -0
  82. package/dist/mcp-proxy.d.ts +21 -0
  83. package/dist/mcp-proxy.js +180 -0
  84. package/dist/mcp.d.ts +62 -0
  85. package/dist/mcp.js +611 -0
  86. package/dist/network.d.ts +20 -0
  87. package/dist/network.js +76 -0
  88. package/dist/orphans.d.ts +40 -0
  89. package/dist/orphans.js +235 -0
  90. package/dist/pending.d.ts +14 -0
  91. package/dist/pending.js +56 -0
  92. package/dist/pool.d.ts +7 -0
  93. package/dist/pool.js +57 -9
  94. package/dist/pr-title.d.ts +11 -0
  95. package/dist/pr-title.js +63 -0
  96. package/dist/recover.d.ts +10 -0
  97. package/dist/recover.js +104 -0
  98. package/dist/secret-scan.d.ts +19 -0
  99. package/dist/secret-scan.js +161 -0
  100. package/dist/session-stream.d.ts +9 -1
  101. package/dist/session-stream.js +20 -2
  102. package/dist/skills.d.ts +11 -0
  103. package/dist/skills.js +164 -0
  104. package/dist/stopped.d.ts +3 -0
  105. package/dist/stopped.js +10 -0
  106. package/dist/usage.d.ts +49 -0
  107. package/dist/usage.js +389 -0
  108. package/dist/version.d.ts +1 -0
  109. package/dist/version.js +17 -0
  110. package/dist/viewer.js +7 -1
  111. package/dist/worktrees.d.ts +15 -0
  112. package/dist/worktrees.js +96 -0
  113. package/package.json +8 -5
  114. package/skill/firefunc/SKILL.md +222 -0
package/dist/limit.js ADDED
@@ -0,0 +1,258 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
4
+ const PLAN_LIMIT_WORDS = /\bhit your (?:[\w-]+ ){0,2}limit\b|\busage limit\b|\b(?:session|weekly|5-hour|five-hour) limit\b/i;
5
+ function epochToIso(v) {
6
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0)
7
+ return null;
8
+ const ms = v < 1e12 ? v * 1000 : v;
9
+ const d = new Date(ms);
10
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
11
+ }
12
+ export function readClaudeLimit(stdout, now = new Date()) {
13
+ try {
14
+ let rejected = null;
15
+ let result = null;
16
+ let mainLoopRateError = false;
17
+ for (const line of stdout.split('\n')) {
18
+ const t = line.trim();
19
+ if (!t.startsWith('{'))
20
+ continue;
21
+ if (t.includes('"type":"assistant"')) {
22
+ if (t.includes('"parent_tool_use_id":null')) {
23
+ mainLoopRateError = t.includes('"error":"rate_limit"');
24
+ }
25
+ continue;
26
+ }
27
+ if (!t.includes('"type":"result"') && !t.includes('"type":"rate_limit_event"'))
28
+ continue;
29
+ let ev;
30
+ try {
31
+ ev = JSON.parse(t);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ if (!isObj(ev))
37
+ continue;
38
+ if (ev.type === 'rate_limit_event' && isObj(ev.rate_limit_info)) {
39
+ const info = ev.rate_limit_info;
40
+ if (info.status !== 'rejected')
41
+ continue;
42
+ const window = typeof info.rateLimitType === 'string'
43
+ ? info.rateLimitType
44
+ : typeof info.rate_limit_type === 'string'
45
+ ? info.rate_limit_type
46
+ : undefined;
47
+ const unified = isObj(info.unifiedWindows) && window && isObj(info.unifiedWindows[window])
48
+ ? info.unifiedWindows[window]
49
+ : null;
50
+ rejected = {
51
+ resetsAt: epochToIso(info.resetsAt) ?? epochToIso(unified?.resetsAt),
52
+ ...(window ? { window } : {}),
53
+ };
54
+ }
55
+ else if (ev.type === 'result') {
56
+ result = ev;
57
+ }
58
+ }
59
+ if (!result || result.is_error !== true)
60
+ return null;
61
+ const text = typeof result.result === 'string' ? result.result.trim() : '';
62
+ if (result.api_error_status !== 429 && !mainLoopRateError)
63
+ return null;
64
+ if (!rejected && !PLAN_LIMIT_WORDS.test(text))
65
+ return null;
66
+ const resetsAt = rejected?.resetsAt ?? resetFromSentence(text, now);
67
+ return {
68
+ kind: 'plan',
69
+ resetsAt,
70
+ ...(rejected?.window ? { window: rejected.window } : {}),
71
+ ...(text ? { said: text.slice(0, 200) } : {}),
72
+ };
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
79
+ function knownZone(zone) {
80
+ if (!zone)
81
+ return null;
82
+ try {
83
+ new Intl.DateTimeFormat('en-US', { timeZone: zone });
84
+ return zone;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ function wallParts(ms, zone) {
91
+ const parts = new Intl.DateTimeFormat('en-US', {
92
+ timeZone: zone,
93
+ hourCycle: 'h23',
94
+ year: 'numeric',
95
+ month: '2-digit',
96
+ day: '2-digit',
97
+ hour: '2-digit',
98
+ minute: '2-digit',
99
+ second: '2-digit',
100
+ }).formatToParts(new Date(ms));
101
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? '0');
102
+ return {
103
+ y: get('year'),
104
+ mo: get('month') - 1,
105
+ d: get('day'),
106
+ h: get('hour') % 24,
107
+ mi: get('minute'),
108
+ s: get('second'),
109
+ };
110
+ }
111
+ function zoneOffset(ms, zone) {
112
+ const p = wallParts(ms, zone);
113
+ return Date.UTC(p.y, p.mo, p.d, p.h, p.mi, p.s) - Math.floor(ms / 1000) * 1000;
114
+ }
115
+ function zonedInstant(y, mo, d, h, mi, zone) {
116
+ const guess = Date.UTC(y, mo, d, h, mi);
117
+ let at = guess - zoneOffset(guess, zone);
118
+ const again = guess - zoneOffset(at, zone);
119
+ if (again !== at)
120
+ at = again;
121
+ return at;
122
+ }
123
+ export function resetFromSentence(text, now = new Date()) {
124
+ const m = /\bresets\s+(?:at\s+)?(?:(?<mon>[A-Za-z]{3,9})\.?\s+(?<day>\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?(?<h>\d{1,2})(?::(?<mi>\d{2}))?\s*(?<ap>am|pm)?(?:\s*\((?<tz>[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+){0,2})\))?/i.exec(text);
125
+ if (!m?.groups)
126
+ return null;
127
+ const g = m.groups;
128
+ let h = Number(g.h);
129
+ const mi = g.mi ? Number(g.mi) : 0;
130
+ if (!Number.isFinite(h) || h > 23 || mi > 59)
131
+ return null;
132
+ const ap = g.ap?.toLowerCase();
133
+ if (ap) {
134
+ if (h < 1 || h > 12)
135
+ return null;
136
+ h = (h % 12) + (ap === 'pm' ? 12 : 0);
137
+ }
138
+ else if (!g.mi) {
139
+ return null;
140
+ }
141
+ const zone = knownZone(g.tz) ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
142
+ const nowMs = now.getTime();
143
+ const today = wallParts(nowMs, zone);
144
+ if (g.mon && g.day) {
145
+ const mo = MONTHS.indexOf(g.mon.slice(0, 3).toLowerCase());
146
+ const d = Number(g.day);
147
+ if (mo < 0 || d < 1 || d > 31)
148
+ return null;
149
+ let at = zonedInstant(today.y, mo, d, h, mi, zone);
150
+ if (at < nowMs - 183 * 86_400_000)
151
+ at = zonedInstant(today.y + 1, mo, d, h, mi, zone);
152
+ return new Date(at).toISOString();
153
+ }
154
+ let at = zonedInstant(today.y, today.mo, today.d, h, mi, zone);
155
+ if (at < nowMs - 60_000) {
156
+ const next = new Date(Date.UTC(today.y, today.mo, today.d + 1));
157
+ at = zonedInstant(next.getUTCFullYear(), next.getUTCMonth(), next.getUTCDate(), h, mi, zone);
158
+ }
159
+ return new Date(at).toISOString();
160
+ }
161
+ export function limitSentence(engineName, limit, kept) {
162
+ const when = limit.resetsAt ? `resets ${limit.resetsAt}` : 'it did not say when the limit resets';
163
+ return (`${engineName} was stopped by the plan's usage limit — ${when}. ` +
164
+ `The runner pushed nothing from this attempt and claims no new work for ${engineName} ` +
165
+ `until the reset. ` +
166
+ (kept
167
+ ? 'When the task runs again after the reset, this machine continues the same session from where it stopped instead of starting over.'
168
+ : 'Run the task again after the reset.'));
169
+ }
170
+ export const UNKNOWN_RESET_WAIT_MS = 15 * 60_000;
171
+ export const RESET_GRACE_MS = 2 * 60_000;
172
+ export class LimitGate {
173
+ file;
174
+ now;
175
+ limits = new Map();
176
+ constructor(file, now = () => Date.now()) {
177
+ this.file = file;
178
+ this.now = now;
179
+ if (!file || !existsSync(file))
180
+ return;
181
+ try {
182
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
183
+ if (!Array.isArray(raw))
184
+ return;
185
+ for (const r of raw) {
186
+ if (!isObj(r) || typeof r.engine !== 'string' || typeof r.until !== 'string')
187
+ continue;
188
+ if (Number.isNaN(Date.parse(r.until)))
189
+ continue;
190
+ this.limits.set(r.engine, {
191
+ engine: r.engine,
192
+ resetsAt: typeof r.resetsAt === 'string' ? r.resetsAt : null,
193
+ ...(typeof r.window === 'string' ? { window: r.window } : {}),
194
+ until: r.until,
195
+ since: typeof r.since === 'string' ? r.since : new Date(this.now()).toISOString(),
196
+ });
197
+ }
198
+ this.prune();
199
+ }
200
+ catch {
201
+ }
202
+ }
203
+ static fileIn(runnerDir) {
204
+ return join(runnerDir, 'limits.json');
205
+ }
206
+ set(engine, limit) {
207
+ const nowMs = this.now();
208
+ const reset = limit.resetsAt ? Date.parse(limit.resetsAt) : Number.NaN;
209
+ const untilMs = Number.isFinite(reset)
210
+ ? Math.max(reset + RESET_GRACE_MS, nowMs + 60_000)
211
+ : nowMs + UNKNOWN_RESET_WAIT_MS;
212
+ const active = {
213
+ engine,
214
+ resetsAt: limit.resetsAt,
215
+ ...(limit.window ? { window: limit.window } : {}),
216
+ until: new Date(untilMs).toISOString(),
217
+ since: new Date(nowMs).toISOString(),
218
+ };
219
+ this.limits.set(engine, active);
220
+ this.save();
221
+ return active;
222
+ }
223
+ isLimited(engine) {
224
+ this.prune();
225
+ return this.limits.get(engine) ?? null;
226
+ }
227
+ active() {
228
+ this.prune();
229
+ return [...this.limits.values()];
230
+ }
231
+ prune() {
232
+ const nowMs = this.now();
233
+ let changed = false;
234
+ for (const [engine, l] of this.limits) {
235
+ if (Date.parse(l.until) <= nowMs) {
236
+ this.limits.delete(engine);
237
+ changed = true;
238
+ }
239
+ }
240
+ if (changed)
241
+ this.save();
242
+ }
243
+ save() {
244
+ if (!this.file)
245
+ return;
246
+ try {
247
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
248
+ const tmp = `${this.file}.tmp`;
249
+ writeFileSync(tmp, `${JSON.stringify([...this.limits.values()], null, 2)}\n`, {
250
+ mode: 0o600,
251
+ });
252
+ renameSync(tmp, this.file);
253
+ }
254
+ catch {
255
+ }
256
+ }
257
+ }
258
+ //# sourceMappingURL=limit.js.map
package/dist/locks.d.ts CHANGED
@@ -2,3 +2,17 @@ export type KeyedMutex = {
2
2
  run<T>(key: string, fn: () => Promise<T>): Promise<T>;
3
3
  };
4
4
  export declare function createKeyedMutex(): KeyedMutex;
5
+ export declare function repoLockKey(repo: string): string;
6
+ export declare function heavyLockDir(runnerDir: string, repo: string): string;
7
+ export type HeavyLockOptions = {
8
+ label?: string;
9
+ pollMs?: number;
10
+ maxWaitMs?: number;
11
+ onWait?: (holder: number | null) => void;
12
+ now?: () => number;
13
+ sleep?: (ms: number) => Promise<void>;
14
+ };
15
+ export declare function acquireHeavyLock(lockDir: string, opts?: HeavyLockOptions): Promise<() => void>;
16
+ export declare function withHeavyLock<T>(lockDir: string, fn: () => Promise<T>, opts?: HeavyLockOptions): Promise<T>;
17
+ export declare function heavyScript(): string;
18
+ export declare function ensureHeavyScript(runnerDir: string): string | null;
package/dist/locks.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+ import { dirname, join } from 'node:path';
1
5
  const noop = () => { };
2
6
  export function createKeyedMutex() {
3
7
  const tails = new Map();
@@ -10,4 +14,164 @@ export function createKeyedMutex() {
10
14
  },
11
15
  };
12
16
  }
17
+ export function repoLockKey(repo) {
18
+ const slug = repo
19
+ .toLowerCase()
20
+ .replace(/[^a-z0-9._-]+/g, '_')
21
+ .replace(/^[._]+/, '')
22
+ .slice(0, 80);
23
+ const hash = createHash('sha256').update(repo.toLowerCase()).digest('hex').slice(0, 8);
24
+ return `${slug || 'repo'}-${hash}`;
25
+ }
26
+ export function heavyLockDir(runnerDir, repo) {
27
+ return join(runnerDir, 'locks', `heavy-${repoLockKey(repo)}.lock`);
28
+ }
29
+ function isAlive(pid) {
30
+ if (!Number.isInteger(pid) || pid <= 0)
31
+ return false;
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ }
36
+ catch (e) {
37
+ return e.code === 'EPERM';
38
+ }
39
+ }
40
+ function holderOf(lockDir) {
41
+ try {
42
+ const first = readFileSync(join(lockDir, 'owner'), 'utf8').split('\n', 1)[0] ?? '';
43
+ const pid = Number(first.trim());
44
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ function breakIfStale(lockDir, now) {
51
+ const holder = holderOf(lockDir);
52
+ let stale = holder !== null && !isAlive(holder);
53
+ if (holder === null) {
54
+ try {
55
+ stale = now() - statSync(lockDir).mtimeMs > 60_000;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ if (!stale)
62
+ return false;
63
+ const away = `${lockDir}.stale-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
64
+ try {
65
+ renameSync(lockDir, away);
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ rmSync(away, { recursive: true, force: true });
71
+ return true;
72
+ }
73
+ export async function acquireHeavyLock(lockDir, opts = {}) {
74
+ const now = opts.now ?? (() => Date.now());
75
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
76
+ const started = now();
77
+ let told = false;
78
+ mkdirSync(dirname(lockDir), { recursive: true, mode: 0o700 });
79
+ for (;;) {
80
+ try {
81
+ mkdirSync(lockDir);
82
+ writeFileSync(join(lockDir, 'owner'), `${process.pid}\n${hostname()}\n${new Date(now()).toISOString()}\n${opts.label ?? 'runner'}\n`);
83
+ let held = true;
84
+ return () => {
85
+ if (!held)
86
+ return;
87
+ held = false;
88
+ if (holderOf(lockDir) === process.pid)
89
+ rmSync(lockDir, { recursive: true, force: true });
90
+ };
91
+ }
92
+ catch (e) {
93
+ if (e.code !== 'EEXIST')
94
+ return noop;
95
+ }
96
+ if (breakIfStale(lockDir, now))
97
+ continue;
98
+ if (!told) {
99
+ told = true;
100
+ opts.onWait?.(holderOf(lockDir));
101
+ }
102
+ if (opts.maxWaitMs !== undefined && now() - started >= opts.maxWaitMs)
103
+ return noop;
104
+ await sleep(opts.pollMs ?? 1000);
105
+ }
106
+ }
107
+ const heavyMutex = createKeyedMutex();
108
+ export async function withHeavyLock(lockDir, fn, opts = {}) {
109
+ return heavyMutex.run(lockDir, async () => {
110
+ const release = await acquireHeavyLock(lockDir, opts);
111
+ try {
112
+ return await fn();
113
+ }
114
+ finally {
115
+ release();
116
+ }
117
+ });
118
+ }
119
+ const HEAVY_SCRIPT_VERSION = 1;
120
+ export function heavyScript() {
121
+ return `#!/bin/sh
122
+ # firefunc-heavy v${HEAVY_SCRIPT_VERSION} — written by the FireFunc runner (locks.ts).
123
+ # Runs ONE heavy command at a time per repository on this machine:
124
+ # "$FIREFUNC_HEAVY" pnpm test
125
+ # It waits for any other heavy command in the same repository, then runs yours.
126
+ lock="\${FIREFUNC_HEAVY_LOCK:-}"
127
+ if [ -z "$lock" ] || [ "\${FIREFUNC_HEAVY_HELD:-}" = "$lock" ]; then
128
+ exec "$@"
129
+ fi
130
+ mkdir -p "$(dirname "$lock")" 2>/dev/null
131
+ told=0
132
+ while ! mkdir "$lock" 2>/dev/null; do
133
+ holder=$(sed -n 1p "$lock/owner" 2>/dev/null)
134
+ if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then
135
+ away="$lock.stale-$$"
136
+ mv "$lock" "$away" 2>/dev/null && rm -rf "$away"
137
+ continue
138
+ fi
139
+ if [ -z "$holder" ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then
140
+ away="$lock.stale-$$"
141
+ mv "$lock" "$away" 2>/dev/null && rm -rf "$away"
142
+ continue
143
+ fi
144
+ if [ "$told" = 0 ]; then
145
+ echo "firefunc-heavy: another heavy command is running in this repository (pid \${holder:-?}) — waiting for it to finish first" >&2
146
+ told=1
147
+ fi
148
+ sleep 2
149
+ done
150
+ printf '%s\\n%s\\n%s\\n%s\\n' "$$" "$(hostname)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "engine" > "$lock/owner"
151
+ trap 'rm -rf "$lock"' EXIT
152
+ trap 'rm -rf "$lock"; exit 130' INT
153
+ trap 'rm -rf "$lock"; exit 143' TERM
154
+ FIREFUNC_HEAVY_HELD="$lock"
155
+ export FIREFUNC_HEAVY_HELD
156
+ "$@"
157
+ `;
158
+ }
159
+ export function ensureHeavyScript(runnerDir) {
160
+ if (process.platform === 'win32')
161
+ return null;
162
+ const dir = join(runnerDir, 'bin');
163
+ const file = join(dir, 'firefunc-heavy');
164
+ const text = heavyScript();
165
+ try {
166
+ if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {
167
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
168
+ writeFileSync(file, text, { mode: 0o755 });
169
+ }
170
+ chmodSync(file, 0o755);
171
+ return file;
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ }
13
177
  //# sourceMappingURL=locks.js.map
@@ -0,0 +1,19 @@
1
+ export type MachineLoginState = 'logged_in' | 'expired' | 'error';
2
+ export type MachineLogin = {
3
+ server: string;
4
+ state: MachineLoginState;
5
+ via: 'runner' | 'claude_code';
6
+ serverUrl: string | null;
7
+ accountLabel: string | null;
8
+ expiresAt: string | null;
9
+ detail?: string;
10
+ };
11
+ export declare const VENDOR_MCP_URLS: Readonly<Record<string, string>>;
12
+ export declare const CATALOG_ONLY: ReadonlySet<string>;
13
+ export declare function runnerLogins(now?: number): MachineLogin[];
14
+ export type ClaudeCodeStoreReader = () => string | null;
15
+ export declare function readClaudeCodeStore(): string | null;
16
+ export declare function claudeCodeLogins(now?: number, read?: ClaudeCodeStoreReader): MachineLogin[];
17
+ export declare function machineLogins(now?: number, read?: ClaudeCodeStoreReader): MachineLogin[];
18
+ export declare function claudeCodeSignsFor(server: string, url: string, now?: number, read?: ClaudeCodeStoreReader): boolean;
19
+ export declare function claudeCodeSignInFix(server: string): string;
@@ -0,0 +1,187 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import { homedir, platform } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { mcpLoginPath } from './mcp.js';
6
+ import { configPath } from './config.js';
7
+ export const VENDOR_MCP_URLS = {
8
+ figma: 'https://mcp.figma.com/mcp',
9
+ jira: 'https://mcp.atlassian.com/v2/mcp',
10
+ linear: 'https://mcp.linear.app/mcp/readonly',
11
+ sentry: 'https://mcp.sentry.dev/mcp',
12
+ slack: 'https://mcp.slack.com/mcp',
13
+ };
14
+ export const CATALOG_ONLY = new Set(['figma']);
15
+ const SERVER_KEY = /^[a-z0-9]+([_-][a-z0-9]+)*$/;
16
+ const SKEW_MS = 60_000;
17
+ const normalizeUrl = (u) => u.replace(/\/+$/, '').toLowerCase();
18
+ function expiryState(expiresAt, now) {
19
+ if (expiresAt === undefined || expiresAt === null || expiresAt === '') {
20
+ return { state: 'logged_in', iso: null };
21
+ }
22
+ const ms = typeof expiresAt === 'number'
23
+ ? expiresAt
24
+ : typeof expiresAt === 'string'
25
+ ? /^\d+$/.test(expiresAt)
26
+ ? Number(expiresAt)
27
+ : Date.parse(expiresAt)
28
+ : Number.NaN;
29
+ if (!Number.isFinite(ms))
30
+ return { state: 'logged_in', iso: null };
31
+ return { state: ms <= now + SKEW_MS ? 'expired' : 'logged_in', iso: new Date(ms).toISOString() };
32
+ }
33
+ export function runnerLogins(now = Date.now()) {
34
+ const dir = join(configPath(), '..', 'mcp-logins');
35
+ let names = [];
36
+ try {
37
+ names = readdirSync(dir).filter((n) => n.endsWith('.json'));
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ const out = [];
43
+ for (const name of names.sort()) {
44
+ const server = name.slice(0, -'.json'.length);
45
+ if (!SERVER_KEY.test(server) || server.length > 64)
46
+ continue;
47
+ let raw;
48
+ try {
49
+ raw = JSON.parse(readFileSync(mcpLoginPath(server), 'utf8'));
50
+ }
51
+ catch {
52
+ out.push({
53
+ server,
54
+ state: 'error',
55
+ via: 'runner',
56
+ serverUrl: null,
57
+ accountLabel: null,
58
+ expiresAt: null,
59
+ detail: 'the cached login could not be read',
60
+ });
61
+ continue;
62
+ }
63
+ const r = (raw && typeof raw === 'object' ? raw : {});
64
+ if (typeof r.accessToken !== 'string' || !r.accessToken) {
65
+ out.push({
66
+ server,
67
+ state: 'error',
68
+ via: 'runner',
69
+ serverUrl: typeof r.serverUrl === 'string' ? r.serverUrl : null,
70
+ accountLabel: null,
71
+ expiresAt: null,
72
+ detail: 'the cached login holds no token',
73
+ });
74
+ continue;
75
+ }
76
+ const { state, iso } = expiryState(r.expiresAt, now);
77
+ out.push({
78
+ server,
79
+ state,
80
+ via: 'runner',
81
+ serverUrl: typeof r.serverUrl === 'string' ? r.serverUrl : null,
82
+ accountLabel: typeof r.accountLabel === 'string' ? r.accountLabel : null,
83
+ expiresAt: iso,
84
+ });
85
+ }
86
+ return out;
87
+ }
88
+ export function readClaudeCodeStore() {
89
+ if (platform() === 'darwin') {
90
+ try {
91
+ const res = spawnSync('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], {
92
+ encoding: 'utf8',
93
+ timeout: 5_000,
94
+ });
95
+ if (res.status === 0 && res.stdout.trim())
96
+ return res.stdout.trim();
97
+ }
98
+ catch {
99
+ }
100
+ }
101
+ const dir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
102
+ const file = join(dir, '.credentials.json');
103
+ if (!existsSync(file))
104
+ return null;
105
+ try {
106
+ return readFileSync(file, 'utf8');
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ export function claudeCodeLogins(now = Date.now(), read = readClaudeCodeStore) {
113
+ const text = read();
114
+ if (!text)
115
+ return [];
116
+ let store;
117
+ try {
118
+ store = JSON.parse(text);
119
+ }
120
+ catch {
121
+ return [];
122
+ }
123
+ const oauth = store?.mcpOAuth;
124
+ if (!oauth || typeof oauth !== 'object')
125
+ return [];
126
+ const byUrl = new Map(Object.entries(VENDOR_MCP_URLS).map(([id, url]) => [normalizeUrl(url), id]));
127
+ const out = [];
128
+ for (const entry of Object.values(oauth)) {
129
+ if (!entry || typeof entry !== 'object')
130
+ continue;
131
+ const e = entry;
132
+ const url = typeof e.serverUrl === 'string' ? e.serverUrl : null;
133
+ const name = typeof e.serverName === 'string' ? e.serverName : null;
134
+ if (!url || !name)
135
+ continue;
136
+ const vendor = byUrl.get(normalizeUrl(url));
137
+ if (!vendor)
138
+ continue;
139
+ const hasToken = (typeof e.accessToken === 'string' && e.accessToken.length > 0) ||
140
+ (typeof e.refreshToken === 'string' && e.refreshToken.length > 0);
141
+ if (!hasToken)
142
+ continue;
143
+ if (name !== vendor) {
144
+ out.push({
145
+ server: vendor,
146
+ state: 'error',
147
+ via: 'claude_code',
148
+ serverUrl: url,
149
+ accountLabel: null,
150
+ expiresAt: null,
151
+ detail: `Claude Code holds this sign-in under the name "${name}"; a run names the server "${vendor}", and Claude Code keys the sign-in by name. Re-add it as "${vendor}".`,
152
+ });
153
+ continue;
154
+ }
155
+ const { state, iso } = expiryState(e.expiresAt, now);
156
+ const refreshable = typeof e.refreshToken === 'string' && e.refreshToken.length > 0;
157
+ out.push({
158
+ server: vendor,
159
+ state: state === 'expired' && refreshable ? 'logged_in' : state,
160
+ via: 'claude_code',
161
+ serverUrl: url,
162
+ accountLabel: null,
163
+ expiresAt: iso,
164
+ });
165
+ }
166
+ return out.sort((a, b) => a.server.localeCompare(b.server));
167
+ }
168
+ export function machineLogins(now = Date.now(), read = readClaudeCodeStore) {
169
+ const mine = runnerLogins(now);
170
+ const seen = new Set(mine.filter((l) => l.state === 'logged_in').map((l) => l.server));
171
+ const theirs = claudeCodeLogins(now, read).filter((l) => !seen.has(l.server));
172
+ return [...mine, ...theirs].sort((a, b) => a.server.localeCompare(b.server));
173
+ }
174
+ export function claudeCodeSignsFor(server, url, now = Date.now(), read = readClaudeCodeStore) {
175
+ return claudeCodeLogins(now, read).some((l) => l.server === server &&
176
+ l.state === 'logged_in' &&
177
+ l.serverUrl !== null &&
178
+ normalizeUrl(l.serverUrl) === normalizeUrl(url));
179
+ }
180
+ export function claudeCodeSignInFix(server) {
181
+ const url = VENDOR_MCP_URLS[server];
182
+ if (!url)
183
+ return `sign Claude Code in to the "${server}" server on this machine`;
184
+ return (`on this machine run \`claude mcp add --transport http ${server} ${url}\`, then inside \`claude\` run \`/mcp\` and authenticate ${server}; ` +
185
+ `the sign-in stays in Claude Code's own store and runs use it without FireFunc ever holding it`);
186
+ }
187
+ //# sourceMappingURL=machine-logins.js.map
@@ -0,0 +1,24 @@
1
+ export type McpLoginRecord = {
2
+ server: string;
3
+ tokenType: string;
4
+ accessToken: string;
5
+ expiresAt: string | null;
6
+ accountLabel: string | null;
7
+ serverUrl: string;
8
+ issuer: string;
9
+ tokenEndpoint: string;
10
+ revocationEndpoint?: string;
11
+ resource?: string;
12
+ clientId: string;
13
+ clientSecret?: string;
14
+ scope?: string;
15
+ refreshToken?: string;
16
+ obtainedAt: string;
17
+ };
18
+ export declare function mcpLoginDir(): string;
19
+ export declare function mcpLoginPath(server: string): string;
20
+ export declare function runMcpLogin(tool: string, opts?: {
21
+ noBrowser?: boolean;
22
+ }): Promise<void>;
23
+ export declare function runMcpList(): void;
24
+ export declare function runMcpLogout(tool: string): Promise<void>;