@firefunc-agent/runner 0.7.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +7 -3
  2. package/README.md +296 -4
  3. package/dist/activity.d.ts +32 -0
  4. package/dist/activity.js +295 -0
  5. package/dist/api.d.ts +69 -1
  6. package/dist/api.js +114 -3
  7. package/dist/brief.d.ts +11 -0
  8. package/dist/brief.js +278 -0
  9. package/dist/build-info.json +4 -0
  10. package/dist/cli.js +59 -2
  11. package/dist/config.d.ts +7 -0
  12. package/dist/config.js +3 -0
  13. package/dist/cut.d.ts +45 -0
  14. package/dist/cut.js +105 -0
  15. package/dist/daemon.d.ts +16 -0
  16. package/dist/daemon.js +196 -7
  17. package/dist/declined.d.ts +11 -0
  18. package/dist/declined.js +27 -0
  19. package/dist/engines/antigravity.d.ts +2 -0
  20. package/dist/engines/antigravity.js +102 -0
  21. package/dist/engines/claude-budget.d.ts +1 -1
  22. package/dist/engines/claude-budget.js +2 -72
  23. package/dist/engines/claude.js +139 -2
  24. package/dist/engines/codex.js +10 -3
  25. package/dist/engines/copilot.d.ts +2 -0
  26. package/dist/engines/copilot.js +117 -0
  27. package/dist/engines/cursor.js +4 -0
  28. package/dist/engines/gemini.js +6 -1
  29. package/dist/engines/index.d.ts +2 -0
  30. package/dist/engines/index.js +22 -4
  31. package/dist/engines/types.d.ts +12 -1
  32. package/dist/exec.d.ts +3 -0
  33. package/dist/exec.js +48 -5
  34. package/dist/firefunc/agents.d.ts +2 -0
  35. package/dist/firefunc/agents.js +343 -0
  36. package/dist/firefunc/args.d.ts +18 -0
  37. package/dist/firefunc/args.js +82 -0
  38. package/dist/firefunc/auth.d.ts +21 -0
  39. package/dist/firefunc/auth.js +129 -0
  40. package/dist/firefunc/catalog.d.ts +10 -0
  41. package/dist/firefunc/catalog.js +201 -0
  42. package/dist/firefunc/cli.d.ts +2 -0
  43. package/dist/firefunc/cli.js +24 -0
  44. package/dist/firefunc/client.d.ts +36 -0
  45. package/dist/firefunc/client.js +177 -0
  46. package/dist/firefunc/command.d.ts +28 -0
  47. package/dist/firefunc/command.js +35 -0
  48. package/dist/firefunc/config.d.ts +29 -0
  49. package/dist/firefunc/config.js +111 -0
  50. package/dist/firefunc/configure.d.ts +6 -0
  51. package/dist/firefunc/configure.js +409 -0
  52. package/dist/firefunc/io.d.ts +25 -0
  53. package/dist/firefunc/io.js +14 -0
  54. package/dist/firefunc/main.d.ts +4 -0
  55. package/dist/firefunc/main.js +259 -0
  56. package/dist/firefunc/output.d.ts +29 -0
  57. package/dist/firefunc/output.js +131 -0
  58. package/dist/firefunc/prompt.d.ts +14 -0
  59. package/dist/firefunc/prompt.js +58 -0
  60. package/dist/firefunc/skill.d.ts +3 -0
  61. package/dist/firefunc/skill.js +80 -0
  62. package/dist/firefunc/tasks.d.ts +2 -0
  63. package/dist/firefunc/tasks.js +279 -0
  64. package/dist/firefunc/version.d.ts +2 -0
  65. package/dist/firefunc/version.js +8 -0
  66. package/dist/git-auth.d.ts +4 -1
  67. package/dist/git-auth.js +6 -2
  68. package/dist/held.d.ts +18 -0
  69. package/dist/held.js +95 -0
  70. package/dist/job.d.ts +3 -0
  71. package/dist/job.js +818 -102
  72. package/dist/keep-local.d.ts +12 -0
  73. package/dist/keep-local.js +651 -0
  74. package/dist/limit.d.ts +30 -0
  75. package/dist/limit.js +258 -0
  76. package/dist/locks.d.ts +14 -0
  77. package/dist/locks.js +164 -0
  78. package/dist/machine-logins.d.ts +19 -0
  79. package/dist/machine-logins.js +187 -0
  80. package/dist/mcp-login.d.ts +24 -0
  81. package/dist/mcp-login.js +993 -0
  82. package/dist/mcp-proxy.d.ts +21 -0
  83. package/dist/mcp-proxy.js +180 -0
  84. package/dist/mcp.d.ts +62 -0
  85. package/dist/mcp.js +611 -0
  86. package/dist/network.d.ts +20 -0
  87. package/dist/network.js +76 -0
  88. package/dist/orphans.d.ts +40 -0
  89. package/dist/orphans.js +235 -0
  90. package/dist/pending.d.ts +14 -0
  91. package/dist/pending.js +56 -0
  92. package/dist/pool.d.ts +7 -0
  93. package/dist/pool.js +57 -9
  94. package/dist/pr-title.d.ts +11 -0
  95. package/dist/pr-title.js +63 -0
  96. package/dist/recover.d.ts +10 -0
  97. package/dist/recover.js +104 -0
  98. package/dist/secret-scan.d.ts +19 -0
  99. package/dist/secret-scan.js +161 -0
  100. package/dist/session-stream.d.ts +9 -1
  101. package/dist/session-stream.js +20 -2
  102. package/dist/skills.d.ts +11 -0
  103. package/dist/skills.js +164 -0
  104. package/dist/stopped.d.ts +3 -0
  105. package/dist/stopped.js +10 -0
  106. package/dist/usage.d.ts +49 -0
  107. package/dist/usage.js +389 -0
  108. package/dist/version.d.ts +1 -0
  109. package/dist/version.js +17 -0
  110. package/dist/viewer.js +7 -1
  111. package/dist/worktrees.d.ts +15 -0
  112. package/dist/worktrees.js +96 -0
  113. package/package.json +8 -5
  114. package/skill/firefunc/SKILL.md +222 -0
