@firefunc-agent/runner 0.9.14 → 0.9.35

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 (158) hide show
  1. package/README.md +184 -10
  2. package/dist/alive.d.ts +40 -0
  3. package/dist/alive.js +138 -0
  4. package/dist/api-fallback.d.ts +4 -2
  5. package/dist/api-fallback.js +26 -1
  6. package/dist/api.d.ts +66 -3
  7. package/dist/api.js +164 -3
  8. package/dist/brief-file.d.ts +15 -0
  9. package/dist/brief-file.js +36 -0
  10. package/dist/brief.d.ts +3 -0
  11. package/dist/brief.js +14 -4
  12. package/dist/build-caches.d.ts +7 -0
  13. package/dist/build-caches.js +63 -0
  14. package/dist/build-info.json +2 -2
  15. package/dist/checkpoint.d.ts +40 -0
  16. package/dist/checkpoint.js +98 -0
  17. package/dist/cli.js +184 -18
  18. package/dist/cloud-boot.d.ts +41 -0
  19. package/dist/cloud-boot.js +239 -0
  20. package/dist/command-activity.d.ts +23 -0
  21. package/dist/command-activity.js +89 -0
  22. package/dist/command-step.d.ts +58 -0
  23. package/dist/command-step.js +248 -0
  24. package/dist/config.d.ts +39 -0
  25. package/dist/config.js +23 -0
  26. package/dist/cut.d.ts +1 -1
  27. package/dist/cut.js +13 -3
  28. package/dist/daemon.js +364 -15
  29. package/dist/device-lease.d.ts +15 -0
  30. package/dist/device-lease.js +608 -0
  31. package/dist/editor/fs-server.d.ts +31 -0
  32. package/dist/editor/fs-server.js +159 -0
  33. package/dist/editor/relay-crypto.d.ts +68 -0
  34. package/dist/editor/relay-crypto.js +191 -0
  35. package/dist/editor/sessions.d.ts +50 -0
  36. package/dist/editor/sessions.js +279 -0
  37. package/dist/editor/worktree-of.d.ts +1 -0
  38. package/dist/editor/worktree-of.js +23 -0
  39. package/dist/editor/ws-client.d.ts +26 -0
  40. package/dist/editor/ws-client.js +227 -0
  41. package/dist/engine-account.d.ts +24 -0
  42. package/dist/engine-account.js +118 -0
  43. package/dist/engine-login.d.ts +12 -0
  44. package/dist/engine-login.js +88 -0
  45. package/dist/engine-models.d.ts +13 -0
  46. package/dist/engine-models.js +71 -0
  47. package/dist/engine-watch.d.ts +1 -0
  48. package/dist/engine-watch.js +22 -6
  49. package/dist/engines/antigravity.d.ts +2 -0
  50. package/dist/engines/antigravity.js +74 -4
  51. package/dist/engines/claude.js +22 -9
  52. package/dist/engines/codex.js +16 -2
  53. package/dist/engines/copilot.js +12 -0
  54. package/dist/engines/crush.d.ts +2 -0
  55. package/dist/engines/crush.js +58 -0
  56. package/dist/engines/cursor.js +12 -0
  57. package/dist/engines/gemini.js +14 -9
  58. package/dist/engines/index.d.ts +8 -0
  59. package/dist/engines/index.js +73 -1
  60. package/dist/engines/kilo.d.ts +2 -0
  61. package/dist/engines/kilo.js +63 -0
  62. package/dist/engines/opencode.d.ts +9 -0
  63. package/dist/engines/opencode.js +234 -0
  64. package/dist/engines/openhands.d.ts +10 -0
  65. package/dist/engines/openhands.js +271 -0
  66. package/dist/engines/pi.d.ts +10 -0
  67. package/dist/engines/pi.js +248 -0
  68. package/dist/engines/qwen.d.ts +8 -0
  69. package/dist/engines/qwen.js +153 -0
  70. package/dist/engines/sessions.d.ts +6 -0
  71. package/dist/engines/sessions.js +68 -0
  72. package/dist/engines/types.d.ts +3 -3
  73. package/dist/exec.d.ts +1 -0
  74. package/dist/exec.js +10 -4
  75. package/dist/firefunc/agents.d.ts +8 -1
  76. package/dist/firefunc/agents.js +53 -3
  77. package/dist/firefunc/auth.js +72 -19
  78. package/dist/firefunc/automations.d.ts +2 -0
  79. package/dist/firefunc/automations.js +290 -0
  80. package/dist/firefunc/cli.js +25 -0
  81. package/dist/firefunc/client.d.ts +5 -1
  82. package/dist/firefunc/client.js +12 -2
  83. package/dist/firefunc/config.d.ts +11 -1
  84. package/dist/firefunc/config.js +6 -4
  85. package/dist/firefunc/io.d.ts +1 -0
  86. package/dist/firefunc/main.js +34 -2
  87. package/dist/firefunc/oauth-login.d.ts +23 -0
  88. package/dist/firefunc/oauth-login.js +304 -0
  89. package/dist/firefunc/tasks.d.ts +4 -0
  90. package/dist/firefunc/tasks.js +89 -2
  91. package/dist/fleet-words.d.ts +2 -0
  92. package/dist/fleet-words.js +7 -0
  93. package/dist/git-auth.d.ts +15 -0
  94. package/dist/git-auth.js +39 -1
  95. package/dist/held.d.ts +3 -0
  96. package/dist/job.d.ts +26 -3
  97. package/dist/job.js +763 -152
  98. package/dist/keep-awake.d.ts +17 -0
  99. package/dist/keep-awake.js +90 -0
  100. package/dist/keep-local.d.ts +1 -1
  101. package/dist/keep-local.js +5 -3
  102. package/dist/limit.d.ts +9 -1
  103. package/dist/limit.js +260 -3
  104. package/dist/local-checks.d.ts +19 -0
  105. package/dist/local-checks.js +79 -0
  106. package/dist/locks.d.ts +18 -1
  107. package/dist/locks.js +249 -69
  108. package/dist/machine-commands.d.ts +21 -0
  109. package/dist/machine-commands.js +107 -0
  110. package/dist/machine-profile.d.ts +18 -0
  111. package/dist/machine-profile.js +69 -0
  112. package/dist/mcp-init.d.ts +2 -0
  113. package/dist/mcp-init.js +28 -0
  114. package/dist/mcp.d.ts +13 -1
  115. package/dist/mcp.js +48 -4
  116. package/dist/network.js +3 -2
  117. package/dist/openrouter.d.ts +15 -0
  118. package/dist/openrouter.js +39 -0
  119. package/dist/orphans.d.ts +4 -0
  120. package/dist/orphans.js +96 -4
  121. package/dist/pool.d.ts +1 -0
  122. package/dist/pool.js +25 -2
  123. package/dist/pr-title.d.ts +10 -0
  124. package/dist/pr-title.js +15 -0
  125. package/dist/recover.d.ts +3 -1
  126. package/dist/recover.js +27 -7
  127. package/dist/release-draft.d.ts +79 -0
  128. package/dist/release-draft.js +301 -0
  129. package/dist/resources.d.ts +86 -0
  130. package/dist/resources.js +217 -0
  131. package/dist/restart-idle.d.ts +23 -0
  132. package/dist/restart-idle.js +67 -0
  133. package/dist/run-attachments.d.ts +5 -0
  134. package/dist/run-attachments.js +14 -9
  135. package/dist/run-stops.d.ts +15 -0
  136. package/dist/run-stops.js +90 -0
  137. package/dist/run-temp.d.ts +12 -0
  138. package/dist/run-temp.js +57 -0
  139. package/dist/secret-scan.d.ts +5 -0
  140. package/dist/secret-scan.js +30 -0
  141. package/dist/self-upgrade.d.ts +36 -0
  142. package/dist/self-upgrade.js +78 -0
  143. package/dist/service.d.ts +7 -1
  144. package/dist/service.js +50 -7
  145. package/dist/sign-in.d.ts +42 -0
  146. package/dist/sign-in.js +243 -0
  147. package/dist/tool-call.d.ts +59 -0
  148. package/dist/tool-call.js +375 -0
  149. package/dist/transport.d.ts +26 -0
  150. package/dist/transport.js +118 -0
  151. package/dist/work-dir.d.ts +11 -0
  152. package/dist/work-dir.js +69 -0
  153. package/dist/worktree-report.d.ts +10 -0
  154. package/dist/worktree-report.js +17 -0
  155. package/dist/worktrees.d.ts +16 -1
  156. package/dist/worktrees.js +62 -17
  157. package/package.json +4 -4
  158. package/skill/firefunc/SKILL.md +22 -3
