@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,239 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { apiKeyFile, claudeApiKeyNow } from './api-fallback.js';
5
+ import { spawnLoginProbe } from './engine-login.js';
6
+ export const ENGINE_KEY_VARS = {
7
+ claude_code: ['ANTHROPIC_API_KEY'],
8
+ codex_cli: ['OPENAI_API_KEY', 'CODEX_API_KEY'],
9
+ gemini_cli: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
10
+ antigravity: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
11
+ cursor_cli: ['CURSOR_API_KEY'],
12
+ copilot_cli: [],
13
+ opencode: ['OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY'],
14
+ pi: ['OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY'],
15
+ kilo: ['OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY'],
16
+ qwen_code: ['DASHSCOPE_API_KEY', 'OPENAI_API_KEY'],
17
+ crush: ['OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY'],
18
+ openhands: ['LLM_API_KEY', 'OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY'],
19
+ };
20
+ const KEY_ONLY = new Set(['opencode', 'pi', 'kilo', 'crush', 'openhands']);
21
+ const readable = (file) => {
22
+ try {
23
+ return existsSync(file) && statSync(file).size > 0 && statSync(file).size <= 4096;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ };
29
+ export function keySourceOf(engine, cfg, env = process.env, dir) {
30
+ for (const name of ENGINE_KEY_VARS[engine] ?? []) {
31
+ if ((cfg.claudeEnv?.[name] ?? '').trim())
32
+ return `runner config: ${name}`;
33
+ if ((env[name] ?? '').trim())
34
+ return `environment: ${name}`;
35
+ }
36
+ if (engine === 'claude_code' && readable(apiKeyFile(cfg, dir)))
37
+ return 'runner folder key file';
38
+ return null;
39
+ }
40
+ export function planStateOf(engine, cfg, probe = spawnLoginProbe, env = process.env, home = homedir()) {
41
+ if (KEY_ONLY.has(engine))
42
+ return 'none';
43
+ const planEnv = { ...env };
44
+ for (const vars of Object.values(ENGINE_KEY_VARS))
45
+ for (const v of vars)
46
+ delete planEnv[v];
47
+ try {
48
+ if (engine === 'claude_code') {
49
+ if (cfg.claudeCodeOAuthToken)
50
+ return 'signed_in';
51
+ const res = probe(cfg.claudeBin ?? 'claude', ['auth', 'status', '--json'], planEnv);
52
+ if (!res)
53
+ return 'unknown';
54
+ const said = JSON.parse(res.stdout.trim());
55
+ if (said.loggedIn === false)
56
+ return 'not';
57
+ if (said.loggedIn === true && said.authMethod !== 'none' && said.authMethod !== 'api_key')
58
+ return 'signed_in';
59
+ return 'unknown';
60
+ }
61
+ if (engine === 'codex_cli') {
62
+ const res = probe(cfg.codexBin ?? 'codex', ['login', 'status'], planEnv);
63
+ if (!res)
64
+ return 'unknown';
65
+ const line = res.stdout.trim().toLowerCase();
66
+ if (/not logged in/.test(line))
67
+ return 'not';
68
+ if (/logged in using chatgpt/.test(line))
69
+ return 'signed_in';
70
+ return 'unknown';
71
+ }
72
+ if (engine === 'gemini_cli' || engine === 'antigravity') {
73
+ return readable(join(home, '.gemini', 'oauth_creds.json')) ? 'signed_in' : 'unknown';
74
+ }
75
+ }
76
+ catch {
77
+ return 'unknown';
78
+ }
79
+ return 'unknown';
80
+ }
81
+ export function signInReport(engines, cfg, opts = {}) {
82
+ const out = {};
83
+ for (const engine of engines) {
84
+ const vars = ENGINE_KEY_VARS[engine];
85
+ if (!vars)
86
+ continue;
87
+ const plan = planStateOf(engine, cfg, opts.probe, opts.env, opts.home);
88
+ const uses = engine === 'claude_code'
89
+ ? (() => {
90
+ const b = claudeApiKeyNow(cfg, opts.dir);
91
+ return b.why === 'opted-in' || b.key !== null ? 'key' : 'plan';
92
+ })()
93
+ : engine === 'codex_cli'
94
+ ? cfg.codexUseApiKey
95
+ ? 'key'
96
+ : 'plan'
97
+ : KEY_ONLY.has(engine)
98
+ ? 'key'
99
+ : undefined;
100
+ const used = uses ? { uses } : {};
101
+ if (vars.length === 0) {
102
+ out[engine] = { plan, key: 'none', ...used };
103
+ continue;
104
+ }
105
+ const source = keySourceOf(engine, cfg, opts.env, opts.dir);
106
+ out[engine] = source
107
+ ? { plan, key: 'found', keySource: source, ...used }
108
+ : { plan, key: 'missing', ...used };
109
+ }
110
+ return out;
111
+ }
112
+ export function parseSignInPrefs(raw) {
113
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
114
+ return null;
115
+ const out = {};
116
+ for (const [engine, v] of Object.entries(raw)) {
117
+ if (!v || typeof v !== 'object')
118
+ continue;
119
+ const p = v;
120
+ const pref = {};
121
+ if (p.use === 'plan' || p.use === 'key')
122
+ pref.use = p.use;
123
+ if (typeof p.planToKey === 'boolean')
124
+ pref.planToKey = p.planToKey;
125
+ if (typeof p.keyToPlan === 'boolean')
126
+ pref.keyToPlan = p.keyToPlan;
127
+ out[engine] = pref;
128
+ }
129
+ return out;
130
+ }
131
+ export function signInFieldsOf(cfg) {
132
+ return {
133
+ claudeUseApiKey: cfg.claudeUseApiKey,
134
+ claudeApiKeyFallback: cfg.claudeApiKeyFallback,
135
+ claudeKeyToPlan: cfg.claudeKeyToPlan,
136
+ codexUseApiKey: cfg.codexUseApiKey,
137
+ };
138
+ }
139
+ export function applySignInPrefs(local, prefs) {
140
+ const out = { ...local };
141
+ const claude = prefs?.claude_code;
142
+ if (claude?.use)
143
+ out.claudeUseApiKey = claude.use === 'key';
144
+ if (claude?.planToKey !== undefined)
145
+ out.claudeApiKeyFallback = claude.planToKey;
146
+ if (claude?.keyToPlan !== undefined)
147
+ out.claudeKeyToPlan = claude.keyToPlan;
148
+ const codex = prefs?.codex_cli;
149
+ if (codex?.use)
150
+ out.codexUseApiKey = codex.use === 'key';
151
+ return out;
152
+ }
153
+ const ENGINE_WORDS = {
154
+ claude_code: 'Claude Code',
155
+ codex_cli: 'Codex',
156
+ gemini_cli: 'Gemini CLI',
157
+ antigravity: 'Antigravity',
158
+ cursor_cli: 'Cursor CLI',
159
+ copilot_cli: 'Copilot CLI',
160
+ opencode: 'OpenCode',
161
+ };
162
+ const PROVIDER_WORDS = {
163
+ claude_code: 'Anthropic',
164
+ codex_cli: 'OpenAI',
165
+ gemini_cli: 'Google',
166
+ antigravity: 'Google',
167
+ cursor_cli: 'Cursor',
168
+ };
169
+ const PLAN_LOGIN = {
170
+ claude_code: 'claude auth login',
171
+ codex_cli: 'codex login',
172
+ gemini_cli: 'gemini (and sign in with Google)',
173
+ cursor_cli: 'cursor-agent login',
174
+ };
175
+ export function jobSignIn(engine, want, cfg, machine, report) {
176
+ if (want !== 'plan' && want !== 'key')
177
+ return { ok: true, cfg, note: null };
178
+ const name = ENGINE_WORDS[engine] ?? engine;
179
+ const vars = ENGINE_KEY_VARS[engine] ?? [];
180
+ if (want === 'key') {
181
+ if (vars.length === 0) {
182
+ return {
183
+ ok: false,
184
+ reason: `${name} signs in with GitHub only, so it has no API key to use on ${machine}.`,
185
+ fix: `Set this job to sign in with the subscription, or pick another engine for it.`,
186
+ };
187
+ }
188
+ if (report?.key !== 'found') {
189
+ const planToo = engine === 'claude_code' ? cfg.claudeKeyToPlan === true && report?.plan !== 'not' : false;
190
+ if (planToo) {
191
+ return {
192
+ ok: true,
193
+ cfg: { ...cfg, claudeUseApiKey: false },
194
+ note: `no ${PROVIDER_WORDS[engine] ?? ''} key on ${machine}: on the plan (key → plan fallback)`,
195
+ };
196
+ }
197
+ return {
198
+ ok: false,
199
+ reason: `No ${PROVIDER_WORDS[engine] ?? name} key on ${machine}.`,
200
+ fix: `Set ${vars[0]} on it, then run the engine check again (\`firefunc-runner restart\`) — or set this job to sign in with the subscription.`,
201
+ };
202
+ }
203
+ if (engine === 'claude_code')
204
+ return { ok: true, cfg: { ...cfg, claudeUseApiKey: true }, note: 'API key' };
205
+ if (engine === 'codex_cli')
206
+ return { ok: true, cfg: { ...cfg, codexUseApiKey: true }, note: 'API key' };
207
+ return { ok: true, cfg, note: 'API key' };
208
+ }
209
+ if (KEY_ONLY.has(engine)) {
210
+ return {
211
+ ok: false,
212
+ reason: `${name} has no subscription of its own: it runs on provider API keys only.`,
213
+ fix: `Set this job to sign in with an API key, or pick an engine whose plan you hold.`,
214
+ };
215
+ }
216
+ if (report?.plan === 'not') {
217
+ const keyToo = engine === 'claude_code'
218
+ ? cfg.claudeApiKeyFallback === true && report.key === 'found'
219
+ : false;
220
+ if (keyToo) {
221
+ return {
222
+ ok: true,
223
+ cfg: { ...cfg, claudeUseApiKey: true },
224
+ note: `the plan is not signed in on ${machine}: on the API key (plan → key fallback)`,
225
+ };
226
+ }
227
+ return {
228
+ ok: false,
229
+ reason: `${name} is not signed in to its plan on ${machine}.`,
230
+ fix: `On ${machine}, run \`${PLAN_LOGIN[engine] ?? 'the engine’s login'}\` as the user the runner runs as — or set this job to sign in with an API key.`,
231
+ };
232
+ }
233
+ if (engine === 'claude_code')
234
+ return { ok: true, cfg: { ...cfg, claudeUseApiKey: false }, note: 'plan' };
235
+ if (engine === 'codex_cli')
236
+ return { ok: true, cfg: { ...cfg, codexUseApiKey: false }, note: 'plan' };
237
+ return { ok: true, cfg, note: 'plan' };
238
+ }
239
+ //# sourceMappingURL=sign-in.js.map
@@ -0,0 +1,59 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { type McpServerSpec } from './mcp.js';
3
+ export type ToolCall = {
4
+ id: string;
5
+ server: string;
6
+ tool: string;
7
+ arguments: Record<string, unknown>;
8
+ timeoutMs: number;
9
+ spec: McpServerSpec;
10
+ };
11
+ export type ToolCallReport = {
12
+ ok: true;
13
+ text: string;
14
+ structured?: unknown;
15
+ isError?: boolean;
16
+ } | {
17
+ ok: false;
18
+ error: {
19
+ code: string;
20
+ reason: string;
21
+ fix: string;
22
+ transient?: boolean;
23
+ };
24
+ };
25
+ export declare const TOOL_CALLS_AT_ONCE = 2;
26
+ export declare const TOOL_CALL_TEXT_MAX = 300000;
27
+ export declare function readToolCall(raw: unknown): {
28
+ call: ToolCall;
29
+ } | {
30
+ id: string;
31
+ report: ToolCallReport;
32
+ } | null;
33
+ export declare function readToolCalls(raw: unknown): Array<{
34
+ call: ToolCall;
35
+ } | {
36
+ id: string;
37
+ report: ToolCallReport;
38
+ }>;
39
+ export declare function reportOfResult(result: unknown): ToolCallReport;
40
+ export type ToolCallDeps = {
41
+ log?: (msg: string) => void;
42
+ spawnProcess?: typeof spawn;
43
+ fetchFn?: typeof fetch;
44
+ now?: () => number;
45
+ };
46
+ export declare function performToolCall(call: ToolCall, deps?: ToolCallDeps): Promise<ToolCallReport>;
47
+ export type ToolCallClient = {
48
+ toolCallResult(id: string, report: ToolCallReport): Promise<boolean>;
49
+ };
50
+ export declare function createToolCallPump(opts: {
51
+ api: ToolCallClient;
52
+ log: (msg: string) => void;
53
+ perform?: (call: ToolCall) => Promise<ToolCallReport>;
54
+ atOnce?: number;
55
+ }): {
56
+ take(raw: unknown): void;
57
+ free(): number;
58
+ idle(): Promise<void>;
59
+ };
@@ -0,0 +1,375 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { cachedMcpLogin, parseMcpServerSpec } from './mcp.js';
3
+ import { RUNNER_VERSION } from './version.js';
4
+ export const TOOL_CALLS_AT_ONCE = 2;
5
+ export const TOOL_CALL_TEXT_MAX = 300_000;
6
+ const PROTOCOL_VERSION = '2025-06-18';
7
+ const TIMEOUT_FLOOR_MS = 1_000;
8
+ const TIMEOUT_CEILING_MS = 120_000;
9
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
10
+ const fail = (code, reason, fix, transient = false) => ({
11
+ ok: false,
12
+ error: { code, reason, fix, ...(transient ? { transient: true } : {}) },
13
+ });
14
+ export function readToolCall(raw) {
15
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !raw.id)
16
+ return null;
17
+ const id = raw.id;
18
+ const server = typeof raw.server === 'string' ? raw.server : '';
19
+ const tool = typeof raw.tool === 'string' ? raw.tool : '';
20
+ const parsed = parseMcpServerSpec(raw.spec);
21
+ if (!server || !tool || 'reject' in parsed) {
22
+ return {
23
+ id,
24
+ report: fail('mcp_spec', `This machine could not use what FireFunc sent for the server ${server || 'of this call'}: ${'reject' in parsed ? parsed.reject : 'the call names no server or no tool'}.`, 'An organization admin checks how the server is registered on Organization → MCP servers (an address must be https, or http on this machine itself). Then retry the run from this step.'),
25
+ };
26
+ }
27
+ if (parsed.spec.transport === 'sse') {
28
+ return {
29
+ id,
30
+ report: fail('mcp_transport', `${server} is registered with the older SSE transport, which a tool call does not speak.`, 'Register its streamable-HTTP address (usually ending in /mcp) on Organization → MCP servers. Then retry the run from this step.'),
31
+ };
32
+ }
33
+ const limit = typeof raw.timeoutMs === 'number' && raw.timeoutMs > 0 ? raw.timeoutMs : 30_000;
34
+ return {
35
+ call: {
36
+ id,
37
+ server,
38
+ tool,
39
+ arguments: isRecord(raw.arguments) ? raw.arguments : {},
40
+ timeoutMs: Math.min(Math.max(limit, TIMEOUT_FLOOR_MS), TIMEOUT_CEILING_MS),
41
+ spec: parsed.spec,
42
+ },
43
+ };
44
+ }
45
+ export function readToolCalls(raw) {
46
+ if (!Array.isArray(raw))
47
+ return [];
48
+ return raw.map(readToolCall).filter((c) => c !== null);
49
+ }
50
+ const cut = (text) => text.length > TOOL_CALL_TEXT_MAX ? text.slice(0, TOOL_CALL_TEXT_MAX) : text;
51
+ export function reportOfResult(result) {
52
+ const r = isRecord(result) ? result : {};
53
+ const parts = Array.isArray(r.content) ? r.content : [];
54
+ const text = parts
55
+ .map((p) => (isRecord(p) && p.type === 'text' && typeof p.text === 'string' ? p.text : ''))
56
+ .filter((t) => t !== '')
57
+ .join('\n');
58
+ const structured = r.structuredContent;
59
+ let keepStructured = false;
60
+ let flat = '';
61
+ if (structured !== undefined && structured !== null) {
62
+ try {
63
+ flat = JSON.stringify(structured) ?? '';
64
+ keepStructured = flat.length <= TOOL_CALL_TEXT_MAX;
65
+ }
66
+ catch {
67
+ flat = '';
68
+ }
69
+ }
70
+ return {
71
+ ok: true,
72
+ text: cut(text || (keepStructured ? '' : flat)),
73
+ ...(keepStructured ? { structured } : {}),
74
+ ...(r.isError === true ? { isError: true } : {}),
75
+ };
76
+ }
77
+ function rpcFailure(server, tool, answer) {
78
+ if (!answer.error)
79
+ return null;
80
+ const said = typeof answer.error.message === 'string' ? answer.error.message : 'no reason given';
81
+ return fail('tool_failed', `${server} refused the call to ${tool}: ${said.slice(0, 400)}`, 'Check the step’s fields against the tool’s own description, and that the tool still exists on the server. Then retry the run from this step.');
82
+ }
83
+ const initializeParams = () => ({
84
+ protocolVersion: PROTOCOL_VERSION,
85
+ capabilities: {},
86
+ clientInfo: { name: 'firefunc-runner', version: RUNNER_VERSION },
87
+ });
88
+ class TimedOut extends Error {
89
+ }
90
+ async function callOverStdio(call, deps) {
91
+ const { spec } = call;
92
+ const log = deps.log ?? (() => { });
93
+ const command = spec.command ?? '';
94
+ const startFix = `Install what ${call.server} needs on this machine so that "${command}" starts from a terminal as the user the runner runs as. Then retry the run from this step.`;
95
+ return new Promise((resolve) => {
96
+ let settled = false;
97
+ let buffer = '';
98
+ let stderrTail = '';
99
+ const pending = new Map();
100
+ const child = (deps.spawnProcess ?? spawn)(command, spec.args ?? [], {
101
+ stdio: ['pipe', 'pipe', 'pipe'],
102
+ windowsHide: true,
103
+ });
104
+ const finish = (report) => {
105
+ if (settled)
106
+ return;
107
+ settled = true;
108
+ clearTimeout(timer);
109
+ try {
110
+ child.stdin?.end();
111
+ }
112
+ catch {
113
+ }
114
+ const killer = setTimeout(() => {
115
+ if (child.exitCode === null && child.signalCode === null)
116
+ child.kill('SIGKILL');
117
+ }, 2_000);
118
+ killer.unref?.();
119
+ if (child.exitCode === null && child.signalCode === null)
120
+ child.kill('SIGTERM');
121
+ resolve(report);
122
+ };
123
+ const timer = setTimeout(() => finish(fail('timeout', `${call.server} did not answer ${call.tool} within ${Math.round(call.timeoutMs / 1000)} seconds.`, 'Raise the step’s time limit, or look at why the server is slow on this machine. Then retry the run from this step.', true)), call.timeoutMs);
124
+ const send = (msg) => {
125
+ try {
126
+ child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', ...msg })}\n`);
127
+ }
128
+ catch {
129
+ }
130
+ };
131
+ const request = (id, method, params) => new Promise((res) => {
132
+ pending.set(id, res);
133
+ send({ id, method, params });
134
+ });
135
+ child.on('error', (err) => {
136
+ finish(err.code === 'ENOENT'
137
+ ? fail('mcp_not_installed', `This machine has no command "${command}", which ${call.server} is launched with.`, startFix)
138
+ : fail('mcp_start', `${call.server} could not be started on this machine (${err.code ?? 'error'}).`, startFix));
139
+ });
140
+ child.on('exit', (code, signal) => {
141
+ if (settled)
142
+ return;
143
+ if (stderrTail.trim()) {
144
+ log(`tool call ${call.id}: ${call.server} said: ${stderrTail.trim().slice(-300)}`);
145
+ }
146
+ finish(fail('mcp_exited', `${call.server} stopped before it answered (${signal ? `signal ${signal}` : `exit code ${code ?? '?'}`}). What it printed is in this machine's runner log.`, startFix));
147
+ });
148
+ child.stdin?.on('error', () => { });
149
+ child.stderr?.on('data', (b) => {
150
+ stderrTail = (stderrTail + b.toString('utf8')).slice(-2_000);
151
+ });
152
+ child.stdout?.on('data', (b) => {
153
+ buffer += b.toString('utf8');
154
+ let at;
155
+ while ((at = buffer.indexOf('\n')) >= 0) {
156
+ const line = buffer.slice(0, at).trim();
157
+ buffer = buffer.slice(at + 1);
158
+ if (!line)
159
+ continue;
160
+ let msg;
161
+ try {
162
+ msg = JSON.parse(line);
163
+ }
164
+ catch {
165
+ continue;
166
+ }
167
+ if (!isRecord(msg))
168
+ continue;
169
+ if (typeof msg.id === 'number' && pending.has(msg.id) && !('method' in msg)) {
170
+ const done = pending.get(msg.id);
171
+ pending.delete(msg.id);
172
+ done(msg);
173
+ }
174
+ else if ('method' in msg && msg.id !== undefined) {
175
+ send({
176
+ id: msg.id,
177
+ error: {
178
+ code: -32601,
179
+ message: 'firefunc-runner makes one tool call and offers nothing else',
180
+ },
181
+ });
182
+ }
183
+ }
184
+ });
185
+ void (async () => {
186
+ const hello = await request(1, 'initialize', initializeParams());
187
+ const refused = rpcFailure(call.server, 'initialize', hello);
188
+ if (refused)
189
+ return finish(refused);
190
+ send({ method: 'notifications/initialized' });
191
+ const answer = await request(2, 'tools/call', { name: call.tool, arguments: call.arguments });
192
+ finish(rpcFailure(call.server, call.tool, answer) ?? reportOfResult(answer.result));
193
+ })();
194
+ });
195
+ }
196
+ async function readRpc(res, id) {
197
+ const type = (res.headers.get('content-type') ?? '').toLowerCase();
198
+ const body = await res.text();
199
+ const pick = (raw) => {
200
+ try {
201
+ const msg = JSON.parse(raw);
202
+ const list = Array.isArray(msg) ? msg : [msg];
203
+ const hit = list.find((m) => isRecord(m) && m.id === id && !('method' in m));
204
+ return hit ?? null;
205
+ }
206
+ catch {
207
+ return null;
208
+ }
209
+ };
210
+ if (!type.includes('text/event-stream'))
211
+ return pick(body);
212
+ for (const event of body.split(/\r?\n\r?\n/)) {
213
+ const data = event
214
+ .split(/\r?\n/)
215
+ .filter((l) => l.startsWith('data:'))
216
+ .map((l) => l.slice(5).replace(/^ /, ''))
217
+ .join('\n');
218
+ if (!data)
219
+ continue;
220
+ const hit = pick(data);
221
+ if (hit)
222
+ return hit;
223
+ }
224
+ return null;
225
+ }
226
+ async function callOverHttp(call, deps) {
227
+ const { spec } = call;
228
+ const doFetch = deps.fetchFn ?? fetch;
229
+ const now = deps.now ?? (() => Date.now());
230
+ const url = spec.url ?? '';
231
+ const headers = {
232
+ ...(spec.headers ?? {}),
233
+ 'content-type': 'application/json',
234
+ accept: 'application/json, text/event-stream',
235
+ };
236
+ if (spec.auth === 'oauth_local') {
237
+ const login = cachedMcpLogin(spec.id, now());
238
+ if (!('login' in login)) {
239
+ return fail('mcp_not_signed_in', login.missing === 'expired'
240
+ ? `This machine's sign-in to ${call.server} has run out.`
241
+ : `This machine is not signed in to ${call.server}.`, `Run "firefunc-runner mcp login ${spec.id}" on this machine. Then retry the run from this step.`);
242
+ }
243
+ headers.authorization = `${login.login.tokenType} ${login.login.accessToken}`;
244
+ }
245
+ else if (spec.auth === 'header') {
246
+ if (!spec.headerName || !spec.secret) {
247
+ return fail('mcp_credential', `FireFunc sent no credential for ${call.server} with this call.`, 'An organization admin enters the server’s credential again on Organization → MCP servers. Then retry the run from this step.');
248
+ }
249
+ headers[spec.headerName] = spec.secret;
250
+ }
251
+ const ctrl = new AbortController();
252
+ const timer = setTimeout(() => ctrl.abort(new TimedOut()), call.timeoutMs);
253
+ let session = null;
254
+ const post = (body) => doFetch(url, {
255
+ method: 'POST',
256
+ headers: { ...headers, ...(session ? { 'mcp-session-id': session } : {}) },
257
+ body: JSON.stringify({ jsonrpc: '2.0', ...body }),
258
+ signal: ctrl.signal,
259
+ redirect: 'error',
260
+ });
261
+ const httpFailure = (res) => res.status === 401 || res.status === 403
262
+ ? fail('mcp_refused', `${call.server} refused this machine's credential (it answered ${res.status}).`, spec.auth === 'oauth_local'
263
+ ? `Run "firefunc-runner mcp login ${spec.id}" on this machine. Then retry the run from this step.`
264
+ : 'An organization admin checks the server’s credential on Organization → MCP servers. Then retry the run from this step.')
265
+ : fail('mcp_http', `${call.server} answered ${res.status} to this machine.`, 'Check that the server is running and that its address on Organization → MCP servers is its streamable-HTTP address. Then retry the run from this step.', res.status === 408 || res.status === 429 || res.status >= 500);
266
+ try {
267
+ const hello = await post({ id: 1, method: 'initialize', params: initializeParams() });
268
+ if (!hello.ok)
269
+ return httpFailure(hello);
270
+ session = hello.headers.get('mcp-session-id');
271
+ const greeted = await readRpc(hello, 1);
272
+ if (!greeted) {
273
+ return fail('mcp_protocol', `${call.server} did not answer as an MCP server over streamable HTTP.`, 'Check the server’s address on Organization → MCP servers (usually ending in /mcp). Then retry the run from this step.');
274
+ }
275
+ const refused = rpcFailure(call.server, 'initialize', greeted);
276
+ if (refused)
277
+ return refused;
278
+ const ready = await post({ method: 'notifications/initialized' });
279
+ await ready.text().catch(() => '');
280
+ const res = await post({
281
+ id: 2,
282
+ method: 'tools/call',
283
+ params: { name: call.tool, arguments: call.arguments },
284
+ });
285
+ if (!res.ok)
286
+ return httpFailure(res);
287
+ const answer = await readRpc(res, 2);
288
+ if (!answer) {
289
+ return fail('mcp_protocol', `${call.server} gave no answer to ${call.tool}.`, 'Retry the run from this step. If it happens again, check the server’s own log.', true);
290
+ }
291
+ return rpcFailure(call.server, call.tool, answer) ?? reportOfResult(answer.result);
292
+ }
293
+ catch (err) {
294
+ if (ctrl.signal.aborted) {
295
+ return fail('timeout', `${call.server} did not answer ${call.tool} within ${Math.round(call.timeoutMs / 1000)} seconds.`, 'Raise the step’s time limit, or look at why the server is slow. Then retry the run from this step.', true);
296
+ }
297
+ void err;
298
+ return fail('mcp_unreachable', `This machine could not reach ${call.server} at its address.`, 'Check that the server is running and that this machine is on the network it lives on. Then retry the run from this step.', true);
299
+ }
300
+ finally {
301
+ clearTimeout(timer);
302
+ if (session) {
303
+ void doFetch(url, {
304
+ method: 'DELETE',
305
+ headers: { ...headers, 'mcp-session-id': session },
306
+ signal: AbortSignal.timeout(3_000),
307
+ }).catch(() => { });
308
+ }
309
+ }
310
+ }
311
+ export async function performToolCall(call, deps = {}) {
312
+ try {
313
+ return call.spec.transport === 'stdio'
314
+ ? await callOverStdio(call, deps)
315
+ : await callOverHttp(call, deps);
316
+ }
317
+ catch (err) {
318
+ return fail('mcp_failed', `This machine failed while calling ${call.server}: ${err.message.slice(0, 200)}`, 'Retry the run from this step. If it fails the same way, update the runner on this machine.');
319
+ }
320
+ }
321
+ export function createToolCallPump(opts) {
322
+ const atOnce = opts.atOnce ?? TOOL_CALLS_AT_ONCE;
323
+ const perform = opts.perform ?? ((call) => performToolCall(call, { log: opts.log }));
324
+ const active = new Set();
325
+ const seen = new Set();
326
+ const waiting = [];
327
+ const report = async (id, what) => {
328
+ const sent = await opts.api.toolCallResult(id, what).catch(() => false);
329
+ if (!sent)
330
+ opts.log(`tool call ${id}: FireFunc did not take the result (the call is no longer this machine's, or FireFunc could not be reached)`);
331
+ };
332
+ const start = (call) => {
333
+ const p = (async () => {
334
+ opts.log(`tool call ${call.id}: calling ${call.server} ${call.tool} (no engine)`);
335
+ const what = await perform(call);
336
+ opts.log(`tool call ${call.id}: ${what.ok ? (what.isError ? 'the tool answered with an error' : 'answered') : what.error.reason}`);
337
+ await report(call.id, what);
338
+ })()
339
+ .catch(() => { })
340
+ .finally(() => {
341
+ active.delete(p);
342
+ seen.delete(call.id);
343
+ const next = waiting.shift();
344
+ if (next)
345
+ start(next);
346
+ });
347
+ active.add(p);
348
+ };
349
+ return {
350
+ take(raw) {
351
+ for (const item of readToolCalls(raw)) {
352
+ const id = 'call' in item ? item.call.id : item.id;
353
+ if (seen.has(id))
354
+ continue;
355
+ if (!('call' in item)) {
356
+ void report(item.id, item.report);
357
+ continue;
358
+ }
359
+ seen.add(id);
360
+ if (active.size < atOnce) {
361
+ start(item.call);
362
+ }
363
+ else {
364
+ waiting.push(item.call);
365
+ }
366
+ }
367
+ },
368
+ free: () => Math.max(0, atOnce - active.size - waiting.length),
369
+ idle: async () => {
370
+ while (active.size > 0)
371
+ await Promise.allSettled([...active]);
372
+ },
373
+ };
374
+ }
375
+ //# sourceMappingURL=tool-call.js.map
@@ -0,0 +1,12 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ export declare const TRAIL_SCHEMA_VERSION = 1;
3
+ export declare function canonicalJson(value: unknown): string;
4
+ export declare function sha256Hex(text: string | Uint8Array): string;
5
+ export declare function genesisHash(runId: string, source: 'machine' | 'firefunc'): string;
6
+ export declare function eventHashOf(ev: Record<string, unknown>): string;
7
+ export declare function merkleRoot(hashes: readonly string[]): string;
8
+ export declare function keyIdOf(publicKeyB64: string): string;
9
+ export declare function signText(privateKey: KeyObject, text: string): string;
10
+ export declare function digestText(d: Record<string, unknown>): string;
11
+ export declare function hmacHex(key: Buffer, bytes: Uint8Array | string): string;
12
+ export declare function ulid(nowMs: number, random?: Uint8Array): string;