@raibitsi/tiresias 1.1.0 → 1.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.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // N-09: the command-line door. Same engine, same store as the MCP server.
4
4
  import "./nodecheck.js"; // first: an older Node gets a plain message before anything else runs
5
- import { textView } from "./textview.js";
5
+ import { escapeTerminal, textView } from "./textview.js";
6
6
  import { parseArgs } from "node:util";
7
7
  import { drainForExit, installShutdown } from "./background.js";
8
8
  import { loadChoice, loadLimits } from "./config.js";
@@ -14,9 +14,13 @@ import { BROWSE_HELP, BROWSE_TAKES, noteCliRead, runBrowseCommand } from "./brow
14
14
  import { VERSION } from "./types.js";
15
15
  import { notice, startupNotice } from "./confirm.js";
16
16
  import { listEnvelope, historyEnvelope, receiptsEnvelope } from "./envelope.js";
17
+ import { localRead, parseLocalBudget } from "./local.js";
17
18
  // JSON output carries `profile` at the top level when it is not `default` (W-18), and `settings_notice` when a risky
18
19
  // setting changed in the last 24 hours or a loosening waits for confirmation (W-32, v0.9).
19
- const json = (x, space = 2) => JSON.stringify(stampNotice(stampProfile(x)), null, space);
20
+ // Terminal display only. Applying the escape again is harmless: backslashes stay unchanged.
21
+ const print = (text) => console.log(escapeTerminal(String(text)));
22
+ const printError = (text) => console.error(escapeTerminal(String(text)));
23
+ const json = (x, space = 2) => escapeTerminal(JSON.stringify(stampNotice(stampProfile(x)), null, space));
20
24
  let noticeLines = null; // null: not looked up yet (once per process, after the profile is chosen)
21
25
  let profileSelected = false;