@@ -0,0 +1,290 @@
1
+ import { bool, str, UsageError } from './args.js';
2
+ import { listIn, resolveProjectId } from './catalog.js';
3
+ import { enc, readInputFile } from './command.js';
4
+ import { Refusal } from './io.js';
5
+ import { printJson, table, text, wrap } from './output.js';
6
+ const MODES = ['live', 'dry', 'test'];
7
+ const FINAL = new Set(['succeeded', 'failed', 'canceled', 'skipped']);
8
+ function problemLines(problems) {
9
+ const list = Array.isArray(problems) ? problems : [];
10
+ const out = [];
11
+ for (const p of list) {
12
+ out.push(...wrap(`${text(p.level)}: ${text(p.text)}`, 78, ' ', ' '));
13
+ if (p.fix)
14
+ out.push(...wrap(`fix: ${text(p.fix)}`, 78, ' ', ' '));
15
+ }
16
+ return out;
17
+ }
18
+ function parseJsonFlag(raw, flag) {
19
+ try {
20
+ return JSON.parse(raw);
21
+ }
22
+ catch (e) {
23
+ throw new Refusal(`--${flag} is not JSON (${e.message}).`, `Write it as a JSON object, for example --${flag} '{"name": "value"}'.`, 'bad_json');
24
+ }
25
+ }
26
+ function runLine(r) {
27
+ const err = r.error;
28
+ return `run #${text(r.number)} ${text(r.state)} ${text(r.id)}${err ? ` ${text(err.reason)}` : ''}`;
29
+ }
30
+ async function printRun(ctx, body) {
31
+ const r = body.run ?? body;
32
+ const lines = [runLine(r)];
33
+ const err = r.error;
34
+ if (err?.fix)
35
+ lines.push(...wrap(`fix: ${text(err.fix)}`, 78, ' ', ' '));
36
+ const steps = Array.isArray(body.steps) ? body.steps : [];
37
+ for (const s of steps) {
38
+ const e = s.error;
39
+ lines.push(` ${text(s.nodeId ?? s.key)} ${text(s.state)} ${text(s.name)}${e ? ` ${text(e.reason ?? e.message)}` : ''}`);
40
+ }
41
+ ctx.io.stdout.write(`${lines.join('\n')}\n`);
42
+ }
43
+ export const automationCommands = [
44
+ {
45
+ path: ['automations', 'list'],
46
+ summary: 'The workflows and orchestrations in this workspace',
47
+ usage: 'automations list [--project <id or name>]',
48
+ flags: { project: 'string' },
49
+ flagHelp: [['--project <id or name>', "only this project's automations"]],
50
+ async run(ctx) {
51
+ const project = str(ctx.args, 'project');
52
+ const query = project ? { project: await resolveProjectId(ctx, project) } : undefined;
53
+ const body = await ctx.api().get('/api/v1/automations', query);
54
+ if (ctx.json)
55
+ return printJson(ctx.io, body);
56
+ const rows = listIn(body, 'automations');
57
+ if (!rows.length) {
58
+ ctx.io.stdout.write('No automations here yet. Make one: firefunc automations create\n');
59
+ return;
60
+ }
61
+ table(ctx.io, rows, [
62
+ { head: 'ID', get: (r) => r.id },
63
+ { head: 'NAME', get: (r) => r.name, max: 40 },
64
+ { head: 'KIND', get: (r) => r.kind },
65
+ { head: 'STATUS', get: (r) => r.status },
66
+ { head: 'PROJECT', get: (r) => r.project?.name ?? 'whole workspace' },
67
+ ]);
68
+ },
69
+ },
70
+ {
71
+ path: ['automations', 'templates'],
72
+ summary: 'Automations to start from, and the agents each brings',
73
+ usage: 'automations templates',
74
+ async run(ctx) {
75
+ const body = await ctx.api().get('/api/v1/automations/templates');
76
+ if (ctx.json)
77
+ return printJson(ctx.io, body);
78
+ table(ctx.io, listIn(body, 'templates'), [
79
+ { head: 'ID', get: (r) => r.id },
80
+ { head: 'KIND', get: (r) => r.kind },
81
+ { head: 'NAME', get: (r) => r.name, max: 40 },
82
+ {
83
+ head: 'BRINGS',
84
+ get: (r) => (Array.isArray(r.brings) ? r.brings : []).map((b) => b.name).join(', '),
85
+ max: 50,
86
+ },
87
+ ]);
88
+ },
89
+ },
90
+ {
91
+ path: ['automations', 'get'],
92
+ summary: 'One automation: how it starts, its inputs and its problems',
93
+ usage: 'automations get <id>',
94
+ positional: { min: 1, max: 1 },
95
+ async run(ctx) {
96
+ const id = ctx.args.positional[0];
97
+ const body = await ctx.api().get(`/api/v1/automations/${enc(id)}`);
98
+ if (ctx.json)
99
+ return printJson(ctx.io, body);
100
+ const a = body.automation ?? {};
101
+ const lines = [
102
+ `${text(a.name)}`,
103
+ ` id: ${text(a.id)}`,
104
+ ` kind: ${text(a.kind)}`,
105
+ ` status: ${text(a.status)}`,
106
+ ];
107
+ const problems = problemLines(body.problems);
108
+ lines.push(problems.length ? ' problems:' : ' problems: none', ...problems);
109
+ ctx.io.stdout.write(`${lines.join('\n')}\n`);
110
+ },
111
+ },
112
+ {
113
+ path: ['automations', 'create'],
114
+ summary: 'Make a workflow or orchestration as a DRAFT (nothing runs until it is published)',
115
+ usage: 'automations create --name <name> (--spec <file.json> | --from-template <id> | --kind workflow|orchestration) [--project <id or name>]',
116
+ flags: {
117
+ name: 'string',
118
+ spec: 'string',
119
+ 'from-template': 'string',
120
+ kind: 'string',
121
+ project: 'string',
122
+ },
123
+ flagHelp: [
124
+ ['--name <name>', 'what people call it'],
125
+ ['--spec <file.json>', 'the whole definition as JSON ("-" for stdin)'],
126
+ [
127
+ '--from-template <id>',
128
+ 'start from a template (automations templates); it brings its agents, paused',
129
+ ],
130
+ ['--kind <kind>', 'an empty workflow or orchestration'],
131
+ ['--project <id or name>', 'the project it belongs to; left out: the whole workspace'],
132
+ ],
133
+ async run(ctx) {
134
+ const name = str(ctx.args, 'name');
135
+ if (!name)
136
+ throw new UsageError('--name is required.', ctx.command);
137
+ const spec = str(ctx.args, 'spec');
138
+ const fromTemplate = str(ctx.args, 'from-template');
139
+ const kind = str(ctx.args, 'kind');
140
+ if (!spec && !fromTemplate && !kind)
141
+ throw new UsageError('Give --spec, --from-template or --kind.', ctx.command);
142
+ const project = str(ctx.args, 'project');
143
+ const body = {
144
+ name,
145
+ ...(project ? { projectId: await resolveProjectId(ctx, project) } : {}),
146
+ ...(spec ? { spec: parseJsonFlag(await readInputFile(ctx.io, spec, 'spec'), 'spec') } : {}),
147
+ ...(fromTemplate ? { fromTemplate } : {}),
148
+ ...(kind ? { kind } : {}),
149
+ };
150
+ const answer = await ctx.api().post('/api/v1/automations', body);
151
+ if (ctx.json)
152
+ return printJson(ctx.io, answer);
153
+ const a = answer.automation ?? {};
154
+ const lines = [`Made "${text(a.name)}" as a draft: ${text(a.id)}`];
155
+ const brought = Array.isArray(answer.brought) ? answer.brought : [];
156
+ for (const b of brought)
157
+ lines.push(` brought ${text(b.name)} (${text(b.how)}, ${text(b.status)})`);
158
+ const problems = problemLines(answer.problems);
159
+ if (problems.length)
160
+ lines.push(' problems before it can be published:', ...problems);
161
+ lines.push(`Next: firefunc automations publish ${text(a.id)}`);
162
+ ctx.io.stdout.write(`${lines.join('\n')}\n`);
163
+ },
164
+ },
165
+ {
166
+ path: ['automations', 'check'],
167
+ summary: 'The checks behind Publish, on the saved draft',
168
+ usage: 'automations check <id>',
169
+ positional: { min: 1, max: 1 },
170
+ async run(ctx) {
171
+ const id = ctx.args.positional[0];
172
+ const body = await ctx.api().post(`/api/v1/automations/${enc(id)}/check`, {});
173
+ if (ctx.json)
174
+ return printJson(ctx.io, body);
175
+ const problems = problemLines(body.problems);
176
+ ctx.io.stdout.write(`${problems.length ? problems.join('\n') : 'No problems.'}\n`);
177
+ },
178
+ },
179
+ {
180
+ path: ['automations', 'publish'],
181
+ summary: 'Publish the draft: from then on its triggers start REAL runs',
182
+ usage: 'automations publish <id> [--note <text>] --yes',
183
+ details: 'Publishing makes it live at once: a tool trigger takes the next real event, a schedule its\n' +
184
+ 'next time. It asks for --yes so a script never does it by accident. The answer says where it\n' +
185
+ 'went live and names the agents a run would wait at (a template brings its agents paused).',
186
+ positional: { min: 1, max: 1 },
187
+ flags: { note: 'string', yes: 'boolean' },
188
+ flagHelp: [
189
+ ['--note <text>', 'what changed, for the version list'],
190
+ ['--yes', 'yes, make it live now'],
191
+ ],
192
+ async run(ctx) {
193
+ const id = ctx.args.positional[0];
194
+ if (!bool(ctx.args, 'yes')) {
195
+ const a = await ctx.api().get(`/api/v1/automations/${enc(id)}`);
196
+ const auto = a.automation ?? {};
197
+ throw new Refusal(`Publishing "${text(auto.name)}" makes it live at once: its triggers start real runs.`, `Read it first (firefunc automations get ${id}), then run this again with --yes.`, 'needs_yes');
198
+ }
199
+ const note = str(ctx.args, 'note');
200
+ const body = await ctx
201
+ .api()
202
+ .post(`/api/v1/automations/${enc(id)}/publish`, note ? { note } : {});
203
+ if (ctx.json)
204
+ return printJson(ctx.io, body);
205
+ const v = body.version ?? {};
206
+ const lines = [`Published version ${text(v.number)}.`];
207
+ if (body.goesLive)
208
+ lines.push(...wrap(text(body.goesLive), 78, ' ', ' '));
209
+ const held = Array.isArray(body.heldAgents) ? body.heldAgents : [];
210
+ if (held.length)
211
+ lines.push(...wrap(`Runs wait at ${held.map((h) => `${text(h.name)} (${text(h.status)})`).join(', ')} until each is switched on: firefunc agents resume <id>.`, 78, ' ', ' '));
212
+ const tokens = body.webhookTokens ?? {};
213
+ for (const [t, token] of Object.entries(tokens))
214
+ lines.push(` webhook token for ${t} (shown once): ${token}`);
215
+ lines.push(...problemLines(body.warnings));
216
+ ctx.io.stdout.write(`${lines.join('\n')}\n`);
217
+ },
218
+ },
219
+ {
220
+ path: ['automations', 'run'],
221
+ summary: 'Start a run of the published version by hand',
222
+ usage: 'automations run <id> [--inputs <json>] [--mode live|dry|test] [--watch]',
223
+ positional: { min: 1, max: 1 },
224
+ flags: { inputs: 'string', mode: 'string', watch: 'boolean' },
225
+ flagHelp: [
226
+ ['--inputs <json>', 'the run’s inputs by name, as a JSON object'],
227
+ ['--mode <mode>', 'live (default); dry starts nothing; test records writes without sending'],
228
+ ['--watch', 'follow the run until it ends'],
229
+ ],
230
+ async run(ctx) {
231
+ const id = ctx.args.positional[0];
232
+ const mode = str(ctx.args, 'mode');
233
+ if (mode && !MODES.includes(mode))
234
+ throw new UsageError(`--mode is one of ${MODES.join(', ')}.`, ctx.command);
235
+ const inputs = str(ctx.args, 'inputs');
236
+ const started = await ctx.api().post(`/api/v1/automations/${enc(id)}/runs`, {
237
+ ...(inputs ? { inputs: parseJsonFlag(inputs, 'inputs') } : {}),
238
+ ...(mode ? { mode } : {}),
239
+ });
240
+ const run = started.run ?? {};
241
+ if (!bool(ctx.args, 'watch')) {
242
+ if (ctx.json)
243
+ return printJson(ctx.io, started);
244
+ ctx.io.stdout.write(`Started ${runLine(run)}\nFollow it: firefunc automations run-get ${text(run.id)}\n`);
245
+ return;
246
+ }
247
+ let body = started;
248
+ for (let i = 0; i < 300; i++) {
249
+ body = await ctx.api().get(`/api/v1/automation-runs/${enc(String(run.id))}`);
250
+ const state = String((body.run ?? {}).state ?? '');
251
+ if (FINAL.has(state) || state === 'waiting')
252
+ break;
253
+ await ctx.io.sleep(2000);
254
+ }
255
+ if (ctx.json)
256
+ return printJson(ctx.io, body);
257
+ await printRun(ctx, body);
258
+ const state = String((body.run ?? {}).state ?? '');
259
+ return state === 'failed' ? 1 : 0;
260
+ },
261
+ },
262
+ {
263
+ path: ['automations', 'runs'],
264
+ summary: "An automation's recent runs",
265
+ usage: 'automations runs <id>',
266
+ positional: { min: 1, max: 1 },
267
+ async run(ctx) {
268
+ const id = ctx.args.positional[0];
269
+ const body = await ctx.api().get(`/api/v1/automations/${enc(id)}/runs`);
270
+ if (ctx.json)
271
+ return printJson(ctx.io, body);
272
+ const rows = listIn(body, 'runs');
273
+ ctx.io.stdout.write(rows.length ? `${rows.map(runLine).join('\n')}\n` : 'No runs yet.\n');
274
+ },
275
+ },
276
+ {
277
+ path: ['automations', 'run-get'],
278
+ summary: 'One run: its state and each step',
279
+ usage: 'automations run-get <run id>',
280
+ positional: { min: 1, max: 1 },
281
+ async run(ctx) {
282
+ const id = ctx.args.positional[0];
283
+ const body = await ctx.api().get(`/api/v1/automation-runs/${enc(id)}`);
284
+ if (ctx.json)
285
+ return printJson(ctx.io, body);
286
+ await printRun(ctx, body);
287
+ },
288
+ },
289
+ ];
290
+ //# sourceMappingURL=automations.js.map
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
2
3
  import { homedir } from 'node:os';
