worktrust 0.11.9 → 0.11.11

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/remote-cli.mjs CHANGED
@@ -41,13 +41,13 @@ import { basename } from "node:path";
41
41
  import { hostname } from "node:os";
42
42
  import { createInterface } from "node:readline/promises";
43
43
  import * as P from "./remote-protocol.mjs";
44
- import { ensureRemoteDir, isLoopbackGateway, issuerKeys, loadIdentity, loadKeys, loadPhones, loadProjects, loadSettings, newKeys, random, readJson, removeFile, saveIdentity, saveKeys, savePhones, saveSettings, writeJson } from "./remote-store.mjs";
44
+ import { ensureRemoteDir, gatewayOf, isLoopbackGateway, issuerKeys, PRODUCTION_GATEWAY, loadIdentity, loadKeys, loadPhones, loadProjects, loadSettings, newKeys, random, readJson, removeFile, saveIdentity, saveKeys, savePhones, saveSettings, writeJson } from "./remote-store.mjs";
45
45
  import { canonicalProject } from "./remote-policy.mjs";
46
- import { IssuerMissing, PairingDenied, PairingExpired, PairingRefused, pairComputer } from "./remote-pairing.mjs";
46
+ import { IssuerMissing, PairingDenied, PairingExpired, PairingRefused, compactForQr, oneScan, oneScanInvite, pairComputer } from "./remote-pairing.mjs";
47
47
  import { startCountdown, waitKey } from "./remote-countdown.mjs";
48
- import { askLine, connectionsCommand, disconnectCommand, removePhones } from "./remote-connections.mjs";
48
+ import { askLine, connectionsCommand, disconnectCommand, linkPhone, removePhones } from "./remote-connections.mjs";
49
49
  import { installService, removeService, serviceState, servicePlatform } from "./remote-service.mjs";
50
- import { qrMatrix, renderQr } from "./remote-qr.mjs";
50
+ import { terminalQr } from "./remote-qr.mjs";
51
51
  import { webSocketAvailable } from "./remote-transport.mjs";
52
52
  import { guideToNode, remoteStopsHere } from "./node-guide.mjs";
53
53
  import { inventory } from "./remote-inventory.mjs";
@@ -60,7 +60,6 @@ import { rootLabel } from "./remote-projects.mjs";
60
60
  import { adminCommand, allowedModes, applySettingsChange, askMacFolderAccess, folderCheck, modesCommand } from "./remote-settings.mjs";
61
61
 
62
62
  const fingerprintOf = (keys) => P.deviceFingerprint(keys.public);
63
- const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
64
63
  /** A question only a person at this keyboard answers: a terminal, a typed "yes"; --yes and Enter are No. */
65
64
  export async function askTyped(question) {
66
65
  if (!process.stdin.isTTY) return false;
@@ -79,7 +78,10 @@ function needPaired(io) {
79
78
  /** `remote app` | `remote web`: the two roads to approve this computer; each does all of what `remote enable` did. */
80
79
  async function approve(io, road) {
81
80
  const settings = loadSettings();
82
- const gateway = io.flag("gateway") ?? process.env.WORKTRUST_REMOTE_GATEWAY ?? settings.gateway;
81
+ // THE GATEWAY (owner, 2026-11-14: on by default): --gateway, then WORKTRUST_REMOTE_GATEWAY, then this computer's saved choice,
82
+ // then WorkTrust's (PRODUCTION_GATEWAY). Only a choice is saved; null keeps "the default" (remote-store.mjs gatewayOf).
83
+ const chosen = io.flag("gateway") ?? process.env.WORKTRUST_REMOTE_GATEWAY ?? settings.gateway ?? null;
84
+ const gateway = chosen ?? PRODUCTION_GATEWAY;
83
85
  if (gateway && !P.isGatewayOrigin(gateway)) io.fail("--gateway is an origin: wss://host[:port], or ws://127.0.0.1:<port> for the dev relay");
84
86
  io.say();
85
87
  io.say(" WorkTrust remote lets your phone steer the AI agents on this computer. It will:");
@@ -90,16 +92,19 @@ async function approve(io, road) {
90
92
  io.say(" - mark every session it steers, so remote work never counts as your AI Hours");
91
93
  if (!(await io.ask("Continue?"))) return;
92
94
  ensureRemoteDir();
93
- let identity = loadIdentity();
95
+ let identity = loadIdentity(), ready = null;
94
96
  if (!identity || io.has("repair")) {
95
97
  const keys = newKeys();
96
98
  const pub = P.publicKeysOf(P.importSecretKeys(keys));
97
99
  try {
98
100
  // The request's own clock under the QR or link (remote-countdown.mjs); after an expiry, Enter asks again with a new one.
99
- let paired = null;
101
+ let paired = null, once = null;
100
102
  while (!paired) {
103
+ // ONE SCAN (0.11.10, remote-pairing.mjs): the app's road carries the pairing secret in the QR's fragment; a new one per QR.
104
+ // --no-pair links no phone, so it carries no pairing secret and writes no invite (review 2026-11-14, P3-6).
105
+ once = road === "app" && !io.has("device") && !io.has("no-pair") ? oneScan({ gateway, publicKeys: pub, nowMs: Date.now(), random }) : null;
101
106
  try {
102
- paired = await pairComputer({ origin: io.origin, secret: P.importSecretKeys(keys), publicKeys: pub, host: hostname(), os: io.os, device: io.has("device"), road, showQr: (link) => io.say(renderQr(qrMatrix(link).modules, { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR })), issuerKeys: issuerKeys(gateway), say: io.say, openBrowser: io.openBrowser, countdown: (w) => startCountdown(w) });
107
+ paired = await pairComputer({ origin: io.origin, secret: P.importSecretKeys(keys), publicKeys: pub, host: hostname(), os: io.os, device: io.has("device"), road, once, showLink: io.has("show-link"), showQr: (link) => io.say(terminalQr(compactForQr(link), { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR })), issuerKeys: issuerKeys(gateway), say: io.say, openBrowser: io.openBrowser, countdown: (w) => startCountdown(w) });
103
108
  } catch (error) {
104
109
  if (error instanceof PairingDenied) return;
105
110
  if (!(error instanceof PairingExpired) || !process.stdin.isTTY) throw error;
@@ -110,53 +115,26 @@ async function approve(io, road) {
110
115
  saveKeys(keys);
111
116
  identity = { v: 1, device_id: paired.device_id, binding: paired.binding, sub: paired.sub, origin: io.origin, paired_at: Date.now() };
112
117
  saveIdentity(identity);
118
+ // The daemon confirms the phone that proves this QR's secret; read per hello, so it is there before the service starts.
119
+ if (once && once.e * 1000 > Date.now()) writeJson("invite.json", (ready = oneScanInvite(once, paired.device_id, P.generatePairingCode(random), Date.now())));
113
120
  io.say(` ✓ Paired${paired.account ? ` for ${paired.account}` : ""}. This computer's remote key: ${P.deviceFingerprint(pub)}`);
114
121
  } catch (error) {
115
122
  if (error instanceof IssuerMissing || error instanceof PairingRefused) io.fail(error.message);
116
123
  throw error;
117
124
  }
118
125
  } else io.say(` Already paired (${identity.device_id}); --repair pairs again with new keys.`);
119
- saveSettings({ ...settings, enabled: true, paused: null, gateway: gateway ?? null, agent_path: process.env.PATH ?? null });
126
+ saveSettings({ ...settings, enabled: true, paused: null, gateway: chosen, agent_path: process.env.PATH ?? null });
120
127
  if (loadProjects().length === 0 && loadRoots().length === 0) io.say(" No folder is granted yet: npx worktrust remote roots add <folder> (or the menu: npx worktrust › Remote Agent › Roots)");
121
- if (!gateway) { io.say(" No gateway is set: the production gateway is not live yet. Nothing runs until one is (--gateway)."); return; }
122
128
  if (servicePlatform() === "foreground") { io.say(" ✓ This computer is connected to Remote Agent."); io.say(" Windows: there is no service; run `npx worktrust remote run` and keep that terminal open."); return; }
123
129
  const runtime = await io.prepare();
124
130
  const service = installService({ program: [runtime.node, ...runtime.nodeArgs, runtime.entry, "remote", "run"], path: process.env.PATH ?? "" });
125
131
  io.say(service.started ? ` ✓ The service runs (${service.kind}, while you are logged in; linger stays off).` : ` ! The service file was written (${service.file}) but did not start; run \`npx worktrust remote run\` to see why.`);
126
132
  if (service.started) io.say(" ✓ This computer is connected to Remote Agent.");
127
- if (!io.has("no-pair")) await pair(io);
133
+ if (!io.has("no-pair")) await linkPhone(io, ready);
128
134
  }
129
135
 
130
- async function pair(io) {
131
- const { keys, identity } = needPaired(io);
132
- const settings = loadSettings();
133
- if (!settings.enabled || !settings.gateway) io.fail("remote is off or has no gateway: run `npx worktrust remote app` (or `remote web`)");
134
- const started = Date.now();
135
- const invite = P.createPairingInvite({ gateway: settings.gateway, deviceId: identity.device_id, ed25519_pub: keys.public.ed25519_pub, x25519_pub: keys.public.x25519_pub, nowMs: started, random });
136
- const code = P.generatePairingCode(random);
137
- writeJson("invite.json", { ...invite, code, used: false, created_at: started });
138
- const link = P.encodePairingInvite(invite);
139
- io.say();
140
- io.say(" Scan this with the WorkTrust app (or the phone's camera):");
141
- io.say(renderQr(qrMatrix(link).modules, { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR }));
142
- io.say(` Link: ${link}`);
143
- io.say(` No camera? Type this code in the app: ${pretty(code)} (then confirm the phone here with \`npx worktrust remote phones\`)`);
144
- io.say(" The code and the QR work once, for five minutes. Ctrl+C cancels.");
145
- const cancel = () => { removeFile("invite.json"); process.exit(130); };
146
- process.once("SIGINT", cancel);
147
- const before = new Set(loadPhones().pending.map((p) => p.fingerprint));
148
- while (Date.now() < invite.e * 1000) {
149
- await new Promise((resolve) => setTimeout(resolve, 1000));
150
- const phones = loadPhones();
151
- const paired = phones.confirmed.find((p) => p.how === "qr" && p.confirmed_at >= started);
152
- if (paired) { process.off("SIGINT", cancel); io.say(` ✓ Paired: phone · ${paired.fingerprint}`); return; }
153
- const asked = phones.pending.find((p) => !before.has(p.fingerprint));
154
- if (asked) { process.off("SIGINT", cancel); io.say(` A phone asked by code (${asked.fingerprint}). Confirm it at this keyboard: npx worktrust remote phones confirm ${asked.fingerprint}`); return; }
155
- }
156
- process.off("SIGINT", cancel);
157
- removeFile("invite.json");
158
- io.say(" The pairing code expired. Run `npx worktrust remote pair` for a new one.");
159
- }
136
+ /** `remote pair`: a new QR for a phone (remote-connections.mjs `linkPhone`, which also ends `remote app`). */
137
+ const pair = (io) => linkPhone(io);
160
138
 
161
139
  async function phones(io, rest) {
162
140
  const list = loadPhones();
@@ -284,12 +262,12 @@ function status(io) {
284
262
  const settings = loadSettings(), identity = loadIdentity(), keys = identity ? loadKeys() : null, phonesList = loadPhones(), service = serviceState();
285
263
  const agents = inventory({ env: { ...process.env, PATH: settings.agent_path ?? process.env.PATH } }).reports.filter((r) => r.installed);
286
264
  const summary = { enabled: settings.enabled, paused: settings.paused, paired: Boolean(identity), device_id: identity?.device_id ?? null, fingerprint: keys ? fingerprintOf(keys) : null,
287
- gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length, modes_allowed: allowedModes(settings), admin: settings.admin !== false,
265
+ gateway: gatewayOf(settings), gateway_default: settings.gateway === null || settings.gateway === undefined, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length, modes_allowed: allowedModes(settings), admin: settings.admin !== false,
288
266
  agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, switched_off: a.capabilities.start && (a.adapter === "codex" || a.adapter === "opencode") && settings[a.adapter] !== true, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
289
267
  if (io.has("json")) { io.say(JSON.stringify(summary, null, 2)); return; }
290
268
  io.say(` Remote: ${settings.enabled ? (settings.paused ? `paused (${settings.paused === "desk" ? "here" : "from a phone"})` : "on") : "off"}`);
291
269
  io.say(` Paired: ${identity ? `${identity.device_id} · key ${summary.fingerprint}` : "no"}`);
292
- io.say(` Gateway: ${settings.gateway ?? "none set"}${settings.gateway && isLoopbackGateway(settings.gateway) ? " (this computer: dev relay)" : ""}`);
270
+ io.say(` Gateway: ${summary.gateway === PRODUCTION_GATEWAY ? `${new URL(PRODUCTION_GATEWAY).host} (WorkTrust's)` : `${summary.gateway}${isLoopbackGateway(summary.gateway) ? " (this computer: dev relay)" : " (chosen here)"}`}`);
293
271
  io.say(` Service: ${service.kind === "foreground" ? "none on this system: run `npx worktrust remote run`" : `${service.installed ? "installed" : "not installed"}, ${service.running ? "running" : "not running"}`}`);
294
272
  io.say(` Phones: ${summary.phones.confirmed} confirmed (${summary.phones.browsers_added} browsers added by a phone), ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
295
273
  io.say(` Phones may add a browser: ${summary.phones.allow_endorse ? "yes" : "no"}`);
@@ -11,8 +11,10 @@
11
11
  * never a model name it was not told.
12
12
  */
13
13
  import { createInterface } from "node:readline/promises";
14
- import { loadIdentity, loadKeys, loadPhones, savePhones } from "./remote-store.mjs";
14
+ import { gatewayOf, loadIdentity, loadKeys, loadPhones, loadSettings, random, removeFile, savePhones, writeJson } from "./remote-store.mjs";
15
15
  import * as P from "./remote-protocol.mjs";
16
+ import { terminalQr } from "./remote-qr.mjs";
17
+ import { compactForQr } from "./remote-pairing.mjs";
16
18
 
17
19
  const KEEP_REMOVED = 20;
18
20
  const when = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 16).replace("T", " ") : "never");
@@ -89,3 +91,55 @@ export async function disconnectCommand(io, rest, ask, tty = Boolean(process.std
89
91
  removePhones([c.fingerprint]);
90
92
  io.say(` ✓ Disconnected ${c.name}: it can no longer steer this computer. End its key for your whole account too: app.worktrust.io › Settings › Remote Agent.`);
91
93
  }
94
+
95
+ /** How long `remote app` waits for the phone that scanned its one QR before it shows the pairing QR (0.11.10). */
96
+ export const ONE_SCAN_WAIT_MS = 30_000;
97
+ const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
98
+
99
+ /**
100
+ * LINK A PHONE (`remote pair`, and the end of `remote app`; moved here from remote-cli.mjs in 0.11.10). Without `ready`: a new
101
+ * invite (five minutes, one phone, once), its QR, its link and the typed code, as before. With `ready` (the one-scan invite
102
+ * `remote app` wrote once the issuer named this computer, remote-pairing.mjs `oneScanInvite`): no second QR while the phone
103
+ * that scanned the first one links by itself; after `waitMs`, or for a phone that opened the code with the camera or runs an
104
+ * older app, the SAME invite as the pairing QR, with one line why. A phone that proves the secret is confirmed by the daemon
105
+ * (PROTOCOL.md §Pairing); a phone that asked by the typed code waits for `remote phones confirm` at this keyboard.
106
+ */
107
+ export async function linkPhone(io, ready = null, { waitMs = ONE_SCAN_WAIT_MS, now = Date.now, tick = 1000 } = {}) {
108
+ const keys = loadKeys(), identity = loadIdentity(), settings = loadSettings();
109
+ if (!keys || !identity) io.fail("this computer is not paired for remote yet: run `npx worktrust remote app` (or `remote web`)");
110
+ // Off is its own state (owner, 2026-11-14): a missing gateway no longer exists, WorkTrust's is the default (gatewayOf).
111
+ if (!settings.enabled) io.fail("remote is off on this computer: run `npx worktrust remote app` (or `remote web`)");
112
+ const started = now();
113
+ const invite = ready ?? { ...P.createPairingInvite({ gateway: gatewayOf(settings), deviceId: identity.device_id, ed25519_pub: keys.public.ed25519_pub, x25519_pub: keys.public.x25519_pub, nowMs: started, random }), code: P.generatePairingCode(random), used: false, created_at: started };
114
+ if (!ready) writeJson("invite.json", invite);
115
+ const { code, used: _used, created_at: since, ...bare } = invite;
116
+ const link = P.encodePairingInvite(bare);
117
+ let shown = false;
118
+ const show = (why) => {
119
+ shown = true;
120
+ io.say();
121
+ io.say(why ?? " Scan this with the WorkTrust app (or the phone's camera):");
122
+ io.say(terminalQr(compactForQr(link), { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR }));
123
+ io.say(` Link: ${link}`);
124
+ io.say(` No camera? Type this code in the app: ${pretty(code)} (then confirm the phone here with \`npx worktrust remote phones\`)`);
125
+ io.say(" The code and the QR work once, for five minutes. Ctrl+C cancels.");
126
+ };
127
+ if (ready) io.say(" Linking the phone that scanned the code …"); else show();
128
+ const cancel = () => { removeFile("invite.json"); process.exit(130); };
129
+ process.once("SIGINT", cancel);
130
+ const before = new Set(loadPhones().pending.map((p) => p.fingerprint));
131
+ try {
132
+ while (now() < invite.e * 1000) {
133
+ await new Promise((resolve) => setTimeout(resolve, tick));
134
+ const phones = loadPhones();
135
+ const paired = phones.confirmed.find((p) => p.how === "qr" && p.confirmed_at >= since);
136
+ if (paired) { io.say(` ✓ Paired: phone · ${paired.fingerprint}`); return paired; }
137
+ const asked = phones.pending.find((p) => !before.has(p.fingerprint));
138
+ if (asked) { io.say(` A phone asked by code (${asked.fingerprint}). Confirm it at this keyboard: npx worktrust remote phones confirm ${asked.fingerprint}`); return null; }
139
+ if (!shown && now() - started >= waitMs) show(" No phone linked by itself (the code was opened with the camera, or the app is older): scan this in the WorkTrust app.");
140
+ }
141
+ } finally { process.off("SIGINT", cancel); }
142
+ removeFile("invite.json");
143
+ io.say(" The pairing code expired. Run `npx worktrust remote pair` for a new one.");
144
+ return null;
145
+ }
package/remote-daemon.mjs CHANGED
@@ -38,9 +38,11 @@ export function createDaemonCore(o) {
38
38
  * unknown keys, so every other channel gets the inventory without them. Kept per phone for the daemon's life; a phone
39
39
  * asks again on every inventory.get.
40
40
  */
41
- const extendedPeers = new Set();
41
+ const extendedPeers = new Set(), switchPeers = new Set(); // release 33: `model_switch` only for a phone that asked for it
42
42
  const EXTENDED_KEYS = ["agent_options", "modes_allowed", "admin", "folders", "connections"];
43
- const bodyFor = (channel, record) => (record.type !== "device.inventory" || extendedPeers.has(channel.peer_device_id) ? record.body
43
+ const withoutSwitch = (body) => (body.agent_options ? { ...body, agent_options: body.agent_options.map(({ model_switch: _drop, ...o }) => o) } : body);
44
+ const bodyFor = (channel, record) => (record.type !== "device.inventory" ? record.body
45
+ : extendedPeers.has(channel.peer_device_id) ? (switchPeers.has(channel.peer_device_id) ? record.body : withoutSwitch(record.body))
44
46
  : Object.fromEntries(Object.entries(record.body).filter(([key]) => !EXTENDED_KEYS.includes(key))));
45
47
 
46
48
  function sealAll(record) {
@@ -181,6 +183,7 @@ export function createDaemonCore(o) {
181
183
  if (settings.paused !== null && !DEVICE_COMMANDS.has(env.type)) return "remote_paused";
182
184
  if (env.type === "inventory.get") {
183
185
  if (payload.extended === true && env.sender_device_id) extendedPeers.add(env.sender_device_id);
186
+ if (payload.extended === true && payload.model_switch === true && env.sender_device_id) switchPeers.add(env.sender_device_id); // kept, as extendedPeers
184
187
  if (payload.device_name && env.sender_device_id) rememberName(env.sender_device_id, payload.device_name);
185
188
  emit(null, "device.inventory", inventoryBody(payload.refresh_models));
186
189
  return "taken";
@@ -89,12 +89,22 @@ export function agentOptionsOf(inv) {
89
89
  const f = inv.features?.["claude-code"] ?? {};
90
90
  return inv.reports.filter((r) => r.installed && r.capabilities.start).map((r) => {
91
91
  const base = r.capabilities.permission_modes.map((m) => (m === "plan" ? "plan" : "manual"));
92
- if (r.adapter !== "claude-code" || r.mode !== "structured") return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => base.includes(m)), efforts: [], extra_projects: 0 };
92
+ const model_switch = modelSwitchOf(r);
93
+ if (r.adapter !== "claude-code" || r.mode !== "structured") return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => base.includes(m)), efforts: [], extra_projects: 0, model_switch };
93
94
  const modes = new Set([...base, ...(f.editMode ? ["edit"] : []), ...(f.autoMode ? ["auto"] : [])]);
94
- return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => modes.has(m)), efforts: [...(f.efforts ?? [])], extra_projects: f.addDir ? P.MAX_EXTRA_PROJECTS : 0 };
95
+ return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => modes.has(m)), efforts: [...(f.efforts ?? [])], extra_projects: f.addDir ? P.MAX_EXTRA_PROJECTS : 0, model_switch };
95
96
  });
96
97
  }
97
98
 
99
+ /**
100
+ * WHETHER A RUNNING SESSION OF THIS REPORT MAY CONTINUE ON ANOTHER OF ITS MODELS (release 33; remote-model-switch.mjs): a
101
+ * structured session of Claude Code that can resume by id (its own `--resume` with another `--model`), Codex (`turn/start`
102
+ * takes `model`) and OpenCode (each run takes `--model`), and only where the agent listed models to choose from. A terminal
103
+ * session never: nothing the phone composed is typed into it. Sent only to a phone that asked `model_switch` (remote-daemon.mjs).
104
+ */
105
+ export const modelSwitchOf = (r) => r.mode === "structured" && Array.isArray(r.models) && r.models.length > 0
106
+ && ((r.adapter === "claude-code" && r.capabilities.resume_by_id === true) || r.adapter === "codex" || r.adapter === "opencode");
107
+
98
108
  /** The model aliases Claude Code's own --model help names, in its order; none when the help names none. */
99
109
  export function claudeAliases(help) {
100
110
  const block = /--model <model>([\s\S]*?)(?=\n\s{2}-|\n\s*\n|$)/.exec(help ?? "")?.[1]?.replace(/\s+/g, " ") ?? "";
@@ -18,6 +18,7 @@ import { createHash, randomBytes } from "node:crypto";
18
18
  import { createServer } from "node:http";
19
19
  import { createInterface } from "node:readline/promises";
20
20
  import * as P from "./remote-protocol.mjs";
21
+ import { PRODUCTION_GATEWAY } from "./remote-store.mjs";
21
22
 
22
23
  const PROOF = P.utf8Encode("worktrust-remote/v1/pair-request\n");
23
24
  const RENEW = P.utf8Encode("worktrust-remote/v1/renew\n");
@@ -36,6 +37,40 @@ async function post(origin, path, body) {
36
37
  return { status: response.status, json: await response.json().catch(() => ({})) };
37
38
  }
38
39
 
40
+ /**
41
+ * ONE SCAN (CLI 0.11.10, owner 2026-11-14: "once you have done that, do you still have to pair? Otherwise you go through the
42
+ * same step twice"). `remote app` draws the approval link with the PAIRING material in its fragment, which no browser sends
43
+ * to a server: `<authorize_url>#v=1&g=<gateway>&k=<Ed25519 pub>&x=<X25519 pub>&s=<32-byte secret>&e=<expiry>`, the pairing
44
+ * invite of PROTOCOL.md §Pairing without `d` (the issuer names this computer's device id only when it approves). The
45
+ * WorkTrust app's own scanner approves with the authenticator, finds this computer in the account's device list by the
46
+ * fingerprint of `k` and `x`, and makes the invite whole with its device id; the daemon then confirms the phone by the
47
+ * secret's proof, exactly as a scanned `remote pair` QR. The camera app or a browser opens the approve link and ignores the
48
+ * fragment: pairing a phone is then the second step it always was (`linkPhone` shows the QR after its wait).
49
+ */
50
+ export const ONE_SCAN_KEYS = Object.freeze(["v", "g", "k", "x", "s", "e"]);
51
+ export function oneScan({ gateway, publicKeys, nowMs, random }) {
52
+ if (!gateway || !P.isGatewayOrigin(gateway)) return null;
53
+ const fields = { v: 1, g: gateway, k: publicKeys.ed25519_pub, x: publicKeys.x25519_pub, s: P.toBase64Url(random(32)), e: Math.floor(nowMs / 1000) + P.PAIRING_INVITE_LIFETIME_S };
54
+ return { ...fields, fragment: ONE_SCAN_KEYS.map((key) => `${key}=${encodeURIComponent(String(fields[key]))}`).join("&") };
55
+ }
56
+ /**
57
+ * THE QR'S OWN, SHORTER FORM OF A LINK (owner, 2026-11-14: "make the QR more compact"): `g` is left out when it names
58
+ * WorkTrust's production relay, the one the phone assumes when `g` is missing (CLI 0.11.10 with the app's 2026-11-14
59
+ * JavaScript, which reads both forms). `d`, `k`, `x`, `s` and `e` are never left out; another gateway (the dev relay) stays
60
+ * named. Only the drawn code is shortened: the printed link and invite.json keep `g`, for a browser it is pasted into and
61
+ * for the daemon. 36 characters fewer: the pairing QR goes from version 12 to 9 with level L.
62
+ */
63
+ const DEFAULT_G = `&g=${encodeURIComponent(PRODUCTION_GATEWAY)}`;
64
+ export const compactForQr = (link) => link.replace(DEFAULT_G, "");
65
+ /** The approval link with the pairing material in its fragment, or the link as it was (no gateway, the browser's road). */
66
+ export const withPairing = (url, once) => (once ? `${url}#${once.fragment}` : url);
67
+ /** The invite the daemon reads (invite.json) once the issuer named this computer: the one-scan secret, now with its `d`; checked by the protocol's own encoder. */
68
+ export function oneScanInvite(once, deviceId, code, nowMs) {
69
+ const invite = { v: once.v, g: once.g, d: deviceId, k: once.k, x: once.x, s: once.s, e: once.e };
70
+ P.encodePairingInvite(invite);
71
+ return { ...invite, code, used: false, created_at: nowMs };
72
+ }
73
+
39
74
  /** Which road, the app's QR here (Enter) or the browser; not a terminal, or --yes: the browser. Since 0.11.7 the person names the road (`remote app` | `remote web`, or the menu); kept for a caller that asks. */
40
75
  export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), yes = false, prompt = null } = {}) {
41
76
  if (!interactive || yes) return "web";
@@ -49,7 +84,7 @@ export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), y
49
84
  * Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. `road`:
50
85
  * "web" opens the approval page in the browser; "app" draws its link with `showQr` for the WorkTrust app and opens nothing.
51
86
  */
52
- export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null }) {
87
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null, once = null, showLink = false }) {
53
88
  const verifier = randomBytes(32).toString("base64url");
54
89
  const code_challenge = createHash("sha256").update(verifier).digest("base64url");
55
90
  const state = randomBytes(24).toString("base64url");
@@ -83,9 +118,12 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
83
118
  let exchanged = null;
84
119
  if (!device) {
85
120
  if (road === "app") {
86
- say(" Scan this with the WorkTrust app (or the phone's camera) and approve with your authenticator code:");
87
- showQr(authorize_url);
88
- say(` Link: ${authorize_url}`);
121
+ // One scan (0.11.10): the app's scanner approves AND links this phone; the camera app only approves.
122
+ say(once ? " Scan this in the WorkTrust app (Scan › Connect agent): approve with your authenticator code, and the phone links too." : " Scan this with the WorkTrust app (or the phone's camera) and approve with your authenticator code:");
123
+ showQr(withPairing(authorize_url, once));
124
+ // The printed link leaves the pairing secret out (scrollback, a shared screen; review 2026-11-14, P3-7): the QR carries
125
+ // it, and --show-link prints it whole for a phone that cannot scan.
126
+ say(` Link: ${showLink ? withPairing(authorize_url, once) : authorize_url}`);
89
127
  } else {
90
128
  say(` Approve in your browser (opening it). If it does not open: ${authorize_url}`);
91
129
  openBrowser(authorize_url);
@@ -83,25 +83,41 @@ export const refuse = (code , detail )
83
83
  */
84
84
 
85
85
  const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
86
- const LOOKUP = Object.fromEntries([...ALPHABET].map((c, i) => [c, i]));
86
+ /** Each alphabet character's code, for encoding into a byte array (one fromCharCode per block, not one string per byte). */
87
+ const CODES = Uint8Array.from(ALPHABET, (c) => c.charCodeAt(0));
88
+ /** Each ASCII code's 6-bit value, -1 outside the alphabet. */
89
+ const VALUES = new Int8Array(128).fill(-1);
90
+ for (let i = 0; i < ALPHABET.length; i += 1) VALUES[ALPHABET.charCodeAt(i)] = i;
91
+ /** The whole alphabet, anchored at both ends (no `m` flag: `$` is the end of the input, never before a newline). */
92
+ const BASE64URL_TEXT = /^[A-Za-z0-9_-]*$/;
93
+ const BLOCK = 8192;
87
94
 
88
95
  /** base64url, no padding. */
89
96
  export function toBase64Url(bytes ) {
90
- let out = "";
97
+ const out = new Uint8Array(Math.ceil((bytes.length * 4) / 3));
98
+ let o = 0;
91
99
  let i = 0;
92
100
  for (; i + 2 < bytes.length; i += 3) {
93
101
  const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2] ;
94
- out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] + ALPHABET[n & 63] ;
102
+ out[o++] = CODES[(n >> 18) & 63] ;
103
+ out[o++] = CODES[(n >> 12) & 63] ;
104
+ out[o++] = CODES[(n >> 6) & 63] ;
105
+ out[o++] = CODES[n & 63] ;
95
106
  }
96
107
  const rest = bytes.length - i;
97
108
  if (rest === 1) {
98
109
  const n = bytes[i] << 16;
99
- out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] ;
110
+ out[o++] = CODES[(n >> 18) & 63] ;
111
+ out[o++] = CODES[(n >> 12) & 63] ;
100
112
  } else if (rest === 2) {
101
113
  const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
102
- out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] ;
114
+ out[o++] = CODES[(n >> 18) & 63] ;
115
+ out[o++] = CODES[(n >> 12) & 63] ;
116
+ out[o++] = CODES[(n >> 6) & 63] ;
103
117
  }
104
- return out;
118
+ let text = "";
119
+ for (let at = 0; at < o; at += BLOCK) text += String.fromCharCode.apply(null, out.subarray(at, Math.min(o, at + BLOCK)) );
120
+ return text;
105
121
  }
106
122
 
107
123
  /**
@@ -109,14 +125,16 @@ export function toBase64Url(bytes ) {
109
125
  * exactly one string decodes to a given byte string; a signature over the string then means one thing).
110
126
  */
111
127
  export function fromBase64Url(text ) {
112
- if (text.length % 4 === 1) return null;
113
- const out = new Uint8Array(Math.floor((text.length * 3) / 4));
128
+ const length = text.length;
129
+ if (length % 4 === 1) return null;
130
+ const out = new Uint8Array(Math.floor((length * 3) / 4));
114
131
  let o = 0;
115
132
  let acc = 0;
116
133
  let bits = 0;
117
- for (const c of text) {
118
- const v = LOOKUP[c];
119
- if (v === undefined) return null;
134
+ for (let i = 0; i < length; i += 1) {
135
+ const code = text.charCodeAt(i);
136
+ const v = code < 128 ? VALUES[code] : -1;
137
+ if (v < 0) return null;
120
138
  acc = (acc << 6) | v;
121
139
  bits += 6;
122
140
  if (bits >= 8) {
@@ -129,16 +147,61 @@ export function fromBase64Url(text ) {
129
147
  return out;
130
148
  }
131
149
 
150
+ /**
151
+ * Whether `text` is canonical base64url (exactly what fromBase64Url accepts) of the stated size, WITHOUT decoding it
152
+ * (release 33; docs/OPEN.md "Rust was measured and not taken"): a 512 KiB attachment chunk was decoded only to be
153
+ * measured, about 110 ms on the phone and 96 ms of the relay's event loop per frame. The length gives the size, one
154
+ * anchored pattern the alphabet, and the last character's low bits the canonical form: of a length 2 past a multiple of
155
+ * four the last character carries 2 bits (its low 4 must be 0), of 3 past it carries 4 (its low 2 must be 0).
156
+ * scripts/lib/remote-protocol-bytes-cases.mjs proves the same accept and refuse set as decoding, over both builds.
157
+ */
132
158
  export function isBase64Url(text , bytes ) {
133
- const decoded = fromBase64Url(text);
134
- if (decoded === null) return false;
135
- if (bytes?.exact !== undefined && decoded.length !== bytes.exact) return false;
136
- if (bytes?.max !== undefined && decoded.length > bytes.max) return false;
137
- return true;
159
+ const length = text.length;
160
+ const tail = length % 4;
161
+ if (tail === 1) return false;
162
+ const size = Math.floor((length * 3) / 4);
163
+ if (bytes?.exact !== undefined && size !== bytes.exact) return false;
164
+ if (bytes?.max !== undefined && size > bytes.max) return false;
165
+ if (!BASE64URL_TEXT.test(text)) return false;
166
+ if (tail === 0) return true;
167
+ const last = VALUES[text.charCodeAt(length - 1)] ;
168
+ return (last & (tail === 2 ? 15 : 3)) === 0;
169
+ }
170
+
171
+ /** A lone surrogate, high without a low after it or low without a high before it (code units: no `u` flag). */
172
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
173
+
174
+ /** Whether a string has a UTF-8 form (no lone surrogate): the engine's own check where it has one, else the pattern. */
175
+ export function wellFormed(text ) {
176
+ const native = (text ).isWellFormed;
177
+ return typeof native === "function" ? native.call(text) : !LONE_SURROGATE.test(text);
138
178
  }
139
179
 
140
- /** UTF-8 encode. Lone surrogates are refused: they have no UTF-8 form and would otherwise round-trip lossy. */
180
+ // The host's encoder, declared here because this package names no DOM or Node library (a bare `typeof` is safe when absent).
181
+
182
+ let nativeEncoder ;
183
+ function encoder() {
184
+ if (nativeEncoder === undefined) {
185
+ nativeEncoder = typeof TextEncoder === "function" ? new TextEncoder() : null;
186
+ }
187
+ return nativeEncoder;
188
+ }
189
+
190
+ /**
191
+ * UTF-8 encode. Lone surrogates are refused: they have no UTF-8 form and would otherwise round-trip lossy (TextEncoder
192
+ * alone would replace them with U+FFFD, so the check comes first). The engine's TextEncoder where it has one (release
193
+ * 33: the per-character loop cost about 11 ms per attachment chunk), the portable loop elsewhere; both give the same
194
+ * bytes (scripts/lib/remote-protocol-bytes-cases.mjs).
195
+ */
141
196
  export function utf8Encode(text ) {
197
+ const native = encoder();
198
+ if (!native) return utf8EncodePortable(text);
199
+ if (!wellFormed(text)) throw new TypeError("lone surrogate");
200
+ return native.encode(text);
201
+ }
202
+
203
+ /** UTF-8 encode without TextEncoder (an engine that has none); the same bytes and the same refusal as utf8Encode. */
204
+ export function utf8EncodePortable(text ) {
142
205
  const out = [];
143
206
  for (let i = 0; i < text.length; i += 1) {
144
207
  let cp = text.charCodeAt(i);
@@ -219,8 +282,8 @@ export function canonicalJson(value ) {
219
282
  if (value === null) return "null";
220
283
  switch (typeof value) {
221
284
  case "string":
222
- // Lone surrogates are refused here too, so the string has a UTF-8 form.
223
- utf8Encode(value);
285
+ // Lone surrogates are refused here too, so the string has a UTF-8 form (checked, not encoded: release 33).
286
+ if (!wellFormed(value)) throw new TypeError("lone surrogate");
224
287
  return JSON.stringify(value);
225
288
  case "boolean":
226
289
  return value ? "true" : "false";
@@ -589,6 +652,13 @@ export const AGENT_OPTIONS_SPEC = object({
589
652
  efforts: list(oneOf(AGENT_EFFORTS), AGENT_EFFORTS.length),
590
653
  /** How many extra projects a session of this adapter may reach; 0: single-project. */
591
654
  extra_projects: int(0, MAX_EXTRA_PROJECTS),
655
+ /**
656
+ * Release 33 (owner, 2026-11-13: option A): a running session of this adapter can continue on another of ITS OWN listed
657
+ * models (agent.prompt `model`): Claude Code by its own `--resume` with another `--model`, Codex by `turn/start`'s model,
658
+ * OpenCode by the next run's `--model`. Only in an inventory for a phone that asked `inventory.get` `model_switch`
659
+ * (an older phone refuses the unknown key); absent or false: another model is a new chat, as before.
660
+ */
661
+ model_switch: optional(bool()),
592
662
  });
593
663
 
594
664
  export const CAPABILITIES_SPEC = object({
@@ -2317,7 +2387,16 @@ export const COMMAND_PAYLOAD_SPECS = {
2317
2387
  * ends; with `interrupt: true` (only where the adapter reports interrupt) the computer ends the running turn first and
2318
2388
  * runs this prompt next (2026-11-07).
2319
2389
  */
2320
- "agent.prompt": object({ text: text(MAX_PROMPT_CHARS, 1), interrupt: optional(bool()), attachments: optional(list(id("att"), MAX_ATTACHMENTS_PER_PROMPT)) }),
2390
+ "agent.prompt": object({
2391
+ text: text(MAX_PROMPT_CHARS, 1), interrupt: optional(bool()), attachments: optional(list(id("att"), MAX_ATTACHMENTS_PER_PROMPT)),
2392
+ /**
2393
+ * Release 33 (owner, 2026-11-13: option A): another model of the SAME agent for this turn and the turns after it, from
2394
+ * the session's adapter's own listed models; sent only to a computer whose extended inventory says `model_switch` for
2395
+ * that adapter (an older computer refuses the unknown key and runs nothing). The computer checks it again
2396
+ * (checkModelSwitch) against its own list and its adapter; another agent is never a model: it is a new chat.
2397
+ */
2398
+ model: optional(text(128, 1)),
2399
+ }),
2321
2400
  /**
2322
2401
  * Words for an agent in the middle of a turn: redirect without stopping. Where the adapter reports steer_mode `live`
2323
2402
  * they enter the running turn (accepted with `landed: "running_turn"` once the agent read them); `queued`, they run as
@@ -2374,6 +2453,11 @@ export const COMMAND_PAYLOAD_SPECS = {
2374
2453
  * computer refuses the field with `extended` and the phone asks again without both.
2375
2454
  */
2376
2455
  device_name: optional(text(MAX_DEVICE_NAME, 1)),
2456
+ /**
2457
+ * Release 33: this phone reads `agent_options[].model_switch` and may send agent.prompt `model`. Only with `extended`.
2458
+ * An older computer refuses the unknown field; the phone then asks again with `extended` alone (client-core.ts).
2459
+ */
2460
+ model_switch: optional(bool()),
2377
2461
  }),
2378
2462
  /** This computer's remote settings, each optional. Pausing from the phone is soft; `worktrust remote disable` at the
2379
2463
  * desk is the hard off, which no message can undo. */
@@ -2532,6 +2616,7 @@ export function validateCommandPayload (type , value
2532
2616
  if (type === "inventory.get") {
2533
2617
  const i = payload ;
2534
2618
  if (i.device_name !== undefined && (i.extended !== true || !deviceNameOk(i.device_name))) return refuse("payload", "$payload.device_name: printable words, with extended");
2619
+ if (i.model_switch !== undefined && i.extended !== true) return refuse("payload", "$payload.model_switch: with extended");
2535
2620
  }
2536
2621
  if (type === "attachment.put") { const bad = attachmentRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
2537
2622
  if (type === "preview.render") { const bad = previewRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
@@ -3276,6 +3361,20 @@ export function checkStart(payload , report
3276
3361
  return null;
3277
3362
  }
3278
3363
 
3364
+ /**
3365
+ * ANOTHER MODEL OF THE SAME AGENT, CHECKED AT THE COMPUTER (release 33; owner, 2026-11-13: option A). An agent.prompt
3366
+ * `model` is taken only when the session's own report (its adapter and mode) is installed and lists that model, and the
3367
+ * computer's own options for it say `model_switch` (its agent's resume or turn takes another model). → null, or
3368
+ * `unsupported` (no switch for this adapter or mode, a terminal session among them) or `unknown_model` (not listed).
3369
+ * A model is never trusted from a phone, and another agent is never a model: the payload has no adapter.
3370
+ */
3371
+ export function checkModelSwitch(model , report , options ) {
3372
+ if (!report || !report.installed || !report.capabilities.start || report.mode !== "structured") return "unsupported";
3373
+ if (!options || options.adapter !== report.adapter || options.mode !== report.mode || options.model_switch !== true) return "unsupported";
3374
+ if (!isModelReported(report, model)) return "unknown_model";
3375
+ return null;
3376
+ }
3377
+
3279
3378
  /**
3280
3379
  * THE 0.11.7 START OPTIONS, CHECKED AT THE COMPUTER (owner, 2026-11-12): the agent mode, the effort and the extra
3281
3380
  * projects of an agent.start, against the options the computer itself offers for that adapter (`options`, from its own