Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ All notable changes to the `indianopinion` npm package. The format follows
### Fixed

- `io.sh`: an invalid `--limit` (on `briefs`, `digest`, `topics list` and `breaking recent`) or a bad `prefs set --digest`/`--nudges` value now stops with exit 2 before any request. The validators ran inside a command substitution, so the usage error was printed and the command carried on and exited 0; `prefs set --digest maybe` even sent a malformed body. The CLI also checks `--limit` before the request on `digest`, `topics list` and `breaking recent` (#28).
- `io.sh` with jq prints an error from the API in the CLI's shape, `{"ok":false,"error":...,"message":...,"status":...}` plus `field`, `allowed`, `attempts_left`, `suggestion`, `options`, `scope` and `retry_after` when the API sends them, instead of the API's own body (WordPress's `{code, message, data}`). A body that is not JSON gives `http_<status>`, as in the CLI. Without jq the body is still passed through unchanged (#29).

## [0.2.2] - 2026-10-22

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ mkdir -p ~/bin && curl -fsSL https://indianopinion.org/agents/cli/io.sh -o ~/bin
~/bin/io briefs --q monsoon --limit 3 # or add ~/bin to PATH and run io
```

With jq installed, `io.sh` prints the same JSON as the CLI; without jq it prints the API's JSON
With jq installed, `io.sh` prints the same JSON as the CLI, errors from the API included
(`{"ok":false,"error":...,"message":...,"status":...}` on stderr); without jq it prints the API's JSON
unchanged, and the few flags that need reshaping (`digest --limit`, `breaking recent --limit` or
`--would-send`, `brief --include`) say they need jq. A flag a command does not take is a usage error
(exit 2) in both.
Expand Down
20 changes: 18 additions & 2 deletions io.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
# ~/bin/io login verify --email you@yourdomain.example --code 123456
# ~/bin/io digest | jq '.stories[] | {title, url}'
# Output: with jq installed, the same JSON as the indianopinion CLI (briefs as
# {ok, count, items, next_cursor} with post_id, summary and so on); without jq,
# {ok, count, items, next_cursor} with post_id, summary and so on, and API errors as
# {ok: false, error, message, status} on stderr); without jq,
# the API's JSON unchanged. Flags that need reshaping (digest --limit, breaking
# recent --limit or --would-send, brief --include) need jq and say so.
# A flag a command does not take is a usage error (exit 2), never ignored.
Expand Down Expand Up @@ -79,9 +80,24 @@ call() {
out=$(curl "${args[@]}" "$API$path" 2>/dev/null) || die 7 network "could not reach $API"
status=${out##*$'\n'}; out=${out%$'\n'*}
code=$(exit_for "$status" "$out")
if [ "$code" != 0 ]; then printf '%s\n' "$out" >&2; exit "$code"; fi
if [ "$code" != 0 ]; then
# With jq, an error from the API gets the CLI's shape (#29); without jq it stays as sent.
if [ "$HAVE_JQ" = 1 ]; then printf '%s' "$out" | jq -cRs --arg s "$status" "$JQ_APIERR" >&2 || printf '%s\n' "$out" >&2
else printf '%s\n' "$out" >&2; fi
exit "$code"
fi
OUT=$out
}
# The CLI's error object for an API error body (WordPress {code, message, data} or the agent API's
# {ok: false, error, message, ...}), as bin/indianopinion.mjs api() builds it. A body that is not
# JSON gives http_<status>. Retry-After is taken from the body only; io.sh does not read headers.
JQ_APIERR='($s | tonumber) as $st | ((try fromjson catch null) | if type == "object" then . else {} end) as $d
| ($d.error // $d.code // "http_\($st)") as $c
| {ok: false, error: $c,
message: (if $c == "rest_no_route" then "The Indian Opinion agent API is not answering yet (rest_no_route); try again later." else ($d.message // "HTTP \($st)") end),
status: $st}
+ ($d | with_entries(select(.key | IN("field", "allowed", "attempts_left", "suggestion", "options", "scope"))))
+ (if $d.retry_after != null then {retry_after: ($d.retry_after | tonumber? // $d.retry_after)} else {} end)'

emit() { # print JSON (pretty on a terminal when jq is there)
if [ -t 1 ] && [ "$HAVE_JQ" = 1 ]; then printf '%s\n' "$1" | jq .; else printf '%s\n' "$1"; fi
Expand Down
90 changes: 90 additions & 0 deletions test/api-error-shape.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// #29: with jq, io.sh prints an error that came from the API in the CLI's shape,
// {ok: false, error, message, status, ...}, instead of the API's own body.
// The error bodies are the REST stub's (test/stub-rest.mjs): WordPress's {code, message,
// data: {status}} for /brief/{id} and rest_no_route, the agent API's {ok: false, error,
// message, ...} elsewhere, and an HTML 404 for a path outside the API. No network.

import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { startStub, GOOD_TOKEN, EMAIL } from './stub-rest.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '..');
const BIN = path.join(ROOT, 'bin', 'indianopinion.mjs');
const IOSH = path.join(ROOT, 'io.sh');
const HAVE_CURL = spawnSync('bash', ['-c', 'command -v curl']).status === 0;
const HAVE_JQ = spawnSync('bash', ['-c', 'command -v jq']).status === 0;
let stub; let dark; let home;

function run(args, { env = {}, bin = 'node' } = {}) {
const [cmd, argv] = bin === 'node' ? [process.execPath, [BIN, ...args]] : ['bash', [IOSH, ...args]];
return new Promise((resolve) => {
const child = spawn(cmd, argv, { env: { PATH: process.env.PATH, HOME: home, XDG_CONFIG_HOME: path.join(home, '.config'), IO_API: stub.api, IO_TOKEN: GOOD_TOKEN, ...env } });
let out = ''; let errs = '';
child.stdout.on('data', (d) => { out += d; });
child.stderr.on('data', (d) => { errs += d; });
child.stdin.end();
child.on('close', (code) => {
let errJson = null;
try { errJson = JSON.parse(errs.trim().split('\n').pop()); } catch { /* text */ }
resolve({ code, out, err: errs, errJson });
});
});
}

before(async () => {
stub = await startStub();
dark = await startStub({ agentLive: false });
home = fs.mkdtempSync(path.join(os.tmpdir(), 'io-errshape-'));
});
after(async () => { await stub.close(); await dark.close(); });

test('#29: io.sh with jq prints the CLI error shape for a WordPress-style 404', { skip: !HAVE_CURL || !HAVE_JQ }, async () => {
const sh = await run(['brief', '99999999999'], { bin: 'bash' });
assert.equal(sh.code, 4);
assert.equal(sh.out, '');
assert.deepEqual(Object.keys(sh.errJson), ['ok', 'error', 'message', 'status']);
assert.equal(sh.errJson.ok, false);
assert.equal(sh.errJson.message, 'No such article.');
assert.equal(sh.errJson.status, 404);
const node = await run(['brief', '99999999999']);
assert.equal(node.code, 4);
assert.deepEqual(sh.errJson, node.errJson);
});

test('#29: io.sh and the CLI print the same error object for every kind of API error', { skip: !HAVE_CURL || !HAVE_JQ }, async () => {
const cases = [
{ name: 'agent API 400 with attempts_left', args: ['login', 'verify', '--email', EMAIL, '--code', '000000'], exit: 6 },
{ name: 'agent API 400 with field', args: ['login', 'start', '--email', 'not-an-address@x'], exit: 6 },
{ name: '429 with retry_after and scope', args: ['login', 'start', '--email', 'slow@agents.example.org'], exit: 5 },
{ name: '409 ambiguous with options', args: ['topics', 'follow', 'metro'], exit: 8 },
{ name: '401 refused token', args: ['me'], env: { IO_TOKEN: 'ioa_000000000000_revokedrevokedrevoked' }, exit: 3 },
{ name: 'agent API 404', args: ['digest', '--date', '1999-01-01'], exit: 4 },
{ name: 'rest_no_route before the agent API is deployed', args: ['me'], env: { IO_API: '' }, dark: true, exit: 4 },
{ name: 'a body that is not JSON', args: ['brief', '1'], env: { IO_API: '' }, html: true, exit: 4 },
];
for (const c of cases) {
const env = { ...(c.env || {}) };
if (c.dark) env.IO_API = dark.api;
if (c.html) env.IO_API = `${stub.url}/not-the-api`;
const node = await run(c.args, { env });
const sh = await run(c.args, { env, bin: 'bash' });
assert.equal(node.code, c.exit, `${c.name}: CLI exit ${node.code} ${node.err}`);
assert.equal(sh.code, c.exit, `${c.name}: io.sh exit ${sh.code} ${sh.err}`);
assert.equal(sh.errJson && sh.errJson.ok, false, `${c.name}: io.sh stderr ${sh.err}`);
assert.deepEqual(sh.errJson, node.errJson, `${c.name}`);
}
});

test('#29: without jq, io.sh still passes the API body through unchanged (as documented)', { skip: !HAVE_CURL }, async () => {
const sh = await run(['brief', '99999999999'], { bin: 'bash', env: { IO_SH_NO_JQ: '1' } });
assert.equal(sh.code, 4);
assert.equal(sh.errJson.ok, undefined);
assert.equal(sh.errJson.message, 'No such article.');
assert.deepEqual(sh.errJson.data, { status: 404 });
});
Loading