3
4
  import { runFirefunc } from './main.js';
4
5
  import { quietWhenReaderLeaves } from './output.js';
@@ -17,7 +18,31 @@ const io = {
17
18
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
18
19
  now: () => Date.now(),
19
20
  platform: process.platform,
21
+ openBrowser: (url) => openInBrowser(url),
20
22
  };
23
+ function openInBrowser(url) {
24
+ const headless = process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
25
+ if (headless || process.env.SSH_CONNECTION)
26
+ return Promise.resolve(false);
27
+ const [cmd, args] = process.platform === 'darwin'
28
+ ? ['open', [url]]
29
+ : process.platform === 'win32'
30
+ ? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
31
+ : ['xdg-open', [url]];
32
+ return new Promise((resolve) => {
33
+ try {
34
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
35
+ child.on('error', () => resolve(false));
36
+ child.on('spawn', () => {
37
+ child.unref();
38
+ resolve(true);
39
+ });
40
+ }
41
+ catch {
42
+ resolve(false);
43
+ }
44
+ });
45
+ }
21
46
  void runFirefunc(process.argv.slice(2), io).then((code) => {
22
47
  process.exitCode = code;
23
48
  });
@@ -18,12 +18,16 @@ export declare class ApiUnreachable extends Error {
18
18
  constructor(url: string, cause: unknown);
19
19
  }
