@oneie/cli 4.0.7 → 4.2.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,256 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { basename, extname } from 'node:path';
4
+ import { mediaListAllWith } from '@oneie/sdk';
5
+ import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
6
+ import { askPath } from './lib/api-path.js';
7
+ // `one media` — the two media doors a JSON body cannot serve comfortably.
8
+ //
9
+ // WHAT IS DELIBERATELY NOT HERE, and why. The CLI already reaches every receiver:
10
+ // `one ask <receiver> --data '<json>'` (substrate.ts). So a subcommand has to earn
11
+ // its place the way `one tasks board` does — by doing work the raw ask cannot.
12
+ //
13
+ // list EARNS IT — media:list is ONE R2 scan per call with a budget and a
14
+ // cursor, and its `total` is per-page AND a floor whenever `truncated`
15
+ // is present. A raw ask prints scan one and READS AS COMPLETE. That is
16
+ // the 200-row-clamp defect, and it is what this renderer refuses to do.
17
+ // upload EARNS IT — media:upload takes `{ url | base64 }`. You cannot put a
18
+ // local file in a JSON body by hand. This reads it, sizes it against the
19
+ // door's own 5 MiB cap before spending a request, and encodes it.
20
+ // generate DECLINED — it is a prompt string in a JSON body. The answer is
21
+ // `one ask media:generate --data '{"prompt":"a red bicycle"}'`, which is
22
+ // not worse than a wrapper would be. Documented, not built.
23
+ //
24
+ // WORKSPACE. `--workspace` is offered on BOTH verbs because media:upload REFUSES a
25
+ // workspace you may not write ("A refusal is never a downgrade to your own
26
+ // workspace" — its own error describe()). That is the one thing that makes a write
27
+ // flag safe here: the older HTTP doors derive the slug from the session and ignore
28
+ // what they are handed, so an agency's upload landed in the agency's library and
29
+ // looked like it worked. This receiver does not, and the printed `key` proves it —
30
+ // it names the workspace prefix the bytes actually reached.
31
+ const DEFAULT_API = 'https://api.one.ie';
32
+ /** The door's own hard cap (media:upload: "5 MiB hard cap"). Checked here so a
33
+ * doomed 6.7 MiB base64 body is never sent — the refusal is instant and names the number. */
34
+ const UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
35
+ /** media:list's `prefix` is an enum, not a free string — refuse locally rather than
36
+ * spend a request on a value the zod schema will reject. */
37
+ const PREFIXES = ['media', 'chat', 'ads', 'products', 'pages', 'brand', 'courses'];
38
+ const VIDEO_EXT = new Set(['.mp4', '.webm', '.mov', '.m4v', '.avi', '.mkv']);
39
+ const CONTENT_TYPES = {
40
+ '.png': 'image/png',
41
+ '.jpg': 'image/jpeg',
42
+ '.jpeg': 'image/jpeg',
43
+ '.gif': 'image/gif',
44
+ '.webp': 'image/webp',
45
+ '.avif': 'image/avif',
46
+ };
47
+ function fail(msg) {
48
+ process.stderr.write(`error ${msg}\n`);
49
+ process.exitCode = 1;
50
+ }
51
+ function asker(api) {
52
+ const base = resolveBase({ api }, DEFAULT_API);
53
+ return async (receiver, data, timeoutMs) => {
54
+ const res = await fetch(askPath(base, receiver), {
55
+ method: 'POST',
56
+ headers: authHeaders(),
57
+ body: JSON.stringify(timeoutMs ? { data, timeoutMs } : { data }),
58
+ });
59
+ const text = await res.text();
60
+ let body;
61
+ try {
62
+ body = text ? JSON.parse(text) : undefined;
63
+ }
64
+ catch {
65
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
66
+ }
67
+ // A refusal wears an envelope at HTTP 200 as readily as at 4xx — read the envelope, not the status.
68
+ if (!res.ok && !(body && typeof body === 'object' && 'outcome' in body)) {
69
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
70
+ }
71
+ return unwrap(receiver, body);
72
+ };
73
+ }
74
+ /** Unwrap the ask door's `{ outcome, result }`. A failure whose result is a receiver
75
+ * body (`{ ok:false, error }`) is RETURNED, not thrown — the caller keeps its receipt. */
76
+ function unwrap(receiver, raw) {
77
+ if (!raw || typeof raw !== 'object')
78
+ throw new Error(`${receiver}: empty response`);
79
+ const o = raw;
80
+ if ('outcome' in o) {
81
+ if (o.outcome === 'result')
82
+ return o.result ?? {};
83
+ const inner = o.result;
84
+ if (inner && typeof inner === 'object' && ('ok' in inner || 'error' in inner)) {
85
+ return { ok: false, ...inner, error: inner.error ?? String(o.outcome) };
86
+ }
87
+ const why = typeof o.reason === 'string' ? ` (${o.reason})` : '';
88
+ throw new Error(`${receiver}: ${String(o.outcome)}${why}`);
89
+ }
90
+ if ('result' in o)
91
+ return o.result ?? {};
92
+ return o;
93
+ }
94
+ function human(bytes) {
95
+ if (bytes === null || bytes === undefined)
96
+ return '?';
97
+ if (bytes < 1024)
98
+ return `${bytes}B`;
99
+ if (bytes < 1024 * 1024)
100
+ return `${(bytes / 1024).toFixed(1)}K`;
101
+ return `${(bytes / 1024 / 1024).toFixed(1)}M`;
102
+ }
103
+ function counts(rec) {
104
+ const rows = Object.entries(rec ?? {}).sort((a, b) => b[1] - a[1]);
105
+ return rows.length ? rows.map(([k, v]) => `${k || '(root)'}=${v}`).join(' ') : '-';
106
+ }
107
+ function renderList(res) {
108
+ const items = res.items ?? [];
109
+ const w = process.stdout;
110
+ // ABSENT IS NOT FALSE: a complete answer carries no `truncated` key at all.
111
+ const short = res.truncated !== undefined;
112
+ // THE RULE: a total beside a present `truncated` is a FLOOR, never a count.
113
+ const totalTxt = res.total === undefined ? '?' : short ? `at least ${res.total}` : `${res.total}`;
114
+ w.write(`${items.length} rows, ${totalTxt} media` +
115
+ `${res.scanned !== undefined ? ` scanned=${res.scanned} objects` : ''}` +
116
+ `${res.pages ? ` pages=${res.pages}` : ''}\n`);
117
+ if (short) {
118
+ w.write(`TRUNCATED: the scan budget bit — "${res.total ?? '?'}" is a FLOOR, not a count ` +
119
+ `${JSON.stringify(res.truncated)}\n`);
120
+ }
121
+ if (res.nextCursor) {
122
+ w.write(`MORE: nextCursor=${res.nextCursor} — rerun with --all to walk every page\n`);
123
+ }
124
+ // scanned far above total means most of the bucket is not media — following the
125
+ // cursor is the right move, and concluding "empty workspace" is the wrong one.
126
+ if (!short && res.scanned !== undefined && res.total !== undefined && res.scanned > res.total * 4) {
127
+ w.write(`note most of what was scanned is not media (${res.total} of ${res.scanned})\n`);
128
+ }
129
+ if (res.byPrefix)
130
+ w.write(`byPrefix ${counts(res.byPrefix)}\n`);
131
+ if (items.length)
132
+ w.write('\n');
133
+ for (const it of items) {
134
+ w.write(`${it.key} ${it.kind} ${human(it.size)} ${it.contentType} ${it.uploaded ?? '-'}\n`);
135
+ }
136
+ }
137
+ export function mediaCmd() {
138
+ const cmd = new Command('media').description('A workspace media library — list the WHOLE of it, upload a local file. ' +
139
+ '(generate has no subcommand on purpose: one ask media:generate --data \'{"prompt":"..."}\')');
140
+ cmd
141
+ .command('list')
142
+ .description('List media (media:list) — rows, an honest total, and a loud word when the scan was cut short')
143
+ .option('--workspace <slug>', 'Group slug to read (default: your own). Honoured only if you may read it.')
144
+ .option('--kind <k>', 'image | video — filters the rows on a page, does not change what is scanned')
145
+ .option('--prefix <p>', `Only this namespace: ${PREFIXES.join(' | ')}`)
146
+ .option('--limit <n>', 'R2 objects to SCAN per page BEFORE filtering — not a row count. Default 500, max 1000.')
147
+ .option('--all', 'Follow nextCursor until every page is read (ceiling 20 pages)')
148
+ .option('--api <url>', 'API base URL', DEFAULT_API)
149
+ .option('--json', 'Print the raw response')
150
+ .action(async (opts, sub) => {
151
+ if (opts.kind && opts.kind !== 'image' && opts.kind !== 'video') {
152
+ return fail("--kind must be 'image' or 'video'");
153
+ }
154
+ if (opts.prefix && !PREFIXES.includes(opts.prefix)) {
155
+ return fail(`--prefix must be one of: ${PREFIXES.join(', ')}`);
156
+ }
157
+ const limit = opts.limit === undefined ? undefined : Number(opts.limit);
158
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 1000)) {
159
+ return fail('--limit must be a whole number from 1 to 1000 (R2\'s own ceiling)');
160
+ }
161
+ const req = {
162
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
163
+ ...(opts.kind ? { kind: opts.kind } : {}),
164
+ ...(opts.prefix ? { prefix: opts.prefix } : {}),
165
+ ...(limit !== undefined ? { limit } : {}),
166
+ };
167
+ const ask = asker(opts.api);
168
+ let res;
169
+ try {
170
+ res = opts.all
171
+ ? await mediaListAllWith((r, d) => ask(r, d), req)
172
+ : (await ask('media:list', req));
173
+ }
174
+ catch (e) {
175
+ return fail(e instanceof Error ? e.message : String(e));
176
+ }
177
+ if (jsonMode(sub))
178
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
179
+ else if (res.ok !== false)
180
+ renderList(res);
181
+ if (res.ok === false)
182
+ fail(res.error ?? 'media:list failed');
183
+ });
184
+ cmd
185
+ .command('upload <path>')
186
+ .description('Upload a LOCAL image file (media:upload) — read, sized against the 5 MiB cap, base64 encoded. ' +
187
+ 'For a remote URL: one ask media:upload --data \'{"url":"https://…"}\'')
188
+ .option('--workspace <slug>', 'Group slug to write (default: your own). A workspace you may not write is REFUSED, never downgraded.')
189
+ .option('--content-type <ct>', 'A HINT only — the stored type is decided by the magic bytes')
190
+ .option('--filename <name>', 'A LABEL for the key, not a path (default: the basename). The extension always comes from the sniffed bytes.')
191
+ .option('--api <url>', 'API base URL', DEFAULT_API)
192
+ .option('--json', 'Print the raw response')
193
+ .action(async (path, opts, sub) => {
194
+ let size;
195
+ try {
196
+ const st = statSync(path);
197
+ if (!st.isFile())
198
+ return fail(`${path} is not a file`);
199
+ size = st.size;
200
+ }
201
+ catch (e) {
202
+ return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
203
+ }
204
+ if (size === 0)
205
+ return fail(`${path} is empty`);
206
+ const ext = extname(path).toLowerCase();
207
+ if (VIDEO_EXT.has(ext)) {
208
+ // Not a policy this CLI invented — media:upload declares "video is not
209
+ // accepted here" and names the door that does. Refusing locally spends no
210
+ // request and points at the right one.
211
+ return fail(`${path} is video, and media:upload takes raster images only. Nothing was sent. ` +
212
+ 'There is no receiver for video yet — the streamed door is PUT /api/media/video-upload (100 MB).');
213
+ }
214
+ if (ext === '.svg') {
215
+ return fail(`${path} is SVG, which media:upload refuses deliberately (the public reader serves the stored type verbatim). Nothing was sent.`);
216
+ }
217
+ if (size > UPLOAD_MAX_BYTES) {
218
+ return fail(`${path} is ${human(size)} — media:upload caps at ${human(UPLOAD_MAX_BYTES)}. Nothing was sent. ` +
219
+ 'Host the file and pass a URL instead: one ask media:upload --data \'{"url":"https://…"}\'');
220
+ }
221
+ const contentType = opts.contentType ?? CONTENT_TYPES[ext];
222
+ let base64;
223
+ try {
224
+ base64 = readFileSync(path).toString('base64');
225
+ }
226
+ catch (e) {
227
+ return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
228
+ }
229
+ const data = {
230
+ base64,
231
+ filename: opts.filename ?? basename(path, ext),
232
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
233
+ ...(contentType ? { contentType } : {}),
234
+ };
235
+ let res;
236
+ try {
237
+ // 30s is the ask door's own ceiling, and a 5 MiB body measured 6.6s wall to prod.
238
+ res = (await asker(opts.api)('media:upload', data, 30_000));
239
+ }
240
+ catch (e) {
241
+ return fail(e instanceof Error ? e.message : String(e));
242
+ }
243
+ if (jsonMode(sub)) {
244
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
245
+ }
246
+ else if (res.ok !== false) {
247
+ // The `key` is the receipt: it names the workspace prefix the bytes ACTUALLY
248
+ // reached. Printed always, so a --workspace upload can never merely look right.
249
+ process.stdout.write(`ok key=${res.key ?? '?'} kind=${res.kind ?? '?'} type=${res.contentType ?? '?'} stored=${human(res.size)} sent=${human(size)}\n` +
250
+ ` ${res.url ?? ''}\n`);
251
+ }
252
+ if (res.ok === false)
253
+ fail(res.error ?? 'media:upload failed');
254
+ });
255
+ return cmd;
256
+ }
package/dist/src/skill.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Command } from 'commander';
2
+ import { KEY_FILE } from './lib/paths.js';
2
3
  import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, readdirSync } from 'node:fs';
3
4
  import { resolve, basename, join } from 'node:path';
4
- import { homedir } from 'node:os';
5
5
  import { parse as parseSkill } from './skill-parser.js';
6
6
  import { askPath } from './lib/api-path.js';
7
7
  export function skillCmd() {
@@ -78,7 +78,7 @@ export function skillCmd() {
78
78
  .option('--name <name>', 'Override skill name')
79
79
  .option('--yes', 'Skip approval prompt (CI-friendly)')
80
80
  .action(async (ref, opts) => {
81
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
81
+ const keyFile = KEY_FILE;
82
82
  const token = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
83
83
  if (!token) {
84
84
  out(cmd, { ok: false, error: 'not authenticated — run `oneie auth login`' });
@@ -151,7 +151,7 @@ export function skillCmd() {
151
151
  out(cmd, { ok: false, error: `invalid skill name "${name}" — lowercase alphanumeric and hyphens only` });
152
152
  return;
153
153
  }
154
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
154
+ const keyFile = KEY_FILE;
155
155
  const key = process.env.ONE_API_KEY ?? process.env.ONEIE_API_KEY
156
156
  ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
157
157
  if (!key) {
@@ -191,7 +191,7 @@ export function skillCmd() {
191
191
  .requiredOption('--slug <slug>', 'Workspace slug')
192
192
  .option('--api <url>', 'API base URL', 'https://one.ie')
193
193
  .action(async (name, opts) => {
194
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
194
+ const keyFile = KEY_FILE;
195
195
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
196
196
  if (!key) {
197
197
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
@@ -227,7 +227,7 @@ export function skillCmd() {
227
227
  .requiredOption('--slug <slug>', 'Workspace slug')
228
228
  .option('--api <url>', 'API base URL', 'https://one.ie')
229
229
  .action(async (opts) => {
230
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
230
+ const keyFile = KEY_FILE;
231
231
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
232
232
  if (!key) {
233
233
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
@@ -254,7 +254,7 @@ export function skillCmd() {
254
254
  .requiredOption('--slug <slug>', 'Workspace slug')
255
255
  .option('--api <url>', 'API base URL', 'https://one.ie')
256
256
  .action(async (name, opts) => {
257
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
257
+ const keyFile = KEY_FILE;
258
258
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
259
259
  if (!key) {
260
260
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
@@ -341,7 +341,7 @@ export function skillCmd() {
341
341
  out(cmd, { ok: false, error: `not found: ${path}` });
342
342
  return;
343
343
  }
344
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
344
+ const keyFile = KEY_FILE;
345
345
  const token = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
346
346
  if (!token) {
347
347
  out(cmd, { ok: false, error: 'not authenticated — run `oneie auth login`' });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function tasksCmd(): Command;