@firefunc-agent/runner 0.9.14 → 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 (153) hide show
  1. package/README.md +167 -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 +65 -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 +38 -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.js +19 -4
  50. package/dist/engines/claude.js +10 -9
  51. package/dist/engines/codex.js +16 -2
  52. package/dist/engines/copilot.js +12 -0
  53. package/dist/engines/crush.d.ts +2 -0
  54. package/dist/engines/crush.js +58 -0
  55. package/dist/engines/cursor.js +12 -0
  56. package/dist/engines/gemini.js +14 -9
  57. package/dist/engines/index.d.ts +8 -0
  58. package/dist/engines/index.js +73 -1
  59. package/dist/engines/kilo.d.ts +2 -0
  60. package/dist/engines/kilo.js +63 -0
  61. package/dist/engines/opencode.d.ts +9 -0
  62. package/dist/engines/opencode.js +234 -0
  63. package/dist/engines/openhands.d.ts +10 -0
  64. package/dist/engines/openhands.js +271 -0
  65. package/dist/engines/pi.d.ts +10 -0
  66. package/dist/engines/pi.js +248 -0
  67. package/dist/engines/qwen.d.ts +8 -0
  68. package/dist/engines/qwen.js +153 -0
  69. package/dist/engines/sessions.d.ts +6 -0
  70. package/dist/engines/sessions.js +68 -0
  71. package/dist/engines/types.d.ts +3 -3
  72. package/dist/exec.d.ts +1 -0
  73. package/dist/exec.js +10 -4
  74. package/dist/firefunc/agents.d.ts +8 -1
  75. package/dist/firefunc/agents.js +53 -3
  76. package/dist/firefunc/auth.js +72 -19
  77. package/dist/firefunc/cli.js +25 -0
  78. package/dist/firefunc/client.d.ts +5 -1
  79. package/dist/firefunc/client.js +12 -2
  80. package/dist/firefunc/config.d.ts +11 -1
  81. package/dist/firefunc/config.js +6 -4
  82. package/dist/firefunc/io.d.ts +1 -0
  83. package/dist/firefunc/main.js +8 -1
  84. package/dist/firefunc/oauth-login.d.ts +23 -0
  85. package/dist/firefunc/oauth-login.js +304 -0
  86. package/dist/firefunc/tasks.d.ts +4 -0
  87. package/dist/firefunc/tasks.js +89 -2
  88. package/dist/fleet-words.d.ts +2 -0
  89. package/dist/fleet-words.js +7 -0
  90. package/dist/git-auth.d.ts +15 -0
  91. package/dist/git-auth.js +39 -1
  92. package/dist/held.d.ts +3 -0
  93. package/dist/job.d.ts +26 -3
  94. package/dist/job.js +752 -152
  95. package/dist/keep-awake.d.ts +17 -0
  96. package/dist/keep-awake.js +90 -0
  97. package/dist/keep-local.d.ts +1 -1
  98. package/dist/keep-local.js +5 -3
  99. package/dist/limit.d.ts +9 -1
  100. package/dist/limit.js +260 -3
  101. package/dist/local-checks.d.ts +19 -0
  102. package/dist/local-checks.js +79 -0
  103. package/dist/locks.d.ts +18 -1
  104. package/dist/locks.js +249 -69
  105. package/dist/machine-commands.d.ts +21 -0
  106. package/dist/machine-commands.js +107 -0
  107. package/dist/machine-profile.d.ts +18 -0
  108. package/dist/machine-profile.js +69 -0
  109. package/dist/mcp-init.d.ts +2 -0
  110. package/dist/mcp-init.js +28 -0
  111. package/dist/mcp.d.ts +13 -1
  112. package/dist/mcp.js +23 -2
  113. package/dist/network.js +3 -2
  114. package/dist/orphans.d.ts +4 -0
  115. package/dist/orphans.js +96 -4
  116. package/dist/pool.d.ts +1 -0
  117. package/dist/pool.js +25 -2
  118. package/dist/pr-title.d.ts +10 -0
  119. package/dist/pr-title.js +15 -0
  120. package/dist/recover.d.ts +3 -1
  121. package/dist/recover.js +27 -7
  122. package/dist/release-draft.d.ts +79 -0
  123. package/dist/release-draft.js +301 -0
  124. package/dist/resources.d.ts +86 -0
  125. package/dist/resources.js +217 -0
  126. package/dist/restart-idle.d.ts +23 -0
  127. package/dist/restart-idle.js +67 -0
  128. package/dist/run-attachments.d.ts +5 -0
  129. package/dist/run-attachments.js +14 -9
  130. package/dist/run-stops.d.ts +15 -0
  131. package/dist/run-stops.js +90 -0
  132. package/dist/run-temp.d.ts +12 -0
  133. package/dist/run-temp.js +57 -0
  134. package/dist/secret-scan.d.ts +5 -0
  135. package/dist/secret-scan.js +30 -0
  136. package/dist/self-upgrade.d.ts +36 -0
  137. package/dist/self-upgrade.js +78 -0
  138. package/dist/service.d.ts +7 -1
  139. package/dist/service.js +50 -7
  140. package/dist/sign-in.d.ts +41 -0
  141. package/dist/sign-in.js +239 -0
  142. package/dist/tool-call.d.ts +59 -0
  143. package/dist/tool-call.js +375 -0
  144. package/dist/transport.d.ts +26 -0
  145. package/dist/transport.js +118 -0
  146. package/dist/work-dir.d.ts +11 -0
  147. package/dist/work-dir.js +69 -0
  148. package/dist/worktree-report.d.ts +10 -0
  149. package/dist/worktree-report.js +17 -0
  150. package/dist/worktrees.d.ts +16 -1
  151. package/dist/worktrees.js +62 -17
  152. package/package.json +4 -4
  153. package/skill/firefunc/SKILL.md +4 -3