20
20
  type Query = Record<string, string | number | undefined>;
21
+ export type RefreshingAuth = {
22
+ token(): Promise<string>;
23
+ refresh(): Promise<string>;
24
+ };
21
25
  export declare class ApiClient {
22
26
  readonly baseUrl: string;
23
27
  private readonly key;
24
28
  private readonly fetchImpl;
25
29
  private readonly timeoutMs;
26
- constructor(baseUrl: string, key: string, fetchImpl: typeof fetch, timeoutMs?: number);
30
+ constructor(baseUrl: string, key: string | RefreshingAuth, fetchImpl: typeof fetch, timeoutMs?: number);
27
31
  get<T>(path: string, query?: Query): Promise<T>;
28
32
  post<T>(path: string, body?: unknown): Promise<T>;
29
33
  patch<T>(path: string, body: unknown): Promise<T>;
@@ -1,3 +1,4 @@
1
+ import { Refusal } from './io.js';
1
2
  import { CLI_VERSION } from './version.js';
2
3
  export class ApiRefusal extends Error {
3
4
  status;
@@ -64,8 +65,10 @@ export class ApiClient {
64
65
  if (v !== undefined && v !== '')
65
66
  url.searchParams.set(k, String(v));
66
67
  }
68
+ const auth = typeof this.key === 'string' ? null : this.key;
69
+ const bearer = auth ? await auth.token() : this.key;
67
70
  const headers = {
68
- Authorization: `Bearer ${this.key}`,
71
+ Authorization: `Bearer ${bearer}`,
69
72
  Accept: 'application/json',
70
73
  'User-Agent': `firefunc-cli/${CLI_VERSION} node/${process.versions.node}`,
71
74
  };
@@ -77,8 +80,15 @@ export class ApiClient {
77
80
  let res;
78
81
  try {
79
82
  res = await this.fetchImpl(url, init);
83
+ if (res.status === 401 && auth) {
84
+ headers.Authorization = `Bearer ${await auth.refresh()}`;
85
+ init.signal = AbortSignal.timeout(this.timeoutMs);
86
+ res = await this.fetchImpl(url, init);
87
+ }
80
88
  }
81
89
  catch (err) {
90
+ if (err instanceof Refusal)
91
+ throw err;
82
92
  throw new ApiUnreachable(this.baseUrl, err);
83
93
  }
84
94
  const text = await res.text().catch(() => '');
@@ -119,7 +129,7 @@ function refusalFrom(res, json, baseUrl) {
119
129
  let fix = s(e.fix) ?? s(e.details?.fix);
120
130
  if (!fix && res.status === 401) {
121
131
  fix =
122
- 'Sign in again with a working key: firefunc login (keys are made in FireFunc → Settings → API keys).';
132
+ 'Sign in again: firefunc login (a script uses a key from FireFunc → Settings → API keys).';
123
133
  }
124
134
  let message = s(e.message) ?? `The API refused the request (${res.status}).`;
125
135
  if (fix && message.endsWith(fix) && message.length > fix.length) {
@@ -1,8 +1,17 @@
1
1
  import { type Io } from './io.js';
2
2
  export declare const DEFAULT_API_URL = "https://api.firefunc.com";
3
+ export type OAuthCredential = {
4
+ clientId: string;
5
+ accessToken: string;
6
+ refreshToken: string;
7
+ expiresAt: string;
8
+ tokenEndpoint: string;
9
+ revocationEndpoint?: string;
10
+ };
3
11
  export type CliConfig = {
4
12
  apiUrl?: string;
5
13
  key?: string;
14
+ oauth?: OAuthCredential;
6
15
  workspace?: {
7
16
  id: string;
8
17
  name?: string | null;
@@ -23,7 +32,8 @@ export declare const API_KEY_SHAPE: RegExp;
23
32
  export type Credentials = {
24
33
  apiUrl: string;
25
34
  key: string;
26
- keySource: 'env' | 'config';
35
+ keySource: 'env' | 'config' | 'oauth';
36
+ config?: CliConfig;
27
37
  };
28
38
  export declare function resolveApiUrl(flag: string | undefined, io: Pick<Io, 'env'>, cfg: CliConfig | null): string;
29
39
  export declare function resolveCredentials(flagApiUrl: string | undefined, io: Pick<Io, 'env' | 'home' | 'stderr' | 'platform'>): Credentials;
@@ -97,15 +97,17 @@ export function resolveCredentials(flagApiUrl, io) {
97
97
  }
98
98
  return { apiUrl, key: envKey, keySource: 'env' };
99
99
  }
100
- if (cfg?.key) {
100
+ if (cfg?.key || cfg?.oauth) {
101
101
  const savedUrl = cfg.apiUrl ?? DEFAULT_API_URL;
102
102
  const target = originOf(apiUrl);
103
103
  if (!target || originOf(savedUrl) !== target) {
104
104
  const by = flagApiUrl !== undefined ? '--api-url' : 'FIREFUNC_API_URL';
105
- throw new Refusal(`The saved key was checked against ${hideSecrets(savedUrl)}, and ${by} points this command at ${target ?? hideSecrets(apiUrl)}: the key is sent only to the address it was checked against.`, `Leave out ${by} to use ${hideSecrets(savedUrl)}. If you mean to use ${target ?? 'that address'}, sign in to it yourself: firefunc login --api-url <its address>.`, 'api_url_mismatch');
105
+ throw new Refusal(`The saved sign-in was checked against ${hideSecrets(savedUrl)}, and ${by} points this command at ${target ?? hideSecrets(apiUrl)}: it is sent only to the address it was checked against.`, `Leave out ${by} to use ${hideSecrets(savedUrl)}. If you mean to use ${target ?? 'that address'}, sign in to it yourself: firefunc login --api-url <its address>.`, 'api_url_mismatch');
106
106
  }
107
- return { apiUrl, key: cfg.key, keySource: 'config' };
107
+ if (cfg.key)
108
+ return { apiUrl, key: cfg.key, keySource: 'config' };
109
+ return { apiUrl, key: cfg.oauth.accessToken, keySource: 'oauth', config: cfg };
108
110
  }
109
- throw new Refusal('Not signed in: there is no workspace API key on this machine.', 'Make a key in FireFunc → Settings → API keys, then run: firefunc login (or set FIREFUNC_API_KEY).', 'not_signed_in');
111
+ throw new Refusal('Not signed in: there is no FireFunc sign-in or workspace API key on this machine.', 'Run: firefunc login (it opens FireFunc in your browser). For a script or CI, set FIREFUNC_API_KEY to a key from Settings → API keys.', 'not_signed_in');
110
112
  }
111
113
  //# sourceMappingURL=config.js.map
@@ -15,6 +15,7 @@ export type Io = {
15
15
  sleep(ms: number): Promise<void>;
16
16
  now(): number;
17
17
  platform: NodeJS.Platform;
18
+ openBrowser?(url: string): Promise<boolean>;
18
19
  };
19
20
  export declare class Refusal extends Error {
20
21
  readonly fix: string | undefined;
@@ -1,7 +1,9 @@
1
1
  import { GLOBAL_FLAGS, parseArgs, str, UsageError } from './args.js';
2
2
  import { agentCommands } from './agents.js';
3
3
  import { authCommands } from './auth.js';
4
+ import { automationCommands } from './automations.js';
4
5
  import { catalogCommands } from './catalog.js';
6
+ import { freshAccessToken } from './oauth-login.js';
5
7
  import { ApiClient } from './client.js';
6
8
  import { configureCommands } from './configure.js';
7
9
  import { DEFAULT_API_URL, resolveCredentials } from './config.js';
@@ -16,10 +18,20 @@ export const COMMANDS = [
16
18
  ...catalogCommands,
17
19
  ...agentCommands,
18
20
  ...taskCommands,
21
+ ...automationCommands,
19
22
  ...configureCommands,
20
23
  ...skillCommands,
21
24
  ];
22
- const GROUPS = ['templates', 'projects', 'connections', 'skills', 'agents', 'tasks', 'skill'];
25
+ const GROUPS = [
26
+ 'templates',
27
+ 'projects',
28
+ 'connections',
29
+ 'skills',
30
+ 'agents',
31
+ 'tasks',
32
+ 'automations',
33
+ 'skill',
34
+ ];
23
35
  const SECTIONS = [
24
36
  ['Sign in', ['login', 'logout', 'whoami']],
25
37
  [
@@ -39,6 +51,20 @@ const SECTIONS = [
39
51
  ],
40
52
  ],
41
53
  ['Tasks', ['run', 'tasks list', 'tasks get', 'tasks watch', 'tasks states']],
54
+ [
55
+ 'Automations (workflows and orchestrations)',
56
+ [
57
+ 'automations list',
58
+ 'automations templates',
59
+ 'automations get',
60
+ 'automations create',
61
+ 'automations check',
62
+ 'automations publish',
63
+ 'automations run',
64
+ 'automations runs',
65
+ 'automations run-get',
66
+ ],
67
+ ],
42
68
  [
43
69
  'Configure the workspace (writes need workspace:configure)',
44
70
  [
@@ -240,7 +266,13 @@ export async function runFirefunc(argv, io) {
240
266
  api() {
241
267
  if (!client) {
242
268
  const c = ctx.credentials();
243
- client = new ApiClient(c.apiUrl, c.key, io.fetch);
269
+ const signIn = c.keySource === 'oauth' ? c.config : undefined;
270
+ client = new ApiClient(c.apiUrl, signIn
271
+ ? {
272
+ token: () => freshAccessToken(io, signIn),
273
+ refresh: () => freshAccessToken(io, signIn, { force: true }),
274
+ }
275
+ : c.key, io.fetch);
244
276
  }
245
277
  return client;
246
278
  },
@@ -0,0 +1,23 @@
1
+ import { type CliConfig, type OAuthCredential } from './config.js';
2
+ import { type Io } from './io.js';
3
+ type ServerMetadata = {
4
+ issuer: string;
5
+ authorization_endpoint: string;
6
+ token_endpoint: string;
7
+ registration_endpoint?: string;
8
+ revocation_endpoint?: string;
9
+ };
10
+ export declare function discover(io: Io, apiUrl: string): Promise<ServerMetadata>;
11
+ export type OpenBrowser = (url: string) => Promise<boolean>;
12
+ export declare function browserLogin(io: Io, apiUrl: string, existing: CliConfig | null, opts: {
13
+ openBrowser: OpenBrowser | undefined;
14
+ noBrowser: boolean;
15
+ }): Promise<{
16
+ config: CliConfig;
17
+ accessToken: string;
18
+ }>;
19
+ export declare function freshAccessToken(io: Io, cfg: CliConfig, opts?: {
20
+ force?: boolean;
21
+ }): Promise<string>;
22
+ export declare function revokeSignIn(io: Io, o: OAuthCredential): Promise<boolean>;
23
+ export {};