oneie 5.5.1 → 5.6.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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oneie",
3
- "version": "5.5.1",
3
+ "version": "5.6.0",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,77 @@
1
+ /**
2
+ * key-sweep.ts — `one key sweep-rule | sweep | sweep-run`, the terminal halves of
3
+ * text/key.md deliverable 8 under Tony's ruling (2026-10-06): "the sweep is
4
+ * signed by the human who owns the agent; agents can be claimed by any owner."
5
+ *
6
+ * sweep-rule OWNER. Proves the owner's address (a signature over a fresh
7
+ * wallet:challenge) and sets the agent's threshold + float.
8
+ * sweep OWNER. Reads what is due, signs an ORDER with the owner's
9
+ * address key, and submits it to wallet:sweep, which records it.
10
+ * sweep-run AGENT. Reads its open orders, re-verifies each locally, performs
11
+ * the transfer with the agent's own key and settles it
12
+ * (@oneie/sdk/sweep-runner). Sui only; other chains are refused by
13
+ * name, because no signer for them exists here.
14
+ *
15
+ * KEYS come from the folder's sealed vault (`.one/wallet.json`) through
16
+ * wallet.ts `unlock` — Keychain or a passphrase typed at a terminal, never argv,
17
+ * env or a pipe. Nothing here prints, logs or sends a private key or the words:
18
+ * only addresses, signatures and the public order cross the wire, and every
19
+ * receipt is built field by field.
20
+ *
21
+ * THE NEW SDK MODULES LOAD LAZILY. key.ts registers these commands, so a static
22
+ * import of `@oneie/sdk/sweep-runner` would make every `one key` verb — `key new`
23
+ * included — crash on an installed SDK that predates that export. Only the three
24
+ * sweep actions reach for it, at the moment they run.
25
+ */
26
+ import { Command } from 'commander';
27
+ import type { SweepOrderChain } from '@oneie/sdk/sweep-order';
28
+ import type { SweepAsk, SweepTransfer } from '@oneie/sdk/sweep-runner';
29
+ /** The order lives 10 minutes: inside the server's 15-minute cap, with room for the agent's 2-minute floor. */
30
+ export declare const ORDER_LIFETIME_MS: number;
31
+ type VaultKey = {
32
+ chain: string;
33
+ address: string;
34
+ privateKeyHex: string;
35
+ };
36
+ export interface SweepDeps {
37
+ ask: SweepAsk;
38
+ /** The folder's vault, opened for this one act. */
39
+ unlock: () => Promise<{
40
+ keys: VaultKey[];
41
+ } | {
42
+ error: string;
43
+ }>;
44
+ /** The agent's balance in base units, read from the chain; null = could not read. */
45
+ readBalance?: (address: string) => Promise<string | null>;
46
+ now?: () => number;
47
+ }
48
+ /** One receiver call through the ask door; answers the receiver's own result. */
49
+ export declare function askVia(base: string, fetchImpl?: typeof fetch): SweepAsk;
50
+ /** Sui balance in mist via suix_getBalance — `totalBalance` is already base units. */
51
+ export declare function suiBalanceReader(rpcUrl: string, fetchImpl?: typeof fetch): (address: string) => Promise<string | null>;
52
+ export declare function ownerSweepRule(args: {
53
+ agent: string;
54
+ workspace: string;
55
+ chain: SweepOrderChain;
56
+ threshold: string;
57
+ float: string;
58
+ }, deps: SweepDeps): Promise<Record<string, unknown>>;
59
+ export declare function ownerSweep(args: {
60
+ agent: string;
61
+ workspace: string;
62
+ chain: SweepOrderChain;
63
+ amount?: string;
64
+ balance?: string;
65
+ }, deps: SweepDeps): Promise<Record<string, unknown>>;
66
+ export declare function agentSweepRun(args: {
67
+ agent: string;
68
+ workspace: string;
69
+ chain: SweepOrderChain;
70
+ rpc?: string;
71
+ network?: 'mainnet' | 'testnet';
72
+ ownerAddress?: string;
73
+ }, deps: SweepDeps & {
74
+ transfer?: Partial<Record<SweepOrderChain, SweepTransfer>>;
75
+ }): Promise<Record<string, unknown>>;
76
+ export declare function keySweepCommands(): Command[];
77
+ export {};
@@ -0,0 +1,220 @@
1
+ /**
2
+ * key-sweep.ts — `one key sweep-rule | sweep | sweep-run`, the terminal halves of
3
+ * text/key.md deliverable 8 under Tony's ruling (2026-10-06): "the sweep is
4
+ * signed by the human who owns the agent; agents can be claimed by any owner."
5
+ *
6
+ * sweep-rule OWNER. Proves the owner's address (a signature over a fresh
7
+ * wallet:challenge) and sets the agent's threshold + float.
8
+ * sweep OWNER. Reads what is due, signs an ORDER with the owner's
9
+ * address key, and submits it to wallet:sweep, which records it.
10
+ * sweep-run AGENT. Reads its open orders, re-verifies each locally, performs
11
+ * the transfer with the agent's own key and settles it
12
+ * (@oneie/sdk/sweep-runner). Sui only; other chains are refused by
13
+ * name, because no signer for them exists here.
14
+ *
15
+ * KEYS come from the folder's sealed vault (`.one/wallet.json`) through
16
+ * wallet.ts `unlock` — Keychain or a passphrase typed at a terminal, never argv,
17
+ * env or a pipe. Nothing here prints, logs or sends a private key or the words:
18
+ * only addresses, signatures and the public order cross the wire, and every
19
+ * receipt is built field by field.
20
+ *
21
+ * THE NEW SDK MODULES LOAD LAZILY. key.ts registers these commands, so a static
22
+ * import of `@oneie/sdk/sweep-runner` would make every `one key` verb — `key new`
23
+ * included — crash on an installed SDK that predates that export. Only the three
24
+ * sweep actions reach for it, at the moment they run.
25
+ */
26
+ import { Command } from 'commander';
27
+ import { addressProofMessage, signAddressProof } from '@oneie/sdk/address-proof';
28
+ import { authHeaders, out, resolveBase } from './lib/client.js';
29
+ import { askPath } from './lib/api-path.js';
30
+ import { unlock } from './wallet.js';
31
+ /** The vault's chain spelling for each sweep chain. */
32
+ const VAULT_CHAIN = { sui: 'sui', evm: 'evm', solana: 'sol', btc: 'btc' };
33
+ const isSweepChain = (c) => Object.prototype.hasOwnProperty.call(VAULT_CHAIN, c);
34
+ const digits = (v) => typeof v === 'string' && /^\d+$/.test(v);
35
+ /** The order lives 10 minutes: inside the server's 15-minute cap, with room for the agent's 2-minute floor. */
36
+ export const ORDER_LIFETIME_MS = 10 * 60 * 1000;
37
+ const runnerModule = () => import('@oneie/sdk/sweep-runner');
38
+ /** One receiver call through the ask door; answers the receiver's own result. */
39
+ export function askVia(base, fetchImpl = fetch) {
40
+ return async (receiver, data) => {
41
+ try {
42
+ const res = await fetchImpl(askPath(base.replace(/\/$/, ''), receiver), {
43
+ method: 'POST', headers: authHeaders(), body: JSON.stringify({ data }),
44
+ });
45
+ const body = (await res.json().catch(() => ({})));
46
+ if (body.outcome !== 'result')
47
+ return { ok: false, error: String(body.error ?? body.outcome ?? `HTTP ${res.status}`) };
48
+ return body.result ?? { ok: false, error: 'no result' };
49
+ }
50
+ catch (e) {
51
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
52
+ }
53
+ };
54
+ }
55
+ /** Sui balance in mist via suix_getBalance — `totalBalance` is already base units. */
56
+ export function suiBalanceReader(rpcUrl, fetchImpl = fetch) {
57
+ return async (address) => {
58
+ try {
59
+ const res = await fetchImpl(rpcUrl, {
60
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
61
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'suix_getBalance', params: [address, '0x2::sui::SUI'] }),
62
+ });
63
+ const json = (await res.json());
64
+ const v = json.result?.totalBalance;
65
+ return digits(v) ? v : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ };
71
+ }
72
+ function keyFor(keys, chain, address) {
73
+ const want = VAULT_CHAIN[chain];
74
+ const k = keys.find((x) => x.chain === want && (address === undefined || x.address.toLowerCase() === address.toLowerCase()));
75
+ return k ?? null;
76
+ }
77
+ // ── owner: prove the address, set the rule ─────────────────────────────────
78
+ export async function ownerSweepRule(args, deps) {
79
+ if (!digits(args.threshold) || !digits(args.float))
80
+ return { ok: false, error: 'threshold and float are integer base units' };
81
+ const opened = await deps.unlock();
82
+ if ('error' in opened)
83
+ return { ok: false, error: opened.error };
84
+ const key = keyFor(opened.keys, args.chain);
85
+ if (!key)
86
+ return { ok: false, error: `the vault holds no ${args.chain} key` };
87
+ // workspace = actor = the caller: the challenge binds to the owner itself.
88
+ const ch = await deps.ask('wallet:challenge', {});
89
+ if (ch['ok'] !== true || typeof ch['challenge'] !== 'string')
90
+ return { ok: false, error: `wallet:challenge — ${String(ch['error'] ?? 'no challenge')}` };
91
+ const message = addressProofMessage({
92
+ challenge: ch['challenge'], workspace: String(ch['workspace']), actor: String(ch['actor']), chain: args.chain, address: key.address,
93
+ });
94
+ const proof = signAddressProof(args.chain, key.privateKeyHex, message);
95
+ const res = await deps.ask('wallet:sweep-set', {
96
+ workspace: args.workspace, actor: args.agent, chain: args.chain,
97
+ threshold: args.threshold, float: args.float, address: key.address, challenge: ch['challenge'], proof,
98
+ });
99
+ if (res['ok'] !== true)
100
+ return { ok: false, error: String(res['error'] ?? 'wallet:sweep-set refused') };
101
+ return { ok: true, agent: args.agent, chain: args.chain, owner: res['owner'], ownerAddress: res['ownerAddress'], thresholdUnits: res['thresholdUnits'], floatUnits: res['floatUnits'] };
102
+ }
103
+ // ── owner: sign and submit an order ────────────────────────────────────────
104
+ export async function ownerSweep(args, deps) {
105
+ const now = deps.now ?? (() => Date.now());
106
+ const base = { workspace: args.workspace, actor: args.agent, chain: args.chain };
107
+ const pending = await deps.ask('wallet:sweep', { ...base, pending: true });
108
+ if (pending['ok'] !== true)
109
+ return { ok: false, error: String(pending['error'] ?? 'wallet:sweep refused') };
110
+ const to = String(pending['to'] ?? '');
111
+ const agentAddress = String(pending['agentAddress'] ?? '');
112
+ let balance = args.balance;
113
+ if (balance === undefined) {
114
+ if (!deps.readBalance)
115
+ return { ok: false, error: 'pass --balance <base units>, or --rpc <url> to read it (sui only)' };
116
+ const read = await deps.readBalance(agentAddress);
117
+ if (read === null)
118
+ return { ok: false, error: 'could not read the agent balance — pass --balance' };
119
+ balance = read;
120
+ }
121
+ if (!digits(balance))
122
+ return { ok: false, error: '--balance is integer base units' };
123
+ const due = await deps.ask('wallet:sweep', { ...base, balance });
124
+ if (due['ok'] !== true)
125
+ return { ok: false, error: String(due['error'] ?? 'wallet:sweep refused') };
126
+ if (due['due'] !== true)
127
+ return { ok: true, due: false, balanceUnits: balance, thresholdUnits: due['thresholdUnits'], note: 'nothing to sweep — the balance is at or below the threshold' };
128
+ const max = BigInt(String(due['maxUnits']));
129
+ if (args.amount !== undefined && !digits(args.amount))
130
+ return { ok: false, error: '--amount is integer base units' };
131
+ const amount = args.amount !== undefined ? BigInt(args.amount) : max;
132
+ if (amount <= 0n || amount > max)
133
+ return { ok: false, error: `--amount must be in (0, ${max}] — balance minus float` };
134
+ const opened = await deps.unlock();
135
+ if ('error' in opened)
136
+ return { ok: false, error: opened.error };
137
+ const key = keyFor(opened.keys, args.chain, to);
138
+ if (!key)
139
+ return { ok: false, error: 'this vault does not hold the address you proved for sweeps — open the vault that does, or re-prove with `key sweep-rule`' };
140
+ const { newOrderNonce, signSweepOrder } = await runnerModule();
141
+ const { ORDER_MAX_TTL_MS } = await import('@oneie/sdk/sweep-order');
142
+ if (ORDER_LIFETIME_MS > ORDER_MAX_TTL_MS)
143
+ return { ok: false, error: 'order lifetime exceeds the server cap' };
144
+ const order = { ...base, destination: to, amount, nonce: newOrderNonce(), expiresAt: now() + ORDER_LIFETIME_MS };
145
+ const signature = signSweepOrder(key.privateKeyHex, order);
146
+ const res = await deps.ask('wallet:sweep', {
147
+ ...base, balance,
148
+ order: { destination: order.destination, amount: order.amount.toString(), nonce: order.nonce, expiresAt: order.expiresAt },
149
+ signature,
150
+ });
151
+ if (res['verified'] !== true)
152
+ return { ok: false, error: String(res['error'] ?? 'order not verified') };
153
+ return { ok: true, verified: true, agent: args.agent, chain: args.chain, to, amountUnits: order.amount.toString(), nonce: order.nonce, expiresAt: order.expiresAt, next: 'the agent runtime performs it: one key sweep-run' };
154
+ }
155
+ // ── agent: perform and settle ──────────────────────────────────────────────
156
+ export async function agentSweepRun(args, deps) {
157
+ const { runSweepOrders, suiTransfer } = await runnerModule();
158
+ const opened = await deps.unlock();
159
+ if ('error' in opened)
160
+ return { ok: false, error: opened.error };
161
+ const key = keyFor(opened.keys, args.chain);
162
+ if (!key)
163
+ return { ok: false, error: `the vault holds no ${args.chain} key` };
164
+ let transfer = deps.transfer;
165
+ if (!transfer && args.chain === 'sui') {
166
+ if (!args.rpc || !args.network)
167
+ return { ok: false, error: 'pass --rpc <url> and --network mainnet|testnet' };
168
+ transfer = { sui: suiTransfer({ rpcUrl: args.rpc, network: args.network }) };
169
+ }
170
+ const res = await runSweepOrders({ workspace: args.workspace, actor: args.agent, chain: args.chain, agentKey: { address: key.address, privateKeyHex: key.privateKeyHex }, ownerAddress: args.ownerAddress }, { ask: deps.ask, transfer, now: deps.now });
171
+ return { ok: res.ok, ...(res.error ? { error: res.error } : {}), agent: args.agent, chain: args.chain, results: res.results };
172
+ }
173
+ function common(c) {
174
+ return c
175
+ .requiredOption('--agent <id>', "The agent's actor id")
176
+ .option('--workspace <slug>', "The workspace that holds the agent's wallet (default: the agent id)")
177
+ .option('--chain <chain>', 'sui | evm | solana | btc', 'sui')
178
+ .option('--dir <path>', 'The folder whose sealed vault (.one/wallet.json) holds the key', '.')
179
+ .option('--api <url>', 'API base URL (default https://one.ie)');
180
+ }
181
+ function depsFor(o) {
182
+ return { ask: askVia(resolveBase({ api: o.api }, 'https://one.ie')), unlock: () => unlock(o.dir) };
183
+ }
184
+ export function keySweepCommands() {
185
+ const rule = common(new Command('sweep-rule'))
186
+ .description("OWNER — prove your address and set an agent's sweep threshold + float (base units)")
187
+ .requiredOption('--threshold <units>', 'A sweep is due when the balance is above this')
188
+ .requiredOption('--float <units>', 'What the agent keeps after a sweep')
189
+ .action(async (o, c) => {
190
+ if (!isSweepChain(o.chain))
191
+ return out(c, { ok: false, error: '--chain must be sui, evm, solana or btc' });
192
+ out(c, await ownerSweepRule({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, threshold: o.threshold, float: o.float }, depsFor(o)));
193
+ });
194
+ const sweep = common(new Command('sweep'))
195
+ .description("OWNER — sign a sweep order for what is due and submit it; the agent's runtime performs it")
196
+ .option('--amount <units>', 'Base units to sweep (default: everything above the float)')
197
+ .option('--balance <units>', "The agent's balance in base units (else read via --rpc, sui only)")
198
+ .option('--rpc <url>', 'Sui RPC to read the balance from')
199
+ .action(async (o, c) => {
200
+ if (!isSweepChain(o.chain))
201
+ return out(c, { ok: false, error: '--chain must be sui, evm, solana or btc' });
202
+ const deps = depsFor(o);
203
+ if (o.rpc && o.chain === 'sui')
204
+ deps.readBalance = suiBalanceReader(o.rpc);
205
+ out(c, await ownerSweep({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, amount: o.amount, balance: o.balance }, deps));
206
+ });
207
+ const run = common(new Command('sweep-run'))
208
+ .description("AGENT — perform and settle the owner's open sweep orders with this agent's own key (sui)")
209
+ .option('--rpc <url>', 'Sui RPC to send the transfer through')
210
+ .option('--network <n>', 'mainnet | testnet')
211
+ .option('--owner-address <addr>', "Pin the owner's address; any other is refused")
212
+ .action(async (o, c) => {
213
+ if (!isSweepChain(o.chain))
214
+ return out(c, { ok: false, error: '--chain must be sui, evm, solana or btc' });
215
+ if (o.network !== undefined && o.network !== 'mainnet' && o.network !== 'testnet')
216
+ return out(c, { ok: false, error: '--network must be mainnet or testnet' });
217
+ out(c, await agentSweepRun({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, rpc: o.rpc, network: o.network, ownerAddress: o.ownerAddress }, depsFor(o)));
218
+ });
219
+ return [rule, sweep, run];
220
+ }
package/dist/src/key.js CHANGED
@@ -29,6 +29,7 @@ import { userIdPubFromPhrase } from '@oneie/sdk/key-identity';
29
29
  import { jsonMode, resolveBase, resolveKey } from './lib/client.js';