@@ -0,0 +1,201 @@
1
+ import { str } from './args.js';
2
+ import { Refusal } from './io.js';
3
+ import { printJson, table, text } from './output.js';
4
+ export const pick = (...keys) => (row) => {
5
+ for (const k of keys) {
6
+ const v = k
7
+ .split('.')
8
+ .reduce((o, part) => (o && typeof o === 'object' ? o[part] : undefined), row);
9
+ if (v !== undefined && v !== null && v !== '')
10
+ return v;
11
+ }
12
+ return undefined;
13
+ };
14
+ export function listIn(body, key) {
15
+ if (Array.isArray(body))
16
+ return body;
17
+ const v = body?.[key];
18
+ return Array.isArray(v) ? v : [];
19
+ }
20
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ export async function resolveProject(ctx, ref) {
22
+ if (UUID.test(ref))
23
+ return { id: ref };
24
+ const body = await ctx.api().get('/api/v1/projects');
25
+ const projects = listIn(body, 'projects');
26
+ const wanted = ref.trim().toLowerCase();
27
+ const hits = projects.filter((p) => String(p.name ?? '').toLowerCase() === wanted ||
28
+ String(p.slug ?? '').toLowerCase() === wanted);
29
+ if (hits.length === 1 && typeof hits[0].id === 'string') {
30
+ const hit = hits[0];
31
+ return { id: hit.id, ...(typeof hit.name === 'string' ? { name: hit.name } : {}) };
32
+ }
33
+ const names = projects.map((p) => `${String(p.name)} (${String(p.id)})`).join('; ');
34
+ throw new Refusal(hits.length
35
+ ? `More than one project is called "${ref}".`
36
+ : `No project called "${ref}" in this workspace.`, hits.length
37
+ ? `Pass the project's id instead: ${hits.map((p) => String(p.id)).join(' or ')}.`
38
+ : names
39
+ ? `Pass one of: ${names}.`
40
+ : 'This workspace has no projects yet; make one in FireFunc first.', hits.length ? 'ambiguous_project' : 'unknown_project');
41
+ }
42
+ export async function resolveProjectId(ctx, ref) {
43
+ return (await resolveProject(ctx, ref)).id;
44
+ }
45
+ function listCommand(opts) {
46
+ return {
47
+ path: [opts.noun, 'list'],
48
+ summary: opts.summary,
49
+ usage: `${opts.noun} list`,
50
+ details: opts.details,
51
+ async run(ctx) {
52
+ const body = await ctx.api().get(opts.path);
53
+ if (ctx.json)
54
+ return printJson(ctx.io, body);
55
+ const rows = listIn(body, opts.key);
56
+ if (!rows.length) {
57
+ ctx.io.stdout.write(`${opts.empty}\n`);
58
+ return;
59
+ }
60
+ table(ctx.io, rows, opts.columns);
61
+ },
62
+ };
63
+ }
64
+ function printConnections(ctx, body) {
65
+ const { io } = ctx;
66
+ const project = body.project;
67
+ const tools = listIn(body, 'tools');
68
+ if (project) {
69
+ io.stdout.write(`Project ${text(project.name)} (${text(project.id)}). An agent here can be granted only the tools marked bound.\n\n`);
70
+ }
71
+ const cols = [
72
+ { head: 'TOOL', get: pick('tool') },
73
+ ...(project ? [{ head: 'BOUND', get: (r) => (r.bound ? 'yes' : 'no') }] : []),
74
+ {
75
+ head: 'ACCOUNTS',
76
+ get: (r) => (r.accounts ?? []).map((a) => {
77
+ const where = (a.boundTo ?? []).map((b) => b.projectName).filter(Boolean);
78
+ return `${text(a.label)}${where.length ? ` (${where.join(', ')})` : ''}`;
79
+ }),
80
+ max: 45,
81
+ },
82
+ { head: 'SOURCE', get: pick('source') },
83
+ { head: 'EVENTS IT SENDS', get: pick('events'), max: 70 },
84
+ ];
85
+ if (tools.length)
86
+ table(io, tools, cols);
87
+ const servers = listIn(body, 'mcpServers');
88
+ if (servers.length) {
89
+ io.stdout.write('\nMCP servers lent to this workspace (grant one by its slug in tool_grants):\n');
90
+ for (const m of servers)
91
+ io.stdout.write(` ${text(m.slug)} ${text(m.name)}\n`);
92
+ }
93
+ const hooks = listIn(body, 'webhooks');
94
+ if (hooks.length) {
95
+ io.stdout.write('\nInbound webhooks (trigger.source "webhook", named by trigger.filters.hook):\n');
96
+ for (const h of hooks) {
97
+ io.stdout.write(` ${text(h.id)} ${text(h.name)}${h.enabled === false ? ' (switched off)' : ''}\n`);
98
+ }
99
+ }
100
+ io.stdout.write('\nThe actions each tool performs (deliverables), with their params: add --json.\n');
101
+ }
102
+ function printSkills(ctx, body) {
103
+ const { io } = ctx;
104
+ const installed = listIn(body, 'skills');
105
+ const directory = listIn(body, 'directory').filter((d) => d.installed !== true);
106
+ if (installed.length) {
107
+ io.stdout.write('Installed — an agent can carry these (skills: [slug]):\n');
108
+ table(io, installed, [
109
+ { head: 'SLUG', get: pick('slug') },
110
+ { head: 'NAME', get: pick('name'), max: 40 },
111
+ { head: 'DESCRIPTION', get: pick('description'), max: 70 },
112
+ ]);
113
+ }
114
+ else {
115
+ io.stdout.write('No skills are installed in this workspace.\n');
116
+ }
117
+ if (directory.length) {
118
+ io.stdout.write('\nIn the curated directory, not installed here (a template installs the ones it names;\n' +
119
+ 'a person installs others on Settings → Skills):\n');
120
+ table(io, directory, [
121
+ { head: 'SLUG', get: pick('slug') },
122
+ { head: 'NAME', get: pick('name'), max: 40 },
123
+ { head: 'DESCRIPTION', get: pick('description'), max: 70 },
124
+ ]);
125
+ }
126
+ }
127
+ export const catalogCommands = [
128
+ listCommand({
129
+ noun: 'templates',
130
+ path: '/api/v1/templates',
131
+ key: 'templates',
132
+ summary: 'Agents to start from — each a whole agent: instruction, tools, deliverables',
133
+ details: 'Create from one with: firefunc agents create --template <slug> [--project <project>] [--name <name>]\n' +
134
+ 'READY says whether this workspace has an account for every tool the template uses.\n' +
135
+ "Each template's trigger, instruction, grants and deliverables: add --json.",
136
+ columns: [
137
+ { head: 'SLUG', get: pick('slug') },
138
+ { head: 'NAME', get: pick('name'), max: 40 },
139
+ { head: 'WORKS WITH', get: pick('integrations'), max: 30 },
140
+ {
141
+ head: 'READY',
142
+ get: (r) => r.integrationsConnected === true
143
+ ? 'yes'
144
+ : Array.isArray(r.missingIntegrations) && r.missingIntegrations.length
145
+ ? `needs ${r.missingIntegrations.map(String).join(', ')}`
146
+ : undefined,
147
+ max: 30,
148
+ },
149
+ { head: 'DESCRIPTION', get: pick('description'), max: 70 },
150
+ ],
151
+ empty: 'No templates are published.',
152
+ }),
153
+ listCommand({
154
+ noun: 'projects',
155
+ path: '/api/v1/projects',
156
+ key: 'projects',
157
+ summary: 'The projects in this workspace — an agent lives in one',
158
+ columns: [
159
+ { head: 'ID', get: pick('id') },
160
+ {
161
+ head: 'NAME',
162
+ get: (r) => `${text(r.name)}${r.isDefault === true ? ' (default)' : ''}`,
163
+ max: 40,
164
+ },
165
+ { head: 'REPOSITORIES', get: pick('repos', 'repositories'), max: 60 },
166
+ ],
167
+ empty: 'This workspace has no projects yet. Make one in FireFunc first.',
168
+ }),
169
+ {
170
+ path: ['connections', 'list'],
171
+ summary: 'What an agent can be built from: tools, accounts, events, MCP servers, webhooks',
172
+ usage: 'connections list [--project <id or name>]',
173
+ details: 'Every tool FireFunc ships, the accounts this workspace holds for each and the projects\n' +
174
+ 'that bind them, and the events each sends (trigger.event, with its trigger.source).\n' +
175
+ 'With --project, BOUND says whether that project has the tool — an agent there can be\n' +
176
+ 'granted only bound tools. --json adds the actions each tool performs, with params.',
177
+ flags: { project: 'string' },
178
+ flagHelp: [['--project <id or name>', 'say which tools this project has bound']],
179
+ async run(ctx) {
180
+ const p = str(ctx.args, 'project');
181
+ const body = await ctx.api().get('/api/v1/connections', {
182
+ project: p ? await resolveProjectId(ctx, p) : undefined,
183
+ });
184
+ if (ctx.json)
185
+ return printJson(ctx.io, body);
186
+ printConnections(ctx, body ?? {});
187
+ },
188
+ },
189
+ {
190
+ path: ['skills', 'list'],
191
+ summary: 'Skills an agent can carry into its runs (by slug)',
192
+ usage: 'skills list',
193
+ async run(ctx) {
194
+ const body = await ctx.api().get('/api/v1/skills');
195
+ if (ctx.json)
196
+ return printJson(ctx.io, body);
197
+ printSkills(ctx, body ?? {});
198
+ },
199
+ },
200
+ ];
201
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ import { homedir } from 'node:os';
3
+ import { runFirefunc } from './main.js';
4
+ import { quietWhenReaderLeaves } from './output.js';
5
+ import { readAll, readHidden } from './prompt.js';
6
+ quietWhenReaderLeaves(process.stdout, process.stderr, (code) => process.exit(code));
7
+ const io = {
8
+ stdout: process.stdout,
9
+ stderr: process.stderr,
10
+ env: process.env,
11
+ home: homedir(),
12
+ cwd: process.cwd(),
13
+ readSecret: (prompt) => readHidden(prompt, process.stdin, process.stderr),
14
+ readStdin: () => readAll(process.stdin.setEncoding('utf8')),
15
+ stdinIsTty: Boolean(process.stdin.isTTY),
16
+ fetch: globalThis.fetch,
17
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
18
+ now: () => Date.now(),
19
+ platform: process.platform,
20
+ };
21
+ void runFirefunc(process.argv.slice(2), io).then((code) => {
22
+ process.exitCode = code;
23
+ });
24
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,36 @@
1
+ export declare class ApiRefusal extends Error {
2
+ readonly status: number;
3
+ readonly code: string;
4
+ readonly fix: string | undefined;
5
+ readonly requestId: string | undefined;
6
+ readonly issues: string[];
7
+ readonly details: Record<string, unknown> | undefined;
8
+ readonly fixIsListed: boolean;
9
+ constructor(status: number, code: string, message: string, fix: string | undefined, requestId: string | undefined, more?: {
10
+ issues?: string[];
11
+ details?: Record<string, unknown>;
12
+ fixIsListed?: boolean;
13
+ });
14
+ }
15
+ export declare class ApiUnreachable extends Error {
16
+ readonly url: string;
17
+ readonly cause: unknown;
18
+ constructor(url: string, cause: unknown);
19
+ }
20
+ type Query = Record<string, string | number | undefined>;
21
+ export declare class ApiClient {
22
+ readonly baseUrl: string;
23
+ private readonly key;
24
+ private readonly fetchImpl;
25
+ private readonly timeoutMs;
26
+ constructor(baseUrl: string, key: string, fetchImpl: typeof fetch, timeoutMs?: number);
27
+ get<T>(path: string, query?: Query): Promise<T>;
28
+ post<T>(path: string, body?: unknown): Promise<T>;
29
+ patch<T>(path: string, body: unknown): Promise<T>;
30
+ put<T>(path: string, body: unknown): Promise<T>;
31
+ request<T>(method: string, path: string, opts?: {
32
+ query?: Query;
33
+ body?: unknown;
34
+ }): Promise<T>;
35
+ }
36
+ export {};
@@ -0,0 +1,177 @@
1
+ import { CLI_VERSION } from './version.js';
2
+ export class ApiRefusal extends Error {
3
+ status;
4
+ code;
5
+ fix;
6
+ requestId;
7
+ issues;
8
+ details;
9
+ fixIsListed;
10
+ constructor(status, code, message, fix, requestId, more = {}) {
11
+ super(message);
12
+ this.status = status;
13
+ this.code = code;
14
+ this.fix = fix;
15
+ this.requestId = requestId;
16
+ this.name = 'ApiRefusal';
17
+ this.issues = more.issues ?? [];
18
+ this.details = more.details;
19
+ this.fixIsListed = more.fixIsListed ?? false;
20
+ }
21
+ }
22
+ export class ApiUnreachable extends Error {
23
+ url;
24
+ cause;
25
+ constructor(url, cause) {
26
+ super(`Could not reach ${url}: ${describeCause(cause)}`);
27
+ this.url = url;
28
+ this.cause = cause;
29
+ this.name = 'ApiUnreachable';
30
+ }
31
+ }
32
+ function describeCause(cause) {
33
+ const c = cause;
34
+ if (c?.name === 'TimeoutError' || c?.name === 'AbortError')
35
+ return 'no answer within 30 seconds';
36
+ return c?.cause?.code ?? c?.cause?.message ?? c?.message ?? String(cause);
37
+ }
38
+ export class ApiClient {
39
+ baseUrl;
40
+ key;
41
+ fetchImpl;
42
+ timeoutMs;
43
+ constructor(baseUrl, key, fetchImpl, timeoutMs = 30_000) {
44
+ this.baseUrl = baseUrl;
45
+ this.key = key;
46
+ this.fetchImpl = fetchImpl;
47
+ this.timeoutMs = timeoutMs;
48
+ }
49
+ get(path, query) {
50
+ return this.request('GET', path, { query });
51
+ }
52
+ post(path, body) {
53
+ return this.request('POST', path, { body });
54
+ }
55
+ patch(path, body) {
56
+ return this.request('PATCH', path, { body });
57
+ }
58
+ put(path, body) {
59
+ return this.request('PUT', path, { body });
60
+ }
61
+ async request(method, path, opts = {}) {
62
+ const url = new URL(`${this.baseUrl}${path}`);
63
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
64
+ if (v !== undefined && v !== '')
65
+ url.searchParams.set(k, String(v));
66
+ }
67
+ const headers = {
68
+ Authorization: `Bearer ${this.key}`,
69
+ Accept: 'application/json',
70
+ 'User-Agent': `firefunc-cli/${CLI_VERSION} node/${process.versions.node}`,
71
+ };
72
+ const init = { method, headers, signal: AbortSignal.timeout(this.timeoutMs) };
73
+ if (opts.body !== undefined) {
74
+ headers['Content-Type'] = 'application/json';
75
+ init.body = JSON.stringify(opts.body);
76
+ }
77
+ let res;
78
+ try {
79
+ res = await this.fetchImpl(url, init);
80
+ }
81
+ catch (err) {
82
+ throw new ApiUnreachable(this.baseUrl, err);
83
+ }
84
+ const text = await res.text().catch(() => '');
85
+ const json = parseJson(text);
86
+ if (res.ok) {
87
+ if (res.status === 204 || text.trim() === '')
88
+ return null;
89
+ if (json === undefined)
90
+ throw notTheApi(res, this.baseUrl);
91
+ return json;
92
+ }
93
+ throw refusalFrom(res, json, this.baseUrl);
94
+ }
95
+ }
96
+ function parseJson(text) {
97
+ if (!text.trim())
98
+ return undefined;
99
+ try {
100
+ return JSON.parse(text);
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
106
+ function notTheApi(res, baseUrl) {
107
+ return new ApiRefusal(res.status, 'not_the_api', `${baseUrl} answered ${res.status} with a page, not with FireFunc's API.`, 'Point the CLI at the API itself: --api-url https://api.firefunc.com (or set FIREFUNC_API_URL).', undefined);
108
+ }
109
+ function refusalFrom(res, json, baseUrl) {
110
+ const body = json;
111
+ const e = body?.error;
112
+ if (!e || typeof e !== 'object')
113
+ return notTheApi(res, baseUrl);
114
+ const s = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
115
+ const reason = s(e.details?.reason);
116
+ const code = (reason && /^[a-z][a-z0-9_.:-]*$/.test(reason) ? reason : undefined) ??
117
+ s(e.code) ??
118
+ `http_${res.status}`;
119
+ let fix = s(e.fix) ?? s(e.details?.fix);
120
+ if (!fix && res.status === 401) {
121
+ fix =
122
+ 'Sign in again with a working key: firefunc login (keys are made in FireFunc → Settings → API keys).';
123
+ }
124
+ let message = s(e.message) ?? `The API refused the request (${res.status}).`;
125
+ if (fix && message.endsWith(fix) && message.length > fix.length) {
126
+ message = message.slice(0, -fix.length).trim();
127
+ }
128
+ const problems = problemsOf(e.details?.issues);
129
+ const gaps = gapsOf(e.details?.missing);
130
+ if (problems.length) {
131
+ const dash = message.indexOf(' — ');
132
+ const first = problems[0].message.replace(/[.\s]+$/, '').slice(0, 24);
133
+ if (dash > 0 && message.slice(dash).includes(first))
134
+ message = `${message.slice(0, dash)}.`;
135
+ }
136
+ if (gaps.length) {
137
+ const listed = gaps.map((g) => g.reason).join(' ');
138
+ if (message.endsWith(listed) && message.length > listed.length) {
139
+ message = `${message.slice(0, -listed.length).replace(/[\s:—-]+$/, '')}.`;
140
+ }
141
+ }
142
+ const fixIsListed = gaps.length > 0 && gaps.every((g) => g.fix) && fix === gaps.map((g) => g.fix).join(' ');
143
+ const details = { ...(e.details ?? {}) };
144
+ delete details.reason;
145
+ delete details.fix;
146
+ return new ApiRefusal(res.status, code, message, fix, s(e.request_id) ?? s(e.requestId), {
147
+ issues: [
148
+ ...problems.map((p) => `${p.path ? `${p.path}: ` : ''}${p.message}`),
149
+ ...gaps.map((g) => `${g.reason}${g.fix ? ` Fix: ${g.fix}` : ''}`),
150
+ ],
151
+ details: Object.keys(details).length ? details : undefined,
152
+ fixIsListed,
153
+ });
154
+ }
155
+ function problemsOf(raw) {
156
+ if (!Array.isArray(raw))
157
+ return [];
158
+ return raw.flatMap((i) => {
159
+ const issue = i;
160
+ if (typeof issue?.message !== 'string')
161
+ return [];
162
+ const path = Array.isArray(issue.path) ? issue.path.map(String).join('.') : '';
163
+ return [{ path, message: issue.message }];
164
+ });
165
+ }
166
+ function gapsOf(raw) {
167
+ if (!Array.isArray(raw))
168
+ return [];
169
+ return raw.flatMap((g) => {
170
+ const gap = g;
171
+ if (typeof gap?.reason !== 'string' || !gap.reason.trim())
172
+ return [];
173
+ const fix = typeof gap.fix === 'string' && gap.fix.trim() ? gap.fix.trim() : undefined;
174
+ return [{ reason: gap.reason.trim(), ...(fix ? { fix } : {}) }];
175
+ });
176
+ }
177
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,28 @@
1
+ import type { FlagSpec, ParsedArgs } from './args.js';
2
+ import type { ApiClient } from './client.js';
3
+ import type { Credentials } from './config.js';
4
+ import { type Io } from './io.js';
5
+ export type Ctx = {
6
+ io: Io;
7
+ args: ParsedArgs;
8
+ json: boolean;
9
+ command: string;
10
+ credentials(): Credentials;
11
+ api(): ApiClient;
12
+ };
13
+ export type Command = {
14
+ path: string[];
15
+ summary: string;
16
+ usage: string;
17
+ details?: string;
18
+ flags?: FlagSpec;
19
+ flagHelp?: [string, string][];
20
+ positional?: {
21
+ min: number;
22
+ max: number;
23
+ };
24
+ run(ctx: Ctx): Promise<number | void>;
25
+ };
26
+ export declare function readInputFile(io: Io, path: string, flag: string): Promise<string>;
27
+ export declare function readSpec(io: Io, path: string): Promise<Record<string, unknown>>;
28
+ export declare const enc: (s: string) => string;
@@ -0,0 +1,35 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { Refusal } from './io.js';
4
+ export async function readInputFile(io, path, flag) {
5
+ if (path === '-') {
6
+ if (io.stdinIsTty) {
7
+ throw new Refusal(`--${flag} - reads from stdin, and stdin is this terminal.`, `Pipe the content in (cat file | firefunc … --${flag} -), or name the file: --${flag} <path>.`, 'stdin_is_tty');
8
+ }
9
+ return io.readStdin();
10
+ }
11
+ const full = isAbsolute(path) ? path : resolve(io.cwd, path);
12
+ try {
13
+ return readFileSync(full, 'utf8');
14
+ }
15
+ catch (err) {
16
+ const code = err.code ?? err.message;
17
+ throw new Refusal(`Could not read --${flag} ${path} (${code}).`, 'Check the path and that the file is readable.', 'unreadable_file');
18
+ }
19
+ }
20
+ export async function readSpec(io, path) {
21
+ const raw = await readInputFile(io, path, 'spec');
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(raw);
25
+ }
26
+ catch (err) {
27
+ throw new Refusal(`--spec ${path} is not valid JSON (${err.message}).`, 'Write the agent as one JSON object — the fields are listed under "firefunc agents create --help".', 'bad_spec');
28
+ }
29
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
30
+ throw new Refusal(`--spec ${path} must hold one JSON object, not ${Array.isArray(parsed) ? 'a list' : typeof parsed}.`, 'Write the agent as one JSON object — the fields are listed under "firefunc agents create --help".', 'bad_spec');
31
+ }
32
+ return parsed;
33
+ }
34
+ export const enc = (s) => encodeURIComponent(s);
35
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,29 @@
1
+ import { type Io } from './io.js';
2
+ export declare const DEFAULT_API_URL = "https://api.firefunc.com";
3
+ export type CliConfig = {
4
+ apiUrl?: string;
5
+ key?: string;
6
+ workspace?: {
7
+ id: string;
8
+ name?: string | null;
9
+ };
10
+ keyId?: string;
11
+ keyName?: string;
12
+ scopes?: string[];
13
+ savedAt?: string;
14
+ };
15
+ export declare function configDir(io: Pick<Io, 'env' | 'home'>): string;
16
+ export declare function configFile(io: Pick<Io, 'env' | 'home'>): string;
17
+ export declare function loadCliConfig(io: Pick<Io, 'env' | 'home' | 'stderr' | 'platform'>, opts?: {
18
+ warnLoose?: boolean;
19
+ }): CliConfig | null;
20
+ export declare function saveCliConfig(io: Pick<Io, 'env' | 'home'>, cfg: CliConfig): string;
21
+ export declare function removeCliConfig(io: Pick<Io, 'env' | 'home'>): boolean;
22
+ export declare const API_KEY_SHAPE: RegExp;
23
+ export type Credentials = {
24
+ apiUrl: string;
25
+ key: string;
26
+ keySource: 'env' | 'config';
27
+ };
28
+ export declare function resolveApiUrl(flag: string | undefined, io: Pick<Io, 'env'>, cfg: CliConfig | null): string;
29
+ export declare function resolveCredentials(flagApiUrl: string | undefined, io: Pick<Io, 'env' | 'home' | 'stderr' | 'platform'>): Credentials;
@@ -0,0 +1,111 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { hideSecrets, Refusal } from './io.js';
4
+ export const DEFAULT_API_URL = 'https://api.firefunc.com';
5
+ export function configDir(io) {
6
+ return io.env.FIREFUNC_CONFIG_DIR || join(io.home, '.firefunc');
7
+ }
8
+ export function configFile(io) {
9
+ return join(configDir(io), 'config.json');
10
+ }
11
+ export function loadCliConfig(io, opts = {}) {
12
+ const file = configFile(io);
13
+ if (!existsSync(file))
14
+ return null;
15
+ if (opts.warnLoose !== false && io.platform !== 'win32') {
16
+ try {
17
+ const mode = statSync(file).mode & 0o777;
18
+ if (mode & 0o077) {
19
+ io.stderr.write(`firefunc: ${file} is readable by other accounts on this machine (mode ${mode.toString(8)}).\n` +
20
+ ` Fix: chmod 600 ${file}\n`);
21
+ }
22
+ }
23
+ catch {
24
+ }
25
+ }
26
+ try {
27
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
28
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
29
+ throw new Error('not an object');
30
+ return parsed;
31
+ }
32
+ catch {
33
+ throw new Refusal(`${file} is not a FireFunc CLI config (it could not be read as JSON).`, 'Sign in again to rewrite it: firefunc login', 'config_unreadable');
34
+ }
35
+ }
36
+ export function saveCliConfig(io, cfg) {
37
+ const dir = configDir(io);
38
+ if (mkdirSync(dir, { recursive: true, mode: 0o700 }) !== undefined) {
39
+ try {
40
+ chmodSync(dir, 0o700);
41
+ }
42
+ catch {
43
+ }
44
+ }
45
+ const file = configFile(io);
46
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
47
+ writeFileSync(tmp, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
48
+ try {
49
+ renameSync(tmp, file);
50
+ }
51
+ catch (err) {
52
+ rmSync(tmp, { force: true });
53
+ throw err;
54
+ }
55
+ chmodSync(file, 0o600);
56
+ return file;
57
+ }
58
+ export function removeCliConfig(io) {
59
+ const file = configFile(io);
60
+ if (!existsSync(file))
61
+ return false;
62
+ rmSync(file, { force: true });
63
+ return true;
64
+ }
65
+ export const API_KEY_SHAPE = /^ffk_[0-9a-f]{32}_[A-Za-z0-9_-]{16,}$/;
66
+ const envApiUrl = (io) => io.env.FIREFUNC_API_URL?.trim() || undefined;
67
+ export function resolveApiUrl(flag, io, cfg) {
68
+ const raw = (flag ?? envApiUrl(io) ?? cfg?.apiUrl ?? DEFAULT_API_URL).trim();
69
+ let url;
70
+ try {
71
+ url = new URL(raw);
72
+ }
73
+ catch {
74
+ throw new Refusal(`"${hideSecrets(raw)}" is not an address the CLI can call.`, `Pass the API's full address, e.g. --api-url ${DEFAULT_API_URL}`, 'bad_api_url');
75
+ }
76
+ const local = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname);
77
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
78
+ throw new Refusal(`${hideSecrets(raw)} is not https, and the CLI sends your workspace key in every request.`, `Use the https address, e.g. --api-url ${DEFAULT_API_URL} (plain http is allowed only to localhost).`, 'insecure_api_url');
79
+ }
80
+ return raw.replace(/\/+$/, '');
81
+ }
82
+ const originOf = (u) => {
83
+ try {
84
+ return new URL(u).origin;
85
+ }
86
+ catch {
87
+ return undefined;
88
+ }
89
+ };
90
+ export function resolveCredentials(flagApiUrl, io) {
91
+ const cfg = loadCliConfig(io);
92
+ const apiUrl = resolveApiUrl(flagApiUrl, io, cfg);
93
+ const envKey = io.env.FIREFUNC_API_KEY?.trim();
94
+ if (envKey) {
95
+ if (!API_KEY_SHAPE.test(envKey)) {
96
+ throw new Refusal('FIREFUNC_API_KEY is set, but not to a FireFunc workspace API key (they look like ffk_<workspace>_<secret>).', 'Set it to a key from FireFunc → Settings → API keys, or unset it to use the key saved by "firefunc login".', 'bad_key');
97
+ }
98
+ return { apiUrl, key: envKey, keySource: 'env' };
99
+ }
100
+ if (cfg?.key) {
101
+ const savedUrl = cfg.apiUrl ?? DEFAULT_API_URL;
102
+ const target = originOf(apiUrl);
103
+ if (!target || originOf(savedUrl) !== target) {
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');
106
+ }
107
+ return { apiUrl, key: cfg.key, keySource: 'config' };
108
+ }
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');
110
+ }
111
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,6 @@
1
+ import { type Command } from './command.js';
2
+ export declare function frontmatterOf(md: string): {
3
+ fields: Record<string, string>;
4
+ hasFrontmatter: boolean;
5
+ };
6
+ export declare const configureCommands: Command[];