@@ -0,0 +1,6 @@
1
+ export declare const ENGINE_SESSION_ID: RegExp;
2
+ export declare function codexSessionId(stdout: string): string | null;
3
+ export declare function geminiSessionId(stdout: string): string | null;
4
+ export declare function cursorSessionId(stdout: string): string | null;
5
+ export declare function copilotSessionId(stdout: string): string | null;
6
+ export declare function antigravitySessionId(stdout: string): string | null;
@@ -0,0 +1,68 @@
1
+ export const ENGINE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{5,127}$/;
2
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
3
+ const clean = (v) => typeof v === 'string' && ENGINE_SESSION_ID.test(v) ? v : null;
4
+ function* jsonEvents(stdout) {
5
+ let any = false;
6
+ for (const line of stdout.split('\n')) {
7
+ const t = line.trim();
8
+ if (!t.startsWith('{'))
9
+ continue;
10
+ try {
11
+ const ev = JSON.parse(t);
12
+ if (isObj(ev)) {
13
+ any = true;
14
+ yield ev;
15
+ }
16
+ }
17
+ catch {
18
+ }
19
+ }
20
+ if (any)
21
+ return;
22
+ try {
23
+ const doc = JSON.parse(stdout.trim());
24
+ if (isObj(doc))
25
+ yield doc;
26
+ }
27
+ catch {
28
+ }
29
+ }
30
+ function firstId(stdout, keys, typeOk) {
31
+ try {
32
+ for (const ev of jsonEvents(stdout)) {
33
+ if (!typeOk(ev))
34
+ continue;
35
+ for (const k of keys) {
36
+ const id = clean(ev[k]);
37
+ if (id)
38
+ return id;
39
+ }
40
+ }
41
+ }
42
+ catch {
43
+ }
44
+ return null;
45
+ }
46
+ export function codexSessionId(stdout) {
47
+ return firstId(stdout, ['thread_id'], (ev) => ev.type === 'thread.started');
48
+ }
49
+ export function geminiSessionId(stdout) {
50
+ return firstId(stdout, ['session_id'], (ev) => ev.type === undefined || ev.type === 'init' || ev.type === 'result');
51
+ }
52
+ export function cursorSessionId(stdout) {
53
+ return firstId(stdout, ['session_id'], (ev) => ev.type === 'system' || ev.type === 'result');
54
+ }
55
+ export function copilotSessionId(stdout) {
56
+ try {
57
+ const hint = /copilot\s+--resume[= ]([A-Za-z0-9][A-Za-z0-9._:-]{5,127})/.exec(stdout)?.[1];
58
+ if (hint && ENGINE_SESSION_ID.test(hint))
59
+ return hint;
60
+ }
61
+ catch {
62
+ }
63
+ return firstId(stdout, ['sessionId', 'session_id'], () => true);
64
+ }
65
+ export function antigravitySessionId(stdout) {
66
+ return firstId(stdout, ['conversation_id'], () => true);
67
+ }
68
+ //# sourceMappingURL=sessions.js.map
@@ -2,7 +2,7 @@ import type { RunnerConfig } from '../config.js';
2
2
  import type { RunUsage } from '../usage.js';
