@oneie/cli 0.3.5 → 0.4.0

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.
@@ -0,0 +1,3 @@
1
+ /** `one catalog` — browse the ONE receiver surface. */
2
+ import { Command } from 'commander';
3
+ export declare function catalogCmd(): Command;
@@ -0,0 +1,48 @@
1
+ /** `one catalog` — browse the ONE receiver surface. */
2
+ import { Command } from 'commander';
3
+ const DEFAULT_API = process.env.ONEIE_BASE_URL ?? process.env.ONE_BASE_URL ?? 'https://api.one.ie';
4
+ function apiKey() {
5
+ return process.env.ONEIE_API_KEY ?? process.env.ONE_API_KEY ?? '';
6
+ }
7
+ async function ask(base, receiver, data) {
8
+ const res = await fetch(`${base}/api/ask/${encodeURIComponent(receiver)}`, {
9
+ method: 'POST',
10
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey()}` },
11
+ body: JSON.stringify({ data }),
12
+ });
13
+ return res.json();
14
+ }
15
+ function out(cmd, data) {
16
+ const isJson = cmd.parent?.opts()?.json;
17
+ if (isJson) {
18
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
19
+ return;
20
+ }
21
+ // Pretty-print catalog rows
22
+ const d = data;
23
+ const rows = d?.result?.catalog ?? [];
24
+ if (!Array.isArray(rows) || rows.length === 0) {
25
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
26
+ return;
27
+ }
28
+ for (const row of rows) {
29
+ const cost = row['cost'] ? ` [${row['cost']} cr]` : '';
30
+ const rev = row['reversible'] === false ? ' (irreversible)' : '';
31
+ const summary = String(row['summary'] ?? '');
32
+ const receiver = String(row['receiver'] ?? '');
33
+ process.stdout.write(` ${receiver.padEnd(32)} ${summary}${cost}${rev}\n`);
34
+ }
35
+ process.stdout.write(`\n Total: ${rows.length} receivers\n`);
36
+ }
37
+ export function catalogCmd() {
38
+ const cmd = new Command('catalog')
39
+ .description('Browse the ONE receiver surface')
40
+ .option('--goal <goal>', 'Filter to a named recipe (spine, build, trade, transact, sop)')
41
+ .option('--api <url>', 'API base URL', DEFAULT_API)
42
+ .action(async (opts) => {
43
+ const base = opts.api.replace(/\/$/, '');
44
+ const result = await ask(base, 'meta:catalog', { goal: opts.goal });
45
+ out(cmd, result);
46
+ });
47
+ return cmd;
48
+ }
@@ -0,0 +1,3 @@
1
+ /** `one client` — provision and manage client nodes. */
2
+ import { Command } from 'commander';
3
+ export declare function clientCmd(): Command;
@@ -0,0 +1,196 @@
1
+ /** `one client` — provision and manage client nodes. */
2
+ import { Command } from 'commander';
3
+ import { readFileSync, existsSync, mkdirSync, cpSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ const DEFAULT_API = process.env.ONEIE_BASE_URL ?? process.env.ONE_BASE_URL ?? 'https://api.one.ie';
6
+ function apiKey() {
7
+ return process.env.ONEIE_API_KEY ?? process.env.ONE_API_KEY ?? '';
8
+ }
9
+ function headers() {
10
+ return { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey()}` };
11
+ }
12
+ async function ask(base, receiver, data) {
13
+ const res = await fetch(`${base}/api/ask/${encodeURIComponent(receiver)}`, {
14
+ method: 'POST', headers: headers(), body: JSON.stringify({ data }),
15
+ });
16
+ return res.json();
17
+ }
18
+ function parseToml(text) {
19
+ const result = {};
20
+ let currentSection = null;
21
+ for (const rawLine of text.split('\n')) {
22
+ const line = rawLine.split('#')[0].trim();
23
+ if (!line)
24
+ continue;
25
+ if (line.startsWith('[[') && line.endsWith(']]')) {
26
+ currentSection = line.slice(2, -2).trim();
27
+ if (!Array.isArray(result[currentSection]))
28
+ result[currentSection] = [];
29
+ result[currentSection].push({});
30
+ continue;
31
+ }
32
+ if (line.startsWith('[') && line.endsWith(']')) {
33
+ currentSection = null;
34
+ continue;
35
+ }
36
+ const eq = line.indexOf('=');
37
+ if (eq < 1)
38
+ continue;
39
+ const key = line.slice(0, eq).trim();
40
+ const raw = line.slice(eq + 1).trim();
41
+ let val;
42
+ if (raw === 'true')
43
+ val = true;
44
+ else if (raw === 'false')
45
+ val = false;
46
+ else if (!isNaN(Number(raw)) && raw !== '')
47
+ val = Number(raw);
48
+ else if (raw.startsWith('"') || raw.startsWith("'"))
49
+ val = raw.slice(1, -1);
50
+ else if (raw.startsWith('[') && raw.endsWith(']')) {
51
+ val = raw.slice(1, -1).split(',').map(v => v.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
52
+ }
53
+ else
54
+ val = raw;
55
+ if (currentSection) {
56
+ const arr = result[currentSection];
57
+ if (arr.length > 0)
58
+ arr[arr.length - 1][key] = val;
59
+ }
60
+ else
61
+ result[key] = val;
62
+ }
63
+ return result;
64
+ }
65
+ function readAgencyConfig(cwd) {
66
+ for (const name of ['agency.toml', '_node.toml']) {
67
+ const p = resolve(cwd, name);
68
+ if (existsSync(p))
69
+ return parseToml(readFileSync(p, 'utf8'));
70
+ }
71
+ return {};
72
+ }
73
+ function out(cmd, data) {
74
+ const isJson = cmd.parent?.opts()?.json;
75
+ if (isJson)
76
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
77
+ else {
78
+ const d = data;
79
+ for (const [k, v] of Object.entries(d)) {
80
+ if (typeof v !== 'object')
81
+ process.stdout.write(` ${k}=${v}\n`);
82
+ }
83
+ }
84
+ }
85
+ export function clientCmd() {
86
+ const cmd = new Command('client').description('Manage client nodes');
87
+ cmd.command('add <slug>')
88
+ .description('Provision a new client workspace and scaffold clients/<slug>/')
89
+ .option('--name <name>', 'Display name (defaults to slug)')
90
+ .option('--plan <plan>', 'Plan tier', 'pro')
91
+ .option('--credits <n>', 'Initial credit grant from agency pool', '5000')
92
+ .option('--markup <pct>', 'Reseller markup %', '20')
93
+ .option('--cap <n>', 'Monthly spend ceiling in credits', '10000')
94
+ .option('--site <url>', 'Crawl a URL to draft ai/ + data/ folders')
95
+ .option('--dry-run', 'Simulate without making API calls')
96
+ .option('--api <url>', 'API base URL', DEFAULT_API)
97
+ .action(async (slug, opts) => {
98
+ const cwd = process.cwd();
99
+ const agencyCfg = readAgencyConfig(cwd);
100
+ const agencySlug = String(agencyCfg['slug'] ?? '');
101
+ const clientName = opts.name ?? slug;
102
+ const base = opts.api.replace(/\/$/, '');
103
+ const key = apiKey();
104
+ if (!key) {
105
+ process.stderr.write('error: ONEIE_API_KEY not set — run `one auth login` first\n');
106
+ process.exit(1);
107
+ }
108
+ // Scaffold clients/<slug>/ from the _node template
109
+ const clientDir = resolve(cwd, 'clients', slug);
110
+ if (!existsSync(clientDir)) {
111
+ if (opts.dryRun) {
112
+ process.stdout.write(`[dry-run] would scaffold clients/${slug}/\n`);
113
+ }
114
+ else {
115
+ mkdirSync(clientDir, { recursive: true });
116
+ // Copy the _node template if present
117
+ const tplDir = resolve(cwd, 'node_modules', '@oneie', 'cli', 'dist', 'templates', '_node');
118
+ if (existsSync(tplDir)) {
119
+ cpSync(tplDir, clientDir, { recursive: true });
120
+ }
121
+ else {
122
+ // Fallback: create minimal structure
123
+ mkdirSync(resolve(clientDir, 'ai', 'agents'), { recursive: true });
124
+ mkdirSync(resolve(clientDir, 'data', 'lifecycles'), { recursive: true });
125
+ mkdirSync(resolve(clientDir, 'site'), { recursive: true });
126
+ }
127
+ process.stdout.write(` ✓ scaffolded clients/${slug}/\n`);
128
+ }
129
+ }
130
+ // Crawl the site if --site provided
131
+ if (opts.site && !opts.dryRun) {
132
+ process.stdout.write(` ~ crawling ${opts.site} to draft ai/ and data/…\n`);
133
+ await ask(base, 'web:crawl', { url: opts.site, slug });
134
+ }
135
+ if (opts.dryRun) {
136
+ process.stdout.write(`[dry-run] would provision: ${slug} (parent=${agencySlug})\n`);
137
+ out(cmd, { ok: true, slug, parent: agencySlug, dry: true });
138
+ return;
139
+ }
140
+ // Provision the workspace
141
+ const result = (await ask(base, 'world:create-workspace', {
142
+ name: clientName,
143
+ slug,
144
+ parent: agencySlug || undefined,
145
+ plan: opts.plan,
146
+ credit: Number(opts.credits),
147
+ markup_pct: Number(opts.markup),
148
+ monthly_cap: Number(opts.cap),
149
+ }));
150
+ if (result?.kind === 'failure') {
151
+ process.stderr.write(` ✗ provision failed: ${result?.error ?? 'unknown'}\n`);
152
+ process.exit(1);
153
+ }
154
+ process.stdout.write(` ✓ workspace: ${slug} (parent=${agencySlug || 'none'})\n`);
155
+ out(cmd, { ok: true, slug, parent: agencySlug, plan: opts.plan });
156
+ process.stdout.write(`\n✓ Client "${clientName}" provisioned. Next: one push clients/${slug}\n`);
157
+ });
158
+ cmd.command('invite <slug>')
159
+ .description('Invite a client owner by email')
160
+ .requiredOption('--email <email>', 'Client owner email address')
161
+ .option('--role <role>', 'Role to assign', 'owner')
162
+ .option('--api <url>', 'API base URL', DEFAULT_API)
163
+ .action(async (slug, opts) => {
164
+ const base = opts.api.replace(/\/$/, '');
165
+ const key = apiKey();
166
+ if (!key) {
167
+ process.stderr.write('error: ONEIE_API_KEY not set\n');
168
+ process.exit(1);
169
+ }
170
+ const result = (await ask(base, 'world:invite-member', {
171
+ slug, email: opts.email, role: opts.role,
172
+ }));
173
+ if (result?.kind === 'failure') {
174
+ process.stderr.write(` ✗ invite failed: ${result?.error ?? 'unknown'}\n`);
175
+ process.exit(1);
176
+ }
177
+ out(cmd, { ok: true, slug, email: opts.email, role: opts.role });
178
+ });
179
+ cmd.command('list')
180
+ .description('List client workspaces in clients/')
181
+ .option('--api <url>', 'API base URL', DEFAULT_API)
182
+ .action(async (_opts) => {
183
+ const cwd = process.cwd();
184
+ const clientsDir = resolve(cwd, 'clients');
185
+ if (!existsSync(clientsDir)) {
186
+ out(cmd, { ok: true, clients: [] });
187
+ return;
188
+ }
189
+ const { readdirSync } = await import('node:fs');
190
+ const slugs = readdirSync(clientsDir, { withFileTypes: true })
191
+ .filter(e => e.isDirectory())
192
+ .map(e => e.name);
193
+ out(cmd, { ok: true, clients: slugs, count: slugs.length });
194
+ });
195
+ return cmd;
196
+ }
@@ -0,0 +1,22 @@
1
+ export interface CompileResult {
2
+ pushed: string[];
3
+ skipped: string[];
4
+ errors: string[];
5
+ }
6
+ /** Minimal TOML parser — supports top-level scalars + array tables ([[section]]). */
7
+ export declare function parseToml(text: string): Record<string, unknown>;
8
+ /** Read _node.toml / agency.toml / client.toml from a dir. */
9
+ export declare function readNodeConfig(dir: string): Record<string, unknown>;
10
+ /**
11
+ * Compile a node directory (root or clients/<slug>).
12
+ * `clientDir` is the client override folder; if set, it is merged OVER `rootDir`.
13
+ */
14
+ export declare function compileNode(opts: {
15
+ rootDir: string;
16
+ clientDir?: string;
17
+ apiBase: string;
18
+ apiKey: string;
19
+ agencySlug: string;
20
+ targetSlug: string;
21
+ dry: boolean;
22
+ }): Promise<CompileResult>;
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Folder-walking compiler for ONE fractal nodes.
3
+ * Walks ai/ + data/ and emits one ask() per file via the REST API.
4
+ * Client push: one push clients/<slug> merges clients/<slug>/ over root.
5
+ */
6
+ import { readdirSync, readFileSync, existsSync } from 'node:fs';
7
+ import { resolve, join, basename, dirname } from 'node:path';
8
+ import { parseFrontmatter } from './validate.js';
9
+ import { namespaced } from './slug.js';
10
+ import { readSecret } from './env.js';
11
+ /** Minimal TOML parser — supports top-level scalars + array tables ([[section]]). */
12
+ export function parseToml(text) {
13
+ const result = {};
14
+ let currentSection = null;
15
+ for (const rawLine of text.split('\n')) {
16
+ const line = rawLine.split('#')[0].trim();
17
+ if (!line)
18
+ continue;
19
+ if (line.startsWith('[[') && line.endsWith(']]')) {
20
+ currentSection = line.slice(2, -2).trim();
21
+ if (!Array.isArray(result[currentSection]))
22
+ result[currentSection] = [];
23
+ result[currentSection].push({});
24
+ continue;
25
+ }
26
+ if (line.startsWith('[') && line.endsWith(']')) {
27
+ currentSection = null;
28
+ continue;
29
+ }
30
+ const eq = line.indexOf('=');
31
+ if (eq < 1)
32
+ continue;
33
+ const key = line.slice(0, eq).trim();
34
+ const raw = line.slice(eq + 1).trim();
35
+ let val;
36
+ if (raw === 'true')
37
+ val = true;
38
+ else if (raw === 'false')
39
+ val = false;
40
+ else if (!isNaN(Number(raw)) && raw !== '')
41
+ val = Number(raw);
42
+ else if (raw.startsWith('"') && raw.endsWith('"'))
43
+ val = raw.slice(1, -1);
44
+ else if (raw.startsWith("'") && raw.endsWith("'"))
45
+ val = raw.slice(1, -1);
46
+ else if (raw.startsWith('[') && raw.endsWith(']')) {
47
+ val = raw.slice(1, -1)
48
+ .split(',')
49
+ .map(v => v.trim().replace(/^["']|["']$/g, ''))
50
+ .filter(Boolean);
51
+ }
52
+ else
53
+ val = raw;
54
+ if (currentSection) {
55
+ const arr = result[currentSection];
56
+ if (arr.length > 0)
57
+ arr[arr.length - 1][key] = val;
58
+ }
59
+ else {
60
+ result[key] = val;
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ /** Read _node.toml / agency.toml / client.toml from a dir. */
66
+ export function readNodeConfig(dir) {
67
+ for (const name of ['_node.toml', 'agency.toml', 'client.toml']) {
68
+ const p = resolve(dir, name);
69
+ if (existsSync(p))
70
+ return parseToml(readFileSync(p, 'utf8'));
71
+ }
72
+ return {};
73
+ }
74
+ function glob(dir, pattern) {
75
+ if (!existsSync(dir))
76
+ return [];
77
+ return readdirSync(dir, { withFileTypes: true })
78
+ .filter(e => e.isFile() && pattern.test(e.name))
79
+ .map(e => join(dir, e.name));
80
+ }
81
+ function globDir(dir, pattern) {
82
+ if (!existsSync(dir))
83
+ return [];
84
+ const results = [];
85
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
86
+ if (e.isDirectory()) {
87
+ const sub = join(dir, e.name);
88
+ const file = resolve(sub, 'SKILL.md');
89
+ if (pattern.test('SKILL.md') && existsSync(file))
90
+ results.push(file);
91
+ }
92
+ }
93
+ return results;
94
+ }
95
+ async function askApi(ctx, receiver, data) {
96
+ const label = `${receiver} (${ctx.slug})`;
97
+ if (ctx.dry) {
98
+ ctx.skipped.push(`[dry-run] ${label}`);
99
+ return;
100
+ }
101
+ try {
102
+ const res = await fetch(`${ctx.base}/api/ask/${encodeURIComponent(receiver)}`, { method: 'POST', headers: ctx.headers, body: JSON.stringify({ data }) });
103
+ const body = (await res.json());
104
+ if (!res.ok || body.kind === 'failure') {
105
+ ctx.errors.push(`${label}: ${body.error ?? res.status}`);
106
+ }
107
+ else {
108
+ ctx.pushed.push(label);
109
+ }
110
+ }
111
+ catch (err) {
112
+ ctx.errors.push(`${label}: ${err.message}`);
113
+ }
114
+ }
115
+ async function compileAgents(ctx, aiDir) {
116
+ for (const file of glob(join(aiDir, 'agents'), /\.md$/)) {
117
+ const { fm, body } = parseFrontmatter(readFileSync(file, 'utf8'));
118
+ const rawName = fm['name'] ?? basename(file, '.md');
119
+ const name = namespaced(ctx.agencySlug, rawName);
120
+ await askApi(ctx, 'world:create-thing', {
121
+ slug: ctx.slug,
122
+ type: 'agent',
123
+ name,
124
+ description: fm['description'] ?? '',
125
+ instructions: body,
126
+ model: fm['model'] ?? 'openrouter/auto',
127
+ });
128
+ }
129
+ }
130
+ async function compileSkills(ctx, aiDir) {
131
+ for (const file of globDir(join(aiDir, 'skills'), /SKILL\.md/)) {
132
+ const { fm, body } = parseFrontmatter(readFileSync(file, 'utf8'));
133
+ const rawName = fm['name'] ?? basename(dirname(file));
134
+ const name = namespaced(ctx.agencySlug, rawName);
135
+ await askApi(ctx, 'world:create-thing', {
136
+ slug: ctx.slug,
137
+ type: 'skill',
138
+ name,
139
+ description: fm['description'] ?? '',
140
+ instructions: body,
141
+ });
142
+ }
143
+ }
144
+ async function compileContext(ctx, aiDir) {
145
+ const file = resolve(aiDir, 'context.md');
146
+ if (!existsSync(file))
147
+ return;
148
+ const value = readFileSync(file, 'utf8').trim();
149
+ await askApi(ctx, 'settings:write', { slug: ctx.slug, key: 'company_context', value });
150
+ }
151
+ async function compileTools(ctx, aiDir) {
152
+ for (const file of glob(join(aiDir, 'tools'), /\.toml$/)) {
153
+ const cfg = parseToml(readFileSync(file, 'utf8'));
154
+ const toolkit = String(cfg['toolkit'] ?? basename(file, '.toml'));
155
+ const mode = String(cfg['mode'] ?? 'api_key');
156
+ if (mode === 'oauth') {
157
+ ctx.skipped.push(`tools:connect ${toolkit} — OAuth; run: one connect ${toolkit} --for ${ctx.slug}`);
158
+ continue;
159
+ }
160
+ const envVar = String(cfg['env_var'] ?? '');
161
+ const credential = envVar ? readSecret(envVar) : '';
162
+ if (!credential) {
163
+ ctx.skipped.push(`tools:connect ${toolkit} — ${envVar} not set in .env.local or env`);
164
+ continue;
165
+ }
166
+ await askApi(ctx, 'tools:connect', { slug: ctx.slug, toolkit, credentials: { api_key: credential } });
167
+ }
168
+ }
169
+ async function compileLifecycles(ctx, dataDir) {
170
+ for (const file of glob(join(dataDir, 'lifecycles'), /\.toml$/)) {
171
+ const raw = parseToml(readFileSync(file, 'utf8'));
172
+ const lifecycle = basename(file, '.toml');
173
+ const def = {
174
+ id: String(raw['id'] ?? lifecycle),
175
+ name: String(raw['name'] ?? lifecycle),
176
+ version: Number(raw['version'] ?? 1),
177
+ monotonic: Boolean(raw['monotonic'] ?? true),
178
+ stages: (raw['stages'] ?? []).map(s => ({
179
+ id: String(s['id'] ?? ''),
180
+ label: String(s['label'] ?? ''),
181
+ tag: String(s['tag'] ?? `lifecycle:${lifecycle}:${s['id']}`),
182
+ slot: Number(s['slot'] ?? 0),
183
+ subSteps: (s['sub_steps'] ?? []),
184
+ enter_when: (s['enter_when'] == null || s['enter_when'] === 'null')
185
+ ? null : String(s['enter_when']),
186
+ })),
187
+ transitions: (raw['transitions'] ?? []).map(t => ({
188
+ source: String(t['source'] ?? ''),
189
+ target: String(t['target'] ?? ''),
190
+ kind: String(t['kind'] ?? 'forward'),
191
+ })),
192
+ arcs: (raw['arcs'] ?? []).map(a => ({
193
+ row: Number(a['row'] ?? 0),
194
+ label: String(a['label'] ?? ''),
195
+ })),
196
+ };
197
+ await askApi(ctx, 'lifecycle:save', { slug: ctx.slug, lifecycle, def });
198
+ }
199
+ }
200
+ async function compileTypes(ctx, dataDir) {
201
+ for (const file of glob(join(dataDir, 'types'), /\.toml$/)) {
202
+ const cfg = parseToml(readFileSync(file, 'utf8'));
203
+ await askApi(ctx, 'world:declare-types', { slug: ctx.slug, types: cfg });
204
+ }
205
+ }
206
+ /**
207
+ * Compile a node directory (root or clients/<slug>).
208
+ * `clientDir` is the client override folder; if set, it is merged OVER `rootDir`.
209
+ */
210
+ export async function compileNode(opts) {
211
+ const headers = {
212
+ 'Content-Type': 'application/json',
213
+ Authorization: `Bearer ${opts.apiKey}`,
214
+ };
215
+ const ctx = {
216
+ base: opts.apiBase,
217
+ headers,
218
+ slug: opts.targetSlug,
219
+ agencySlug: opts.agencySlug,
220
+ rootDir: opts.rootDir,
221
+ dry: opts.dry,
222
+ pushed: [],
223
+ skipped: [],
224
+ errors: [],
225
+ };
226
+ // Resolve effective dirs — client overrides root when both exist
227
+ const aiDirs = [
228
+ join(opts.rootDir, 'ai'),
229
+ ...(opts.clientDir ? [join(opts.clientDir, 'ai')] : []),
230
+ ];
231
+ const dataDirs = [
232
+ join(opts.rootDir, 'data'),
233
+ ...(opts.clientDir ? [join(opts.clientDir, 'data')] : []),
234
+ ];
235
+ for (const aiDir of aiDirs) {
236
+ if (!existsSync(aiDir))
237
+ continue;
238
+ await compileAgents(ctx, aiDir);
239
+ await compileSkills(ctx, aiDir);
240
+ await compileContext(ctx, aiDir);
241
+ await compileTools(ctx, aiDir);
242
+ }
243
+ for (const dataDir of dataDirs) {
244
+ if (!existsSync(dataDir))
245
+ continue;
246
+ await compileLifecycles(ctx, dataDir);
247
+ await compileTypes(ctx, dataDir);
248
+ }
249
+ return { pushed: ctx.pushed, skipped: ctx.skipped, errors: ctx.errors };
250
+ }
@@ -0,0 +1,3 @@
1
+ /** `one recall|reputation` — memory and reputation commands. */
2
+ import { Command } from 'commander';
3
+ export declare function coordinateCmd(): Command;
@@ -0,0 +1,71 @@
1
+ /** `one recall|reputation` — memory and reputation commands. */
2
+ import { Command } from 'commander';
3
+ const DEFAULT_API = process.env.ONEIE_BASE_URL ?? process.env.ONE_BASE_URL ?? 'https://api.one.ie';
4
+ function apiKey() {
5
+ return process.env.ONEIE_API_KEY ?? process.env.ONE_API_KEY ?? '';
6
+ }
7
+ async function ask(base, receiver, data) {
8
+ const res = await fetch(`${base}/api/ask/${encodeURIComponent(receiver)}`, {
9
+ method: 'POST',
10
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey()}` },
11
+ body: JSON.stringify({ data }),
12
+ });
13
+ return res.json();
14
+ }
15
+ function out(cmd, data) {
16
+ const isJson = cmd.parent?.opts()?.json;
17
+ if (isJson) {
18
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
19
+ return;
20
+ }
21
+ const d = data;
22
+ if (d?.kind === 'result') {
23
+ const r = d.result;
24
+ if (Array.isArray(r)) {
25
+ for (const item of r) {
26
+ process.stdout.write(` ${JSON.stringify(item)}\n`);
27
+ }
28
+ return;
29
+ }
30
+ if (typeof r === 'object' && r !== null) {
31
+ for (const [k, v] of Object.entries(r)) {
32
+ if (typeof v !== 'object')
33
+ process.stdout.write(` ${k}: ${v}\n`);
34
+ }
35
+ return;
36
+ }
37
+ }
38
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
39
+ }
40
+ export function coordinateCmd() {
41
+ const cmd = new Command('coordinate').description('Coordination — memory and reputation');
42
+ cmd.command('recall')
43
+ .description('Cross-session memory lookup (meta:recall)')
44
+ .argument('[about]', 'Optional search term')
45
+ .option('--limit <n>', 'Max results', '10')
46
+ .option('--api <url>', 'API base URL', DEFAULT_API)
47
+ .action(async (about, opts) => {
48
+ const base = opts.api.replace(/\/$/, '');
49
+ const result = await ask(base, 'meta:recall', { about, limit: Number(opts.limit) });
50
+ out(cmd, result);
51
+ });
52
+ cmd.command('reputation')
53
+ .description('Show or signal reputation for an agent')
54
+ .argument('[uid]', 'Agent uid to commend (omit to show own reputation)')
55
+ .option('--commend', 'Send a commendation signal')
56
+ .option('--api <url>', 'API base URL', DEFAULT_API)
57
+ .action(async (uid, opts) => {
58
+ const base = opts.api.replace(/\/$/, '');
59
+ if (opts.commend && uid) {
60
+ const result = await ask(base, 'agents:commend', { uid });
61
+ out(cmd, result);
62
+ }
63
+ else {
64
+ const result = await ask(base, 'dashboard:usage', {
65
+ slug: uid ?? (process.env.ONEIE_SLUG ?? process.env.ONE_SLUG ?? ''),
66
+ });
67
+ out(cmd, result);
68
+ }
69
+ });
70
+ return cmd;
71
+ }
@@ -0,0 +1,3 @@
1
+ /** `one deploy [path]` — wrangler pages deploy wrapper. */
2
+ import { Command } from 'commander';
3
+ export declare function deployCmd(): Command;
@@ -0,0 +1,46 @@
1
+ /** `one deploy [path]` — wrangler pages deploy wrapper. */
2
+ import { Command } from 'commander';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+ function out(cmd, data) {
7
+ const isJson = cmd.parent?.opts()?.json;
8
+ if (isJson)
9
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
10
+ else {
11
+ const d = data;
12
+ if (d['ok'])
13
+ process.stdout.write(`✓ deployed\n`);
14
+ else
15
+ process.stderr.write(`✗ deploy failed\n`);
16
+ }
17
+ }
18
+ export function deployCmd() {
19
+ const cmd = new Command('deploy')
20
+ .description('Deploy the site/ directory via wrangler pages deploy')
21
+ .argument('[path]', 'Path to deploy (defaults to site/ in cwd)', 'site')
22
+ .option('--project <name>', 'Cloudflare Pages project name')
23
+ .option('--branch <branch>', 'Git branch for the deployment')
24
+ .option('--dry-run', 'Pass --dry-run to wrangler')
25
+ .action((path, opts) => {
26
+ const dir = resolve(process.cwd(), path);
27
+ if (!existsSync(dir)) {
28
+ process.stderr.write(`error: directory not found: ${dir}\n`);
29
+ process.exit(1);
30
+ }
31
+ const args = ['wrangler', 'pages', 'deploy', dir];
32
+ if (opts.project)
33
+ args.push('--project-name', opts.project);
34
+ if (opts.branch)
35
+ args.push('--branch', opts.branch);
36
+ if (opts.dryRun)
37
+ args.push('--dry-run');
38
+ process.stdout.write(` deploying ${dir}…\n`);
39
+ const result = spawnSync('npx', args, { stdio: 'inherit', encoding: 'utf8' });
40
+ const ok = result.status === 0;
41
+ out(cmd, { ok, path: dir, exit: result.status });
42
+ if (!ok)
43
+ process.exit(result.status ?? 1);
44
+ });
45
+ return cmd;
46
+ }
@@ -0,0 +1,6 @@
1
+ /** Read existing .env.local (or return empty map). */
2
+ export declare function readEnvLocal(cwd?: string): Map<string, string>;
3
+ /** Upsert key=value pairs into .env.local, preserving existing entries. */
4
+ export declare function mergeEnvLocal(pairs: Record<string, string>, cwd?: string): void;
5
+ /** Read a single key from .env.local, then fallback to process.env. */
6
+ export declare function readSecret(key: string, cwd?: string): string;