22
26
  function currentNotice() {
@@ -49,6 +53,9 @@ const HELP = `Tiresias ${VERSION}: the honest browser for AI agents.
49
53
  request through Tiresias's rules), when the owner allows it
50
54
  [--save] keep a signed snapshot of the bytes this read received, when the owner
51
55
  allows saving (tiresias settings set saving ask --confirm "YES, TURN ON SAVING")
56
+ [--local [--local-budget 6000]] print the reply a local model gets from tiresias mcp --local.
57
+ With --local, the only other options are --question, --section,
58
+ --page and --local-budget
52
59
  tiresias doors <url>
53
60
  tiresias check <url> [--page 2] [--fresh] if it changed: what changed (added and removed blocks)
54
61
  tiresias resume <ticket> [--from-file <path>] pick up a read that stopped at a wall: retry it, or read
@@ -102,6 +109,19 @@ const HELP = `Tiresias ${VERSION}: the honest browser for AI agents.
102
109
  translation (none is included); it gets the text on standard
103
110
  input and the source and target languages as its last two arguments
104
111
  tiresias translator show | translator off the translator setting, or remove it
112
+ tiresias guard setup --url http://localhost:1234/v1 --model <embedding model id> [--prefix "..."]
113
+ [--false-alarms 1] [--ordinary <file.jsonl> | --ordinary-urls <file.txt>] [--timeout 4]
114
+ the meaning check for local model mode: your own embedding model
115
+ compares each passage with known planted instructions (none is
116
+ included). Setup reads about 100 ordinary pages through Tiresias to
117
+ calibrate, unless you give your own; an address outside your network
118
+ takes --confirm "YES, SEND PAGE TEXT OUTSIDE MY NETWORK"
119
+ tiresias guard import <file> [--name <collection>] create a new collection of planted texts (.jsonl with
120
+ "text", or one text per line). Pick an unused --name; "starter"
121
+ is reserved. Without --name, a unique name comes from the file
122
+ tiresias guard show | guard check [--file <path> | <text>] | guard off
123
+ the setting and library sizes; score one text; remove the setting and
124
+ the library
105
125
  tiresias settings every owner setting: value, default, what it does, where it is stored
106
126
  tiresias settings set <name> [<site>] <value> | settings reset <name> [<site>] [--confirm "..."]
107
127
  change one setting (site settings: spacing_seconds, ports, hand_off,
@@ -133,6 +153,10 @@ const HELP = `Tiresias ${VERSION}: the honest browser for AI agents.
133
153
  delete one profile's folder (--delete-key when it has a signing key)
134
154
  ${BROWSE_HELP}
135
155
  tiresias mcp start the MCP server (stdio)
156
+ tiresias mcp --local [--local-budget 6000] the MCP server for small models that run on your own
157
+ computer: one read tool, short instructions and short replies, about
158
+ 6,000 characters of page text (--local-budget: 1000 to 20000).
159
+ Tiresias does not search the web, so give your model a search tool too
136
160
 
137
161
  Add --profile <name> to any command (or set TIRESIAS_PROFILE) to use that profile; without it,
138
162
  the default profile (the store folder itself) is used. The MCP server serves one profile, fixed
@@ -171,7 +195,7 @@ export function exitFor(status) {
171
195
  // --profile, --text and --help go with every command; --private with every command that reads the store.
172
196
  const COMMON = ["profile", "text", "help", "private"];
173
197
  const TAKES = {
174
- read: ["question", "section", "page", "changes", "fresh", "allow-flagged", "translate", "render", "save"],
198
+ read: ["question", "section", "page", "changes", "fresh", "allow-flagged", "translate", "render", "save", "local", "local-budget"],
175
199
  saved: ["page", "all"], // v0.8 (W-28)
176
200
  doors: ["allow-flagged"],
177
201
  check: ["page", "fresh", "allow-flagged"],
@@ -188,12 +212,13 @@ const TAKES = {
188
212
  keys: ["force", "host", "days", "out", "overlap", "finish", "slips", "confirm"], // overlap, finish, slips, confirm: v1.1 keys rotate
189
213
  scanner: ["timeout", "send-file", "confirm"], // confirm: v0.9 (W-32)
190
214
  translator: ["timeout", "confirm"], // v0.7 (W-26)
215
+ guard: ["url", "model", "prefix", "false-alarms", "ordinary", "ordinary-urls", "timeout", "confirm", "name", "file"], // v1.2 (W-38)
191
216
  settings: ["confirm"], // v0.6 (W-29); confirm: v0.9 (W-32)
192
217
  safety: [],
193
218
  slip: ["action", "site", "path", "until", "for", "uses", "note", "all", "page"],
194
219
  form: ["form", "set", "unset", "preview", "allow-flagged"],
195
220
  profile: ["yes", "delete-key"],
196
- mcp: [],
221
+ mcp: ["local", "local-budget"], // W-34 (v1.2)
197
222
  ...BROWSE_TAKES, // v0.6 W-24 tabs, W-27 files (browsecli.ts)
198
223
  };
199
224
  // Per-command help: the lines of HELP for that command (and their continuation lines).
@@ -217,15 +242,15 @@ function helpFor(cmd) {
217
242
  // form (plain text, or JSON) only on --text.
218
243
  function printReply(r, text, plain = r.message) {
219
244
  if (r.status === "error")
220
- console.error(text ? plain : json(r, 0));
245
+ printError(text ? plain : json(r, 0));
221
246
  else
222
- console.log(text ? plain : json(r));
247
+ print(text ? plain : json(r));
223
248
  }
224
249
  function printEnvelope(e, text) {
225
250
  if (e.status === "error")
226
- console.error(text ? summary(e) : json(e, 0));
251
+ printError(text ? summary(e) : json(e, 0));
227
252
  else
228
- console.log(text ? summary(e) : json(e));
253
+ print(text ? summary(e) : json(e));
229
254
  }
230
255
  function summary(e) {
231
256
  const uc = e.untrusted_content;
@@ -382,6 +407,8 @@ async function main() {
382
407
  form: { type: "string" }, set: { type: "string", multiple: true }, unset: { type: "string", multiple: true }, preview: { type: "string" },
383
408
  action: { type: "string" }, path: { type: "string" }, until: { type: "string" }, for: { type: "string" }, uses: { type: "string" }, note: { type: "string" },
384
409
  timeout: { type: "string" }, "send-file": { type: "boolean" }, translate: { type: "string" }, render: { type: "boolean" }, save: { type: "boolean" }, confirm: { type: "string" },
410
+ local: { type: "boolean" }, "local-budget": { type: "string" },
411
+ model: { type: "string" }, prefix: { type: "string" }, "false-alarms": { type: "string" }, ordinary: { type: "string" }, "ordinary-urls": { type: "string" }, name: { type: "string" }, file: { type: "string" },
385
412
  force: { type: "boolean" }, overlap: { type: "string" }, finish: { type: "boolean" }, slips: { type: "boolean" }, host: { type: "string" }, days: { type: "string" }, out: { type: "string" }, "older-than": { type: "string" }, all: { type: "boolean" }, "dry-run": { type: "boolean" }, help: { type: "boolean", short: "h" }, version: { type: "boolean" },
386
413
  },
387
414
  });
@@ -424,17 +451,17 @@ async function main() {
424
451
  const all = profiles.list();
425
452
  const left = profiles.leftovers().length; // interrupted removals (Codex round 46)
426
453
  const note = left ? `${left} interrupted profile removal(s) left files in profiles/.removing-*; the next "tiresias profile remove" finishes them.` : undefined;
427
- console.log(values.text ? all.map((p) => `${p.name}${p.created_at ? ` made ${p.created_at}` : ""} key: ${p.signing_key ? "yes" : "no"} signature_agent: ${p.signature_agent ?? "none"}${p.problem ? ` PROBLEM: ${p.problem}` : ""}`).concat(note ? [note] : []).join("\n") : json({ profiles: all, ...(left ? { removing_leftovers: left, note } : {}) }));
454
+ print(values.text ? all.map((p) => `${p.name}${p.created_at ? ` made ${p.created_at}` : ""} key: ${p.signing_key ? "yes" : "no"} signature_agent: ${p.signature_agent ?? "none"}${p.problem ? ` PROBLEM: ${p.problem}` : ""}`).concat(note ? [note] : []).join("\n") : json({ profiles: all, ...(left ? { removing_leftovers: left, note } : {}) }));
428
455
  return 0;
429
456
  }
430
457
  if (sub === "create" && name !== undefined) {
431
458
  const r = profiles.create(name, sessionPriv);
432
- console.log(values.text ? r.message : json(r));
459
+ print(values.text ? r.message : json(r));
433
460
  return 0;
434
461
  }
435
462
  if (sub === "remove" && name !== undefined) {
436
463
  const r = profiles.remove(name, { yes: values.yes, deleteKey: values["delete-key"], priv: sessionPriv });
437
- console.log(values.text ? r.message : json(r));
464
+ print(values.text ? r.message : json(r));
438
465
  return 0;
439
466
  }
440
467
  throw new Error("Usage: tiresias profile create <name> | profile list | profile remove <name> --yes [--delete-key]");
@@ -442,6 +469,10 @@ async function main() {
442
469
  // W-18: one process serves one profile, chosen here once (--profile, else TIRESIAS_PROFILE, else
443
470
  // default). A profile that does not exist stops the command before anything is read or created.
444
471
  assertProfile();
472
+ // W-34 (v1.2): local model mode. --local-budget goes with --local only.
473
+ if (values["local-budget"] !== undefined && !values.local)
474
+ throw new Error("--local-budget goes with --local.");
475
+ const localBudget = values.local ? parseLocalBudget(values["local-budget"]) : undefined;
445
476
  if (cmd === "mcp") {
446
477
  // Integration Codex round 3 (v0.8): `mcp --private` is the documented TIRESIAS_PRIVATE=1, for the whole server
447
478
  // (before, the flag was accepted and ignored, so calls without their own `private` were recorded).
@@ -456,8 +487,8 @@ async function main() {
456
487
  // held back for confirmation (the agent may never pass the reply notice on).
457
488
  const held = startupNotice(profileName());
458
489
  if (held)
459
- process.stderr.write(`${held}\n`);
460
- await serveStdio();
490
+ process.stderr.write(escapeTerminal(`${held}\n`));
491
+ await serveStdio(localBudget === undefined ? {} : { local: { budget: localBudget } });
461
492
  return -1; // keep running
462
493
  }
463
494
  installShutdown(); // v0.6 (Codex round 6): a signal during ANY command runs the bounded cleanup (lifetime.ts)
@@ -478,18 +509,18 @@ async function main() {
478
509
  if (sessionPriv)
479
510
  throw new Error("Private mode: nothing is written, so the log is not exported. Run it without --to to print it.");
480
511
  const r = await engine.exportDailyLog(values.to, values.day);
481
- console.log(values.json ? json(r) : r.message + `\n${r.file}`);
512
+ print(values.json ? json(r) : r.message + `\n${r.file}`);
482
513
  }
483
514
  else {
484
515
  const r = await engine.dailyLog(values.day, page);
485
- console.log(values.json ? json(listEnvelope("", { day: r.day, entries: r.entries, log: r.text }, { page: r.page, pages: r.pages, total: r.entries })) : textView(r.text + (r.pages > 1 ? `\nPage ${r.page} of ${r.pages}. Use --page N for more.` : "")));
516
+ print(values.json ? json(listEnvelope("", { day: r.day, entries: r.entries, log: r.text }, { page: r.page, pages: r.pages, total: r.entries })) : textView(r.text + (r.pages > 1 ? `\nPage ${r.page} of ${r.pages}. Use --page N for more.` : "")));
486
517
  }
487
518
  return 0;
488
519
  }
489
520
  if (cmd === "needs") {
490
521
  const { toMarkdown } = await import("./needs.js");
491
522
  const r = await engine.needsReport(values.since, page);
492
- console.log(values.json ? json(r) : textView(toMarkdown(r)));
523
+ print(values.json ? json(r) : textView(toMarkdown(r)));
493
524
  return 0;
494
525
  }
495
526
  if (cmd === "bookmark") {
@@ -520,7 +551,7 @@ async function main() {
520
551
  await confirmByTyping(site, `Grant a permission slip: ${String(values.action)} on ${site}${values.path ? String(values.path) : ""}.`);
521
552
  const v = slips.grant({ action: values.action, site: values.site, path: values.path, until: values.until, for: values.for, uses: values.uses, note: values.note }, sessionPriv);
522
553
  const msg = `Granted slip ${v.id}: ${v.action} on ${v.site}${v.path ?? ""}${v.path ? " (and below)" : ""}, ${v.uses} use${v.uses === 1 ? "" : "s"}, until ${v.expires_at}. Revoke it with: tiresias slip revoke ${v.id}`;
523
- console.log(values.text ? msg : json({ status: "ok", message: msg, slip: v }));
554
+ print(values.text ? msg : json({ status: "ok", message: msg, slip: v }));
524
555
  return 0;
525
556
  }
526
557
  if (sub === "revoke" && (id !== undefined) !== !!values.all) {
@@ -529,14 +560,14 @@ async function main() {
529
560
  await confirmByTyping("revoke all", "Revoke every permission slip of this profile.");
530
561
  const n = slips.revokeAll(sessionPriv);
531
562
  const msg = `Revoked ${n} slip${n === 1 ? "" : "s"}. None of them can be used again.`;
532
- console.log(values.text ? msg : json({ status: "ok", message: msg, revoked: n }));
563
+ print(values.text ? msg : json({ status: "ok", message: msg, revoked: n }));
533
564
  }
534
565
  else {
535
566
  const what = slips.confirmTextFor(id);
536
567
  await confirmByTyping(what, `Revoke slip ${id}.`);
537
568
  slips.revoke(id, sessionPriv);
538
569
  const msg = "Revoked. That slip can never be used again.";
539
- console.log(values.text ? msg : json({ status: "ok", message: msg, revoked: 1 }));
570
+ print(values.text ? msg : json({ status: "ok", message: msg, revoked: 1 }));
540
571
  }
541
572
  return 0;
542
573
  }
@@ -549,7 +580,7 @@ async function main() {
549
580
  lines.push(` ${s.id} ${s.action} on ${s.site}${s.path ?? ""} ${s.uses_left} of ${s.uses} uses left until ${s.expires_at}${notes.has(s.id) ? ` note: ${JSON.stringify(notes.get(s.id))}` : ""}`);
550
581
  if (r.pages > 1)
551
582
  lines.push(`Page ${r.page} of ${r.pages}. Use --page N for more.`);
552
- console.log(values.text ? lines.join("\n") : json(r));
583
+ print(values.text ? lines.join("\n") : json(r));
553
584
  return 0;
554
585
  }
555
586
  throw new Error("Usage: tiresias slip grant --action submit_form --site <origin> [--path /p] [--until <date> | --for 7d] [--uses N] [--note text] | slip list | slip revoke <id> | slip revoke --all");
@@ -594,7 +625,7 @@ async function main() {
594
625
  }
595
626
  if (cmd === "watch") {
596
627
  const r = await engine.watch(ctx, page);
597
- console.log(values.text ? watchText(r) : json(r));
628
+ print(values.text ? watchText(r) : json(r));
598
629
  return 0;
599
630
  }
600
631
  if (cmd === "scanner") {
@@ -609,23 +640,71 @@ async function main() {
609
640
  throw new Error("Usage: tiresias scanner set [--timeout 10] [--send-file] -- /full/path/to/program [args...]");
610
641
  const cfg = scanner.setScanner(command, { timeout: values.timeout, sendFile: values["send-file"], confirm: values.confirm }, sessionPriv);
611
642
  const msg = `Scanner set: ${cfg.command[0]}${cfg.command.length > 1 ? ` with ${cfg.command.length - 1} argument(s)` : ""}, up to ${cfg.timeout_seconds} s per file, ${cfg.send_file ? "and it is handed the file itself (a quarantine copy, deleted after)" : "fingerprint only (not the file)"}. It runs on every high-risk file warning.`;
612
- console.log(values.text ? msg : json({ status: "ok", message: msg, scanner: cfg }));
643
+ print(values.text ? msg : json({ status: "ok", message: msg, scanner: cfg }));
613
644
  return 0;
614
645
  }
615
646
  if (arg === "show") {
616
647
  const cfg = loadScanner();
617
648
  const msg = cfg ? `Scanner: ${JSON.stringify(cfg.command)}, ${cfg.timeout_seconds} s, send_file ${cfg.send_file}.` : "No scanner is set. Tiresias includes none; set your own with: tiresias scanner set -- /full/path/to/program [args...]";
618
- console.log(values.text ? msg : json({ status: "ok", message: msg, scanner: cfg }));
649
+ print(values.text ? msg : json({ status: "ok", message: msg, scanner: cfg }));
619
650
  return 0;
620
651
  }
621
652
  if (arg === "off") {
622
653
  const was = scanner.clearScanner(sessionPriv);
623
654
  const msg = was ? "Scanner removed. File warnings are no longer checked by it." : "No scanner was set.";
624
- console.log(values.text ? msg : json({ status: "ok", message: msg }));
655
+ print(values.text ? msg : json({ status: "ok", message: msg }));
625
656
  return 0;
626
657
  }
627
658
  throw new Error("Usage: tiresias scanner set [--timeout 10] [--send-file] -- /full/path/to/program [args...] | scanner show | scanner off");
628
659
  }
660
+ if (cmd === "guard") {
661
+ // W-38 (v1.2): the owner's meaning check. Only here, from the command line (or by editing config.json): nothing
662
+ // in either MCP server reads, sets, changes or triggers it. Replies name collections and counts, never a text.
663
+ const g = await import("./guard.js");
664
+ const print = (r) => console.log(values.text ? r.message : json(r));
665
+ if (arg === "setup") {
666
+ const r = await g.setup({ url: values.url, model: values.model, prefix: values.prefix, falseAlarms: values["false-alarms"], timeout: values.timeout, ordinary: values.ordinary, ordinaryUrls: values["ordinary-urls"], confirm: values.confirm }, sessionPriv);
667
+ print(r);
668
+ return 0;
669
+ }
670
+ if (arg === "import") {
671
+ const file = positionals[2];
672
+ if (!file || positionals.length > 3)
673
+ throw new Error("Usage: tiresias guard import <file> [--name <collection>]");
674
+ print(await g.importFile(file, values.name, sessionPriv));
675
+ return 0;
676
+ }
677
+ if (arg === "show" && positionals.length === 2) {
678
+ print(g.show());
679
+ return 0;
680
+ }
681
+ if (arg === "check") {
682
+ const words = positionals.slice(2).join(" ");
683
+ if ((values.file !== undefined) === (words !== ""))
684
+ throw new Error("Usage: tiresias guard check [--file <path> | <text>]");
685
+ let text = words;
686
+ if (values.file !== undefined) {
687
+ const fsm = await import("node:fs");
688
+ const fd = fsm.openSync(values.file, fsm.constants.O_RDONLY | (fsm.constants.O_NONBLOCK ?? 0));
689
+ try {
690
+ const st = fsm.fstatSync(fd);
691
+ if (!st.isFile() || st.size > 64 * 1024)
692
+ throw new Error("guard check --file takes a plain file of at most 64 KB.");
693
+ text = fsm.readFileSync(fd, "utf8");
694
+ }
695
+ finally {
696
+ fsm.closeSync(fd);
697
+ }
698
+ }
699
+ print(await g.check(text));
700
+ return 0;
701
+ }
702
+ if (arg === "off" && positionals.length === 2) {
703
+ print(g.off(sessionPriv));
704
+ return 0;
705
+ }
706
+ throw new Error("Usage: tiresias guard setup --url <url> --model <id> [...] | guard import <file> [--name <collection>] | guard show | guard check [--file <path> | <text>] | guard off");
707
+ }
629
708
  if (cmd === "saved") {
630
709
  // W-28 (v0.8): saved snapshots. Owner's commands: nothing in the MCP server lists, verifies or deletes them.
631
710
  const sv = await import("./saved.js");
@@ -635,12 +714,12 @@ async function main() {
635
714
  const L = [r.message, ...r.saved.map((i) => ` ${i.id.slice(0, 16)} ${i.saved_at ?? "(damaged)"} ${i.fingerprint_only ? "fingerprint only" : `${i.bytes} bytes${i.rendered ? ", rendered" : ""}`}, ${i.receipts} receipts <${r.untrusted_content.urls.find((u) => u.id === i.id)?.final_url ?? ""}>`)];
636
715
  if (r.pages > 1)
637
716
  L.push(`Page ${r.page} of ${r.pages}. Use --page N for more.`);
638
- console.log(values.text ? textView(L.join("\n")) : json(r));
717
+ print(values.text ? textView(L.join("\n")) : json(r));
639
718
  return 0;
640
719
  }
641
720
  if (sub === "show" && id) {
642
721
  const r = sv.show(id);
643
- console.log(values.text ? textView(`${r.message}\nFolder: ${r.folder}${r.untrusted_content ? `\n${JSON.stringify(r.untrusted_content.manifest, null, 2)}` : ""}`) : json(r));
722
+ print(values.text ? textView(`${r.message}\nFolder: ${r.folder}${r.untrusted_content ? `\n${JSON.stringify(r.untrusted_content.manifest, null, 2)}` : ""}`) : json(r));
644
723
  return 0;
645
724
  }
646
725
  if (sub === "verify" && (id || values.all)) {
@@ -658,7 +737,7 @@ async function main() {
658
737
  if (sessionPriv)
659
738
  throw new Error("Private mode: nothing in the store is changed, so no snapshot is deleted.");
660
739
  const r = sv.remove(values.all ? "all" : id);
661
- console.log(values.text ? r.message : json(r));
740
+ print(values.text ? r.message : json(r));
662
741
  return 0;
663
742
  }
664
743
  throw new Error("Usage: tiresias saved [list] [--page N] | saved show <id> | saved verify <id> | --all | saved delete <id> | --all");
@@ -676,15 +755,15 @@ async function main() {
676
755
  }
677
756
  if (sub === "upgrade") {
678
757
  const r = await an.upgrade();
679
- console.log(values.text ? r.message : json(r));
758
+ print(values.text ? r.message : json(r));
680
759
  return 0;
681
760
  }
682
761
  if (sub === "status") {
683
762
  const r = await an.status(page);
684
- const L = [r.message, `Calendars: ${r.calendars.join(", ")}`, ...r.batches.map((b) => ` ${b.id.slice(0, 16)} ${b.created_at} ${b.leaves} leaves ${b.status === "complete" ? `in Bitcoin block ${b.bitcoin.join(", ")}` : "pending"}`)];
763
+ const L = [r.message, `Calendars: ${r.calendars.join(", ")}`, ...r.batches.map((b) => ` ${b.id.slice(0, 16)} ${b.created_at} ${b.leaves} leaves ${b.status === "complete" ? `reported in Bitcoin block ${b.bitcoin.join(", ")}` : "pending"}`)];
685
764
  if (r.pages > 1)
686
765
  L.push(`Page ${r.page} of ${r.pages}. Use --page N for more.`);
687
- console.log(values.text ? L.join("\n") : json(r));
766
+ print(values.text ? L.join("\n") : json(r));
688
767
  return 0;
689
768
  }
690
769
  throw new Error("Usage: tiresias anchor | anchor status [--page N] | anchor upgrade");
@@ -700,10 +779,10 @@ async function main() {
700
779
  const msg = an.proveText(bd);
701
780
  if (values.out !== undefined) {
702
781
  const files = an.writeBundle(bd, values.out, !!sessionPriv);
703
- console.log(values.text ? `${msg}\nWritten:\n${files.map((f) => ` ${f}`).join("\n")}\nCheck it with: tiresias receipts verify ${files[0]}${bd.batch.status === "complete" ? ` (or the official tool: ots verify ${files[files.length - 1]})` : ""}` : json({ status: "ok", message: msg, files }));
782
+ print(values.text ? `${msg}\nWritten:\n${files.map((f) => ` ${f}`).join("\n")}\nCheck it with: tiresias receipts verify ${files[0]}${bd.batch.status === "complete" ? ` (or the official tool: ots verify ${files[files.length - 1]})` : ""}` : json({ status: "ok", message: msg, files }));
704
783
  }
705
784
  else
706
- console.log(values.text ? msg : json({ status: "ok", message: msg, notice: (await import("./types.js")).NOTICE, untrusted_content: { bundle: bd } }));
785
+ print(values.text ? msg : json({ status: "ok", message: msg, notice: (await import("./types.js")).NOTICE, untrusted_content: { bundle: bd } }));
707
786
  return 0;
708
787
  }
709
788
  const r = an.verifyBundle(target);
@@ -724,19 +803,19 @@ async function main() {
724
803
  throw new Error("Usage: tiresias translator set [--timeout 20] -- /full/path/to/program [args...]");
725
804
  const cfg = tr.setTranslator(command, { timeout: values.timeout, confirm: values.confirm }, sessionPriv);
726
805
  const msg = `Translator set: ${cfg.command[0]}${cfg.command.length > 1 ? ` with ${cfg.command.length - 1} argument(s)` : ""}, up to ${cfg.timeout_seconds} s per read. It runs only when a read asks for a translation, with the text on standard input and the source and target languages as its last two arguments.`;
727
- console.log(values.text ? msg : json({ status: "ok", message: msg, translator: cfg }));
806
+ print(values.text ? msg : json({ status: "ok", message: msg, translator: cfg }));
728
807
  return 0;
729
808
  }
730
809
  if (arg === "show") {
731
810
  const cfg = loadTranslator();
732
811
  const msg = cfg ? `Translator: ${JSON.stringify(cfg.command)}, ${cfg.timeout_seconds} s.` : "No translator is set. Tiresias includes none; set your own with: tiresias translator set -- /full/path/to/program [args...]";
733
- console.log(values.text ? msg : json({ status: "ok", message: msg, translator: cfg }));
812
+ print(values.text ? msg : json({ status: "ok", message: msg, translator: cfg }));
734
813
  return 0;
735
814
  }
736
815
  if (arg === "off") {
737
816
  const was = tr.clearTranslator(sessionPriv);
738
817
  const msg = was ? "Translator removed. Reads no longer offer translations." : "No translator was set.";
739
- console.log(values.text ? msg : json({ status: "ok", message: msg }));
818
+ print(values.text ? msg : json({ status: "ok", message: msg }));
740
819
  return 0;
741
820
  }
742
821
  throw new Error("Usage: tiresias translator set [--timeout 20] -- /full/path/to/program [args...] | translator show | translator off");
@@ -746,15 +825,15 @@ async function main() {
746
825
  const r = (await import("./settings.js")).command(positionals.slice(1), sessionPriv, { confirm: values.confirm });
747
826
  noticeLines = null; // look again: this command may have just changed what the notice says
748
827
  if (r.code)
749
- console.error(values.text ? r.text : json(r.reply, 0));
828
+ printError(values.text ? r.text : json(r.reply, 0));
750
829
  else
751
- console.log(values.text ? r.text : json(r.reply));
830
+ print(values.text ? r.text : json(r.reply));
752
831
  return r.code;
753
832
  }
754
833
  if (cmd === "safety") {
755
834
  if (arg === "status") {
756
835
  const r = engine.safetyStatus();
757
- console.log(values.text ? `${r.message}\nList: ${r.list.state}${r.list.entries !== undefined ? `, ${r.list.entries} domains, confirmed ${r.list.verified_at}` : ""}\nWeb Risk: ${r.web_risk.configured ? `set up (${r.web_risk.from})` : "not set up"}` : json(r));
836
+ print(values.text ? `${r.message}\nList: ${r.list.state}${r.list.entries !== undefined ? `, ${r.list.entries} domains, confirmed ${r.list.verified_at}` : ""}\nWeb Risk: ${r.web_risk.configured ? `set up (${r.web_risk.from})` : "not set up"}` : json(r));
758
837
  return 0;
759
838
  }
760
839
  if (arg === "update") {
@@ -773,7 +852,7 @@ async function main() {
773
852
  if (sessionPriv)
774
853
  throw new Error("Private mode: nothing is written, so no key is made.");
775
854
  const r = await keys.initKey(values.force);
776
- console.log(json({ message: r.replaced ? "Replaced your signing key." : "Made your signing key.", private_key_file: r.file, keyid: r.keyid, public_jwk: r.public_jwk, directory: r.directory, next: 'Host "directory" at /.well-known/http-message-signatures-directory on your site, and set "signature_agent" in config.json. The private key was not printed.' }));
855
+ print(json({ message: r.replaced ? "Replaced your signing key." : "Made your signing key.", private_key_file: r.file, keyid: r.keyid, public_jwk: r.public_jwk, directory: r.directory, next: 'Host "directory" at /.well-known/http-message-signatures-directory on your site, and set "signature_agent" in config.json. The private key was not printed.' }));
777
856
  }
778
857
  else if (sub === "show" || sub === "directory") {
779
858
  const { info, previous } = await keys.publishedKeys(); // v1.1: the previous key too, while its overlap window is open
@@ -788,7 +867,7 @@ async function main() {
788
867
  agent = `(config.json problem: ${e.message})`;
789
868
  }
790
869
  const rotation = previous ? { previous_keyid: previous.keyid, rotated_at: previous.rotated_at, previous_leaves_directory_at: previous.until, note: "New requests are signed with the new key only. The previous key stays in the directory until then; run `tiresias keys rotate --finish` to drop it now." } : undefined;
791
- console.log(json({ public_jwk: info.public_jwk, keyid: info.keyid, directory: info.directory, ...(rotation ? { rotation } : {}), signature_agent: agent, signing: agent && !agent.startsWith("(") ? "on" : "off (set signature_agent in config.json)" }));
870
+ print(json({ public_jwk: info.public_jwk, keyid: info.keyid, directory: info.directory, ...(rotation ? { rotation } : {}), signature_agent: agent, signing: agent && !agent.startsWith("(") ? "on" : "off (set signature_agent in config.json)" }));
792
871
  }
793
872
  }
794
873
  else if (sub === "sign-directory") {
@@ -822,10 +901,10 @@ async function main() {
822
901
  fsm.writeFileSync(tmp, content, { flag: "wx", mode: 0o644 });
823
902
  fsm.renameSync(tmp, target);
824
903
  }
825
- console.log(json({ host: r.host, serve_at: `https://${r.host}${r.path}`, files: Object.keys(files).map((n) => pathm.join(folder, n)), expires_at: r.expires_at, reminder }));
904
+ print(json({ host: r.host, serve_at: `https://${r.host}${r.path}`, files: Object.keys(files).map((n) => pathm.join(folder, n)), expires_at: r.expires_at, reminder }));
826
905
  }
827
906
  else
828
- console.log(json({ host: r.host, serve_at: `https://${r.host}${r.path}`, created_at: r.created_at, expires_at: r.expires_at, body: JSON.parse(r.body), headers: r.headers, reminder }));
907
+ print(json({ host: r.host, serve_at: `https://${r.host}${r.path}`, created_at: r.created_at, expires_at: r.expires_at, body: JSON.parse(r.body), headers: r.headers, reminder }));
829
908
  }