30
30
  import { promptSecret, writeKeysFile } from './wallet.js';
31
31
  import { wordsStdoutRefusal } from './lib/agent-env.js';
32
+ import { keySweepCommands } from './key-sweep.js';
32
33
  const REFUSE_ARGV_SECRET = 'A secret on the command line is refused on purpose: it is written to your shell history and is ' +
33
34
  'visible in `ps` to every user on this machine. Set ONE_WALLET_MNEMONIC or pipe the words on stdin.';
34
35
  const REFUSE_ARGV = 'Unrecognised argument. It is not repeated here on purpose — it may BE your recovery phrase. ' +
@@ -305,6 +306,10 @@ export function keyCmd() {
305
306
  if (verdict === 'mismatch')
306
307
  process.exitCode = 1;
307
308
  }));
309
+ // sweep-rule · sweep · sweep-run — the owner's and the agent's halves of the
310
+ // sweep (key-sweep.ts). Keys come from the folder's sealed vault, never argv.
311
+ for (const sub of keySweepCommands())
312
+ cmd.addCommand(sub);
308
313
  // `one key <token>`: commander would print "unknown command '<token>'" — and the
309
314
  // token may BE the first word of a phrase. Refuse it here without repeating it.
310
315
  cmd.argument('[refused...]').allowUnknownOption().action((rest, _opts, c) => {
@@ -45,8 +45,8 @@ export async function shopInit(deps, opts) {
45
45
  const seed = readEnvelope(seedEnv, 'pages:instantiate-shop-pack');
46
46
  if (!seed.ok)
47
47
  return { ...base, error: seed.error };
48
- // Today the receiver answers with ONE page; C9.1 answers with the whole pack.
49
- // Read both rather than making this command wait on that cycle.
48
+ // The receiver answers with all twelve role pages in `pages`; the bare `slug`
49
+ // (the home page) is the fallback for an older worker that predates them.
50
50
  const listed = Array.isArray(seed.result.pages) ? seed.result.pages : [];
51
51
  const pages = listed.map(p => p.slug).filter((s) => typeof s === 'string' && s.length > 0);
52
52
  if (!pages.length && seed.result.slug)
@@ -1,2 +1,14 @@
1
1
  import { Command } from 'commander';
2
+ /** The three containers PUT /api/media/video-upload sniffs. `.avi`/`.mkv` are
3
+ * refused locally — the door would store them, sniff them, and 415 after the
4
+ * whole upload; nothing is gained by sending 100 MB to learn that. */
5
+ export declare const VIDEO_CONTENT_TYPES: Record<string, string>;
6
+ /** The door's own ceiling (video-upload.ts MAX_BYTES) — refused before a byte is sent. */
7
+ export declare const VIDEO_MAX_BYTES: number;
8
+ /** The library hands back ROOT-RELATIVE urls. Meta, TikTok and every social
9
+ * platform fetch media by URL from their own servers, so the printed url is
10
+ * made absolute against the web host — the one form that works off this machine. */
11
+ export declare function absoluteUrl(base: string, url: string | undefined): string;
12
+ /** `{workspace}/media/{name}` — the receipt names where the bytes landed. */
13
+ export declare function workspaceOfKey(key: string | undefined): string;
2
14
  export declare function mediaCmd(): Command;
package/dist/src/media.js CHANGED
@@ -4,6 +4,7 @@ import { basename, extname } from 'node:path';
4
4
  import { mediaListAllWith } from '@oneie/sdk';
5
5
  import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
6
6
  import { askPath } from './lib/api-path.js';
7
+ import { webBase } from './lib/roster.js';
7
8
  // `one media` — the two media doors a JSON body cannot serve comfortably.
8
9
  //
9
10
  // WHAT IS DELIBERATELY NOT HERE, and why. The CLI already reaches every receiver:
@@ -36,6 +37,29 @@ const UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
36
37
  * spend a request on a value the zod schema will reject. */
37
38
  const PREFIXES = ['media', 'chat', 'ads', 'products', 'pages', 'brand', 'courses'];
38
39
  const VIDEO_EXT = new Set(['.mp4', '.webm', '.mov', '.m4v', '.avi', '.mkv']);
40
+ /** The three containers PUT /api/media/video-upload sniffs. `.avi`/`.mkv` are
41
+ * refused locally — the door would store them, sniff them, and 415 after the
42
+ * whole upload; nothing is gained by sending 100 MB to learn that. */
43
+ export const VIDEO_CONTENT_TYPES = {
44
+ '.mp4': 'video/mp4',
45
+ '.m4v': 'video/mp4',
46
+ '.webm': 'video/webm',
47
+ '.mov': 'video/quicktime',
48
+ };
49
+ /** The door's own ceiling (video-upload.ts MAX_BYTES) — refused before a byte is sent. */
50
+ export const VIDEO_MAX_BYTES = 100 * 1024 * 1024;
51
+ /** The library hands back ROOT-RELATIVE urls. Meta, TikTok and every social
52
+ * platform fetch media by URL from their own servers, so the printed url is
53
+ * made absolute against the web host — the one form that works off this machine. */
54
+ export function absoluteUrl(base, url) {
55
+ if (!url)
56
+ return '';
57
+ return /^https?:\/\//i.test(url) ? url : `${webBase(base).replace(/\/$/, '')}${url.startsWith('/') ? '' : '/'}${url}`;
58
+ }
59
+ /** `{workspace}/media/{name}` — the receipt names where the bytes landed. */
60
+ export function workspaceOfKey(key) {
61
+ return key ? key.split('/')[0] ?? '' : '';
62
+ }
39
63
  const CONTENT_TYPES = {
40
64
  '.png': 'image/png',
41
65
  '.jpg': 'image/jpeg',
@@ -134,6 +158,88 @@ function renderList(res) {
134
158
  w.write(`${it.key} ${it.kind} ${human(it.size)} ${it.contentType} ${it.uploaded ?? '-'}\n`);
135
159
  }
136
160
  }
161
+ /**
162
+ * PUT the file to the streamed video door. It lives on the WEB host, never the
163
+ * gateway: api.one.ie forwards receivers, not this route, so webBase() picks the
164
+ * host whatever --api says. 100 MB fits in memory here; reading it whole gives fetch
165
+ * a Content-Length, which lets the door refuse an oversized body before writing.
166
+ */
167
+ async function uploadVideo(api, path, contentType, workspace) {
168
+ const base = webBase(resolveBase({ api }, DEFAULT_API)).replace(/\/$/, '');
169
+ const qs = workspace ? `?workspace=${encodeURIComponent(workspace)}` : '';
170
+ const headers = { ...authHeaders(), 'Content-Type': contentType };
171
+ const res = await fetch(`${base}/api/media/video-upload${qs}`, {
172
+ method: 'PUT',
173
+ headers,
174
+ body: readFileSync(path),
175
+ });
176
+ const text = await res.text();
177
+ let body;
178
+ try {
179
+ body = text ? JSON.parse(text) : {};
180
+ }
181
+ catch {
182
+ throw new Error(`video-upload → ${res.status} ${text.slice(0, 200)}`);
183
+ }
184
+ if (!res.ok) {
185
+ const why = body.reason ?? body.error ?? text.slice(0, 200);
186
+ const hint = res.status === 401
187
+ ? ' — no valid key: run `one login`'
188
+ : res.status === 403
189
+ ? ` — your key may not write ${workspace ?? 'this workspace'}`
190
+ : '';
191
+ return { ok: false, error: `video-upload → ${res.status} ${why}${hint}` };
192
+ }
193
+ return { ...body, kind: 'video', workspace: body.workspace ?? workspaceOfKey(body.key) };
194
+ }
195
+ /** Draft a post carrying the uploaded media. Drafts only: the posts door refuses
196
+ * scheduledAt/status from a key, because a scheduled post publishes itself. */
197
+ async function draftPost(api, group, caption, platforms, mediaUrl, mediaType) {
198
+ const base = webBase(resolveBase({ api }, DEFAULT_API)).replace(/\/$/, '');
199
+ const res = await fetch(`${base}/api/social/posts`, {
200
+ method: 'POST',
201
+ headers: authHeaders(),
202
+ body: JSON.stringify({ groupId: group, content: caption, platforms, mediaUrl, mediaType }),
203
+ });
204
+ const text = await res.text();
205
+ if (!res.ok)
206
+ return { ok: false, error: `social/posts → ${res.status} ${text.slice(0, 200)}` };
207
+ try {
208
+ return { ok: true, id: JSON.parse(text).post?.id };
209
+ }
210
+ catch {
211
+ return { ok: false, error: `social/posts → ${res.status} unreadable body` };
212
+ }
213
+ }
214
+ async function finish(sub, res, sent, opts) {
215
+ if (res.ok === false) {
216
+ if (jsonMode(sub))
217
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
218
+ return fail(res.error ?? 'upload failed');
219
+ }
220
+ const url = absoluteUrl(resolveBase({ api: opts.api }, DEFAULT_API), res.url);
221
+ const workspace = res.workspace ?? workspaceOfKey(res.key);
222
+ let post;
223
+ if (opts.post) {
224
+ const platforms = opts.platforms.split(',').map((p) => p.trim()).filter(Boolean);
225
+ const mediaType = res.kind === 'video' || (res.contentType ?? '').startsWith('video/') ? 'video' : 'image';
226
+ post = await draftPost(opts.api, workspace, opts.post, platforms, url, mediaType);
227
+ }
228
+ const review = `${webBase(resolveBase({ api: opts.api }, DEFAULT_API)).replace(/\/$/, '')}/u/${workspace}/marketing/social`;
229
+ if (jsonMode(sub)) {
230
+ process.stdout.write(JSON.stringify({ ...res, url, ...(post ? { post, review } : {}) }, null, 2) + '\n');
231
+ }
232
+ else {
233
+ // The `key` is the receipt: it names the workspace prefix the bytes ACTUALLY
234
+ // reached. Printed always, so a --workspace upload can never merely look right.
235
+ process.stdout.write(`ok key=${res.key ?? '?'} kind=${res.kind ?? '?'} type=${res.contentType ?? '?'} stored=${human(res.size)} sent=${human(sent)}\n` +
236
+ ` ${url}\n`);
237
+ if (post?.ok)
238
+ process.stdout.write(`draft post=${post.id ?? '?'} — publish it here: ${review}\n`);
239
+ }
240
+ if (post && !post.ok)
241
+ fail(`uploaded, but the post draft failed: ${post.error}`);
242
+ }
137
243
  export function mediaCmd() {
138
244
  const cmd = new Command('media').description('A workspace media library — list the WHOLE of it, upload a local file. ' +
139
245
  '(generate has no subcommand on purpose: one ask media:generate --data \'{"prompt":"..."}\')');
@@ -183,11 +289,14 @@ export function mediaCmd() {
183
289
  });
184
290
  cmd
185
291
  .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://…"}\'')
292
+ .description('Upload a LOCAL image (media:upload, 5 MiB) or video (.mp4/.mov/.webm, streamed, 100 MB) into the library. ' +
293
+ 'Add --post "<caption>" [--platforms facebook] to draft a social post with it — a person publishes it. ' +
294
+ 'For a remote image URL: one ask media:upload --data \'{"url":"https://…"}\'')
188
295
  .option('--workspace <slug>', 'Group slug to write (default: your own). A workspace you may not write is REFUSED, never downgraded.')
189
296
  .option('--content-type <ct>', 'A HINT only — the stored type is decided by the magic bytes')
190
297
  .option('--filename <name>', 'A LABEL for the key, not a path (default: the basename). The extension always comes from the sniffed bytes.')
298
+ .option('--post <caption>', 'Also draft a social post carrying this media (drafts only — publish on the social page)')
299
+ .option('--platforms <list>', 'With --post: comma-separated platforms. Default facebook — the one platform that posts the video itself; linkedin/twitter post the caption only', 'facebook')
191
300
  .option('--api <url>', 'API base URL', DEFAULT_API)
192
301
  .option('--json', 'Print the raw response')
193
302
  .action(async (path, opts, sub) => {
@@ -205,11 +314,21 @@ export function mediaCmd() {
205
314
  return fail(`${path} is empty`);
206
315
  const ext = extname(path).toLowerCase();
207
316
  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).');
317
+ const videoType = VIDEO_CONTENT_TYPES[ext];
318
+ if (!videoType) {
319
+ return fail(`${path} is ${ext} — the library takes .mp4, .mov and .webm. Nothing was sent. Convert it first (ffmpeg -i ${basename(path)} out.mp4).`);
320
+ }
321
+ if (size > VIDEO_MAX_BYTES) {
322
+ return fail(`${path} is ${human(size)} — the video door caps at ${human(VIDEO_MAX_BYTES)}. Nothing was sent.`);
323
+ }
324
+ let res;
325
+ try {
326
+ res = await uploadVideo(opts.api, path, videoType, opts.workspace);
327
+ }
328
+ catch (e) {
329
+ return fail(e instanceof Error ? e.message : String(e));
330
+ }
331
+ return finish(sub, res, size, opts);
213
332
  }
214
333
  if (ext === '.svg') {
215
334
  return fail(`${path} is SVG, which media:upload refuses deliberately (the public reader serves the stored type verbatim). Nothing was sent.`);
@@ -240,17 +359,7 @@ export function mediaCmd() {
240
359
  catch (e) {
241
360
  return fail(e instanceof Error ? e.message : String(e));
242
361
  }
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');
362
+ return finish(sub, res, size, opts);
254
363
  });
255
364
  return cmd;
256
365
  }
@@ -1,5 +1,6 @@
1
1
  import { Command } from 'commander';
2
2
  import { out, resolveBase, resolveKey } from './lib/client.js';
3
+ import { webBase } from './lib/roster.js';
3
4
  const DEFAULT_API = resolveBase({}, 'https://one.ie');
4
5
  function readApiKey() {
5
6
  const key = resolveKey();
@@ -16,7 +17,7 @@ export function socialCmd() {
16
17
  .option('--api <url>', 'API base URL', DEFAULT_API)
17
18
  .action(async (opts) => {
18
19
  const key = readApiKey();
19
- const base = opts.api.replace(/\/$/, '');
20
+ const base = webBase(opts.api).replace(/\/$/, '');
20
21
  const params = new URLSearchParams({ groupId: opts.group, limit: opts.limit });
21
22
  if (opts.status)
22
23
  params.set('status', opts.status);
@@ -32,11 +33,13 @@ export function socialCmd() {
32
33
  });
33
34
  cmd
34
35
  .command('create')
35
- .description('Create a draft social post')
36
+ .description('Create a DRAFT social post. A key drafts only — scheduling or publishing is a person\'s step on ' +
37
+ '/u/<group>/marketing/social, because a scheduled post publishes itself with nobody in the loop.')
36
38
  .requiredOption('--group <groupId>', 'Group ID')
37
39
  .requiredOption('--content <text>', 'Post content')
38
40
  .requiredOption('--platforms <list>', 'Comma-separated platforms (twitter,linkedin,...)')
39
- .option('--schedule <epoch>', 'Scheduled publish time (Unix epoch seconds)')
41
+ .option('--media-url <url>', 'Absolute URL of an image or video (e.g. the url `one media upload` prints)')
42
+ .option('--media-type <type>', 'image | video (default: guessed from the URL extension)')
40
43
  .option('--api <url>', 'API base URL', DEFAULT_API)
41
44
  .action(async (opts) => {
42
45
  const key = readApiKey();
@@ -44,11 +47,22 @@ export function socialCmd() {
44
47
  out(cmd, { ok: false, error: 'no API key — run: oneie auth login' });
45
48
  return;
46
49
  }
47
- const base = opts.api.replace(/\/$/, '');
50
+ const base = webBase(opts.api).replace(/\/$/, '');
48
51
  const platforms = opts.platforms.split(',').map((p) => p.trim());
49
52
  const body = { groupId: opts.group, content: opts.content, platforms };
50
- if (opts.schedule)
51
- body.scheduledAt = parseInt(opts.schedule, 10);
53
+ if (opts.mediaUrl) {
54
+ if (!/^https?:\/\//i.test(opts.mediaUrl)) {
55
+ out(cmd, { ok: false, error: '--media-url must be absolute — platforms fetch it from their own servers' });
56
+ return;
57
+ }
58
+ const mediaType = opts.mediaType ?? (/\.(mp4|m4v|mov|webm)(\?|#|$)/i.test(opts.mediaUrl) ? 'video' : 'image');
59
+ if (mediaType !== 'image' && mediaType !== 'video') {
60
+ out(cmd, { ok: false, error: "--media-type must be 'image' or 'video'" });
61
+ return;
62
+ }
63
+ body.mediaUrl = opts.mediaUrl;
64
+ body.mediaType = mediaType;
65
+ }
52
66
  const res = await fetch(`${base}/api/social/posts`, {
53
67
  method: 'POST',
54
68
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
@@ -60,7 +74,12 @@ export function socialCmd() {
60
74
  return;
61
75
  }
62
76
  const data = await res.json();
63
- out(cmd, { ok: true, id: data.post.id, status: data.post.status });
77
+ out(cmd, {
78
+ ok: true,
79
+ id: data.post.id,
80
+ status: data.post.status,
81
+ review: `${base}/u/${opts.group}/marketing/social`,
82
+ });
64
83
  });
65
84
  cmd
66
85
  .command('accounts')
@@ -72,7 +91,7 @@ export function socialCmd() {
72
91
  out(cmd, { ok: false, error: 'no API key — run: oneie auth login' });
73
92
  return;
74
93
  }
75
- const base = opts.api.replace(/\/$/, '');
94
+ const base = webBase(opts.api).replace(/\/$/, '');
76
95
  const res = await fetch(`${base}/api/social/accounts`, {
77
96
  headers: { Authorization: `Bearer ${key}` },
78
97
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oneie",
3
- "version": "5.5.1",
3
+ "version": "5.6.0",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {