worktrust 0.10.37 → 0.11.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.
Files changed (43) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +59 -2
  3. package/SECURITY.md +25 -0
  4. package/chat-exports.mjs +20 -20
  5. package/engine-release.json +1 -1
  6. package/export-facts.mjs +71 -0
  7. package/log-session.mjs +15 -15
  8. package/package-release.json +1 -1
  9. package/package.json +36 -2
  10. package/remote-adapter-claude-code.mjs +111 -0
  11. package/remote-adapter-codex.mjs +119 -0
  12. package/remote-approval-bridge.mjs +122 -0
  13. package/remote-approvals.mjs +124 -0
  14. package/remote-attachments.mjs +129 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +325 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +205 -0
  22. package/remote-inventory.mjs +132 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-pairing.mjs +104 -0
  25. package/remote-pipeline-config.mjs +177 -0
  26. package/remote-pipeline-parsers.mjs +121 -0
  27. package/remote-pipeline.mjs +234 -0
  28. package/remote-policy.mjs +199 -0
  29. package/remote-preview.mjs +146 -0
  30. package/remote-projects.mjs +87 -0
  31. package/remote-protocol.mjs +3881 -0
  32. package/remote-qr.mjs +175 -0
  33. package/remote-release-plans.mjs +88 -0
  34. package/remote-releases.mjs +297 -0
  35. package/remote-run.mjs +174 -0
  36. package/remote-service.mjs +101 -0
  37. package/remote-session-list.mjs +25 -0
  38. package/remote-sessions.mjs +348 -0
  39. package/remote-steered.mjs +114 -0
  40. package/remote-steering.mjs +97 -0
  41. package/remote-store.mjs +123 -0
  42. package/remote-transport.mjs +88 -0
  43. package/worktrust.mjs +13 -6
package/log-session.mjs CHANGED
@@ -66,7 +66,7 @@ import { dirname, join, resolve, sep } from "node:path";
66
66
  import { fileURLToPath } from "node:url";
