@oneie/cli 5.2.1 → 5.3.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,73 @@
1
+ // tasks-workspace — A tid carries no workspace, so the board row is the only place a client can learn it; the receiver accepts a per-edit workspace override.
2
+ import { boardAllWith } from '@oneie/sdk/tasks-bulk';
3
+ export function workspaceSpread(rows) {
4
+ const counts = {};
5
+ for (const row of rows) {
6
+ counts[row.workspace] = (counts[row.workspace] ?? 0) + 1;
7
+ }
8
+ return counts;
9
+ }
10
+ export function spreadWarning(spread) {
11
+ const keys = Object.keys(spread);
12
+ if (keys.length < 2)
13
+ return undefined;
14
+ const n = keys.length;
15
+ const pairs = keys
16
+ .sort((a, b) => {
17
+ const diff = spread[b] - spread[a];
18
+ if (diff !== 0)
19
+ return diff;
20
+ return a.localeCompare(b);
21
+ })
22
+ .map((k) => `${k}=${spread[k]}`)
23
+ .join(' ');
24
+ return `warning this read spans ${n} workspaces (${pairs}) — an edit sent with one --workspace answers not_found for rows in the others; tasks bulk resolves each row's own`;
25
+ }
26
+ export function fillEditWorkspaces(edits, rows) {
27
+ const rowMap = new Map();
28
+ for (const row of rows) {
29
+ rowMap.set(row.tid, row);
30
+ }
31
+ const resultEdits = [];
32
+ let filled = 0;
33
+ const unknown = [];
34
+ for (const edit of edits) {
35
+ if (edit.workspace && edit.workspace.length > 0) {
36
+ resultEdits.push(edit);
37
+ }
38
+ else {
39
+ const row = rowMap.get(edit.tid);
40
+ if (row) {
41
+ resultEdits.push({ ...edit, workspace: row.workspace });
42
+ filled++;
43
+ }
44
+ else {
45
+ resultEdits.push(edit);
46
+ unknown.push(edit.tid);
47
+ }
48
+ }
49
+ }
50
+ return { edits: resultEdits, filled, unknown };
51
+ }
52
+ export async function resolveBulkWorkspaces(ask, req) {
53
+ const missingWorkspace = req.edits?.some((e) => !e.workspace || e.workspace.length === 0);
54
+ if (!missingWorkspace) {
55
+ return { ok: true, req, filled: 0, unknown: [] };
56
+ }
57
+ const boardReq = {
58
+ ...(req.workspace ? { workspace: req.workspace } : {}),
59
+ scope: 'tree',
60
+ status: 'all',
61
+ limit: 2000,
62
+ };
63
+ const res = await boardAllWith(ask, boardReq);
64
+ if (res.ok === false) {
65
+ return {
66
+ ok: false,
67
+ error: `could not read the board to resolve each edit's workspace: ${res.error ?? 'tasks:board failed'} — nothing sent`,
68
+ };
69
+ }
70
+ const tasks = res.tasks ?? [];
71
+ const f = fillEditWorkspaces(req.edits, tasks);
72
+ return { ok: true, req: { ...req, edits: f.edits }, filled: f.filled, unknown: f.unknown };
73
+ }
@@ -0,0 +1,25 @@
1
+ export declare function usd(credits: number | undefined): string | null;
2
+ interface Usage {
3
+ model?: string;
4
+ tokensIn?: number;
5
+ tokensOut?: number;
6
+ costCredits?: number;
7
+ unmetered?: true;
8
+ }
9
+ interface Frontier {
10
+ model?: string;
11
+ usd?: number;
12
+ }
13
+ interface Reply {
14
+ text?: string;
15
+ model?: string;
16
+ picked?: string;
17
+ shape?: string;
18
+ reason?: string;
19
+ usage?: Usage;
20
+ frontier?: Frontier;
21
+ }
22
+ export declare function renderReceipt(reply: Reply, opts?: {
23
+ slug?: string;
24
+ }): string;
25
+ export {};
@@ -0,0 +1,71 @@
1
+ /* Message receipt — no imports */
2
+ // Up to 6 significant digits, never scientific: a measured $0.00000042 never prints as $0.
3
+ function formatDollar(n) {
4
+ return n.toLocaleString('en-US', { maximumSignificantDigits: 6, useGrouping: false });
5
+ }
6
+ export function usd(credits) {
7
+ if (typeof credits !== 'number' || !isFinite(credits) || credits < 0) {
8
+ return null;
9
+ }
10
+ const dollars = credits / 1000;
11
+ // A positive figure below what a float can divide down to is still not $0.
12
+ if (credits > 0 && !(dollars > 0))
13
+ return 'under $0.000001';
14
+ return '$' + formatDollar(dollars);
15
+ }
16
+ export function renderReceipt(reply, opts = {}) {
17
+ const model = reply.model ?? reply.usage?.model ?? 'unmeasured';
18
+ const reason = reply.reason === 'cold'
19
+ ? 'cold'
20
+ : reply.reason
21
+ ? 'warmed'
22
+ : 'unmeasured';
23
+ const shape = reply.shape ?? 'unmeasured';
24
+ // tokens line
25
+ const tokensLine = reply.usage &&
26
+ typeof reply.usage.tokensIn === 'number' &&
27
+ typeof reply.usage.tokensOut === 'number'
28
+ ? `${reply.usage.tokensIn} in / ${reply.usage.tokensOut} out`
29
+ : 'unmeasured';
30
+ // cost line
31
+ let costLine;
32
+ if (!reply.usage ||
33
+ reply.usage.unmetered ||
34
+ typeof reply.usage.costCredits !== 'number') {
35
+ costLine = 'unmeasured';
36
+ }
37
+ else {
38
+ const usdStr = usd(reply.usage.costCredits);
39
+ if (usdStr === null) {
40
+ costLine = 'unmeasured';
41
+ }
42
+ else {
43
+ costLine = `${usdStr} est. (measured tokens × registry price)`;
44
+ }
45
+ }
46
+ // billed line
47
+ const slug = opts.slug ?? '<your-group>';
48
+ const billedLine = `billed pending → https://one.ie/u/${slug}/stream`;
49
+ // frontier line
50
+ let frontierLine;
51
+ if (reply.frontier &&
52
+ typeof reply.frontier.usd === 'number' &&
53
+ isFinite(reply.frontier.usd) &&
54
+ reply.frontier.usd > 0) {
55
+ const frontierDollar = reply.frontier.usd;
56
+ const frontierUsdStr = '$' + formatDollar(frontierDollar);
57
+ frontierLine = `at ${reply.frontier.model ?? 'model'} list price: ${frontierUsdStr}`;
58
+ }
59
+ else {
60
+ frontierLine = 'at frontier list price: unmeasured';
61
+ }
62
+ const dashLine = '\u2014'.repeat(3); // three em dashes
63
+ const lines = [
64
+ `model ${model} \u00b7 ${reason} (shape ${shape})`,
65
+ `tokens ${tokensLine}`,
66
+ `cost ${costLine}`,
67
+ billedLine,
68
+ frontierLine,
69
+ ];
70
+ return dashLine + '\n' + lines.join('\n');
71
+ }
@@ -0,0 +1,13 @@
1
+ export declare const MESSAGE_TIMEOUT_MS = 30000;
2
+ export declare const SIGN_IN = "not signed in \u2014 run: npx oneie login";
3
+ export interface MessageIO {
4
+ fetch: typeof fetch;
5
+ key: string;
6
+ base: string;
7
+ stdout: (s: string) => void;
8
+ stderr: (s: string) => void;
9
+ }
10
+ export declare function sendMessage(text: string, io: MessageIO, opts?: {
11
+ json?: boolean;
12
+ }): Promise<number>;
13
+ export declare function bareMessageArgv(argv: string[], known: ReadonlySet<string>): string[];
@@ -0,0 +1,92 @@
1
+ import { askPath } from './lib/api-path.js';
2
+ import { renderReceipt } from './message-receipt.js';
3
+ export const MESSAGE_TIMEOUT_MS = 30000;
4
+ export const SIGN_IN = 'not signed in — run: npx oneie login';
5
+ export async function sendMessage(text, io, opts = {}) {
6
+ const trimmed = text.trim();
7
+ if (!trimmed) {
8
+ io.stderr('usage: oneie message <text...>');
9
+ return 2;
10
+ }
11
+ if (!io.key) {
12
+ io.stderr(SIGN_IN);
13
+ return 1;
14
+ }
15
+ const url = askPath(io.base, 'world:route');
16
+ let response;
17
+ try {
18
+ response = await io.fetch(url, {
19
+ method: 'POST',
20
+ headers: {
21
+ 'Content-Type': 'application/json',
22
+ Authorization: 'Bearer ' + io.key,
23
+ },
24
+ body: JSON.stringify({
25
+ data: { text: trimmed, reply: true, deliver: false },
26
+ timeoutMs: MESSAGE_TIMEOUT_MS,
27
+ }),
28
+ });
29
+ }
30
+ catch (err) {
31
+ io.stderr(`could not reach ${io.base}: ${err instanceof Error ? err.message : String(err)}`);
32
+ return 1;
33
+ }
34
+ // Check HTTP 401/403 FIRST before parsing body
35
+ if (response.status === 401 || response.status === 403) {
36
+ io.stderr(SIGN_IN);
37
+ return 1;
38
+ }
39
+ let body;
40
+ try {
41
+ body = await response.json();
42
+ }
43
+ catch {
44
+ body = {};
45
+ }
46
+ // Treat null or non-object body as failure
47
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
48
+ io.stderr('no answer');
49
+ return 1;
50
+ }
51
+ // Body-level forbidden/unauthor check (redundant for 401/403 but catches 200 with forbidden)
52
+ const isForbidden = (body.error &&
53
+ (typeof body.error === 'string'
54
+ ? /forbidden|unauthor/i.test(body.error)
55
+ : /forbidden|unauthor/i.test(body.error.message || ''))) ||
56
+ (body.result?.error &&
57
+ /forbidden|unauthor/i.test(typeof body.result.error === 'string'
58
+ ? body.result.error
59
+ : body.result.error.message || ''));
60
+ if (isForbidden) {
61
+ io.stderr(SIGN_IN);
62
+ return 1;
63
+ }
64
+ if (body.outcome === 'timeout') {
65
+ io.stderr('no answer within 30s — the reply is still running; see https://one.ie/u/<you>/stream');
66
+ return 1;
67
+ }
68
+ const reply = body.result?.reply;
69
+ if (opts.json) {
70
+ const output = JSON.stringify(reply ?? body.result ?? body, null, 2) + '\n';
71
+ io.stdout(output);
72
+ return reply?.text ? 0 : 1;
73
+ }
74
+ const answer = reply?.text;
75
+ if (!answer) {
76
+ const replyError = reply?.error;
77
+ const resultError = body.result?.error;
78
+ const bodyError = body.error;
79
+ const errMsg = replyError || resultError || bodyError || '';
80
+ io.stderr(errMsg ? `no answer: ${errMsg}` : 'no answer');
81
+ return 1;
82
+ }
83
+ io.stdout(answer + '\n');
84
+ io.stdout(renderReceipt(reply) + '\n');
85
+ return 0;
86
+ }
87
+ export function bareMessageArgv(argv, known) {
88
+ if (argv[2] !== undefined && !argv[2].startsWith('-') && !known.has(argv[2])) {
89
+ return [argv[0], argv[1], 'message', ...argv.slice(2)];
90
+ }
91
+ return argv;
92
+ }
@@ -1,5 +1,6 @@
1
- import { authHeaders, resolveBase } from './lib/client.js';
1
+ import { authHeaders, resolveBase, resolveKey } from './lib/client.js';
2
2
  import { askPath } from './lib/api-path.js';
3
+ import { sendMessage } from './message.js';
3
4
  const DEFAULT_API = resolveBase({}, 'https://api.one.ie');
4
5
  function base(opts) {
5
6
  return resolveBase(opts, 'https://api.one.ie');
@@ -68,6 +69,18 @@ export function substrateCommands(program) {
68
69
  body: JSON.stringify({ data, timeoutMs: Number(opts.timeout) }),
69
70
  }));
70
71
  });
72
+ program
73
+ .command('message <text...>')
74
+ .description('Say anything — the router picks who answers, the answer prints here')
75
+ .option('--json', 'Print the whole reply as JSON')
76
+ .option('--api <url>', 'API base URL', DEFAULT_API)
77
+ .action(async (words, opts) => {
78
+ const code = await sendMessage(words.join(' '), {
79
+ fetch, key: resolveKey(), base: base(opts),
80
+ stdout: (s) => process.stdout.write(s), stderr: (s) => process.stderr.write(s + '\n'),
81
+ }, { json: opts.json });
82
+ process.exit(code);
83
+ });
71
84
  program
72
85
  .command('mark <edge>')
73
86
  .description('Strengthen a path. Edge format: source>target')
@@ -125,7 +138,8 @@ export function substrateCommands(program) {
125
138
  .option('--exploration <n>', 'Exploration factor 0–1')
126
139
  .option('--api <url>', 'API base URL', DEFAULT_API)
127
140
  .action(async (type, opts) => {
128
- const q = new URLSearchParams({ type });
141
+ // The route reads `tag` (api/select.ts:11); sending `type` was silently ignored.
142
+ const q = new URLSearchParams({ tag: type });
129
143
  if (opts.exploration)
130
144
  q.set('exploration', opts.exploration);
131
145
  out(await api(`${base(opts)}/api/select?${q}`));