830
909
  else if (sub === "rotate") {
831
910
  // v1.1 workstream 4: rotate the signing key (overlap window) or, with --slips, the slip key.
@@ -842,7 +921,7 @@ async function main() {
842
921
  await confirmByTyping("rotate slip key", "Rotate the slip key: every permission slip of this profile is revoked now and can never be used again. Saved pages stay checkable against the old key's public half.");
843
922
  const r = slips.rotateSlipKey(values.confirm, sessionPriv);
844
923
  const msg = `Rotated the slip key. Revoked ${r.revoked} slip${r.revoked === 1 ? "" : "s"}; grant new ones with tiresias slip grant. ${r.retired ? "Saved pages signed before now still verify (tiresias saved verify names the retired key)." : "The old key could not be read, so it was replaced without keeping its public half: saved pages it signed no longer verify."} Receipts do not use the slip key and are unchanged. The private key was not printed.`;
845
- console.log(values.text ? msg : json({ status: "ok", message: msg, revoked: r.revoked, old_key_kept_for_saved_pages: r.retired }));
924
+ print(values.text ? msg : json({ status: "ok", message: msg, revoked: r.revoked, old_key_kept_for_saved_pages: r.retired }));
846
925
  }
847
926
  else if (values.finish) {
848
927
  if (values.overlap !== undefined || values.confirm !== undefined)
@@ -853,7 +932,7 @@ async function main() {
853
932
  const msg = r.finished
854
933
  ? `Finished the rotation: the previous key${r.previous_keyid ? ` (${r.previous_keyid})` : ""} is out of the directory and its private half is deleted. Publish the directory again (tiresias keys directory or keys sign-directory).`
855
934
  : "No rotation is in its overlap window, so there was nothing to finish.";
856
- console.log(values.text ? msg : json({ status: "ok", message: msg, finished: r.finished, ...(r.previous_keyid ? { previous_keyid: r.previous_keyid } : {}) }));
935
+ print(values.text ? msg : json({ status: "ok", message: msg, finished: r.finished, ...(r.previous_keyid ? { previous_keyid: r.previous_keyid } : {}) }));
857
936
  }
858
937
  else {
859
938
  if (values.confirm !== undefined)
@@ -864,7 +943,7 @@ async function main() {
864
943
  ? `Rotated your signing key. New requests are signed with the new key (${r.keyid}). The previous key (${r.previous_keyid}) stays in your directory until ${r.overlap_until}, then drops out by itself (tiresias keys rotate --finish drops it now).`
865
944
  : `Rotated your signing key with no overlap. New requests are signed with the new key (${r.keyid}); the previous key (${r.previous_keyid}) is deleted and out of the directory now.`;
866
945
  const next = 'Publish the new directory now: tiresias keys directory (or keys sign-directory for a static host) and upload it to /.well-known/http-message-signatures-directory. A server that signs your directory itself (such as a Cloudflare Worker holding a copy of the key) needs the new key too. The private key was not printed.';
867
- console.log(values.text ? `${msg}\n${next}` : json({ status: "ok", message: msg, keyid: r.keyid, public_jwk: r.public_jwk, previous_keyid: r.previous_keyid, overlap_days: r.overlap_days, overlap_until: r.overlap_until, directory: r.directory, private_key_file: r.file, next }));
946
+ print(values.text ? `${msg}\n${next}` : json({ status: "ok", message: msg, keyid: r.keyid, public_jwk: r.public_jwk, previous_keyid: r.previous_keyid, overlap_days: r.overlap_days, overlap_until: r.overlap_until, directory: r.directory, private_key_file: r.file, next }));
868
947
  }
869
948
  }
870
949
  else
@@ -881,9 +960,25 @@ async function main() {
881
960
  if (sessionPriv && !values["dry-run"])
882
961
  throw new Error("Private mode: nothing in the store is changed, so nothing is cleared. Use --dry-run to see what clear would remove.");
883
962
  const r = await clearStore({ limits: loadLimits(), olderThanMs, all: values.all, dryRun: values["dry-run"] });
884
- console.log(values.text ? r.summary : json(r));
963
+ print(values.text ? r.summary : json(r));
885
964
  return r.not_removed ? 1 : 0; // v0.6: something clear meant to remove is still there
886
965
  }
966
+ if (cmd === "read" && localBudget !== undefined) {
967
+ // What a local model gets: the read local mode makes, printed as JSON. A local model can pass only these
968
+ // options, and its reads are not tabs.
969
+ const extra = (tokens ?? []).find((t) => t.kind === "option" && !["local", "local-budget", "question", "section", "page", "private", "profile"].includes(t.name));
970
+ if (extra)
971
+ throw new Error(`--local takes only --question, --section, --page and --local-budget, not --${extra.name}.`);
972
+ const section = values.section === undefined ? undefined : Number(values.section);
973
+ if (section !== undefined && (!Number.isInteger(section) || section < 1))
974
+ throw new Error("--section must be a whole number, 1 or more");
975
+ const r = await localRead(need(), { question: values.question, section, page }, ctx, localBudget);
976
+ if (r.status === "error")
977
+ printError(json(r, 0));
978
+ else
979
+ print(json(r));
980
+ return exitFor(r.status);
981
+ }
887
982
  let out;
888
983
  if (cmd === "read") {
889
984
  const section = values.section === undefined ? undefined : Number(values.section);
@@ -909,7 +1004,7 @@ async function main() {
909
1004
  if (isEnv)
910
1005
  printEnvelope(out, values.text);
911
1006
  else
912
- console.log(json(out));
1007
+ print(json(out));
913
1008
  return isEnv ? exitFor(out.status) : 0;
914
1009
  }
915
1010
  // W-30 (v0.6): the door checks a read started in the background finish (or end by their own deadline)
@@ -920,7 +1015,7 @@ main().then(async (code) => {
920
1015
  // W-32 (v0.9): a --text reply ends with the settings notice (a JSON reply carries it as settings_notice).
921
1016
  const n = process.argv.includes("--text") && loadChoice("text_views") !== "wrapped" ? currentNotice() : undefined;
922
1017
  if (n)
923
- (code === 0 ? console.log : console.error)(`\nSettings notice:\n${n.map((l) => ` ${l}`).join("\n")}`);
1018
+ (code === 0 ? print : printError)(`\nSettings notice:\n${n.map((l) => ` ${l}`).join("\n")}`);
924
1019
  await drainForExit();
925
1020
  process.exit(code);
926
1021
  }, async (e) => {
@@ -941,7 +1036,7 @@ main().then(async (code) => {
941
1036
  const sub = process.argv[2] && /^[a-z]{1,20}$/.test(process.argv[2]) ? process.argv[2] : "<command>";
942
1037
  const msg = opt !== undefined ? `Unknown option ${JSON.stringify(opt)}. Run tiresias ${sub} --help for the options it takes.` : e.message;
943
1038
  const n = process.argv.includes("--text") ? currentNotice() : undefined;
944
- console.error(process.argv.includes("--text") ? msg + (n ? `\n\nSettings notice:\n${n.map((l) => ` ${l}`).join("\n")}` : "") : json({ status: "error", message: msg }, 0));
1039
+ printError(process.argv.includes("--text") ? msg + (n ? `\n\nSettings notice:\n${n.map((l) => ` ${l}`).join("\n")}` : "") : json({ status: "error", message: msg }, 0));
945
1040
  await drainForExit();
946
1041
  process.exit(1);
947
1042
  });
package/dist/config.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // Absent means these defaults. A bad value is a clear error, never a guess.
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
+ import { isOwnerAddress } from "./guardnetwork.js";
6
7
  import { releaseLock, stillOwned, takeLock } from "./ownedlock.js";
7
8
  import { NOFOLLOW, NONBLOCK, home, ownFile, randomTmp, readOwnedText } from "./store.js";
8
9
  // W-32 (v0.9): readers of a risky setting use the value in force (an unconfirmed loosening is held back).
@@ -64,6 +65,63 @@ export function loadTranslator() {
64
65
  return null;
65
66
  return parseTranslator(o.translator);
66
67
  }
68
+ export const GUARD_TIMEOUT = 4;
69
+ const GUARD_KEYS = new Set(["url", "model", "prefix", "timeout_seconds", "allow_public"]);
70
+ const BAD_GUARD = 'config.json: "guard" must be {"url": "http://localhost:1234/v1", "model": "<embedding model id>", "prefix": "...", "timeout_seconds": 1 to 60}. Set it with: tiresias guard setup --url <url> --model <id>';
71
+ const CONTROL = /[\u0000-\u001f\u007f]/;
72
+ // Addresses written as an IP that are public. A host NAME is judged when the call is made (guardclient.ts), from
73
+ // the addresses it resolves to.
74
+ const PUBLIC_LITERAL = (host, isPrivate) => {
75
+ const h = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
76
+ return /^[0-9.]+$/.test(h) || h.includes(":") ? !isPrivate(h) : false;
77
+ };
78
+ export function parseGuardUrl(v, isPrivate = isOwnerAddress) {
79
+ if (typeof v !== "string" || v.length === 0 || v.length > 2048 || CONTROL.test(v))
80
+ throw new ConfigError(BAD_GUARD);
81
+ let u;
82
+ try {
83
+ u = new URL(v);
84
+ }
85
+ catch {
86
+ throw new ConfigError('The guard "url" is not a valid address. Give the base of an OpenAI-compatible API, like http://localhost:1234/v1');
87
+ }
88
+ if (u.protocol !== "http:" && u.protocol !== "https:")
89
+ throw new ConfigError('The guard "url" must start with http:// or https://.');
90
+ if (u.username || u.password)
91
+ throw new ConfigError('The guard "url" must not contain a user name or password. A key goes in the environment variable TIRESIAS_GUARD_KEY.');
92
+ if (u.search || u.hash || v.includes("?") || v.includes("#"))
93
+ throw new ConfigError('The guard "url" must not have a query or a # part.');
94
+ if (u.protocol === "http:" && PUBLIC_LITERAL(u.hostname, isPrivate))
95
+ throw new ConfigError("Plain http to a public address is refused: page text would cross the internet unencrypted. Use https, or an address on your own network.");
96
+ return (u.origin + u.pathname).replace(/\/+$/, "");
97
+ }
98
+ export function parseGuard(v, isPrivate) {
99
+ if (typeof v !== "object" || v === null || Array.isArray(v))
100
+ throw new ConfigError(BAD_GUARD);
101
+ const o = v;
102
+ for (const k of Object.keys(o))
103
+ if (!GUARD_KEYS.has(k))
104
+ throw new ConfigError(BAD_GUARD);
105
+ const url = parseGuardUrl(o.url, isPrivate);
106
+ if (typeof o.model !== "string" || o.model.length === 0 || o.model.length > 200 || CONTROL.test(o.model))
107
+ throw new ConfigError(BAD_GUARD);
108
+ const prefix = Object.hasOwn(o, "prefix") ? o.prefix : "";
109
+ if (typeof prefix !== "string" || prefix.length > 200 || CONTROL.test(prefix))
110
+ throw new ConfigError(BAD_GUARD);
111
+ const t = Object.hasOwn(o, "timeout_seconds") ? o.timeout_seconds : GUARD_TIMEOUT;
112
+ if (typeof t !== "number" || !Number.isSafeInteger(t) || t < 1 || t > 60)
113
+ throw new ConfigError(BAD_GUARD);
114
+ if (Object.hasOwn(o, "allow_public") && o.allow_public !== true)
115
+ throw new ConfigError(BAD_GUARD);
116
+ return { url, model: o.model, prefix, timeout_seconds: t, ...(o.allow_public === true ? { allow_public: true } : {}) };
117
+ }
118
+ // The meaning check of this profile, or null when none is set. A bad setting is a ConfigError.
119
+ export function loadGuard(isPrivate) {
120
+ const o = inForceConfig();
121
+ if (!o || !Object.hasOwn(o, "guard"))
122
+ return null;
123
+ return parseGuard(o.guard, isPrivate);
124
+ }
67
125
  // The whole config.json as an object (null when there is none). A bad file is a ConfigError.
68
126
  function readConfigFile() {
69
127
  const raw = readOwnedText("config.json");
@@ -201,6 +259,7 @@ export const SECURITY_CHOICES = {
201
259
  private_spacing: ["shared", "none"],
202
260
  hook_secrets: ["hidden", "inherit"],
203
261
  text_views: ["marked", "wrapped"],
262
+ written_by: ["on", "off"], // W-39 (v1.2): local mode's written_by label
204
263
  };
205
264
  export function parseChoice(name, value) {
206
265
  if (typeof value === "string" && SECURITY_CHOICES[name].includes(value))
@@ -211,7 +270,7 @@ export function loadChoice(name) {
211
270
  const o = inForceConfig();
212
271
  return o && Object.hasOwn(o, name) ? parseChoice(name, o[name]) : SECURITY_CHOICES[name][0];
213
272
  }
214
- const OWN_CHECK_KEYS = [...Object.keys(SECURITY_CHOICES), "doors", "sites", "translator", "rendering", "saving", "anchoring", "anchor_calendars"]; // translator: v0.7 W-26; rendering: v0.7 W-10; saving: v0.8 W-28; anchoring, anchor_calendars: v0.8 W-08
273
+ const OWN_CHECK_KEYS = [...Object.keys(SECURITY_CHOICES), "doors", "sites", "translator", "rendering", "saving", "anchoring", "anchor_calendars", "guard"]; // translator: v0.7 W-26; rendering: v0.7 W-10; saving: v0.8 W-28; anchoring, anchor_calendars: v0.8 W-08; guard: v1.2 W-38
215
274
  export const KNOWN_KEYS = [...Object.keys(DEFAULT_LIMITS), ...SIGNING_KEYS, ...SAFETY_KEYS, "scanner", ...OWN_CHECK_KEYS];
216
275
  export const DEFAULT_DOORS = "background";
217
276
  export function parseDoors(v) {