3
3
  import type { EngineEnding } from '../declined.js';
4
4
  import type { PlanLimit } from '../limit.js';
5
- export type EngineId = 'claude_code' | 'codex_cli' | 'gemini_cli' | 'cursor_cli' | 'antigravity' | 'copilot_cli';
5
+ export type EngineId = 'claude_code' | 'codex_cli' | 'gemini_cli' | 'cursor_cli' | 'antigravity' | 'copilot_cli' | 'opencode' | 'pi' | 'kilo' | 'qwen_code' | 'crush' | 'openhands';
6
6
  export type InvocationContext = {
7
7
  prompt: string;
8
8
  model: string | null;
@@ -26,7 +26,7 @@ export type UnattendedContext = {
26
26
  permissionMode: string;
27
27
  };
28
28
  export type UnattendedBlock = {
29
- code: 'runs_as_root';
29
+ code: 'runs_as_root' | 'not_signed_in' | 'api_key_no_credit';
30
30
  reason: string;
31
31
  fix: string;
32
32
  detail: string;
@@ -63,7 +63,7 @@ export interface AgentAdapter {
63
63
  unattendedBlock?(ctx: UnattendedContext): UnattendedBlock | null;
64
64
  ending?(stdout: string): EngineEnding | undefined;
65
65
  meter?(stdout: string): RunUsage | null;
66
- planLimit?(stdout: string, now: Date): PlanLimit | null;
66
+ planLimit?(stdout: string, now: Date, stderr?: string): PlanLimit | null;
67
67
  sessionId?(stdout: string): string | null;
68
68
  openCommandsAtEnd?(stdout: string): string[];
69
69
  readonly resumesSessions?: boolean;
package/dist/exec.d.ts CHANGED
@@ -19,5 +19,6 @@ export declare function exec(cmd: string, args: string[], opts?: {
19
19
  onStdout?: (chunk: string) => void;
20
20
  ownGroup?: boolean;
21
21
  onSpawn?: (pid: number) => void;
22
+ signalGroup?: (pgid: number, sig: NodeJS.Signals) => boolean;
22
23
  }): Promise<ExecResult>;
23
24
  export declare function execOut(cmd: string, args: string[], cwd?: string): Promise<string>;
package/dist/exec.js CHANGED
@@ -76,11 +76,17 @@ export function exec(cmd, args, opts = {}) {
76
76
  if (exited)
77
77
  return;
78
78
  if (grouped && child.pid) {
79
- try {
80
- process.kill(-child.pid, sig);
81
- return;
79
+ if (opts.signalGroup) {
80
+ if (opts.signalGroup(child.pid, sig))
81
+ return;
82
82
  }
83
- catch {
83
+ else {
84
+ try {
85
+ process.kill(-child.pid, sig);
86
+ return;
87
+ }
88
+ catch {
89
+ }
84
90
  }
85
91
  }
86
92
  child.kill(sig);
@@ -1,2 +1,9 @@
1
- import { type Command } from './command.js';
1
+ import { type Command, type Ctx } from './command.js';
2
+ export declare function parseMachinesFlag(raw: string): string[] | null;
3
+ export declare function resolveMachines(ctx: Ctx, raw: string): Promise<{
4
+ mode: 'any';
5
+ } | {
6
+ mode: 'only';
7
+ runnerIds: string[];
8
+ }>;
2
9
  export declare const agentCommands: Command[];
@@ -74,7 +74,7 @@ const SPEC_FIELDS = "The spec is the composer's own agent body, as JSON (firefun
74
74
  ' tool_grants { <tool or MCP server slug>: { read, write } } — only tools the\n' +
75
75
  " project has bound. Left out: the template's, or GitHub read+write\n" +
76
76
  ' deliverables [{ id, action: "tool.action", params, gate, position }]\n' +
77
- ' guardrails left out: Autonomous (dry_run_mode false, auto_merge false)\n' +
77
+ ' guardrails left out: Autonomous (dry_run_mode false; auto_merge follows the project)\n' +
78
78
  ' caps { runs_per_day, max_in_flight } — left out: { runs_per_day: 5 }\n' +
79
79
  ' description, schedule, skills (installed slugs), engine, engine_firmness\n' +
80
80
  "The API checks it the way the composer's Save does and refuses what it would refuse,\n" +
@@ -86,6 +86,47 @@ function refuseStatus(spec) {
86
86
  throw new Refusal('A spec cannot set "status": agents are made and edited as drafts, and switching one on is its own step.', 'Remove "status" from the spec. A person activates the draft in the composer, or run "firefunc agents activate <agent>" with a key granted agents:activate (pause/resume likewise).', 'status_not_settable');
87
87
  }
88
88
  }
89
+ const MACHINE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
90
+ export function parseMachinesFlag(raw) {
91
+ const names = [
92
+ ...new Set(raw
93
+ .split(',')
94
+ .map((x) => x.trim())
95
+ .filter(Boolean)),
96
+ ];
97
+ if (names.length === 1 && names[0].toLowerCase() === 'any')
98
+ return null;
99
+ if (names.length === 0) {
100
+ throw new UsageError('Pass --machines <name,name> (the machines its runs may go to), or --machines any.', 'agents update');
101
+ }
102
+ return names;
103
+ }
104
+ export async function resolveMachines(ctx, raw) {
105
+ const names = parseMachinesFlag(raw);
106
+ if (!names)
107
+ return { mode: 'any' };
108
+ const machines = listIn(await ctx.api().get('/api/v1/machines'), 'machines');
109
+ const ids = [];
110
+ for (const ref of names) {
111
+ const wanted = ref.toLowerCase();
112
+ const hits = machines.filter((m) => String(m.name ?? '').toLowerCase() === wanted ||
113
+ (MACHINE_ID.test(ref) && String(m.id ?? '').toLowerCase() === wanted));
114
+ if (hits.length === 1 && typeof hits[0].id === 'string') {
115
+ if (!ids.includes(hits[0].id))
116
+ ids.push(hits[0].id);
117
+ continue;
118
+ }
119
+ const listed = machines.map((m) => String(m.name)).join(', ');
120
+ throw new Refusal(hits.length
121
+ ? `More than one machine is called "${ref}".`
122
+ : `No machine called "${ref}" in this workspace.`, hits.length
123
+ ? `Pass the machine's id instead: ${hits.map((m) => String(m.id)).join(' or ')}.`
124
+ : listed
125
+ ? `Pass one of: ${listed} — or --machines any.`
126
+ : 'This workspace has no machines yet; pair one on Settings → Machines first.', hits.length ? 'ambiguous_machine' : 'unknown_machine');
127
+ }
128
+ return { mode: 'only', runnerIds: ids };
129
+ }
89
130
  async function specFromFlags(ctx, forCreate) {
90
131
  const specPath = str(ctx.args, 'spec');
91
132
  const spec = specPath ? await readSpec(ctx.io, specPath) : {};
@@ -107,6 +148,9 @@ async function specFromFlags(ctx, forCreate) {
107
148
  if (instructionFile !== undefined) {
108
149
  body.instruction = (await readInputFile(ctx.io, instructionFile, 'instruction-file')).trim();
109
150
  }
151
+ const machines = str(ctx.args, 'machines');
152
+ if (machines !== undefined)
153
+ body.machines = await resolveMachines(ctx, machines);
110
154
  let project;
111
155
  if (forCreate) {
112
156
  const template = str(ctx.args, 'template');
@@ -119,7 +163,7 @@ async function specFromFlags(ctx, forCreate) {
119
163
  }
120
164
  }
121
165
  else if (!Object.keys(body).length) {
122
- throw new UsageError('Nothing to change. Pass --spec <file.json> with the fields to change, or --name / --handle / --instruction.', ctx.command);
166
+ throw new UsageError('Nothing to change. Pass --spec <file.json> with the fields to change, or --name / --handle / --instruction / --machines.', ctx.command);
123
167
  }
124
168
  return { body, project };
125
169
  }
@@ -182,6 +226,7 @@ const specFlags = {
182
226
  handle: 'string',
183
227
  instruction: 'string',
184
228
  'instruction-file': 'string',
229
+ machines: 'string',
185
230
  spec: 'string',
186
231
  };
187
232
  const specFlagHelp = [
@@ -189,6 +234,10 @@ const specFlagHelp = [
189
234
  ['--handle <handle>', 'the @handle it answers to'],
190
235
  ['--instruction <text>', 'its standing instruction'],
191
236
  ['--instruction-file <path>', 'the instruction from a file ("-" for stdin)'],
237
+ [
238
+ '--machines <names>|any',
239
+ 'only these machines take its runs (comma-separated names); "any" lets every machine that serves its project',
240
+ ],
192
241
  ['--spec <file.json>', 'the whole agent as JSON ("-" for stdin); flags win over it'],
193
242
  ];
194
243
  function lifecycle(action) {
@@ -321,7 +370,8 @@ export const agentCommands = [
321
370
  {
322
371
  path: ['agents', 'update'],
323
372
  summary: 'Change an agent (only the fields you pass)',
324
- usage: 'agents update <id or @handle> [--spec <file.json>] [--name …] [--handle …] [--instruction …]',
373
+ usage: 'agents update <id or @handle> [--spec <file.json>] [--name …] [--handle …] [--instruction …]\n' +
374
+ ' [--machines <name,name>|any]',
325
375
  details: 'Sends only what you pass; everything else stays as it is. An agent cannot move to\n' +
326
376
  'another project (create a new one there instead), so an update takes no projectId,\n' +
327
377
  'and no templateSlug. tool_grants, deliverables, skills and caps are replaced whole,\n' +
@@ -1,7 +1,8 @@
1
- import { str } from './args.js';
1
+ import { bool, str } from './args.js';
2
2
  import { ApiClient } from './client.js';
3
3
  import { API_KEY_SHAPE, configFile, loadCliConfig, removeCliConfig, resolveApiUrl, saveCliConfig, } from './config.js';
4
4
  import { Refusal } from './io.js';
5
+ import { browserLogin, revokeSignIn } from './oauth-login.js';
5
6
  import { printJson } from './output.js';
6
7
  export const scopesOf = (me) => {
7
8
  for (const v of [me.key?.scopes, me.grant?.scopes])
@@ -11,33 +12,41 @@ export const scopesOf = (me) => {
11
12
  };
12
13
  const keyIdOf = (me) => me.key?.id;
13
14
  const ACTIVATE_NOTE = 'This key cannot activate agents (no agents:activate scope): agents it creates stay drafts until a person activates them in FireFunc.';
15
+ const SIGN_IN_ACTIVATE_NOTE = 'This sign-in cannot activate agents (Activate agents was not ticked): agents it creates stay drafts until a person activates them in FireFunc. Run firefunc login again to tick it.';
14
16
  function printIdentity(ctx, me, apiUrl, source) {
15
17
  const scopes = scopesOf(me);
16
18
  const ws = me.workspace;
17
19
  const lines = [
18
20
  `Workspace: ${ws?.name ?? '(unnamed)'}${ws?.id ? ` (${ws.id})` : ''}`,
19
- `Key: ${me.key?.name ? `"${me.key.name}" ` : ''}${keyIdOf(me) ? `(${keyIdOf(me)}) ` : ''}— ${source}`,
21
+ me.key
22
+ ? `Key: ${me.key?.name ? `"${me.key.name}" ` : ''}${keyIdOf(me) ? `(${keyIdOf(me)}) ` : ''}— ${source}`
23
+ : `Sign-in: you, through FireFunc CLI — ${source}`,
20
24
  `Scopes: ${scopes.length ? scopes.join(', ') : 'none'}`,
21
25
  `API: ${apiUrl}`,
22
26
  ];
23
27
  if (!scopes.includes('agents:activate'))
24
- lines.push('', ACTIVATE_NOTE);
28
+ lines.push('', me.key ? ACTIVATE_NOTE : SIGN_IN_ACTIVATE_NOTE);
25
29
  ctx.io.stdout.write(`${lines.join('\n')}\n`);
26
30
  }
27
31
  const login = {
28
32
  path: ['login'],
29
- summary: 'Sign in with a workspace API key (asked for without echo)',
30
- usage: 'login [--key <ffk_…>] [--api-url <url>]',
31
- details: 'Make a key in FireFunc → Settings → API keys, then run "firefunc login" and paste it at the\n' +
32
- 'prompt — nothing you type is shown. Piped in (printf %s "$KEY" | firefunc login) or in\n' +
33
- 'FIREFUNC_API_KEY works too. The key is checked against the API before it is saved to\n' +
34
- '~/.firefunc/config.json (readable only by you). It is never printed, and it is sent\n' +
35
- 'only to the address it was checked against (--api-url here names another).\n\n' +
36
- 'Which key to make: agents:read to look (templates, projects, connections, skills,\n' +
37
- 'agents), agents:write to create and edit drafts, tasks:write to start runs. Add\n' +
38
- 'agents:activate only if you mean this key to switch agents on without a person.',
39
- flags: { key: 'string' },
33
+ summary: 'Sign in through your browser (or with a workspace API key)',
34
+ usage: 'login [--no-browser] [--with-key | --key <ffk_…>] [--api-url <url>]',
35
+ details: 'Opens FireFunc in your browser: pick the workspace and what the CLI may do, press Allow,\n' +
36
+ 'and the browser hands the sign-in back to this terminal (a one-off address on 127.0.0.1).\n' +
37
+ 'The same sign-in Claude, ChatGPT and Codex use. Activate agents and Configure the\n' +
38
+ 'workspace stay off unless you tick them. The sign-in is saved to ~/.firefunc/config.json\n' +
39
+ '(readable only by you), refreshes itself, and shows in FireFunc → Settings → AI tools,\n' +
40
+ 'where it can be disconnected. On a machine with no browser, --no-browser prints the\n' +
41
+ 'address to open on this computer.\n\n' +
42
+ 'For a script or CI, use a workspace key instead (FireFunc → Settings → API keys):\n' +
43
+ 'FIREFUNC_API_KEY, piped in (printf %s "$KEY" | firefunc login), or --with-key to paste it\n' +
44
+ 'at a prompt that shows nothing. A key is checked against the API before it is saved; it\n' +
45
+ 'is never printed, and it is sent only to the address it was checked against.',
46
+ flags: { key: 'string', 'with-key': 'boolean', 'no-browser': 'boolean' },
40
47
  flagHelp: [
48
+ ['--no-browser', 'print the sign-in address instead of opening it'],
49
+ ['--with-key', 'paste a workspace key (ffk_…) at a prompt instead of signing in'],
41
50
  ['--key <ffk_…>', 'the key itself — it lands in your shell history; prefer the prompt'],
42
51
  ],
43
52
  async run(ctx) {
@@ -56,10 +65,33 @@ const login = {
56
65
  io.stderr.write('Note: a key passed with --key is now in your shell history. The prompt keeps it out.\n');
57
66
  }
58
67
  key ??= io.env.FIREFUNC_API_KEY?.trim() || undefined;
59
- if (key === undefined) {
68
+ if (key === undefined && !io.stdinIsTty)
69
+ key = (await io.readStdin()).trim() || undefined;
70
+ if (key === undefined && bool(ctx.args, 'with-key')) {
60
71
  key = io.stdinIsTty
61
72
  ? await io.readSecret('Workspace API key (ffk_…, from Settings → API keys): ')
62
- : (await io.readStdin()).trim();
73
+ : '';
74
+ }
75
+ if (key === undefined) {
76
+ const signed = await browserLogin(io, apiUrl, existing, {
77
+ openBrowser: io.openBrowser?.bind(io),
78
+ noBrowser: bool(ctx.args, 'no-browser'),
79
+ });
80
+ const me = await new ApiClient(apiUrl, signed.accessToken, io.fetch).get('/api/v1/me');
81
+ const file = saveCliConfig(io, {
82
+ ...signed.config,
83
+ workspace: me.workspace?.id
84
+ ? { id: me.workspace.id, name: me.workspace.name ?? null }
85
+ : undefined,
86
+ scopes: scopesOf(me),
87
+ });
88
+ if (ctx.json) {
89
+ printJson(io, { ...me, apiUrl, savedTo: file });
90
+ return;
91
+ }
92
+ io.stdout.write(`Signed in. Saved to ${file} (readable only by you).\n\n`);
93
+ printIdentity(ctx, me, apiUrl, 'saved by firefunc login');
94
+ return;
63
95
  }
64
96
  if (!key) {
65
97
  throw new Refusal('No key was given.', 'Make one in FireFunc → Settings → API keys, then paste it at the "firefunc login" prompt.', 'no_key');
@@ -89,14 +121,31 @@ const login = {
89
121
  };
90
122
  const logout = {
91
123
  path: ['logout'],
92
- summary: 'Forget the key saved on this machine',
124
+ summary: 'Sign out: end the browser sign-in, or forget the saved key',
93
125
  usage: 'logout',
94
126
  details: 'Removes ~/.firefunc/config.json. The key itself keeps working until it is revoked in\n' +
95
127
  'FireFunc → Settings → API keys — this command cannot revoke it.',
96
128
  async run(ctx) {
97
129
  const { io } = ctx;
98
130
  const file = configFile(io);
131
+ let saved = null;
132
+ try {
133
+ saved = loadCliConfig(io, { warnLoose: false });
134
+ }
135
+ catch {
136
+ }
137
+ const ended = saved?.oauth ? await revokeSignIn(io, saved.oauth) : false;
99
138
  const removed = removeCliConfig(io);
139
+ if (saved?.oauth) {
140
+ if (ctx.json) {
141
+ printJson(io, { removed, file, signInEnded: ended });
142
+ return;
143
+ }
144
+ io.stdout.write(ended
145
+ ? `Signed out: the sign-in is ended in FireFunc and removed from ${file}.\n`
146
+ : `Removed the sign-in from ${file}. FireFunc could not be told, so it may still show in Settings → AI tools until it lapses — disconnect it there.\n`);
147
+ return;
148
+ }
100
149
  const envStillSet = Boolean(io.env.FIREFUNC_API_KEY?.trim());
101
150
  if (ctx.json) {
102
151
  printJson(io, { removed, file, envKeyStillSet: envStillSet });
@@ -112,7 +161,7 @@ const logout = {
112
161
  };
113
162
  const whoami = {
114
163
  path: ['whoami'],
115
- summary: 'Which workspace and key this machine is using, and its scopes',
164
+ summary: 'Which workspace and sign-in (or key) this machine is using, and its scopes',
116
165
  usage: 'whoami',
117
166
  async run(ctx) {
118
167
  const { io } = ctx;
@@ -122,7 +171,11 @@ const whoami = {
122
171
  printJson(io, { ...me, apiUrl: creds.apiUrl, keySource: creds.keySource });
123
172
  return;
124
173
  }
125
- printIdentity(ctx, me, creds.apiUrl, creds.keySource === 'env' ? 'from FIREFUNC_API_KEY' : 'saved by firefunc login');
174
+ printIdentity(ctx, me, creds.apiUrl, creds.keySource === 'env'
175
+ ? 'from FIREFUNC_API_KEY'
176
+ : creds.keySource === 'oauth'
177
+ ? 'signed in by firefunc login'
178
+ : 'saved by firefunc login');
126
179
  },
127
180
  };
128
181
  export const authCommands = [login, logout, whoami];
@@ -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;
@@ -2,6 +2,7 @@ import { GLOBAL_FLAGS, parseArgs, str, UsageError } from './args.js';
2
2
  import { agentCommands } from './agents.js';
3
3
  import { authCommands } from './auth.js';
4
4
  import { catalogCommands } from './catalog.js';
5
+ import { freshAccessToken } from './oauth-login.js';
5
6
  import { ApiClient } from './client.js';
6
7
  import { configureCommands } from './configure.js';
7
8
  import { DEFAULT_API_URL, resolveCredentials } from './config.js';
@@ -240,7 +241,13 @@ export async function runFirefunc(argv, io) {
240
241
  api() {
241
242
  if (!client) {
242
243
  const c = ctx.credentials();
243
- client = new ApiClient(c.apiUrl, c.key, io.fetch);
244
+ const signIn = c.keySource === 'oauth' ? c.config : undefined;
245
+ client = new ApiClient(c.apiUrl, signIn
246
+ ? {
247
+ token: () => freshAccessToken(io, signIn),
248
+ refresh: () => freshAccessToken(io, signIn, { force: true }),
249
+ }
250
+ : c.key, io.fetch);
244
251
  }
245
252
  return client;
246
253
  },
@@ -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 {};