67
67
  import { createHash, createHmac, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
68
68
 
69
- import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs";
69
+ import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs"; import { remoteSteeredOf } from "./remote-steered.mjs"; // 2026-11-07: a day steered from a phone is measured headless, steered_from "remote", never the person's hours (owner decision 1)
70
70
 
71
71
  async function main() {
72
72
  const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
@@ -244,7 +244,7 @@ const { stackOfFiles = () => [], displayStackOfFiles = () => [] } = (await impor
244
244
  const EXPORT_PATHS = []; for (let i = 0; i < args.length; i += 1) if (args[i] === "--export" && args[i + 1]) EXPORT_PATHS.push(args[i + 1]);
245
245
  const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot", "gemini-cli"]; // the registry's keys, the name each line carries (0.10.35: Gemini CLI)
246
246
  const LIVE_SOURCE = new RegExp(`^(codex|antigravity|${DATABASE_CLIENTS.join("|")}):`); // a sweep entry's id → the client it names (every database client, 0.6.16)
247
- const READER_FILES = ["history-outbox.mjs", "transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
247
+ const READER_FILES = ["history-outbox.mjs", "transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs", "remote-steered.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
248
248
  /** The roots this machine's transcripts live under; a test names its own. */
249
249
  const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
250
250
  const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
@@ -516,7 +516,7 @@ function stretchesOf(file, since, saved = null) {
516
516
  messages.sort((a, b) => a.at - b.at);
517
517
  const byDay = byDayOf(messages);
518
518
  const agents = agentsByDay(file, since), session = kind.kind();
519
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay, session); return stretch && { ...stretch, ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
519
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const remote = remoteSteeredOf(file, ofDay), kindOf = remote ? "headless" : session; const stretch = measure(cwd, ofDay, kindOf); return stretch && { ...stretch, ref: stretchRef(file, day), steered: remote ? "remote" : steered, session: kindOf, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
520
520
  }
521
521
  /** stretchesOf for a Claude Code transcript, from its read position when `saved` holds a usable one; `positionAt(t)` on the list is the position to keep. */
522
522
  function claudeStretchesOf(file, since, saved) {
@@ -548,7 +548,7 @@ function claudeStretchesOf(file, since, saved) {
548
548
  const byDay = byDayOf(messages), positions = {};
549
549
  const agents = agentsByDay(file, since, saved?.a ?? null, positions), session = kind.kind();
550
550
  subs = positions;
551
- stretches = [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay, session); return stretch && { ...stretch, ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
551
+ stretches = [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const remote = remoteSteeredOf(file, ofDay), kindOf = remote ? "headless" : session; const stretch = measure(cwd, ofDay, kindOf); return stretch && { ...stretch, ref: stretchRef(file, day), steered: remote ? "remote" : steered, session: kindOf, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
552
552
  }
553
553
  // A read that failed keeps no position: the next run reads the file whole.
554
554
  if (!at.failed && at.end !== undefined && carry !== null) {
@@ -1102,7 +1102,7 @@ const historyRunId = (bodies) => {
1102
1102
  function historyPlan(door, entries, rebuild = false, { byDay = false, withdrawUnknown = false } = {}) {
1103
1103
  const groups = [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS, ...EXPORT_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])];
1104
1104
  // Imported entries carry no live commit/session join.
1105
- const encodeBatch = (batch, run = null, days = null) => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map(({commits, ...rest}) => { void commits; return rest; }), ...(run ? { run } : {}), ...(days ? { days } : {}) } } });
1105
+ const encodeBatch = (batch, run = null, days = null) => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map(({commits, ...rest}) => { void commits; return rest; }), ...(exportOf(batch) ? { export: exportOf(batch) } : {}), ...(run ? { run } : {}), ...(days ? { days } : {}) } } }); const exportOf = (batch) => { const envelopes = new Set(batch.map((entry) => entryExport.get(entry))); return envelopes.size === 1 ? [...envelopes][0] ?? null : null; }; // 0.10.38: a batch of one export carries its envelope, of two none
1106
1106
  const plan = groups.flatMap(([source, group]) => { const target = source === "codex" ? codexDoor ?? door : door; return group.length > 0 && target ? batchesOf(group, byDay).map((batch) => ({ source, target, batch, run: null })) : []; });
1107
1107
  if (rebuild && !byDay) for (const token of new Set(plan.map((item) => item.target.token))) {
1108
1108
  const run = plan.filter((item) => item.target.token === token), id = historyRunId(run.map((item) => encodeBatch(item.batch)));
@@ -1335,7 +1335,7 @@ function historyEntries(floor = null, all = false) {
1335
1335
  // The live window belongs to the hook: a stretch that log_work may still report is not history.
1336
1336
  if (!all && Date.now() - last < WINDOW_HOURS * 3600_000) continue;
1337
1337
  // The same measure as a live day (seconds, layers, tokens, turns, model); history differs only in the door it goes through.
1338
- const stretch = { ...measure(cwd, messages, session), ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) };
1338
+ const remote = remoteSteeredOf(file, messages), kindOf = remote ? "headless" : session; const stretch = { ...measure(cwd, messages, kindOf), ref: stretchRef(file, day), steered: remote ? "remote" : steered, session: kindOf, agents: agents.get(day) ?? null, live: liveOf(file, day) };
1339
1339
  // ONE LINE PER PROCESS PER DAY (0.10.33), as live: an autonomous run joins its process's day, sent below as one line.
1340
1340
  if (isProcessRun(stretch)) {
1341
1341
  const key = processKey(CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : DATABASE_SESSION.test(file) ? file.slice(0, file.indexOf(":")) : null, stretch, false);
@@ -1390,37 +1390,37 @@ async function exportEntries() {
1390
1390
  if (!exportSessions || !exportRunRef) throw Error("chat-exports.mjs is not beside this file, or is older than this hook: a data export cannot be read");
1391
1391
  const entries = [], reports = [];
1392
1392
  for (const given of EXPORT_PATHS) {
1393
- const read = { onProgress: (counts) => historyProgressOut?.({ phase: "read", unit: "parts", ...counts }) }, report = { days: new Set() }; // 0.10.18: the reader streams the export and fills `read` as it goes (path and vendor first; digest, count and the conversations left out as too large at the end)
1394
- for await (const { id, lines } of exportSessions(given, { excluded, report: read })) {
1393
+ const read = { onProgress: (counts) => historyProgressOut?.({ phase: "read", unit: "parts", ...counts }) }, report = { days: new Set() }, ofExport = []; let lastMessage = null; // 0.10.38: this export's entries carry its envelope once the read ended. // 0.10.18: the reader streams the export and fills `read` as it goes (path and vendor first; digest, count and the conversations left out as too large at the end)
1394
+ for await (const { id, lines, clock = null } of exportSessions(given, { excluded, report: read })) {
1395
1395
  const messages = [];
1396
1396
  for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
1397
- messages.sort((a, b) => a.at - b.at);
1397
+ messages.sort((a, b) => a.at - b.at); if (messages.length > 0) lastMessage = Math.max(lastMessage ?? -Infinity, messages[messages.length - 1].at);
1398
1398
  for (const [day, ofDay] of byDayOf(messages)) {
1399
1399
  if (ofDay.length === 0) continue;
1400
1400
  // ONE STRETCH PER RUN OF ACTIVITY (0.10.17): the day's messages cut where the hook calls a stretch finished; one run
1401
1401
  // is the day as before, under the name it always had; several name the one-envelope line they replace.
1402
1402
  const runs = runsOf(ofDay), old = exportRef(read.vendor, id, day);
1403
1403
  runs.forEach(({ messages: run, tail }, index) => {
1404
- const stretch = measure(null, run), ref = runs.length === 1 ? old : exportRunRef(read.vendor, id, day, index);
1404
+ const stretch = measure(null, run), ref = runs.length === 1 ? old : exportRunRef(read.vendor, id, day, index), models = [...new Set(run.map((message) => message.model).filter((slug) => typeof slug === "string" && /^[a-z0-9][a-z0-9._-]{0,59}$/.test(slug)))].sort().slice(0, 20); // 0.10.38: every model slug of the run
1405
1405
  // The run's timeline, with the gap to the next run as a closing step (the loop's own, never a turn), so WorkTrust
1406
1406
  // counts it with this run as the one envelope did; the last run of the day closes where the day did.
1407
1407
  const timeline = stretch.timeline ? `${stretch.timeline}${tail ? `U${Math.min(999999, Math.max(0, Math.round((tail - run[run.length - 1].at) / 1000)))}` : ""}` : null;
1408
1408
  const entry = {
1409
1409
  title: EXPORT_TITLES[read.vendor], kind: "researched",
1410
1410
  ...(timeline ? { timeline, duration_basis: "reconstructed", turn_basis: "humanOnly" } : {}),
1411
- ...(stretch.model ? { model: stretch.model } : {}),
1411
+ ...(stretch.model ? { model: stretch.model } : {}), ...(models.length > 0 ? { models } : {}), ...(Number.isInteger(clock?.inversions) ? { tree_inversions: clock.inversions } : {}), ...(Number.isInteger(clock?.idSkew) ? { id_skew: clock.idSkew } : {}), // 0.10.38: and the conversation's clock facts, never its id
1412
1412
  stretch_ref: ref, source_event_id: `exp_${ref}`,
1413
1413
  ...(runs.length > 1 ? { supersedes_ref: old } : {}),
1414
1414
  started_at: new Date(stretch.from).toISOString(), utc_offset: stretch.offset, at: new Date(stretch.to).toISOString(),
1415
1415
  };
1416
1416
  entrySource.set(entry, read.vendor);
1417
1417
  entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
1418
- entries.push(entry);
1418
+ entries.push(entry); ofExport.push(entry);
1419
1419
  });
1420
1420
  report.days.add(day);
1421
1421
  }
1422
1422
  }
1423
- const days = [...report.days].sort();
1423
+ const envelope = read.envelope ? { ...read.envelope, ...(lastMessage !== null && (read.envelope.kind === "zip" || read.envelope.kind === "zips") ? { last_message_at: new Date(lastMessage).toISOString() } : {}) } : null; if (envelope) for (const entry of ofExport) entryExport.set(entry, envelope); const days = [...report.days].sort(); // ONE ENVELOPE PER EXPORT (0.10.38): its kind, named moment, write times, shape and last message; never its name
1424
1424
  // A DOWNLOAD CUT OFF (2026-10-31): the reader read the conversations parts the archive held whole before the cut, and says
1425
1425
  // where it stopped; the person is told every time, so a partial export is never shown as the whole (counts and part names only).
1426
1426
  for (const cut of read.cut ?? []) process.stderr.write(`export: the archive is cut off (${cut.where}) after ${cut.last}: ${cut.parts} conversations part${cut.parts === 1 ? "" : "s"} read whole, ${read.conversations} conversations; nothing past the cut is read, so this is not the whole export\n`);
@@ -1478,7 +1478,7 @@ function folderEntries(given) {
1478
1478
  report.stretches += 1;
1479
1479
  if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
1480
1480
  seen.add(ref);
1481
- const rest = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
1481
+ const remote = remoteSteeredOf(file, messages), rest = payloadFor({ ...measure(cwd, messages, remote ? "headless" : null), ref, steered: remote ? "remote" : null, session: remote ? "headless" : null, agents: null }); // a copied steered session stays out of the person's hours (P2-d)
1482
1482
  const entry = { ...rest, title: rest.layer ? `AI-assisted work from a copied session folder · ${rest.layer}` : "AI-assisted work from a copied session folder", ...(rest.timeline ? { duration_basis: "reconstructed" } : {}) };
1483
1483
  if (client !== "claude") entrySource.set(entry, client);
1484
1484
  entryFile.set(entry, { file, from: firstOf(messages), folder: null });
@@ -1638,7 +1638,7 @@ const door = coupling();
1638
1638
  */
1639
1639
  const codexDoor = codexCoupling();
1640
1640
  const doorFor = (entry) => (String(entry?.id ?? "").startsWith("codex:") ? codexDoor ?? door : door);
1641
- const entrySource = new WeakMap(); // an entry → "codex" or "antigravity" by the client that wrote it; the sends route and name by it
1641
+ const entrySource = new WeakMap(), entryExport = new WeakMap(); // an entry → "codex" or "antigravity" by the client that wrote it; the sends route and name by it. 0.10.38: an export's entry → its envelope
1642
1642
  const entryFile = new WeakMap(); // a history entry → its transcript (`--summary` counts sessions), first moment and folder name (`--archive-lines`)
1643
1643
  // THE LOCAL ARCHIVE (`npx worktrust preserve --archive`, 2026-10-06): every measured day, live window and floors aside, as JSON lines to preserve.mjs on this computer, which keeps metadata only; nothing is sent.
1644
1644
  // WHAT THIS COMPUTER MEASURES (0.8.3, for `npx worktrust status`): the last thirty days of its own sessions, summed from
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"e8abb38c293b57b71d3a6163d6242d1f375e773372b91b6d8ce39c584c51262a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"f603caa93e074200d8ebde79cfed1c6b884ac6a3079926a94536c71d21a3b538","SECURITY.md":"4f2b644d8a7ff87bd87d593f2bdff3f1149454151559f633fc16801cedff7dbe","chat-exports.mjs":"1dc109a971f88605ee3fa3a7564bcd57bce2047b86bfcd92eb3e5acf865d8f11","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"527a7674f9d52b284bfda3b8089eb4b930a709bf14aedbec7f6eef1e59ef52ee","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"0e766c012881c228e0472ec3426620e0d1e4e01d5668f6f33d3c60e4a0e0ed1b","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"85c70389effc5b4ec9d9b33af9192314e67f47af2752515b42a7959344ce2354","history-progress.mjs":"dcc25ee94b727f2605a763349a4d8764640335d6cf0043fb6108cebeed16dcb9","log-session.mjs":"f7e8f247edcc5a3ad17c2c05b83452a938d0e9e20cde5f806a54c1fb04f28958","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"fb98ed631188c3ffe3d516646056408556899c74368e1d7d517c68837b79b84a","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"cd111cae0f53a25a2d878a158479abfb1ace353361454843f91a16d241101d46","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","self-update.mjs":"378e3620d48c72cf0bf812be408883b995cdb2223de34a20f762dd73eeffb258","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"b732e3dd9b3e522b7cc8acf167ce28ba8f1a8dee797ee15bd7c3b02919b13e6f","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"c417a0cabf02318cb3200bda514a3d4ca39dc95f5528d36ff59307f2f045b839"},"format":"worktrust-package/1","kind":"npm","version":"0.10.37"},"signature":"XHc9pXa0YEZrsLz9bB4Zy9AMprpIipFsGNpGUbefQwzJpqPHhqOjN4ch5rXJcGb1JZBxIiqq_FMKGK25EZQZBA"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"e8abb38c293b57b71d3a6163d6242d1f375e773372b91b6d8ce39c584c51262a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"b38ea343eb95892d4164274be4184d6e34eade9d4c454e1dcf8bc7735736425e","README.md":"5d3761035c4ef5efcfc91cfa0a2a6294c73aef402f8c111a721018ca11f86b82","SECURITY.md":"69f654b8101ab49821b8eb54b631f0a028035149c727953dc7d609faa2a9b2e0","chat-exports.mjs":"f026c5a063f62c22ba6f25474a9d9fdbb6074beebbfe1faff2a876c437a1a000","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"527a7674f9d52b284bfda3b8089eb4b930a709bf14aedbec7f6eef1e59ef52ee","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"03f37811391bbb10ee5996995e11bb140c69adff29ffc9780cdcf2fa4c88f579","export-facts.mjs":"3bbb46c80e8678b5cea7e15dcbfc456a2b48595053241c2b3cea508092f9b917","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"85c70389effc5b4ec9d9b33af9192314e67f47af2752515b42a7959344ce2354","history-progress.mjs":"dcc25ee94b727f2605a763349a4d8764640335d6cf0043fb6108cebeed16dcb9","log-session.mjs":"eb3bc0972bc30788521a492e136ed792d8265e0c5b8aede81fec4f3e071a25d0","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"385eab3ba728f06a484b92d0093625f0de0596a93abfd301c18a6f878f36ee1c","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"cd111cae0f53a25a2d878a158479abfb1ace353361454843f91a16d241101d46","remote-adapter-claude-code.mjs":"fe11c7fd37b570404e90fe53c11b471c2b5f114e8616bcdc281792cb000ecaf4","remote-adapter-codex.mjs":"44c41bc92a12ea6aa2232d67ba4a02f335aaea1429816e9a9e3eb3911a97cb3a","remote-approval-bridge.mjs":"9661bb2d698aed1c788246506e842dfaa4507d5357e454bf67b5b4b65da1621d","remote-approvals.mjs":"c033f36d261b3a5be552c9b02f92f30bd7217c8a1a55116fb514acb61e198c6f","remote-attachments.mjs":"2e9c1277329a45cf26c0c62abda632cf0ab9fad78d0504416ecee9805220e16c","remote-changes.mjs":"2141fece4961a5bc1bb1b046f78222812617457b1ba6452275eac6a897e62e19","remote-claude-events.mjs":"58822471203c6a1b66cf81c115c4d713657c3dea5c7b98df959f894ee5b2e704","remote-claude-progress.mjs":"2ca626d3dbc16d8d570abe1df6477b7e44ffb43c1d9145228ec5ea1928e415ca","remote-cli.mjs":"85a6b26e332f6b89584edfa58bff6d753918cc391ca62bb02b9f344b0508db37","remote-coalesce.mjs":"cb0967d9cfe81e3892bcade8349d6814db98be8c2adbdb54df0b8d1b142f65d1","remote-codex-events.mjs":"58657d6070a50c837737cb85f5a1eaf9c2cbc4e1adfe3e970748ab3b2af94631","remote-daemon.mjs":"c22eec13da604d262c116a7a389555dae8a3b68fd9de7df44dad178f3ea0ec63","remote-inventory.mjs":"d5a1c0180bab5c0522e73c913876050b9b36eb9ed06a8fa0e8e258ce54b67282","remote-journal.mjs":"907ebd48c53162b22dc743ef95b53c1a6be6886a7495605b5cfa820b8de9d330","remote-pairing.mjs":"ae03427b6510e52da08aaf9387d5e08516ee25380c7efa420432f4e1e936a7c5","remote-pipeline-config.mjs":"00cde6a61ce21144c51ac56fce42fee159aa9dba6586218a7ea790ce4a6bd40b","remote-pipeline-parsers.mjs":"43ca0d332d7bc883c4759a754a555815ae5dfe133446b91ba9f2e48a350fa20f","remote-pipeline.mjs":"b856ead989b29ddb618ef69bbacd104bae2b02c9d1c5214291d08ce469a8b24e","remote-policy.mjs":"aacf7578537021ab3849095bb1f58f0ed12c453c6ca2ab1352a1716fb13b0ca4","remote-preview.mjs":"fe504ad6f83dcb4a4ebdcc018686a9a5a900c47cdf8c45b75e7d02e2f3056155","remote-projects.mjs":"d07997167d1f51139ff010c8753639e48c5cd33688568459e184eabb12bfff84","remote-protocol.mjs":"f0beb91750397d1c6f0042fe716413cf8027684a84d4ed17bccee996cc5e2544","remote-qr.mjs":"b80e2b4a5bc020cf6ed92e91d06b327cb5197de1c35b3445a0fc2c7a3bf1ab3f","remote-release-plans.mjs":"11884a62b7d6dcccb5e154a26603bdf650f7b40f946329fb174d8c13729bec74","remote-releases.mjs":"fb08b72593ea00013c8b679e0c0d7dee95b0fd7cc5fd31b80ac575d0e340927d","remote-run.mjs":"914af621d768abd126adda479f5ee7d52f3ed93c17897ab184c7116980b299e2","remote-service.mjs":"1b9d4ecf99b667f2ab7c78fe1dfd5cf507cbb36c5bcad15bfa2a88c313ae758e","remote-session-list.mjs":"0fc1e9df7997e28c8c9a63d3ae63347120fa91238b82ee05c1041b1e9d297ebd","remote-sessions.mjs":"24e24d0e574c40049edd7ae11d4cc98965f2a962bbd59c642a0ea7d6b74f5171","remote-steered.mjs":"fbbd3685a8cd497ae03235d258e2116e2129aac19046759fb2468fe79911f0b3","remote-steering.mjs":"7ba22e6110cea3ac75a4f084f8f92a5bd90c31a19d3ce58a88a0843bdadea834","remote-store.mjs":"c68fd7b55d857cd4c06d0e53a5989c4f20e7f8e7add5e18443b3c16d864cabd1","remote-transport.mjs":"68650fd77ea09b5762377f87cabdc1c73a34d77324aa5bf0cd9742094a50c32b","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","self-update.mjs":"378e3620d48c72cf0bf812be408883b995cdb2223de34a20f762dd73eeffb258","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"b732e3dd9b3e522b7cc8acf167ce28ba8f1a8dee797ee15bd7c3b02919b13e6f","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"5321c67b7bb0699780a155d87473a4975ef81e47deada06f7d5b5bde9a973f98"},"format":"worktrust-package/1","kind":"npm","version":"0.11.0"},"signature":"nhkweQcjZafacdx-z25thk9gfupt1ky7I1lOGsosm9vJWmUB9A825pL3FIgAKDWf5HRu4EFTYVV0i52ujpyzAw"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.37",
3
+ "version": "0.11.0",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,6 +19,7 @@
19
19
  "preserve-lines.mjs",
20
20
  "stretch-evidence.mjs",
21
21
  "chat-exports.mjs",
22
+ "export-facts.mjs",
22
23
  "stack-rules.mjs",
23
24
  "runtime-install.mjs",
24
25
  "README.md",
@@ -41,7 +42,40 @@
41
42
  "credential-vault.mjs",
42
43
  "credential-vault-scripts.mjs",
43
44
  "self-update.mjs",
44
- "history-progress.mjs"
45
+ "history-progress.mjs",
46
+ "remote-protocol.mjs",
47
+ "remote-store.mjs",
48
+ "remote-policy.mjs",
49
+ "remote-journal.mjs",
50
+ "remote-steered.mjs",
51
+ "remote-inventory.mjs",
52
+ "remote-claude-events.mjs",
53
+ "remote-claude-progress.mjs",
54
+ "remote-attachments.mjs",
55
+ "remote-preview.mjs",
56
+ "remote-coalesce.mjs",
57
+ "remote-steering.mjs",
58
+ "remote-codex-events.mjs",
59
+ "remote-adapter-codex.mjs",
60
+ "remote-projects.mjs",
61
+ "remote-pipeline-config.mjs",
62
+ "remote-pipeline-parsers.mjs",
63
+ "remote-pipeline.mjs",
64
+ "remote-releases.mjs",
65
+ "remote-release-plans.mjs",
66
+ "remote-adapter-claude-code.mjs",
67
+ "remote-approval-bridge.mjs",
68
+ "remote-approvals.mjs",
69
+ "remote-sessions.mjs",
70
+ "remote-session-list.mjs",
71
+ "remote-changes.mjs",
72
+ "remote-daemon.mjs",
73
+ "remote-transport.mjs",
74
+ "remote-run.mjs",
75
+ "remote-service.mjs",
76
+ "remote-pairing.mjs",
77
+ "remote-qr.mjs",
78
+ "remote-cli.mjs"
45
79
  ],
46
80
  "engines": {
47
81
  "node": ">=18"
@@ -0,0 +1,111 @@
1
+ /**
2
+ * THE CLAUDE CODE ADAPTER, STRUCTURED (2026-11-07). One managed process per remote session:
3
+ *
4
+ * claude -p --input-format stream-json --output-format stream-json --verbose
5
+ * --permission-mode <the mode its help lists for "ask", or plan>
6
+ * --permission-prompt-tool mcp__worktrust_remote__approve --mcp-config <this session's file>
7
+ * [--model <a model the computer listed>] (--session-id <uuid chosen here> | --resume <the agent's own id>)
8
+ *
9
+ * in the granted project folder, in a process group of its own. Every argument comes from this file and the closed start
10
+ * options the computer checked again (checkStart); no text from the phone becomes an argument except a resume id that is
11
+ * a UUID. Prompts go in as stream-json user messages; Claude Code takes one turn at a time, so a prompt (or a steer) that
12
+ * arrives mid-turn waits for the next turn and is accepted only when that turn begins. There is no pause: Claude Code has
13
+ * none, the report says so, and a pause is refused. Stop interrupts the group (SIGINT), then ends it (SIGTERM, SIGKILL).
14
+ * The approval tool is remote-approval-bridge.mjs, started by Claude Code itself from the MCP config written here.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { writeFileSync, rmSync } from "node:fs";
18
+
19
+ export const APPROVAL_TOOL = "mcp__worktrust_remote__approve";
20
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
21
+ export const isClaudeSessionId = (value) => typeof value === "string" && UUID.test(value);
22
+
23
+ /** The command line, from closed options only. Throws on anything else: nothing unchecked is passed through. */
24
+ /**
25
+ * WHAT A REMOTE SESSION MAY NEVER DO, AS CLAUDE CODE'S OWN DENY RULES (review 2026-11-07, P1-c). The person's allow rules
26
+ * and a repository's committed settings apply before the permission-prompt tool is asked, so a phone prompt could otherwise
27
+ * push, install or deploy with no approval at all. Deny beats allow in Claude Code, so these are passed with
28
+ * --disallowedTools; and --setting-sources user keeps a granted repository's own rules and hooks out of a remote session.
29
+ */
30
+ export const REMOTE_DENY = Object.freeze([
31
+ "Bash(git push:*)", "Bash(git push)", "Bash(git remote:*)", "Bash(npm install:*)", "Bash(npm i:*)", "Bash(npm ci:*)", "Bash(npm publish:*)", "Bash(npm exec:*)",
32
+ "Bash(pnpm add:*)", "Bash(pnpm install:*)", "Bash(pnpm i:*)", "Bash(pnpm dlx:*)", "Bash(pnpm publish:*)", "Bash(yarn add:*)", "Bash(yarn install:*)", "Bash(yarn dlx:*)",
33
+ "Bash(npx:*)", "Bash(bunx:*)", "Bash(bun add:*)", "Bash(bun install:*)", "Bash(pip install:*)", "Bash(pip3 install:*)", "Bash(pipx:*)", "Bash(uv pip:*)", "Bash(poetry add:*)",
34
+ "Bash(brew:*)", "Bash(curl:*)", "Bash(wget:*)", "Bash(gem install:*)", "Bash(cargo install:*)", "Bash(go install:*)", "Bash(go get:*)",
35
+ "Bash(vercel:*)", "Bash(netlify:*)", "Bash(fly:*)", "Bash(flyctl:*)", "Bash(firebase:*)", "Bash(heroku:*)", "Bash(wrangler:*)", "Bash(kubectl:*)", "Bash(helm:*)", "Bash(terraform:*)", "Bash(pulumi:*)", "Bash(eas:*)",
36
+ "Bash(rm -rf:*)", "Bash(sudo:*)", "Read(**/.env)", "Read(**/.env.*)", "Read(~/.ssh/**)", "Read(**/*.pem)", "Read(**/*.key)", "Read(~/.aws/**)", "Read(~/.worktrust/**)",
37
+ "Edit(~/.worktrust/**)", "Write(~/.worktrust/**)", "Edit(**/.env)", "Edit(**/.env.*)",
38
+ ]);
39
+
40
+ /** The planning tools of the session's own MCP server (remote-approval-bridge.mjs): they only write a plan, so no prompt. */
41
+ export const PLAN_TOOLS = Object.freeze(["mcp__worktrust_remote__plan_release", "mcp__worktrust_remote__plan_task", "mcp__worktrust_remote__plan_list"]);
42
+ /** The one line the session's system prompt gains (owner, 2026-11-08: the agent arranges its own work). */
43
+ export const PLAN_HINT = "WorkTrust remote: plan multi-step work with plan_release and report each task with plan_task; the person follows it on their phone.";
44
+
45
+ export function claudeArgs({ features, mode, model, resume, sessionRef, mcpConfig }) {
46
+ if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
47
+ const permission = mode === "plan" ? features.planMode : features.askMode;
48
+ if (!permission) throw new Error("this Claude Code offers no such permission mode");
49
+ if (resume !== null && !isClaudeSessionId(resume)) throw new Error("a resume id is Claude Code's own session uuid");
50
+ if (resume === null && !isClaudeSessionId(sessionRef)) throw new Error("a new session needs its uuid");
51
+ if (model !== null && (typeof model !== "string" || model.startsWith("-") || !/^[A-Za-z0-9._:@\[\]-]{1,128}$/.test(model))) throw new Error("not a model name");
52
+ if (!features.disallowed || !features.settingSources) throw new Error("this Claude Code cannot take deny rules or limit its setting sources");
53
+ // --replay-user-messages: Claude Code echoes each user message as it reads it (isReplay), which is how a live steer is
54
+ // known to have entered the running turn (remote-steering.mjs; measured on 2.1.286: at the next tool boundary).
55
+ return ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", ...(features.replay ? ["--replay-user-messages"] : []), "--permission-mode", permission, "--setting-sources", "user", "--disallowedTools", ...REMOTE_DENY,
56
+ ...(features.allowed ? ["--allowedTools", ...PLAN_TOOLS] : []), ...(features.appendPrompt ? ["--append-system-prompt", PLAN_HINT] : []),
57
+ "--permission-prompt-tool", APPROVAL_TOOL, "--mcp-config", mcpConfig, ...(features.partial ? ["--include-partial-messages"] : []), ...(model ? ["--model", model] : []), ...(resume ? ["--resume", resume] : ["--session-id", sessionRef])];
58
+ }
59
+
60
+ /** The session's MCP config: our bridge only, its socket and its one-time token. Mode 0600, removed with the session. */
61
+ export function writeMcpConfig(file, { node, bridge, socket, token }) {
62
+ writeFileSync(file, JSON.stringify({ mcpServers: { worktrust_remote: { command: node, args: [bridge], env: { WORKTRUST_REMOTE_APPROVAL_SOCKET: socket, WORKTRUST_REMOTE_APPROVAL_TOKEN: token } } } }), { mode: 0o600 });
63
+ return file;
64
+ }
65
+
66
+ /** A user message on stdin, as Claude Code's stream-json input reads it. */
67
+ export const userMessage = (text) => `${JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text }] } })}\n`;
68
+
69
+ export function startClaude({ file, cwd, env, args, onLine, onExit, onNoise = () => {} }) {
70
+ const child = spawn(file, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
71
+ let buffer = "", exited = false, interrupts = 0;
72
+ child.stdout.setEncoding("utf8");
73
+ child.stdout.on("data", (chunk) => {
74
+ buffer += chunk;
75
+ if (buffer.length > 16 * 1024 * 1024) { buffer = ""; onNoise("line too long"); return; }
76
+ let end;
77
+ while ((end = buffer.indexOf("\n")) >= 0) {
78
+ const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
79
+ if (!raw.trim()) continue;
80
+ let line = null;
81
+ try { line = JSON.parse(raw); } catch { onNoise("not JSON"); continue; }
82
+ onLine(line);
83
+ }
84
+ });
85
+ child.stderr.on("data", () => onNoise("stderr")); // never logged: it may hold the agent's words
86
+ child.stdin.on("error", () => {});
87
+ const exit = new Promise((resolve) => child.on("exit", (code, signal) => { exited = true; onExit({ code, signal }); resolve({ code, signal }); }));
88
+ child.on("error", () => { if (!exited) { exited = true; onExit({ code: null, signal: null, error: true }); } });
89
+ const signal = (sig) => { try { if (process.platform === "win32") child.kill(sig); else process.kill(-child.pid, sig); } catch { /* gone */ } };
90
+ return {
91
+ pid: child.pid,
92
+ alive: () => !exited,
93
+ write: (text) => { if (!exited) child.stdin.write(userMessage(text)); },
94
+ /**
95
+ * End the running turn and keep the session: stream-json's control request (measured on 2.1.286: the turn ends
96
+ * error_during_execution about 0.3 s later, the process stays, the next user message runs as a new turn).
97
+ */
98
+ interrupt: async () => { if (exited) return false; interrupts += 1; child.stdin.write(`${JSON.stringify({ type: "control_request", request_id: `wt_interrupt_${interrupts}`, request: { subtype: "interrupt" } })}\n`); return true; },
99
+ /** Interrupt, then end, the whole process group; resolves when it is gone. */
100
+ async stop(graceMs = 3000) {
101
+ if (exited) return;
102
+ for (const sig of ["SIGINT", "SIGTERM", "SIGKILL"]) {
103
+ signal(sig);
104
+ if (await Promise.race([exit.then(() => true), new Promise((r) => setTimeout(() => r(false), graceMs))])) return;
105
+ }
106
+ },
107
+ close: () => { try { child.stdin.end(); } catch { /* closed */ } },
108
+ };
109
+ }
110
+
111
+ export const removeQuietly = (file) => rmSync(file, { force: true });
@@ -0,0 +1,119 @@
1
+ /**
2
+ * THE CODEX ADAPTER (2026-11-07; docs/remote-agents/PROTOCOL.md "Steering a running turn"). Codex runs as
3
+ * `codex app-server` (JSON-RPC over stdio, Codex 0.154.0), one process per remote session, no shell between us and it.
4
+ *
5
+ * initialize, initialized once
6
+ * thread/start | thread/resume the session (resume by the agent's own thread id); its id reaches `onThread`
7
+ * BEFORE the first turn starts, so the steered ledger names it first
8
+ * turn/start a prompt
9
+ * turn/steer { expectedTurnId } words into the RUNNING turn: measured on 0.154.0, they enter it at the next
10
+ * item boundary (a running command finishes first) and the turn's answer heeds them
11
+ * turn/interrupt end the running turn; the thread stays (measured: 0.7 s to `interrupted`)
12
+ * item/.../requestApproval Codex asks: classified by the computer's own policy as Bash or Edit actions;
13
+ * only an approvable class reaches the phone, everything else is declined here
14
+ * The approval policy is `untrusted` and the sandbox `workspace-write` (`read-only` in the plan mode): Codex asks before
15
+ * anything it does not already trust, and never writes outside the project on its own. No free argument reaches Codex.
16
+ */
17
+ import { spawn } from "node:child_process";
18
+ import { changePaths, codexApprovalAsTool, refusalFor } from "./remote-codex-events.mjs";
19
+
20
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
21
+ const THREAD = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
+ export const isCodexThreadId = (value) => typeof value === "string" && THREAD.test(value);
23
+
24
+ /**
25
+ * The fixed command line. The person's own Codex config stays (its model, its notify hook), but a remote session never
26
+ * widens the sandbox or reaches a configured MCP server (review 2026-11-07, P2-1): no extra writable roots, no network in
27
+ * the sandbox, no mcp_servers. MCP servers a Codex PLUGIN brings still start (measured on 0.154.0); that is part of the
28
+ * risk the person accepts when they turn Codex on (`worktrust remote codex on`).
29
+ */
30
+ export function codexArgs() {
31
+ return ["app-server", "--config", "sandbox_workspace_write.network_access=false", "--config", "sandbox_workspace_write.writable_roots=[]", "--config", "mcp_servers={}"];
32
+ }
33
+
34
+ /** thread/start or thread/resume parameters from the protocol's closed options. */
35
+ export function threadParams({ cwd, model, mode, resume }) {
36
+ if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
37
+ if (model !== null && !MODEL.test(model)) throw new Error("not a model name");
38
+ if (resume !== null && !isCodexThreadId(resume)) throw new Error("a resume id is Codex's own thread id");
39
+ const common = { cwd, approvalPolicy: "untrusted", sandbox: mode === "plan" ? "read-only" : "workspace-write", ...(model ? { model } : {}) };
40
+ return resume ? { method: "thread/resume", params: { threadId: resume, ...common } } : { method: "thread/start", params: common };
41
+ }
42
+
43
+ const text = (t) => [{ type: "text", text: t }];
44
+
45
+ /**
46
+ * o: { file, cwd, env, model, mode, resume, onMessage(msg), onThread(threadId), onExit(how), approve(tool, input) → Promise<boolean> }.
47
+ * → { pid, alive, write(text), steer(text) → Promise<{ ok }>, interrupt() → Promise<boolean>, stop(), close() }.
48
+ */
49
+ export function startCodex(o) {
50
+ const child = spawn(o.file, codexArgs(), { cwd: o.cwd, env: o.env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
51
+ let buffer = "", exited = false, nextId = 1, threadId = null, turnId = null, ready = false;
52
+ const waiting = new Map(), queue = [], fileChanges = {};
53
+ const send = (msg) => { if (!exited) child.stdin.write(`${JSON.stringify(msg)}\n`); };
54
+ const call = (method, params) => new Promise((resolve) => { if (exited) { resolve({ error: { message: "codex exited" } }); return; } const id = nextId++; waiting.set(id, resolve); send({ id, method, params }); });
55
+ const turn = (t) => call("turn/start", { threadId, input: text(t) });
56
+ async function answer(msg) {
57
+ const asks = msg.method === "item/permissions/requestApproval" ? null : codexApprovalAsTool(msg.method, msg.params, fileChanges, o.cwd);
58
+ let allowed = false;
59
+ if (asks) { allowed = true; for (const a of asks) if (!(await o.approve(a.tool, a.input))) { allowed = false; break; } }
60
+ send({ id: msg.id, result: { decision: allowed ? "accept" : refusalFor(msg.params) } });
61
+ }
62
+ child.stdout.setEncoding("utf8");
63
+ child.stdout.on("data", (chunk) => {
64
+ buffer += chunk;
65
+ if (buffer.length > 16 * 1024 * 1024) { buffer = ""; return; }
66
+ let end;
67
+ while ((end = buffer.indexOf("\n")) >= 0) {
68
+ const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
69
+ let msg;
70
+ try { msg = JSON.parse(raw); } catch { continue; }
71
+ if (msg.id !== undefined && msg.method === undefined) { waiting.get(msg.id)?.(msg); waiting.delete(msg.id); continue; }
72
+ if (msg.id !== undefined && typeof msg.method === "string") { answer(msg).catch(() => send({ id: msg.id, result: { decision: refusalFor(msg.params) } })); continue; }
73
+ if (msg.method === "turn/started") turnId = msg.params?.turn?.id ?? turnId;
74
+ if (msg.method === "turn/completed") turnId = null;
75
+ if (msg.method === "item/started" && msg.params?.item?.type === "fileChange") fileChanges[msg.params.item.id] = changePaths(msg.params.item.changes);
76
+ o.onMessage(msg);
77
+ }
78
+ });
79
+ child.stderr.on("data", () => {}); // never logged: it may hold the agent's words
80
+ child.stdin.on("error", () => {});
81
+ // A call never hangs on a Codex that is gone: every one waiting is answered with an error (review 2026-11-07, P2-3).
82
+ const settle = () => { for (const [id, resolve] of waiting) resolve({ id, error: { message: "codex exited" } }); waiting.clear(); };
83
+ const exit = new Promise((resolve) => child.on("exit", (code, signal) => { exited = true; settle(); o.onExit({ code, signal }); resolve(); }));
84
+ child.on("error", () => { if (!exited) { exited = true; settle(); o.onExit({ code: null, signal: null, error: true }); } });
85
+ (async () => {
86
+ await call("initialize", { clientInfo: { name: "worktrust-remote", version: "1" } });
87
+ send({ method: "initialized" });
88
+ const { method, params } = threadParams({ cwd: o.cwd, model: o.model, mode: o.mode, resume: o.resume });
89
+ const started = await call(method, params);
90
+ threadId = started.result?.thread?.id ?? null;
91
+ if (!isCodexThreadId(threadId)) { child.kill("SIGTERM"); return; }
92
+ o.onThread(threadId); // the ledger names the thread before its first turn
93
+ ready = true;
94
+ for (const t of queue.splice(0)) turn(t);
95
+ })().catch(() => child.kill("SIGTERM"));
96
+ const signal = (sig) => { try { if (process.platform === "win32") child.kill(sig); else process.kill(-child.pid, sig); } catch { /* gone */ } };
97
+ return {
98
+ pid: child.pid,
99
+ alive: () => !exited,
100
+ threadId: () => threadId,
101
+ write: (t) => { if (ready) turn(t); else queue.push(t); },
102
+ /** Words into the running turn, guarded by its id: a turn that just ended refuses them, and they wait for the next. */
103
+ async steer(t) { if (!ready || !turnId) return { ok: false }; const r = await call("turn/steer", { threadId, expectedTurnId: turnId, input: text(t) }); return { ok: !r.error }; },
104
+ async interrupt() { if (!ready || !turnId) return false; const r = await call("turn/interrupt", { threadId, turnId }); return !r.error; },
105
+ async stop(graceMs = 3000) {
106
+ if (exited) return;
107
+ if (turnId) await Promise.race([this.interrupt(), new Promise((r) => setTimeout(r, 1000))]);
108
+ for (const sig of ["SIGTERM", "SIGKILL"]) { signal(sig); if (await Promise.race([exit.then(() => true), new Promise((r) => setTimeout(() => r(false), graceMs))])) return; }
109
+ },
110
+ close: () => { try { child.stdin.end(); } catch { /* closed */ } },
111
+ };
112
+ }
113
+
114
+ /** What `codex --version` and its help say this Codex can do; the app-server's methods are fixed per version. */
115
+ export function codexReport(version, appServerHelp) {
116
+ const v = /codex-cli\s+(\d+)\.(\d+)\.(\d+)/.exec(version ?? "");
117
+ const usable = Boolean(v) && /generate-json-schema|--listen/.test(appServerHelp ?? "") && (Number(v[1]) > 0 || Number(v[2]) >= 154);
118
+ return { usable, capabilities: usable ? { start: true, prompt: true, steer: true, steer_mode: "live", interrupt: true, stop: true, structured_events: true, resume_by_id: true, permission_modes: ["ask", "plan"], approvals: "structured" } : null };
119
+ }
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * THE PERMISSION-PROMPT TOOL CLAUDE CODE CALLS IN A REMOTE SESSION (2026-11-07). A tiny MCP server on stdio, started by
4
+ * Claude Code itself from the --mcp-config the daemon wrote for one session (`--permission-prompt-tool
5
+ * mcp__worktrust_remote__approve`). Claude Code calls it whenever the person's own permission rules would have asked; the
6
+ * person's allow and deny rules still apply first, at the desk's settings.
7
+ *
8
+ * It decides nothing. It forwards each request ({ tool_name, input, tool_use_id }) over the daemon's local socket
9
+ * (~/.worktrust/remote/run/, this user only), with the session's one-time token, and answers what the daemon answers:
10
+ * { "behavior": "allow", "updatedInput": <the input, unchanged> } only after a signed phone approval of that exact input
11
+ * { "behavior": "deny", "message": "<why>" } everything else, including any failure here
12
+ * Fail closed: no daemon, a lost socket, a malformed answer or six minutes without one is a denial. This is not the
13
+ * WorkTrust MCP door and opens no network connection. It also carries the agent's PLANNING tools (plan_release,
14
+ * plan_task, plan_list; 2026-11-08), answered by the daemon's release queue for the session's own project.
15
+ */
16
+ import { createConnection } from "node:net";
17
+ import { createInterface } from "node:readline";
18
+
19
+ export const TOOL = "approve";
20
+ const SOCKET = process.env.WORKTRUST_REMOTE_APPROVAL_SOCKET ?? "";
21
+ const TOKEN = process.env.WORKTRUST_REMOTE_APPROVAL_TOKEN ?? "";
22
+ const WAIT_MS = 6 * 60_000;
23
+ const deny = (message) => ({ behavior: "deny", message });
24
+
25
+ /** Ask the daemon; any failure is a denial. */
26
+ export function askDaemon(request, socket = SOCKET, token = TOKEN, waitMs = WAIT_MS) {
27
+ return new Promise((resolve) => {
28
+ if (!socket || !token) { resolve(deny("WorkTrust remote: no approval channel for this session; denied")); return; }
29
+ let settled = false, buffer = "";
30
+ const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
31
+ const conn = createConnection(socket);
32
+ const timer = setTimeout(() => done(deny("WorkTrust remote: no decision in time; denied")), waitMs);
33
+ conn.on("connect", () => conn.write(`${JSON.stringify({ token, ...request })}\n`));
34
+ conn.on("data", (chunk) => {
35
+ buffer += chunk;
36
+ if (buffer.length > 1_048_576) { done(deny("WorkTrust remote: malformed answer; denied")); return; }
37
+ const end = buffer.indexOf("\n");
38
+ if (end < 0) return;
39
+ let answer = null;
40
+ try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
41
+ if (answer?.behavior === "allow" && answer.updatedInput && typeof answer.updatedInput === "object") done({ behavior: "allow", updatedInput: answer.updatedInput });
42
+ else done(deny(typeof answer?.message === "string" ? answer.message.slice(0, 2000) : "WorkTrust remote: denied"));
43
+ });
44
+ conn.on("error", () => done(deny("WorkTrust remote: the daemon is not reachable; denied")));
45
+ conn.on("close", () => done(deny("WorkTrust remote: the daemon closed the request; denied")));
46
+ });
47
+ }
48
+
49
+ /** A planning call over the same socket: the daemon's answer ({ ok, ... }), or a refusal on any failure. */
50
+ export function askPlan(op, args, socket = SOCKET, token = TOKEN, waitMs = 30_000) {
51
+ return new Promise((resolve) => {
52
+ const refuse = (reason) => ({ ok: false, reason });
53
+ if (!socket || !token) { resolve(refuse("no planning channel for this session")); return; }
54
+ let settled = false, buffer = "";
55
+ const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
56
+ const conn = createConnection(socket);
57
+ const timer = setTimeout(() => done(refuse("no answer in time")), waitMs);
58
+ conn.on("connect", () => conn.write(`${JSON.stringify({ token, plan: { op, args } })}\n`));
59
+ conn.on("data", (chunk) => {
60
+ buffer += chunk;
61
+ if (buffer.length > 1_048_576) { done(refuse("malformed answer")); return; }
62
+ const end = buffer.indexOf("\n");
63
+ if (end < 0) return;
64
+ let answer = null;
65
+ try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
66
+ done(answer && typeof answer === "object" && typeof answer.ok === "boolean" ? answer : refuse("malformed answer"));
67
+ });
68
+ conn.on("error", () => done(refuse("the daemon is not reachable")));
69
+ conn.on("close", () => done(refuse("the daemon closed the request")));
70
+ });
71
+ }
72
+
73
+ /**
74
+ * THE PLANNING TOOLS (owner, 2026-11-08: the agent arranges its own work, the phone shows it on Status). Short on
75
+ * purpose: their descriptions travel with every turn. The project is the session's own; nothing here runs anything.
76
+ */
77
+ const n = (description) => ({ type: "integer", description });
78
+ const PLAN_TOOLS = [
79
+ { name: "plan_release", op: "release", description: "Plan multi-step work as a release on the phone's Status: tasks you then do yourself. Check plan_list first.",
80
+ inputSchema: { type: "object", properties: { title: { type: "string" }, label: { type: "string", description: "short name, e.g. CLI 0.11.0" }, estimate_min: n("your estimate, minutes"), after: n("release number it waits for"),
81
+ tasks: { type: "array", items: { type: "object", properties: { title: { type: "string" }, estimate_min: n("minutes") }, required: ["title"] } } }, required: ["title"] } },
82
+ { name: "plan_task", op: "task", description: "Add a task to a release, or report yours: running, done or failed (note: one line).",
83
+ inputSchema: { type: "object", properties: { release: n("release number, to add"), title: { type: "string" }, estimate_min: n("minutes"), task_id: { type: "string" }, state: { type: "string", enum: ["running", "done", "failed"] }, note: { type: "string" } } } },
84
+ { name: "plan_list", op: "list", description: "This project's open releases and tasks.", inputSchema: { type: "object", properties: {} } },
85
+ ];
86
+
87
+ const reply = (id, result) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
88
+ const error = (id, code, message) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`);
89
+
90
+ export async function handle(message, ask = askDaemon, plan = askPlan) {
91
+ const { id, method, params } = message ?? {};
92
+ if (method === "initialize") return { id, result: { protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "worktrust-remote", version: "1" } } };
93
+ if (method === "ping") return { id, result: {} };
94
+ if (method === "tools/list") return { id, result: { tools: [{ name: TOOL, description: "WorkTrust remote: asks the person's confirmed phone to approve one permission request, or denies it.", inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } },
95
+ ...PLAN_TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))] } };
96
+ if (method === "tools/call") {
97
+ const planTool = PLAN_TOOLS.find((t) => t.name === params?.name);
98
+ if (planTool) {
99
+ const answer = await plan(planTool.op, params.arguments && typeof params.arguments === "object" ? params.arguments : {});
100
+ return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }], ...(answer?.ok ? {} : { isError: true }) } };
101
+ }
102
+ if (params?.name !== TOOL) return { id, error: { code: -32602, message: "unknown tool" } };
103
+ const a = params.arguments ?? {};
104
+ const answer = typeof a.tool_name === "string" && a.input && typeof a.input === "object"
105
+ ? await ask({ tool_name: a.tool_name, input: a.input, tool_use_id: typeof a.tool_use_id === "string" ? a.tool_use_id : null })
106
+ : deny("WorkTrust remote: malformed permission request; denied");
107
+ return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }] } };
108
+ }
109
+ if (id === undefined) return null; // a notification
110
+ return { id, error: { code: -32601, message: "method not found" } };
111
+ }
112
+
113
+ const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].split(/[\\/]/).pop());
114
+ if (isMain) {
115
+ createInterface({ input: process.stdin }).on("line", async (line) => {
116
+ let message;
117
+ try { message = JSON.parse(line); } catch { return; }
118
+ const answer = await handle(message);
119
+ if (!answer) return;
120
+ if (answer.error) error(answer.id, answer.error.code, answer.error.message); else reply(answer.id, answer.result);
121
+ });
122
+ }