worktrust 0.10.38 → 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.
@@ -0,0 +1,3881 @@
1
+ // GENERATED by scripts/build-remote-protocol-cli.mjs from packages/remote-protocol/src: do not edit; run the build.
2
+ // @worktrust/remote-protocol for the worktrust CLI, with node:crypto in place of @noble (docs/remote-agents/PROTOCOL.md).
3
+ import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, hkdfSync, randomBytes, sign as nodeSign, verify as nodeVerify } from "node:crypto";
4
+ // ---- packages/remote-protocol/src/version.ts
5
+ /**
6
+ * THE PROTOCOL'S VERSION AND ITS LIMITS. A version is an integer, raised when the meaning of a message changes. Both
7
+ * ends sign the list of versions they support during the handshake (crypto/handshake.ts), so a relay cannot strike
8
+ * the newest one out and push the two ends onto an older, weaker version.
9
+ */
10
+ export const PROTOCOL_VERSION = 1;
11
+ export const SUPPORTED_PROTOCOL_VERSIONS = [1];
12
+ /** The lowest version this build will speak. A version below it is a downgrade, refused. */
13
+ export const MIN_PROTOCOL_VERSION = 1;
14
+
15
+ /** Clock skew tolerated between a phone, a computer and the Passport app, in milliseconds. */
16
+ export const CLOCK_SKEW_MS = 60_000;
17
+ /** A command lives at most a day; a stop or a pause far less (commands.ts, COMMAND_TTL_MS). */
18
+ export const MAX_COMMAND_TTL_MS = 24 * 60 * 60 * 1000;
19
+ /** An authorization assertion for the gateway lives at most five minutes. */
20
+ export const MAX_ASSERTION_LIFETIME_S = 300;
21
+ /** A signed approval decision lives at most five minutes, and never past the request's own expiry. */
22
+ export const MAX_APPROVAL_LIFETIME_S = 300;
23
+ /** A key binding lives at most thirty days; the Passport app re-issues one while the device is still approved. */
24
+ export const MAX_BINDING_LIFETIME_S = 30 * 24 * 60 * 60;
25
+ /** A handshake message older than this is refused, so a recorded hello cannot be replayed later. */
26
+ export const MAX_HANDSHAKE_AGE_MS = 5 * 60 * 1000;
27
+ /** A channel is re-keyed after this long or after this many messages in one direction, whichever comes first. */
28
+ export const CHANNEL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
29
+ export const CHANNEL_MAX_MESSAGES = 2 ** 31;
30
+ /** How far behind the highest counter a reordered message may still arrive. */
31
+ export const REPLAY_WINDOW = 128;
32
+ /** The largest plaintext a sealed body carries. */
33
+ export const MAX_PLAINTEXT_BYTES = 1_048_576;
34
+
35
+ export const PASSPORT_ISSUER = "app.worktrust.io";
36
+ export const GATEWAY_AUDIENCE = "remote.worktrust.io";
37
+
38
+ // ---- packages/remote-protocol/src/result.ts
39
+ /**
40
+ * EVERY REFUSAL HAS A CODE. A caller keys on `code`, never on `detail`: the detail names a field or a rule for a
41
+ * log line and never carries content (no prompt, no file name, no value read from a sealed body).
42
+ */
43
+ export const REFUSAL_CODES = [
44
+ "shape", // the value does not have the schema's shape
45
+ "version", // no protocol version both sides support
46
+ "downgrade", // a version lower than both sides support was chosen or claimed
47
+ "binding", // a key binding failed verification
48
+ "account_mismatch", // the two bindings name different accounts
49
+ "revoked", // a binding or device was revoked
50
+ "signature", // a signature did not verify
51
+ "unknown_key", // a token names a key id this verifier does not hold
52
+ "issuer", // wrong `iss`
53
+ "audience", // wrong `aud`
54
+ "lifetime", // a token lives longer than its kind allows
55
+ "expired", // past its expiry
56
+ "not_yet_valid", // issued in the future beyond the allowed skew
57
+ "capability", // an assertion lacks a capability the call needs
58
+ "replay", // a counter, jti or handshake seen before
59
+ "too_old", // a counter below the replay window
60
+ "wrong_channel", // a sealed box addressed to another channel
61
+ "wrong_device", // a message from or to a device this channel does not join
62
+ "channel_known", // a handshake for a channel that already exists
63
+ "key_agreement", // X25519 produced the all-zero secret (a low-order point)
64
+ "decrypt", // the AEAD tag did not verify
65
+ "padding", // the plaintext's padding is malformed
66
+ "payload", // the decrypted payload does not match its type's schema
67
+ "action_mismatch", // an approval decision for a different action than the one pending
68
+ "already_decided", // a second decision for one approval
69
+ "not_pending", // no approval with that id is waiting
70
+ "not_approvable", // an approval of a class that is never approved from a phone
71
+ "not_confirmed", // a phone not yet confirmed at the computer's keyboard
72
+ ] ;
73
+
74
+ export const accept = (value ) => ({ ok: true, value });
75
+ export const refuse = (code , detail ) => ({ ok: false, code, detail });
76
+
77
+ // ---- packages/remote-protocol/src/bytes.ts
78
+ /**
79
+ * BYTES WITHOUT A PLATFORM. Node has Buffer, browsers have TextEncoder and atob, Hermes (React Native) has some of
80
+ * these depending on its version. The protocol must encode identically everywhere, so it encodes by itself:
81
+ * base64url without padding (RFC 4648 section 5, canonical form only) and strict UTF-8 (a malformed sequence is
82
+ * refused, never replaced, because a replaced character would let two different byte strings decode equal).
83
+ */
84
+
85
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
86
+ const LOOKUP = Object.fromEntries([...ALPHABET].map((c, i) => [c, i]));
87
+
88
+ /** base64url, no padding. */
89
+ export function toBase64Url(bytes ) {
90
+ let out = "";
91
+ let i = 0;
92
+ for (; i + 2 < bytes.length; i += 3) {
93
+ 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] ;
95
+ }
96
+ const rest = bytes.length - i;
97
+ if (rest === 1) {
98
+ const n = bytes[i] << 16;
99
+ out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] ;
100
+ } else if (rest === 2) {
101
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
102
+ out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] ;
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * Decodes canonical base64url only: no padding, no whitespace, and no stray low bits in the last character (so
109
+ * exactly one string decodes to a given byte string; a signature over the string then means one thing).
110
+ */
111
+ export function fromBase64Url(text ) {
112
+ if (text.length % 4 === 1) return null;
113
+ const out = new Uint8Array(Math.floor((text.length * 3) / 4));
114
+ let o = 0;
115
+ let acc = 0;
116
+ let bits = 0;
117
+ for (const c of text) {
118
+ const v = LOOKUP[c];
119
+ if (v === undefined) return null;
120
+ acc = (acc << 6) | v;
121
+ bits += 6;
122
+ if (bits >= 8) {
123
+ bits -= 8;
124
+ out[o++] = (acc >> bits) & 0xff;
125
+ }
126
+ acc &= (1 << bits) - 1;
127
+ }
128
+ if (acc !== 0) return null;
129
+ return out;
130
+ }
131
+
132
+ 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;
138
+ }
139
+
140
+ /** UTF-8 encode. Lone surrogates are refused: they have no UTF-8 form and would otherwise round-trip lossy. */
141
+ export function utf8Encode(text ) {
142
+ const out = [];
143
+ for (let i = 0; i < text.length; i += 1) {
144
+ let cp = text.charCodeAt(i);
145
+ if (cp >= 0xd800 && cp <= 0xdbff) {
146
+ const next = text.charCodeAt(i + 1);
147
+ if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError("lone surrogate");
148
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (next - 0xdc00);
149
+ i += 1;
150
+ } else if (cp >= 0xdc00 && cp <= 0xdfff) {
151
+ throw new TypeError("lone surrogate");
152
+ }
153
+ if (cp < 0x80) out.push(cp);
154
+ else if (cp < 0x800) out.push(0xc0 | (cp >> 6), 0x80 | (cp & 63));
155
+ else if (cp < 0x10000) out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63));
156
+ else out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 63), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63));
157
+ }
158
+ return Uint8Array.from(out);
159
+ }
160
+
161
+ /** Strict UTF-8 decode: overlong forms, surrogates and truncated sequences give null. */
162
+ export function utf8Decode(bytes ) {
163
+ let out = "";
164
+ for (let i = 0; i < bytes.length; ) {
165
+ const b = bytes[i] ;
166
+ let cp ;
167
+ let need ;
168
+ let min ;
169
+ if (b < 0x80) { cp = b; need = 0; min = 0; }
170
+ else if (b >= 0xc2 && b <= 0xdf) { cp = b & 31; need = 1; min = 0x80; }
171
+ else if (b >= 0xe0 && b <= 0xef) { cp = b & 15; need = 2; min = 0x800; }
172
+ else if (b >= 0xf0 && b <= 0xf4) { cp = b & 7; need = 3; min = 0x10000; }
173
+ else return null;
174
+ for (let k = 1; k <= need; k += 1) {
175
+ const c = bytes[i + k];
176
+ if (c === undefined || (c & 0xc0) !== 0x80) return null;
177
+ cp = (cp << 6) | (c & 63);
178
+ }
179
+ if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return null;
180
+ out += String.fromCodePoint(cp);
181
+ i += need + 1;
182
+ }
183
+ return out;
184
+ }
185
+
186
+ export function concatBytes(...parts ) {
187
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
188
+ let at = 0;
189
+ for (const p of parts) { out.set(p, at); at += p.length; }
190
+ return out;
191
+ }
192
+
193
+ /** Equality without an early exit, for comparing hashes and tags. */
194
+ export function equalBytes(a , b ) {
195
+ if (a.length !== b.length) return false;
196
+ let diff = 0;
197
+ for (let i = 0; i < a.length; i += 1) diff |= a[i] ^ b[i] ;
198
+ return diff === 0;
199
+ }
200
+
201
+ export function u32be(n ) {
202
+ return Uint8Array.of((n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff);
203
+ }
204
+
205
+ export function readU32be(bytes , at ) {
206
+ return ((bytes[at] << 24) >>> 0) + (bytes[at + 1] << 16) + (bytes[at + 2] << 8) + bytes[at + 3] ;
207
+ }
208
+
209
+ // ---- packages/remote-protocol/src/canonical.ts
210
+ /**
211
+ * CANONICAL JSON: one byte string per value, so a signature or an AEAD's associated data means exactly one thing.
212
+ * Keys sorted by UTF-16 code unit (JavaScript's default sort, as RFC 8785 does), no whitespace, and the value space
213
+ * cut to what the protocol uses: strings, booleans, null, arrays, plain objects and SAFE INTEGERS. A float has no
214
+ * single shortest form across platforms, so the protocol has none (times are integer milliseconds, sizes integer
215
+ * bytes). `undefined` is refused rather than dropped: a dropped key would sign a different object than was meant.
216
+ */
217
+
218
+ export function canonicalJson(value ) {
219
+ if (value === null) return "null";
220
+ switch (typeof value) {
221
+ case "string":
222
+ // Lone surrogates are refused here too, so the string has a UTF-8 form.
223
+ utf8Encode(value);
224
+ return JSON.stringify(value);
225
+ case "boolean":
226
+ return value ? "true" : "false";
227
+ case "number":
228
+ if (!Number.isSafeInteger(value)) throw new TypeError("canonical JSON carries safe integers only");
229
+ return Object.is(value, -0) ? "0" : String(value);
230
+ case "object": {
231
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
232
+ const proto = Object.getPrototypeOf(value);
233
+ if (proto !== Object.prototype && proto !== null) throw new TypeError("canonical JSON carries plain objects only");
234
+ const record = value ;
235
+ const keys = Object.keys(record).sort();
236
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
237
+ }
238
+ default:
239
+ throw new TypeError(`canonical JSON cannot carry ${typeof value}`);
240
+ }
241
+ }
242
+
243
+ export const canonicalBytes = (value ) => utf8Encode(canonicalJson(value));
244
+
245
+ /** Parses JSON and gives null instead of throwing. Duplicate keys are not detectable through JSON.parse; the
246
+ * schemas' exact-key rule plus canonical re-encoding (signatures are over canonical bytes) make them harmless. */
247
+ export function parseJson(text ) {
248
+ try {
249
+ return JSON.parse(text) ;
250
+ } catch {
251
+ return undefined;
252
+ }
253
+ }
254
+
255
+ // ---- scripts/lib/remote-protocol-node-primitives.mjs (in place of packages/remote-protocol/src/crypto/primitives.ts)
256
+ /**
257
+ * THE PROTOCOL'S PRIMITIVES ON node:crypto ALONE, for the CLI (2026-11-07). The worktrust CLI ships no dependency, so its
258
+ * copy of @worktrust/remote-protocol (scripts/build-remote-protocol-cli.mjs) replaces the one file that touches @noble,
259
+ * packages/remote-protocol/src/crypto/primitives.ts, with this one: the same exports, the same bytes. Every other file of
260
+ * the package is taken as it is. scripts/test-remote-cli-protocol.mjs proves the result reproduces every known-answer
261
+ * vector in packages/remote-protocol/test-vectors.json and passes the package's own cases.
262
+ *
263
+ * Ed25519 node:crypto sign/verify (OpenSSL, RFC 8032), keys built from the 32-byte seed
264
+ * X25519 node:crypto diffieHellman, refusing the all-zero output of a low-order point
265
+ * HKDF-SHA-256 node:crypto hkdfSync
266
+ * XChaCha20-Poly1305 HChaCha20 from the raw chacha20 keystream (the block minus its known input words), then IETF
267
+ * ChaCha20-Poly1305 under the subkey with the nonce's last 8 bytes
268
+ *
269
+ * Node 18 has every one of these. Values are plain Uint8Array, never Buffer, so they compare as the package's do.
270
+ */
271
+
272
+ export const systemRandom = (length) => new Uint8Array(randomBytes(length));
273
+
274
+ export const KEY_BYTES = 32;
275
+ export const SIGNATURE_BYTES = 64;
276
+ export const NONCE_BYTES = 24;
277
+ export const TAG_BYTES = 16;
278
+
279
+ const DER = {
280
+ ed25519: { pkcs8: Buffer.from("302e020100300506032b657004220420", "hex"), spki: Buffer.from("302a300506032b6570032100", "hex") },
281
+ x25519: { pkcs8: Buffer.from("302e020100300506032b656e04220420", "hex"), spki: Buffer.from("302a300506032b656e032100", "hex") },
282
+ };
283
+ const u8 = (bytes) => new Uint8Array(bytes);
284
+ const privateKeyOf = (kind, seed) => createPrivateKey({ key: Buffer.concat([DER[kind].pkcs8, Buffer.from(seed)]), format: "der", type: "pkcs8" });
285
+ const publicKeyOf = (kind, raw) => createPublicKey({ key: Buffer.concat([DER[kind].spki, Buffer.from(raw)]), format: "der", type: "spki" });
286
+ const rawPublic = (kind, seed) => u8(createPublicKey(privateKeyOf(kind, seed)).export({ format: "der", type: "spki" }).subarray(DER[kind].spki.length));
287
+
288
+ export const sha256 = (data) => u8(createHash("sha256").update(data).digest());
289
+
290
+ export const hkdfSha256 = (ikm, salt, info, length) => u8(Buffer.from(hkdfSync("sha256", ikm, salt, info, length)));
291
+
292
+ export const ed25519PublicKey = (secret) => rawPublic("ed25519", secret);
293
+ export const x25519PublicKey = (secret) => rawPublic("x25519", secret);
294
+
295
+ export const ed25519Sign = (message, secret) => u8(nodeSign(null, message, privateKeyOf("ed25519", secret)));
296
+
297
+ /** Never throws: a malformed key or signature is simply not a valid signature. */
298
+ export function ed25519Verify(signature, message, publicKey) {
299
+ if (signature.length !== SIGNATURE_BYTES || publicKey.length !== KEY_BYTES) return false;
300
+ try {
301
+ return nodeVerify(null, message, publicKeyOf("ed25519", publicKey), signature);
302
+ } catch {
303
+ return false;
304
+ }
305
+ }
306
+
307
+ /** X25519, or null for the all-zero shared secret (a low-order public key), which must never become a key. */
308
+ export function x25519Shared(secret, publicKey) {
309
+ if (publicKey.length !== KEY_BYTES) return null;
310
+ try {
311
+ const shared = u8(diffieHellman({ privateKey: privateKeyOf("x25519", secret), publicKey: publicKeyOf("x25519", publicKey) }));
312
+ return shared.every((b) => b === 0) ? null : shared;
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ /** HChaCha20 (draft-irtf-cfrg-xchacha section 2.2) from one chacha20 block: words 0..3 and 12..15 before the final addition. */
319
+ function hchacha20(key, nonce16) {
320
+ const block = createCipheriv("chacha20", Buffer.from(key), Buffer.from(nonce16)).update(Buffer.alloc(64));
321
+ const input = Buffer.from(nonce16);
322
+ const sigma = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];
323
+ const out = Buffer.alloc(32);
324
+ for (let i = 0; i < 4; i += 1) out.writeUInt32LE((block.readUInt32LE(i * 4) - sigma[i]) >>> 0, i * 4);
325
+ for (let i = 0; i < 4; i += 1) out.writeUInt32LE((block.readUInt32LE(48 + i * 4) - input.readUInt32LE(i * 4)) >>> 0, 16 + i * 4);
326
+ return out;
327
+ }
328
+ const ietfNonce = (nonce24) => Buffer.concat([Buffer.alloc(4), Buffer.from(nonce24).subarray(16, 24)]);
329
+
330
+ export function aeadSeal(key, nonce, aad, plaintext) {
331
+ const cipher = createCipheriv("chacha20-poly1305", hchacha20(key, nonce.subarray(0, 16)), ietfNonce(nonce), { authTagLength: TAG_BYTES });
332
+ cipher.setAAD(Buffer.from(aad), { plaintextLength: plaintext.length });
333
+ return u8(Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final(), cipher.getAuthTag()]));
334
+ }
335
+
336
+ /** Null when the tag does not verify: wrong key, a changed byte, or changed associated data. */
337
+ export function aeadOpen(key, nonce, aad, ciphertext) {
338
+ if (nonce.length !== NONCE_BYTES || ciphertext.length < TAG_BYTES) return null;
339
+ try {
340
+ const body = Buffer.from(ciphertext.subarray(0, ciphertext.length - TAG_BYTES));
341
+ const decipher = createDecipheriv("chacha20-poly1305", hchacha20(key, nonce.subarray(0, 16)), ietfNonce(nonce), { authTagLength: TAG_BYTES });
342
+ decipher.setAAD(Buffer.from(aad), { plaintextLength: body.length });
343
+ decipher.setAuthTag(Buffer.from(ciphertext.subarray(ciphertext.length - TAG_BYTES)));
344
+ return u8(Buffer.concat([decipher.update(body), decipher.final()]));
345
+ } catch {
346
+ return null;
347
+ }
348
+ }
349
+
350
+ // ---- packages/remote-protocol/src/ids.ts
351
+ /**
352
+ * OPAQUE IDS. Every id the relay sees is a prefix and 16 random bytes in base64url, nothing else: a project id is
353
+ * never a folder name, a session id never a title. The prefix says what kind of thing it names, so an id of one kind
354
+ * cannot be passed where another is meant. A computer that needs a STABLE id for a folder derives one (an HMAC of the
355
+ * path under a key that never leaves the computer, cut to 16 bytes); the relay still sees only noise.
356
+ */
357
+
358
+ export const ID_PREFIXES = {
359
+ cmd: "a command",
360
+ idk: "an idempotency key",
361
+ ses: "an agent session",
362
+ dev: "a device (one phone install or one computer)",
363
+ prj: "a project folder on a computer",
364
+ chn: "an end-to-end channel between one phone and one computer",
365
+ apr: "an approval request",
366
+ qst: "a question from an agent",
367
+ stp: "a step of an agent run",
368
+ pli: "an item of an agent's own plan (its to-do list), stable across the plan's versions",
369
+ sag: "a subagent an agent started, for the agent map",
370
+ rot: "a root folder on a computer where a phone may create new project folders (worktrust remote roots add)",
371
+ att: "a file sent from the phone into a session's project inbox (transfer.ts)",
372
+ pvw: "one local preview render (transfer.ts)",
373
+ rel: "a release on a computer: a bundle of tasks in one project (release.ts)",
374
+ tsk: "a task of a release, run as one remote session",
375
+ plr: "one run of a release's pipeline on the computer (pipeline.ts)",
376
+ usr: "an account, as the remote system knows it (never the Passport owner id)",
377
+ jti: "a token's single-use id",
378
+ } ;
379
+
380
+ const ID_BYTES = 16;
381
+ const ID_BODY = /^[A-Za-z0-9_-]{22}$/;
382
+
383
+ export function mintId(prefix , random ) {
384
+ return `${prefix}_${toBase64Url(random(ID_BYTES))}`;
385
+ }
386
+
387
+ export function isOpaqueId(value , prefix ) {
388
+ if (typeof value !== "string" || !value.startsWith(`${prefix}_`)) return false;
389
+ const body = value.slice(prefix.length + 1);
390
+ return ID_BODY.test(body) && fromBase64Url(body)?.length === ID_BYTES;
391
+ }
392
+
393
+ // ---- packages/remote-protocol/src/schema.ts
394
+ /**
395
+ * ONE SPEC, THREE USES. A schema here is plain data: the validator walks it, `Infer` turns it into the TypeScript
396
+ * type (so the type and the runtime check cannot drift), and scripts/check-remote-protocol.mjs reads it to prove
397
+ * that nothing the relay can see is able to carry content. Hand-written type guards, no zod: the repo standardises
398
+ * on none, and a schema the checker can introspect is worth more here than a library's ergonomics.
399
+ *
400
+ * `text` is the one CONTENT kind: a prompt, a step label, a file name, output. It may appear only inside a sealed
401
+ * body. Every other kind is bounded so that it cannot smuggle a sentence: ids are prefixed random strings, enums
402
+ * are closed lists, integers are integers.
403
+ */
404
+
405
+ /** The relay-visible box a sealed body travels in (see crypto/channel.ts). */
406
+
407
+ export const text = (max , min = 0) => ({ t: "text", min, max }) ;
408
+ export const token = (max = 4096) => ({ t: "token", max }) ;
409
+ export const id = (prefix ) => ({ t: "id", prefix }) ;
410
+ export const oneOf = (values ) => ({ t: "enum", values }) ;
411
+ export const int = (min , max = Number.MAX_SAFE_INTEGER) => ({ t: "int", min, max }) ;
412
+ export const bool = () => ({ t: "bool" }) ;
413
+ export const b64 = (bytes ) => ({ t: "b64", ...bytes }) ;
414
+ export const sealed = () => ({ t: "sealed" }) ;
415
+ export const nullable = (of ) => ({ t: "nullable", of }) ;
416
+ export const optional = (of ) => ({ t: "optional", of }) ;
417
+ export const list = (of , max , min = 0) => ({ t: "list", of, min, max }) ;
418
+ export const object = (fields ) => ({ t: "object", fields }) ;
419
+ /** A tagged union: `key` names the field whose value picks the branch, and each branch is an object spec. */
420
+ export const union = (key , branches ) => ({ t: "union", key, branches }) ;
421
+
422
+ /** The largest sealed box: 1 MiB of plaintext, padded and base64url-encoded. */
423
+ export const MAX_CIPHERTEXT_BYTES = 1_048_576 + 65_536 + 16;
424
+
425
+ export const SEALED_BOX_SPEC = object({
426
+ channel_id: id("chn"),
427
+ counter: int(1, 2 ** 31),
428
+ nonce: b64({ exact: 24 }),
429
+ ciphertext: b64({ max: MAX_CIPHERTEXT_BYTES }),
430
+ });
431
+
432
+ const isRecord = (v ) =>
433
+ typeof v === "object" && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
434
+
435
+ function walk(spec , value , path ) {
436
+ switch (spec.t) {
437
+ case "text":
438
+ if (typeof value !== "string") return `${path}: expected text`;
439
+ if (value.length < spec.min || value.length > spec.max) return `${path}: length out of bounds`;
440
+ return null;
441
+ case "token":
442
+ return typeof value === "string" && value.length > 0 && value.length <= spec.max && /^[A-Za-z0-9_.-]+$/.test(value)
443
+ ? null
444
+ : `${path}: expected a compact token`;
445
+ case "id":
446
+ return isOpaqueId(value, spec.prefix) ? null : `${path}: expected an opaque ${spec.prefix}_ id`;
447
+ case "enum":
448
+ return typeof value === "string" && spec.values.includes(value) ? null : `${path}: not one of the closed values`;
449
+ case "int":
450
+ return Number.isSafeInteger(value) && (value ) >= spec.min && (value ) <= spec.max
451
+ ? null
452
+ : `${path}: expected an integer in range`;
453
+ case "bool":
454
+ return typeof value === "boolean" ? null : `${path}: expected a boolean`;
455
+ case "b64":
456
+ return typeof value === "string" && isBase64Url(value, spec) ? null : `${path}: expected base64url of the stated size`;
457
+ case "sealed":
458
+ return walk(SEALED_BOX_SPEC, value, path);
459
+ case "nullable":
460
+ return value === null ? null : walk(spec.of, value, path);
461
+ case "optional":
462
+ return value === undefined ? null : walk(spec.of, value, path);
463
+ case "list": {
464
+ if (!Array.isArray(value)) return `${path}: expected a list`;
465
+ if (value.length < spec.min || value.length > spec.max) return `${path}: list length out of bounds`;
466
+ for (let i = 0; i < value.length; i += 1) {
467
+ const bad = walk(spec.of, value[i], `${path}[${i}]`);
468
+ if (bad) return bad;
469
+ }
470
+ return null;
471
+ }
472
+ case "object": {
473
+ if (!isRecord(value)) return `${path}: expected an object`;
474
+ // EXACT KEYS: an unknown key is refused, never ignored. A field that is ignored today is a field that leaks
475
+ // tomorrow, when some sender starts putting a prompt in it and nothing complains.
476
+ for (const key of Object.keys(value)) if (!(key in spec.fields)) return `${path}.${key}: unknown field`;
477
+ for (const [key, field] of Object.entries(spec.fields)) {
478
+ if (!(key in value) && field.t !== "optional") return `${path}.${key}: missing`;
479
+ if (key in value && value[key] === undefined) return `${path}.${key}: undefined is not a value`;
480
+ const bad = walk(field, value[key], `${path}.${key}`);
481
+ if (bad) return bad;
482
+ }
483
+ return null;
484
+ }
485
+ case "union": {
486
+ const tag = isRecord(value) ? value[spec.key] : undefined;
487
+ const branch = typeof tag === "string" && Object.hasOwn(spec.branches, tag) ? spec.branches[tag] : undefined;
488
+ if (!branch) return `${path}.${spec.key}: not a known branch`;
489
+ return walk(branch, value, path);
490
+ }
491
+ }
492
+ }
493
+
494
+ export function validate (spec , value , path = "$") {
495
+ const bad = walk(spec, value, path);
496
+ return bad === null ? accept(value ) : refuse("shape", bad);
497
+ }
498
+
499
+ /** The same check for a spec chosen at run time (a table lookup by type); the caller narrows the result. */
500
+ export function check(spec , value , path = "$") {
501
+ const bad = walk(spec, value, path);
502
+ return bad === null ? accept(value) : refuse("shape", bad);
503
+ }
504
+
505
+ /** Every leaf of a spec with its path, for the checker and the tests. */
506
+ export function leaves(spec , path = "$") {
507
+ const key = path.split(".").at(-1)?.replace(/\[\]$/, "") ?? path;
508
+ switch (spec.t) {
509
+ case "nullable":
510
+ case "optional":
511
+ return leaves(spec.of, path);
512
+ case "list":
513
+ return leaves(spec.of, `${path}[]`);
514
+ case "object":
515
+ return Object.entries(spec.fields).flatMap(([k, f]) => leaves(f, `${path}.${k}`));
516
+ case "union":
517
+ return Object.values(spec.branches).flatMap((b) => leaves(b, path));
518
+ default:
519
+ return [{ path, key, spec }];
520
+ }
521
+ }
522
+
523
+ // ---- packages/remote-protocol/src/adapters.ts
524
+ /**
525
+ * WHAT A COMPUTER SAYS ITS AGENTS CAN DO. The phone shows only what a computer reports: a button for pause appears
526
+ * because the adapter on that computer said `pause: true`, never because Claude Code "usually" can. Model lists are
527
+ * the agent's own list as the computer read it (`codex debug models`, `opencode models` and the like); `models: null`
528
+ * means NOT LISTED (no lister, signed out, the lister failed) and is never read as "no models" or filled in with a
529
+ * guess. An empty list is a real answer: the agent listed nothing.
530
+ *
531
+ * TWO KINDS OF ADAPTER, one capability model:
532
+ * structured: the agent speaks a machine protocol (Claude Code's `-p --output-format stream-json
533
+ * --input-format stream-json` with a permission-prompt tool for approvals, Codex's app-server JSON-RPC). Steps,
534
+ * approvals and completion arrive as events; `acceptance: "acknowledged"`.
535
+ * terminal: the agent runs in a terminal session the person can also see at the desk (tmux on WorkTrust's own
536
+ * socket by default); the adapter attaches and reads the screen. Typing a prompt proves nothing, so
537
+ * `acceptance: "state_change"`: accepted means the agent's state was seen to change afterwards. An idle status is
538
+ * never proof that no dialog is on screen, and nothing is typed while one is (attention.ts, promptAllowed).
539
+ *
540
+ * THERE ARE NO RAW KEYS. A phone cannot send keystrokes: a free key channel is a remote approval channel. Stop is its
541
+ * own command, a question is answered by question.answer matched to a question the computer reported, and an
542
+ * approval by a signed decision bound to the action's hash.
543
+ */
544
+
545
+ export const STEER_MODES = ["live", "queued", "none"] ;
546
+
547
+ export const ADAPTER_IDS = ["claude-code", "codex", "cursor-agent", "opencode", "local"] ;
548
+
549
+ export const ADAPTER_MODES = ["structured", "terminal"] ;
550
+
551
+ /**
552
+ * Start options, a closed set. The adapter builds the agent's command line itself; nothing from the phone is passed
553
+ * through as an argument. `ask` keeps every one of the person's own permission rules and sends the rest to the phone;
554
+ * `plan` is read-only planning where the agent offers it. No mode switches approvals off.
555
+ */
556
+ export const PERMISSION_MODES = ["ask", "plan"] ;
557
+
558
+ export const MAX_MODELS_PER_ADAPTER = 200;
559
+
560
+ export const CAPABILITIES_SPEC = object({
561
+ start: bool(),
562
+ attach: bool(),
563
+ prompt: bool(),
564
+ steer: bool(),
565
+ pause: bool(),
566
+ resume: bool(),
567
+ stop: bool(),
568
+ structured_events: bool(),
569
+ screen: bool(),
570
+ focus: bool(),
571
+ resume_by_id: bool(),
572
+ permission_modes: list(oneOf(PERMISSION_MODES), PERMISSION_MODES.length, 1),
573
+ approvals: oneOf(["structured", "screen", "none"]),
574
+ acceptance: oneOf(["acknowledged", "state_change"]),
575
+ /**
576
+ * How words sent while a turn runs reach the agent (owner, 2026-11-07), measured per adapter: `live` (they enter the
577
+ * running turn; Claude Code 2.1.286 and Codex 0.154.0 read them at the next tool boundary), `queued` (they wait for the
578
+ * turn to end and run as the next turn), `none`. Absent in an older report: `steer` decides (queued or none).
579
+ */
580
+ steer_mode: optional(oneOf(STEER_MODES)),
581
+ /** The adapter can end the running turn and keep the session, so a prompt can be sent "now" (agent.prompt interrupt). */
582
+ interrupt: optional(bool()),
583
+ });
584
+
585
+ /** What the phone may offer for words sent while a turn runs: only what the computer reported. */
586
+ export const steerOffered = (c ) => c.steer_mode ?? (c.steer ? "queued" : "none");
587
+ export const interruptOffered = (c ) => c.interrupt === true && c.stop;
588
+
589
+ /** Sealed: travels inside device.inventory, so even the agent's version line stays between the two ends. */
590
+ export const ADAPTER_REPORT_SPEC = object({
591
+ adapter: oneOf(ADAPTER_IDS),
592
+ mode: oneOf(ADAPTER_MODES),
593
+ installed: bool(),
594
+ version: nullable(text(200)),
595
+ signed_in: nullable(bool()),
596
+ capabilities: CAPABILITIES_SPEC,
597
+ models: nullable(list(text(128, 1), MAX_MODELS_PER_ADAPTER)),
598
+ models_status: oneOf(["listed", "not_listed", "signed_out", "lister_failed"]),
599
+ models_at: nullable(int(0)),
600
+ default_model: nullable(text(128, 1)),
601
+ });
602
+
603
+ /** The schema, then the rules between fields that a schema alone cannot say. */
604
+ export function validateAdapterReport(value ) {
605
+ const shaped = validate(ADAPTER_REPORT_SPEC, value);
606
+ if (!shaped.ok) return shaped;
607
+ const r = shaped.value;
608
+ const c = r.capabilities;
609
+ if (r.mode === "terminal" && c.structured_events) return refuse("shape", "a terminal adapter reports no structured events");
610
+ if (r.mode === "structured" && c.screen) return refuse("shape", "a screen belongs to a terminal adapter");
611
+ if (!c.permission_modes.includes("ask")) return refuse("shape", "every adapter offers the ask mode");
612
+ if (c.steer_mode !== undefined && (c.steer_mode !== "none") !== c.steer) return refuse("shape", "steer_mode and steer disagree");
613
+ if (c.interrupt === true && !c.stop) return refuse("shape", "an interrupt needs a stop");
614
+ if (new Set(c.permission_modes).size !== c.permission_modes.length) return refuse("shape", "a permission mode is listed twice");
615
+ if (c.approvals === "structured" && !c.structured_events) return refuse("shape", "structured approvals need structured events");
616
+ if (c.approvals === "screen" && r.mode !== "terminal") return refuse("shape", "screen approvals need a terminal adapter");
617
+ if (r.mode === "structured" && c.acceptance !== "acknowledged") return refuse("shape", "a structured adapter acknowledges");
618
+ if (r.mode === "terminal" && c.acceptance !== "state_change") return refuse("shape", "a terminal adapter proves acceptance by a state change");
619
+ if ((r.models === null) !== (r.models_status !== "listed")) return refuse("shape", "models is null exactly when not listed");
620
+ if (!r.installed && (r.models !== null || r.version !== null)) return refuse("shape", "an adapter not installed reports nothing about itself");
621
+ if (r.default_model !== null && r.models !== null && !r.models.includes(r.default_model))
622
+ return refuse("shape", "the default model is not in the adapter's own list");
623
+ if (r.models !== null && new Set(r.models).size !== r.models.length) return refuse("shape", "a model is listed twice");
624
+ return accept(r);
625
+ }
626
+
627
+ /** What the UI may offer for one reported adapter: the report's own word, and nothing for an adapter not installed. */
628
+ export function availableActions(report ) {
629
+ const c = report.capabilities;
630
+ const on = report.installed;
631
+ return {
632
+ start: on && c.start,
633
+ attach: on && c.attach,
634
+ prompt: on && c.prompt,
635
+ steer: on && c.steer,
636
+ pause: on && c.pause,
637
+ resume: on && c.resume,
638
+ stop: on && c.stop,
639
+ screen: on && c.screen,
640
+ focus: on && c.focus,
641
+ resumeById: on && c.resume_by_id,
642
+ chooseModel: on && report.models !== null && report.models.length > 0,
643
+ permissionModes: on ? c.permission_modes : [],
644
+ };
645
+ }
646
+
647
+ /** A model may be named only if the computer listed it; null asks for the agent's own default. */
648
+ export function isModelReported(report , model ) {
649
+ if (model === null) return true;
650
+ return report.models !== null && report.models.includes(model);
651
+ }
652
+
653
+ // ---- packages/remote-protocol/src/attention.ts
654
+ /**
655
+ * "NEEDS YOU" AND "FOLLOW". A session's activity in five words:
656
+ * working the agent is running a turn,
657
+ * needs_you something waits for a person: an approval, a question, a trust or sign-in screen, a dialog,
658
+ * finished_unseen a turn finished and the person has not looked since,
659
+ * idle ready for input, nothing unseen,
660
+ * unknown an agent is there but its state cannot be told; this proves nothing.
661
+ *
662
+ * Two counters carry the meaning, not the word: `state_change_seq` advances on every change (news is a higher value
663
+ * than the last one reported on), `completion_seq` advances when a turn completes (a turn finished when it advanced,
664
+ * whatever the word says; null counts below any value). When a completion and a wait are seen in the same look, the
665
+ * wait wins: the person is needed, which matters more than knowing the turn ended.
666
+ *
667
+ * A person FOLLOWS a session to be told about it. Sessions started from the phone are followed from the start; a
668
+ * session started at the desk is not until the person follows it. The computer stamps each event with a content-free
669
+ * `notify` hint (needs_you, finished, none) in the relay-visible envelope, and the relay pushes only for sessions the
670
+ * phone follows, with a payload that names the session id and the hint and nothing else.
671
+ */
672
+
673
+ export const ACTIVITIES = ["working", "needs_you", "finished_unseen", "idle", "unknown"] ;
674
+
675
+ export const NEEDS_REASONS = ["approval", "question", "trust", "login", "dialog"] ;
676
+
677
+ export const NOTIFY_HINTS = ["none", "needs_you", "finished"] ;
678
+
679
+ export const ATTENTION_SPEC = object({
680
+ activity: oneOf(ACTIVITIES),
681
+ needs: nullable(oneOf(NEEDS_REASONS)),
682
+ state_change_seq: int(0),
683
+ completion_seq: nullable(int(0)),
684
+ });
685
+
686
+ export function validateAttention(value , path = "$") {
687
+ const checked = validate(ATTENTION_SPEC, value, path);
688
+ if (!checked.ok) return checked;
689
+ if ((checked.value.activity === "needs_you") !== (checked.value.needs !== null))
690
+ return { ok: false, code: "shape", detail: `${path}.needs: set exactly when the activity is needs_you` };
691
+ return checked;
692
+ }
693
+
694
+ const seqAbove = (a , b ) => (a ?? -1) > (b ?? -1);
695
+
696
+ /** News: anything with a higher state_change_seq than the last snapshot reported on. */
697
+ export const isNews = (previous , next ) =>
698
+ previous === null || next.state_change_seq > previous.state_change_seq;
699
+
700
+ /** A turn finished between two looks: completion_seq advanced. */
701
+ export const turnFinished = (previous , next ) =>
702
+ seqAbove(next.completion_seq, previous?.completion_seq ?? null);
703
+
704
+ /** The hint the computer stamps on an event, from two looks at the session. The wait wins over the completion. */
705
+ export function notifyHint(previous , next ) {
706
+ if (!isNews(previous, next)) return "none";
707
+ if (next.activity === "needs_you" && (previous === null || previous.activity !== "needs_you" || previous.needs !== next.needs))
708
+ return "needs_you";
709
+ if (turnFinished(previous, next)) return "finished";
710
+ return "none";
711
+ }
712
+
713
+ /** Whether the relay pushes: a hint other than none, for a followed session. */
714
+ export const shouldPush = (hint , following ) => following && hint !== "none";
715
+
716
+ /** The whole push payload. Nothing in it is content: an opaque session id and the hint. */
717
+ export const PUSH_PAYLOAD_SPEC = object({ session_id: id("ses"), hint: oneOf(["needs_you", "finished"]) });
718
+
719
+ /**
720
+ * Whether a prompt may be typed into a session now. Never while something waits for a person (a dialog would take the
721
+ * keystrokes as its answer), never when the state cannot be told, and never mid-turn (agent.steer is for that, on an
722
+ * adapter that reports steer). Keyed on the reported attention, never on a status word alone.
723
+ */
724
+ export const promptAllowed = (attention ) =>
725
+ attention !== null && (attention.activity === "idle" || attention.activity === "finished_unseen");
726
+
727
+ // ---- packages/remote-protocol/src/progress.ts
728
+ /**
729
+ * PROGRESS SAYS WHAT WAS COUNTED. Three shapes and no fourth:
730
+ * measured: a real denominator the agent or a tool reported (13 of 25 tests, 4 of 9 files),
731
+ * steps: counts of steps started and completed, with no claim about how many remain,
732
+ * indeterminate: nothing countable.
733
+ * There is no percentage field and no elapsed-time field, so a bar that fills because time passes cannot be built
734
+ * from this type: the schema refuses `percent`, `elapsed_ms` and every other key it does not name.
735
+ *
736
+ * A PERCENTAGE IS DERIVED, NEVER SENT (owner, 2026-11-07: the roadmap's 0 to 100% loader). `progressPercent` gives one
737
+ * for a measured count, and plan.ts's `planPercent` for the agent's own reported plan (completed over total items of
738
+ * the current version); everything else is null, so the surface draws a count or a spinner. The plan can grow, so its
739
+ * percentage can fall, and the plan event says so (`change: "plan_changed"`). scripts/check-remote-protocol.mjs refuses
740
+ * a field named like a percentage, a fraction or an elapsed time in any shape, sealed or not.
741
+ *
742
+ * AN ETA IS AN ESTIMATE WITH A SOURCE. `agent` (the agent said so) or `history` (similar runs on this computer took
743
+ * this long), with a confidence. A weak estimate is shown as unavailable, not as a small grey number: a guess that
744
+ * looks like a measurement is the failure this file exists to prevent.
745
+ */
746
+
747
+ export const PROGRESS_UNITS = ["tests", "files", "steps", "items", "checks"] ;
748
+
749
+ export const PROGRESS_SPEC = union("kind", {
750
+ measured: object({ kind: oneOf(["measured"]), done: int(0), total: int(1), unit: oneOf(PROGRESS_UNITS) }),
751
+ steps: object({ kind: oneOf(["steps"]), started: int(0), completed: int(0) }),
752
+ indeterminate: object({ kind: oneOf(["indeterminate"]) }),
753
+ });
754
+
755
+ export const ETA_SPEC = union("kind", {
756
+ estimate: object({
757
+ kind: oneOf(["estimate"]),
758
+ remaining_s: int(1, 7 * 24 * 3600),
759
+ source: oneOf(["agent", "history"]),
760
+ confidence: oneOf(["low", "medium", "high"]),
761
+ }),
762
+ unavailable: object({
763
+ kind: oneOf(["unavailable"]),
764
+ source: oneOf(["agent", "history", "none"]),
765
+ reason: oneOf(["no_source", "weak", "overrun"]),
766
+ }),
767
+ });
768
+
769
+ /** The rule a schema cannot say: a count never runs past its own denominator. */
770
+ export function progressRule(p ) {
771
+ if (p.kind === "measured" && p.done > p.total) return "done above total";
772
+ if (p.kind === "steps" && p.completed > p.started) return "more completed than started";
773
+ return null;
774
+ }
775
+
776
+ export function validateProgress(value , path = "$") {
777
+ const checked = validate(PROGRESS_SPEC, value, path);
778
+ if (!checked.ok) return checked;
779
+ const bad = progressRule(checked.value);
780
+ return bad ? { ok: false, code: "shape", detail: `${path}: ${bad}` } : checked;
781
+ }
782
+
783
+ export const validateEta = (value , path = "$") => validate(ETA_SPEC, value, path);
784
+
785
+ /** A fraction exists only for a measured denominator. Steps and indeterminate give null: no bar, a count or a spinner. */
786
+ export function progressFraction(progress ) {
787
+ return progress.kind === "measured" ? progress.done / progress.total : null;
788
+ }
789
+
790
+ /** The percentage of a measured count, rounded down (100 only when done equals total); null for anything else. */
791
+ export function progressPercent(progress ) {
792
+ return progress.kind === "measured" ? Math.floor((Math.min(progress.done, progress.total) * 100) / progress.total) : null;
793
+ }
794
+
795
+ /** What to show, as data for the UI's own catalogue (the package carries no copy). */
796
+
797
+ export function progressView(progress ) {
798
+ if (progress.kind === "measured") return { view: "bar", done: progress.done, total: progress.total, unit: progress.unit };
799
+ if (progress.kind === "steps") return { view: "count", completed: progress.completed, started: progress.started };
800
+ return { view: "spinner" };
801
+ }
802
+
803
+ /** The ETA a person may see: a low-confidence estimate becomes unavailable. */
804
+ export function etaForDisplay(eta ) {
805
+ if (eta.kind === "estimate" && eta.confidence === "low") return { kind: "unavailable", source: eta.source, reason: "weak" };
806
+ return eta;
807
+ }
808
+
809
+ /** The agent's own estimate, kept only with its confidence. */
810
+ export function etaFromAgent(remainingSeconds , confidence ) {
811
+ if (remainingSeconds === null || !Number.isSafeInteger(remainingSeconds) || remainingSeconds < 1)
812
+ return { kind: "unavailable", source: remainingSeconds === null ? "none" : "agent", reason: remainingSeconds === null ? "no_source" : "overrun" };
813
+ return etaForDisplay({ kind: "estimate", remaining_s: remainingSeconds, source: "agent", confidence });
814
+ }
815
+
816
+ export const HISTORY_MIN_SAMPLES = 5;
817
+ export const HISTORY_MAX_SPREAD = 0.5;
818
+
819
+ const quantile = (sorted , q ) => {
820
+ const at = (sorted.length - 1) * q;
821
+ const lo = Math.floor(at);
822
+ const hi = Math.ceil(at);
823
+ return sorted[lo] + (sorted[hi] - sorted[lo] ) * (at - lo);
824
+ };
825
+
826
+ /**
827
+ * From the durations of similar finished runs on this computer (seconds) and this run's elapsed time. Fewer than five
828
+ * samples, or a spread (interquartile range over median) above one half, is too weak to show. A run already past the
829
+ * median has no estimate left: it is "overrun", not "almost done".
830
+ */
831
+ export function etaFromHistory(durationsSeconds , elapsedSeconds ) {
832
+ const samples = durationsSeconds.filter((d) => Number.isFinite(d) && d > 0).sort((a, b) => a - b);
833
+ if (samples.length < HISTORY_MIN_SAMPLES) return { kind: "unavailable", source: "history", reason: "weak" };
834
+ const median = quantile(samples, 0.5);
835
+ const spread = (quantile(samples, 0.75) - quantile(samples, 0.25)) / median;
836
+ if (spread > HISTORY_MAX_SPREAD) return { kind: "unavailable", source: "history", reason: "weak" };
837
+ const remaining = Math.round(median - elapsedSeconds);
838
+ if (remaining < 1) return { kind: "unavailable", source: "history", reason: "overrun" };
839
+ const confidence = samples.length >= 20 && spread <= 0.25 ? "high" : "medium";
840
+ return { kind: "estimate", remaining_s: remaining, source: "history", confidence };
841
+ }
842
+
843
+ // ---- packages/remote-protocol/src/plan.ts
844
+ /**
845
+ * THE AGENT'S OWN PLAN IS THE DENOMINATOR (owner, 2026-11-07: a roadmap with a 0 to 100% loader while a prompt runs).
846
+ *
847
+ * A percentage exists in exactly two cases, and both are counts the computer read, never time and never a model's guess:
848
+ * 1. a REPORTED PLAN: the agent's own to-do list (Claude Code's TodoWrite, or its TaskCreate/TaskUpdate list), as
849
+ * completed items over all items of the plan's current version;
850
+ * 2. a MEASURED COUNT: a `measured` progress (13 of 25 tests) a tool reported.
851
+ * No plan and no measured count is INDETERMINATE: a spinner, never a bar. A plan cut at MAX_PLAN_ITEMS has an unknown
852
+ * denominator, so it is indeterminate too.
853
+ *
854
+ * THE PLAN CAN GROW, SO THE PERCENTAGE CAN FALL. An agent that finds more work adds items; 3 of 4 (75%) becomes 3 of 6
855
+ * (50%). That is the truth and it is shown as it is: a surface never holds the bar at its highest value, and every
856
+ * version whose items changed (added, removed, relabelled) carries the marker `change: "plan_changed"`, so the surface
857
+ * can say why the bar went back. A version where only states moved is `progressed`; the first is `created`.
858
+ *
859
+ * The plan travels sealed (`agent.plan`, events.ts), re-sent whole on every change with a rising `plan_version`. Item
860
+ * ids are opaque (`pli_`) and stable across versions, so a step (`agent.step_started.plan_item_id`) stays attached to
861
+ * its item when the list grows or is reordered. No field here is a percentage: the number is derived by `planPercent`,
862
+ * the one place it is computed, so no sender can put a figure on the wire that the counts do not support.
863
+ */
864
+
865
+ export const MAX_PLAN_ITEMS = 100;
866
+ export const MAX_PLAN_LABEL = 500;
867
+ export const PLAN_ITEM_STATES = ["pending", "in_progress", "completed"] ;
868
+ export const PLAN_CHANGES = ["created", "progressed", "plan_changed"] ;
869
+
870
+ export const PLAN_ITEM_SPEC = object({
871
+ item_id: id("pli"),
872
+ /** The item as the agent wrote it (Claude Code's `content` or `subject`). */
873
+ label: text(MAX_PLAN_LABEL, 1),
874
+ state: oneOf(PLAN_ITEM_STATES),
875
+ /** The agent's own words for the item while it runs (Claude Code's `activeForm`); null unless in progress. */
876
+ active: nullable(text(MAX_PLAN_LABEL, 1)),
877
+ /**
878
+ * The item's description as the agent wrote it (Claude Code's task `description`; owner, 2026-11-08: a step's one-line
879
+ * line under its title). Sealed like the label; absent or null when the agent gave none: never made up.
880
+ */
881
+ detail: optional(nullable(text(MAX_PLAN_LABEL, 1))),
882
+ });
883
+
884
+ export const PLAN_BODY_SPEC = object({
885
+ plan_version: int(1),
886
+ change: oneOf(PLAN_CHANGES),
887
+ items: list(PLAN_ITEM_SPEC, MAX_PLAN_ITEMS),
888
+ /**
889
+ * The list is not whole: more items than MAX_PLAN_ITEMS, or it names a task the computer never saw created (a resumed
890
+ * session). The denominator is unknown, so no percentage.
891
+ */
892
+ items_cut: bool(),
893
+ });
894
+
895
+ /** The rules a schema cannot say: one id per item, and words for "now doing" only on the item being done. */
896
+ export function planRule(plan ) {
897
+ if (new Set(plan.items.map((i) => i.item_id)).size !== plan.items.length) return "an item id twice";
898
+ if (plan.items.some((i) => i.active !== null && i.state !== "in_progress")) return "active words on an item not in progress";
899
+ return null;
900
+ }
901
+
902
+ /** How a new version differs from the one before: the plan_changed marker is the surface's reason a bar went back. */
903
+ export function planChange(previous , next ) {
904
+ if (previous === null) return "created";
905
+ const before = previous.items.map((i) => `${i.item_id}\u0000${i.label}`).join("\u0001");
906
+ const after = next.items.map((i) => `${i.item_id}\u0000${i.label}`).join("\u0001");
907
+ return before === after ? "progressed" : "plan_changed";
908
+ }
909
+
910
+ /** The plan as progress: a measured count of items, or indeterminate (no plan, an empty plan, a cut plan). */
911
+ export function planProgress(plan ) {
912
+ if (plan === null || plan.items_cut || plan.items.length === 0) return { kind: "indeterminate" };
913
+ return { kind: "measured", done: plan.items.filter((i) => i.state === "completed").length, total: plan.items.length, unit: "items" };
914
+ }
915
+
916
+ /** The one percentage of a plan: completed over total, rounded down (100 only when every item is done), or null. */
917
+ export function planPercent(plan ) {
918
+ const p = planProgress(plan);
919
+ return p.kind === "measured" ? Math.floor((p.done * 100) / p.total) : null;
920
+ }
921
+
922
+ /**
923
+ * The item a step belongs to: the first item in progress, in the plan's own order, at the moment the step began. Null
924
+ * when no plan exists or nothing is in progress: a step is never attached to an item by guess.
925
+ */
926
+ export function currentPlanItem(plan ) {
927
+ return plan?.items.find((i) => i.state === "in_progress") ?? null;
928
+ }
929
+
930
+ /** What a roadmap shows, as data for the surface's own catalogue (the package carries no copy). */
931
+
932
+ export function planView(plan ) {
933
+ const p = planProgress(plan);
934
+ return {
935
+ percent: planPercent(plan),
936
+ completed: p.kind === "measured" ? p.done : plan?.items.filter((i) => i.state === "completed").length ?? 0,
937
+ total: plan?.items.length ?? 0,
938
+ current: currentPlanItem(plan),
939
+ changed: plan?.change === "plan_changed",
940
+ };
941
+ }
942
+
943
+ // ---- packages/remote-protocol/src/agent-map.ts
944
+ /**
945
+ * THE AGENT MAP: THE MAIN AGENT AND THE SUBAGENTS IT STARTED (owner, 2026-11-07). Sealed `agent.subagent` events, one
946
+ * per change of one subagent, each carrying its whole current record: who started it (`parent_id`, null for the main
947
+ * agent), the step that delegated it (`step_id`), the agent's own description and type, its state, how many steps it
948
+ * took, its tokens where the agent reported them, and its time.
949
+ *
950
+ * States: `started` (the main agent asked for it), `working` (its first own line or progress report arrived), then one
951
+ * final state, `done`, `failed` or `stopped` (ended by someone, not by its own work). A final state is final: a late
952
+ * `working` for a finished subagent changes nothing (`foldSubagent`). The computer tracks at most MAX_SUBAGENTS per
953
+ * session; one past the cap is not drawn, and its steps are not attributed to anyone.
954
+ *
955
+ * `agentTree` nests the records under their parents for a surface, so no surface builds the tree itself. A record whose
956
+ * parent is unknown (never seen, or past the cap) sits at the top level, marked `orphan`, never under a guessed parent.
957
+ */
958
+
959
+ export const MAX_SUBAGENTS = 100;
960
+ export const MAX_SUBAGENT_DEPTH = 8;
961
+ export const SUBAGENT_STATES = ["started", "working", "done", "failed", "stopped"] ;
962
+
963
+ const RANK = { started: 0, working: 1, done: 2, failed: 2, stopped: 2 };
964
+ export const isFinalSubagentState = (state ) => RANK[state] === 2;
965
+
966
+ export const SUBAGENT_TOKENS_SPEC = object({
967
+ /** The agent's own total for the subagent (Claude Code's totalTokens / total_tokens), or null. */
968
+ total: nullable(int(0)),
969
+ input: nullable(int(0)),
970
+ output: nullable(int(0)),
971
+ cache_read: nullable(int(0)),
972
+ cache_creation: nullable(int(0)),
973
+ });
974
+
975
+ export const SUBAGENT_BODY_SPEC = object({
976
+ subagent_id: id("sag"),
977
+ parent_id: nullable(id("sag")),
978
+ step_id: nullable(id("stp")),
979
+ label: nullable(text(500, 1)),
980
+ agent_type: nullable(text(128, 1)),
981
+ state: oneOf(SUBAGENT_STATES),
982
+ steps: int(0),
983
+ tokens: SUBAGENT_TOKENS_SPEC,
984
+ started_at: nullable(int(0)),
985
+ duration_ms: nullable(int(0)),
986
+ });
987
+
988
+ export function subagentRule(s ) {
989
+ if (s.parent_id === s.subagent_id) return "a subagent is its own parent";
990
+ if (s.duration_ms !== null && !isFinalSubagentState(s.state)) return "a duration before the subagent ended";
991
+ return null;
992
+ }
993
+
994
+ /** The latest record per subagent; a final state is never replaced by an earlier one. */
995
+ export function foldSubagent(map , next ) {
996
+ const out = new Map(map);
997
+ const prev = map.get(next.subagent_id);
998
+ if (prev && RANK[next.state] < RANK[prev.state]) return out;
999
+ if (prev && isFinalSubagentState(prev.state) && next.state !== prev.state) return out;
1000
+ if (!prev && out.size >= MAX_SUBAGENTS) return out;
1001
+ out.set(next.subagent_id, next);
1002
+ return out;
1003
+ }
1004
+
1005
+ /** The records as a tree under the main agent: children in the order they started, cycles and depth bounded. */
1006
+ export function agentTree(map ) {
1007
+ const all = [...map.values()];
1008
+ const kids = new Map ();
1009
+ for (const s of all) if (s.parent_id !== null && map.has(s.parent_id)) kids.set(s.parent_id, [...(kids.get(s.parent_id) ?? []), s]);
1010
+ const placed = new Set ();
1011
+ const node = (s , depth , orphan ) => {
1012
+ placed.add(s.subagent_id);
1013
+ const children = depth >= MAX_SUBAGENT_DEPTH ? [] : (kids.get(s.subagent_id) ?? []).filter((c) => !placed.has(c.subagent_id)).map((c) => node(c, depth + 1, false));
1014
+ return { agent: s, depth, orphan, children };
1015
+ };
1016
+ const roots = all.filter((s) => s.parent_id === null || !map.has(s.parent_id)).map((s) => node(s, 1, s.parent_id !== null));
1017
+ // A parent chain that loops has no root; its members are drawn at the top, marked, rather than lost.
1018
+ for (const s of all) if (!placed.has(s.subagent_id)) roots.push(node(s, 1, true));
1019
+ return roots;
1020
+ }
1021
+
1022
+ // ---- packages/remote-protocol/src/usage.ts
1023
+ /**
1024
+ * TOKENS AND TIME, AS REPORTED (owner, 2026-11-07: the phone shows the current token usage and the elapsed time, so a
1025
+ * person can trust what happens). Sealed, like everything an agent produces.
1026
+ *
1027
+ * TOKENS ARE NEVER ESTIMATED. Each count is the agent's own report (Claude Code's `usage`: input_tokens, output_tokens,
1028
+ * cache_read_input_tokens, cache_creation_input_tokens) and a count the agent did not report is null, never 0 and never
1029
+ * a guess. `agent.usage` carries the current turn and the remote session so far:
1030
+ * - while a turn runs, `turn` is the sum of the per-message reports the stream carried (`turn_final: false`); the
1031
+ * stream reports a message's output when it starts, so a running output count can only rise, and
1032
+ * - when the turn ends, `turn` is the agent's own total for the turn (`turn_final: true`), which replaces the sum.
1033
+ * - `session` is the sum of the turns' final totals plus the running turn; a field is null in it unless every turn
1034
+ * reported that field.
1035
+ * The computer sends `agent.usage` at most once per two seconds while a turn runs (USAGE_MIN_INTERVAL_MS, coalesced:
1036
+ * the latest wins) and the turn's final total at once. The model is the one the agent reported for the turn.
1037
+ *
1038
+ * TIME IS A CLOCK READING, NEVER PROGRESS. `started_at` (on the acceptance that began a turn, and on a subagent) is the
1039
+ * computer's clock in milliseconds; `duration_ms` (on a completed or failed turn, a completed step, a finished subagent)
1040
+ * is measured on the computer or reported by the agent. Elapsed time is shown as elapsed time, never as a bar.
1041
+ */
1042
+
1043
+ export const USAGE_MIN_INTERVAL_MS = 2000;
1044
+
1045
+ export const TOKEN_COUNTS_SPEC = object({
1046
+ input: nullable(int(0)),
1047
+ output: nullable(int(0)),
1048
+ cache_read: nullable(int(0)),
1049
+ cache_creation: nullable(int(0)),
1050
+ });
1051
+
1052
+ export const TOKEN_FIELDS = ["input", "output", "cache_read", "cache_creation"] ;
1053
+
1054
+ export const USAGE_BODY_SPEC = object({
1055
+ /** The model the agent reported for this turn, or null when it named none. */
1056
+ model: nullable(text(128, 1)),
1057
+ turn: TOKEN_COUNTS_SPEC,
1058
+ /** True when `turn` is the agent's own total for the finished turn; false while it is the running sum. */
1059
+ turn_final: bool(),
1060
+ session: TOKEN_COUNTS_SPEC,
1061
+ });
1062
+
1063
+ export const NO_TOKENS = Object.freeze({ input: null, output: null, cache_read: null, cache_creation: null });
1064
+
1065
+ /** Every field reported is summed; a field absent in either is absent in the sum. */
1066
+ export function addTokens(a , b ) {
1067
+ const sum = (x , y ) => (x === null || y === null ? null : x + y);
1068
+ return { input: sum(a.input, b.input), output: sum(a.output, b.output), cache_read: sum(a.cache_read, b.cache_read), cache_creation: sum(a.cache_creation, b.cache_creation) };
1069
+ }
1070
+
1071
+ /** All four counts together, or null when any of them was not reported: a total is never built from a part. */
1072
+ export function tokenTotal(counts ) {
1073
+ return TOKEN_FIELDS.every((f) => counts[f] !== null) ? TOKEN_FIELDS.reduce((n, f) => n + (counts[f] ), 0) : null;
1074
+ }
1075
+
1076
+ /** Elapsed milliseconds since a computer's `started_at`, read on another clock: null when that clock is behind. */
1077
+ export function elapsedMs(startedAt , now ) {
1078
+ if (typeof startedAt !== "number" || !Number.isSafeInteger(startedAt) || !Number.isFinite(now) || now < startedAt) return null;
1079
+ return Math.floor(now - startedAt);
1080
+ }
1081
+
1082
+ // ---- packages/remote-protocol/src/pipeline.ts
1083
+ /**
1084
+ * A RELEASE'S PIPELINE: HOW FAR IS IT FROM PRODUCTION-READY (owner, 2026-11-07: the Live view shows build, tests, SAST,
1085
+ * DAST, package checks and release prep for a release, and how far each is).
1086
+ *
1087
+ * The stages are the PERSON'S, written in a file in the project (`.worktrust/pipeline.json`), reviewed at the computer's
1088
+ * keyboard (`worktrust remote pipeline review`, which pins the file's hash), and run by the daemon on the computer. The
1089
+ * phone starts or cancels a pipeline the computer already has; it never names a command. A stage's command comes from an
1090
+ * allowlist (`pnpm <script>`, `npm run <script>`, `node scripts/<file>.mjs`, `semgrep ...`, `zap-baseline.py ...`), run
1091
+ * without a shell. None of that crosses the wire: the phone sees a stage's id, label, kind, state and what its parser read.
1092
+ *
1093
+ * DEPLOY AND PUBLISH STAY AT THE DESK (owner rule: production deploys and publishing are run at the computer, in the ship
1094
+ * scripts). A stage of kind `deploy` or `publish` is never run by the daemon at all: it is shown as `at_desk`, a step the
1095
+ * person takes at their computer. `pipelineRule` refuses any other state for one, and any desk state for another kind.
1096
+ *
1097
+ * COUNTS ONLY WHEN READ. `measured` is present only when the stage's parser read the counts from the tool's own report
1098
+ * (TAP, JUnit XML, the node test runner's summary, Vitest or Jest JSON); `findings` only from a scanner's JSON (Semgrep,
1099
+ * ZAP). A stage with no parser, or whose report did not parse, has neither: passed or failed by its exit code, no number.
1100
+ * The pipeline's percentage is derived, never sent: finished stages over the stages the daemon runs (`pipelinePercent`),
1101
+ * and the tests' percentage from the measured counts (`pipelineTests`). An ETA comes only from history (`etaForDisplay`).
1102
+ */
1103
+
1104
+ export const MAX_PIPELINE_STAGES = 30;
1105
+ export const STAGE_KINDS = ["build", "unit", "integration", "e2e", "sast", "dast", "package", "release_prep", "deploy", "publish", "other"] ;
1106
+
1107
+ /** Never run by the daemon: shown as a step the person takes at their computer. */
1108
+ export const DESK_STAGE_KINDS = new Set (["deploy", "publish"]);
1109
+ export const STAGE_STATES = ["queued", "running", "passed", "failed", "skipped", "at_desk"] ;
1110
+
1111
+ export const PIPELINE_STATES = ["queued", "running", "passed", "failed", "cancelled"] ;
1112
+
1113
+ export const PIPELINE_REASONS = ["stage_failed", "cancelled", "interrupted", "unreviewed", "invalid_config", "timeout"] ;
1114
+ export const PIPELINE_PARSERS = ["none", "tap", "junit_xml", "node_test", "vitest_json", "jest_json", "semgrep_json", "zap_json"] ;
1115
+
1116
+ export const MEASURED_UNITS = ["tests", "checks", "files"] ;
1117
+
1118
+ export const STAGE_MEASURED_SPEC = object({ done: int(0), total: int(1), failed: int(0), unit: oneOf(MEASURED_UNITS) });
1119
+ export const STAGE_FINDINGS_SPEC = object({ high: int(0), medium: int(0), low: int(0) });
1120
+
1121
+ export const STAGE_SPEC = object({
1122
+ /** The person's own id for the stage in pipeline.json ([a-z0-9_-]), sealed with the rest. */
1123
+ stage_id: text(64, 1),
1124
+ label: text(200, 1),
1125
+ kind: oneOf(STAGE_KINDS),
1126
+ state: oneOf(STAGE_STATES),
1127
+ measured: optional(STAGE_MEASURED_SPEC),
1128
+ findings: optional(STAGE_FINDINGS_SPEC),
1129
+ started_at: optional(int(0)),
1130
+ duration_ms: optional(int(0)),
1131
+ eta: optional(ETA_SPEC),
1132
+ });
1133
+
1134
+ export const PIPELINE_BODY_SPEC = object({
1135
+ pipeline_run_id: id("plr"),
1136
+ release_id: nullable(id("rel")),
1137
+ project_id: id("prj"),
1138
+ state: oneOf(PIPELINE_STATES),
1139
+ reason: nullable(oneOf(PIPELINE_REASONS)),
1140
+ stages: list(STAGE_SPEC, MAX_PIPELINE_STAGES),
1141
+ started_at: int(0),
1142
+ ended_at: nullable(int(0)),
1143
+ eta: optional(ETA_SPEC),
1144
+ });
1145
+
1146
+ const FINAL_STAGE = new Set (["passed", "failed", "skipped", "at_desk"]);
1147
+ const FINAL_PIPELINE = new Set (["passed", "failed", "cancelled"]);
1148
+ export const isFinalPipelineState = (s ) => FINAL_PIPELINE.has(s);
1149
+
1150
+ /** An ETA on the wire is history's estimate that etaForDisplay keeps, or nothing. */
1151
+ export const etaShown = (eta ) => eta === undefined || (eta.kind === "estimate" && eta.source === "history" && etaForDisplay(eta).kind === "estimate");
1152
+
1153
+ export function stageRule(s ) {
1154
+ if (DESK_STAGE_KINDS.has(s.kind) !== (s.state === "at_desk")) return `stage ${s.stage_id}: deploy and publish are at the desk, and only they`;
1155
+ if (s.measured && (s.measured.done > s.measured.total || s.measured.failed > s.measured.done)) return `stage ${s.stage_id}: a count past its denominator`;
1156
+ if (s.duration_ms !== undefined && !FINAL_STAGE.has(s.state)) return `stage ${s.stage_id}: a duration before the stage ended`;
1157
+ if (s.eta !== undefined && (FINAL_STAGE.has(s.state) || !etaShown(s.eta))) return `stage ${s.stage_id}: an ETA that is not history's, shown, on a live stage`;
1158
+ if (s.state === "at_desk" && (s.measured || s.findings || s.started_at !== undefined)) return `stage ${s.stage_id}: a desk step the daemon never ran has no result`;
1159
+ return null;
1160
+ }
1161
+
1162
+ export function pipelineRule(p ) {
1163
+ if (new Set(p.stages.map((s) => s.stage_id)).size !== p.stages.length) return "a stage id twice";
1164
+ for (const s of p.stages) { const bad = stageRule(s); if (bad) return bad; }
1165
+ if (isFinalPipelineState(p.state) !== (p.ended_at !== null)) return "ended_at exactly when the pipeline ended";
1166
+ if (p.ended_at !== null && p.ended_at < p.started_at) return "ended before it started";
1167
+ if ((p.state === "failed" || p.state === "cancelled") !== (p.reason !== null)) return "a reason exactly for a failed or cancelled pipeline";
1168
+ if (p.state === "passed" && p.stages.some((s) => s.state !== "passed" && s.state !== "at_desk" && s.state !== "skipped")) return "passed with a stage that did not pass";
1169
+ if (p.stages.filter((s) => s.state === "running").length > 1) return "two stages running at once";
1170
+ if (p.eta !== undefined && (isFinalPipelineState(p.state) || !etaShown(p.eta))) return "an ETA that is not history's, shown, on a live pipeline";
1171
+ return null;
1172
+ }
1173
+
1174
+ /** The stages the daemon runs (every one but the desk's), and how many of them finished without failing. */
1175
+ export function pipelineProgress(p ) {
1176
+ const runnable = (p?.stages ?? []).filter((s) => s.state !== "at_desk");
1177
+ if (runnable.length === 0) return { kind: "indeterminate" };
1178
+ return { kind: "measured", done: runnable.filter((s) => s.state === "passed" || s.state === "skipped").length, total: runnable.length, unit: "checks" };
1179
+ }
1180
+
1181
+ /** Finished stages over runnable stages, rounded down; null without a runnable stage. Never from time. */
1182
+ export function pipelinePercent(p ) {
1183
+ const progress = pipelineProgress(p);
1184
+ return progress.kind === "measured" ? Math.floor((progress.done * 100) / progress.total) : null;
1185
+ }
1186
+
1187
+ /** The tests the parsers read, summed over the stages that measured tests ("400 / 500 tests"); null when none did. */
1188
+ export function pipelineTests(p ) {
1189
+ const measured = (p?.stages ?? []).flatMap((s) => (s.measured?.unit === "tests" ? [s.measured] : []));
1190
+ if (measured.length === 0) return null;
1191
+ return measured.reduce((a, m) => ({ done: a.done + m.done, total: a.total + m.total, failed: a.failed + m.failed }), { done: 0, total: 0, failed: 0 });
1192
+ }
1193
+
1194
+ /** The stage in progress (the Live tile "Verifying · Security & quality"), or null. */
1195
+ export const currentStage = (p ) => p?.stages.find((s) => s.state === "running") ?? null;
1196
+
1197
+ // ---- packages/remote-protocol/src/release.ts
1198
+ /**
1199
+ * RELEASES: A BUNDLE OF TASKS, AND ONE QUEUE PER COMPUTER (owner, 2026-11-07: "In the roadmap you see releases, and tasks
1200
+ * added to a release, all tasks as a bundle; several releases can run at the same time and they all communicate with
1201
+ * each other. Releases in a table so you see the whole backlog and can scroll back.").
1202
+ *
1203
+ * A release belongs to one project on one computer. Its tasks are prompts, each run as an ordinary remote session by the
1204
+ * daemon's ONE scheduler: every task of every release waits in the same queue, under the computer's session cap (the
1205
+ * daemon's max_sessions, default 4), in release order, and starts when a slot frees. One queue means no task runs twice
1206
+ * and every release sees what the others hold. A task or a release may wait for another release (`after_release`: the
1207
+ * roadmap's "after release 1"); it starts only once that release is `ready` or `released`.
1208
+ *
1209
+ * States, as the computer knows them:
1210
+ * release planned -> in_progress -> verifying (its pipeline runs) -> ready | failed; released is set at the desk only
1211
+ * (the ship scripts publish; the phone never marks a release released).
1212
+ * task queued -> running -> done | failed | cancelled.
1213
+ * Everything here is SEALED: the relay sees `release.updated` and its size class, never a title, a label, a count or an id
1214
+ * of a release or a task (those ids live inside the body). A percentage is derived, never sent (`releaseProgress`), and a
1215
+ * task's ETA is present only when history gives one etaForDisplay keeps (`etaShown`), else absent.
1216
+ */
1217
+
1218
+ export const MAX_RELEASE_TASKS = 50;
1219
+ export const MAX_RELEASE_PAGE = 20;
1220
+ export const MAX_RELEASE_TITLE = 200;
1221
+ export const MAX_TASK_LABEL = 200;
1222
+ export const MAX_TASK_NOTE = 120;
1223
+ /** A release's own short name ("CLI 0.11.0"), the person's or the agent's words, in place of "Release N: title". */
1224
+ export const MAX_RELEASE_LABEL = 40;
1225
+ /** How many of one release's tasks may run at once (they share one working tree, so one by default). */
1226
+ export const MAX_RELEASE_PARALLEL = 4;
1227
+ export const MAX_REORDER_RELEASES = 200;
1228
+ export const RELEASE_STATES = ["planned", "in_progress", "verifying", "ready", "released", "failed"] ;
1229
+
1230
+ export const TASK_STATES = ["queued", "running", "done", "failed", "cancelled"] ;
1231
+
1232
+ export const TASK_FAIL_REASONS = ["agent_failed", "interrupted", "refused", "stopped"] ;
1233
+ /** Whether the project has a pipeline the daemon may run: none written, written but not reviewed at the keyboard, reviewed. */
1234
+ export const PIPELINE_CONFIG_STATES = ["absent", "unreviewed", "reviewed"] ;
1235
+
1236
+ export const TASK_SPEC = object({
1237
+ task_id: id("tsk"),
1238
+ /** The person's label for the task, or the prompt's first line, cut. The prompt itself stays on the computer. */
1239
+ label: text(MAX_TASK_LABEL, 1),
1240
+ adapter: oneOf(ADAPTER_IDS),
1241
+ model: nullable(text(128, 1)),
1242
+ state: oneOf(TASK_STATES),
1243
+ reason: nullable(oneOf(TASK_FAIL_REASONS)),
1244
+ after_release: nullable(id("rel")),
1245
+ /** The task it continues (the agent resumes that task's own session), or null. */
1246
+ follow_up_of: nullable(id("tsk")),
1247
+ /** The remote session the task runs as, once started: the phone attaches to it for steps, plan and tokens. */
1248
+ session_id: nullable(id("ses")),
1249
+ started_at: nullable(int(0)),
1250
+ duration_ms: nullable(int(0)),
1251
+ eta: optional(ETA_SPEC),
1252
+ /** A failed task's one line, in its agent's words (a task the agent planned and reported itself, 2026-11-08). */
1253
+ note: optional(text(MAX_TASK_NOTE, 1)),
1254
+ });
1255
+
1256
+ export const RELEASE_COUNTS_SPEC = object({ queued: int(0), running: int(0), done: int(0), failed: int(0), cancelled: int(0) });
1257
+
1258
+ export const RELEASE_BODY_SPEC = object({
1259
+ release_id: id("rel"),
1260
+ /** "Release 18": counts from 1 on this computer, never reused. */
1261
+ number: int(1),
1262
+ title: text(MAX_RELEASE_TITLE, 1),
1263
+ /** Its own short name when it has one (2026-11-08); absent, a surface says "Release N". */
1264
+ label: optional(text(MAX_RELEASE_LABEL, 1)),
1265
+ project_id: id("prj"),
1266
+ state: oneOf(RELEASE_STATES),
1267
+ after_release: nullable(id("rel")),
1268
+ /** Its place in the computer's one queue (0 runs first); releases of every project share the order. */
1269
+ position: int(0),
1270
+ parallel: int(1, MAX_RELEASE_PARALLEL),
1271
+ tasks: list(TASK_SPEC, MAX_RELEASE_TASKS),
1272
+ counts: RELEASE_COUNTS_SPEC,
1273
+ pipeline_config: oneOf(PIPELINE_CONFIG_STATES),
1274
+ pipeline_run_id: nullable(id("plr")),
1275
+ created_at: int(0),
1276
+ started_at: nullable(int(0)),
1277
+ ended_at: nullable(int(0)),
1278
+ /** What is left of the estimate its creator gave (etaFromAgent), only while it has not ended and only as shown. */
1279
+ eta: optional(ETA_SPEC),
1280
+ });
1281
+
1282
+ /** The estimate a release's creator gives for the whole of it (release.create): seconds and how sure. */
1283
+ export const RELEASE_ESTIMATE_SPEC = object({ total_s: int(60, 7 * 24 * 3600), confidence: oneOf(["low", "medium", "high"]) });
1284
+
1285
+ /** A release's ETA (and a planned task's) is only its creator's estimate (source agent), and only as etaForDisplay shows it. */
1286
+ export function releaseEtaShown(eta ) {
1287
+ return eta.kind === "estimate" && eta.source === "agent" && etaForDisplay(eta).kind === "estimate";
1288
+ }
1289
+
1290
+ /** The release's ETA from its creator's estimate and the time since it started (0 while it waits); none once ended. */
1291
+ export function releaseEta(r , estimate , now ) {
1292
+ if (!estimate || isEndedRelease(r.state)) return undefined;
1293
+ const elapsed = r.started_at === null ? 0 : Math.max(0, Math.floor((now - r.started_at) / 1000));
1294
+ const eta = etaFromAgent(estimate.total_s - elapsed, estimate.confidence);
1295
+ return eta.kind === "estimate" ? eta : undefined;
1296
+ }
1297
+
1298
+ /** The backlog, newest first: `before_number` of the next page, null at the oldest. */
1299
+ export const RELEASE_PAGE_SPEC = object({
1300
+ releases: list(RELEASE_BODY_SPEC, MAX_RELEASE_PAGE),
1301
+ next_before: nullable(int(1)),
1302
+ total: int(0),
1303
+ });
1304
+
1305
+ export function releaseCounts(tasks ) {
1306
+ const counts = { queued: 0, running: 0, done: 0, failed: 0, cancelled: 0 };
1307
+ for (const t of tasks) counts[t.state] += 1;
1308
+ return counts;
1309
+ }
1310
+
1311
+ const ENDED_TASK = new Set (["done", "failed", "cancelled"]);
1312
+ export const isEndedTask = (s ) => ENDED_TASK.has(s);
1313
+ const ENDED_RELEASE = new Set (["ready", "released", "failed"]);
1314
+ export const isEndedRelease = (s ) => ENDED_RELEASE.has(s);
1315
+ /** A release another waits for has delivered: its tasks and its pipeline passed. */
1316
+ export const releaseDelivered = (s ) => s === "ready" || s === "released";
1317
+
1318
+ export function taskRule(t ) {
1319
+ if ((t.session_id === null) !== (t.started_at === null)) return `task ${t.task_id}: a session exactly when it started`;
1320
+ if (t.state === "queued" && t.session_id !== null) return `task ${t.task_id}: a queued task has not started`;
1321
+ if ((t.state === "running" || t.state === "done") && t.session_id === null) return `task ${t.task_id}: a running or done task has its session`;
1322
+ if (t.duration_ms !== null && (!isEndedTask(t.state) || t.started_at === null)) return `task ${t.task_id}: a duration only once a started task ended`;
1323
+ if (t.state === "failed" ? t.reason === null || t.reason === "stopped" : t.reason !== null && !(t.state === "cancelled" && t.reason === "stopped"))
1324
+ return `task ${t.task_id}: a reason exactly for a failed task (or a stopped cancel)`;
1325
+ if (t.eta !== undefined && (isEndedTask(t.state) || !(etaShown(t.eta) || releaseEtaShown(t.eta)))) return `task ${t.task_id}: an ETA that is not history's or its agent's, shown, on a live task`;
1326
+ if (t.note !== undefined && t.state !== "failed") return `task ${t.task_id}: a note only on a failed task`;
1327
+ if (t.follow_up_of === t.task_id) return `task ${t.task_id}: follows itself`;
1328
+ return null;
1329
+ }
1330
+
1331
+ export function releaseRule(r ) {
1332
+ if (new Set(r.tasks.map((t) => t.task_id)).size !== r.tasks.length) return "a task id twice";
1333
+ for (const t of r.tasks) { const bad = taskRule(t); if (bad) return bad; if (t.after_release === r.release_id) return `task ${t.task_id}: waits for its own release`; }
1334
+ const counts = releaseCounts(r.tasks);
1335
+ if ((Object.keys(counts) ).some((k) => counts[k] !== r.counts[k])) return "counts that are not the tasks'";
1336
+ if (r.after_release === r.release_id) return "a release waits for itself";
1337
+ if (r.state === "planned" && (counts.running > 0 || r.started_at !== null)) return "a planned release runs nothing";
1338
+ if (counts.running > r.parallel) return "more tasks running than the release allows";
1339
+ if (isEndedRelease(r.state) !== (r.ended_at !== null)) return "ended_at exactly when the release ended";
1340
+ if (isEndedRelease(r.state) && (counts.running > 0 || counts.queued > 0)) return "an ended release with work left";
1341
+ if (releaseDelivered(r.state) && counts.failed > 0) return "delivered with a failed task";
1342
+ if (r.state === "verifying" && r.pipeline_run_id === null) return "verifying without a pipeline";
1343
+ if (r.eta !== undefined && (isEndedRelease(r.state) || !releaseEtaShown(r.eta))) return "an ETA that is not its creator's, shown, on a live release";
1344
+ return null;
1345
+ }
1346
+
1347
+ /**
1348
+ * The release's measured progress: its tasks done plus its pipeline's finished stages, over its tasks (cancelled ones
1349
+ * left out) plus the stages the daemon runs. Indeterminate with nothing to count. Never from time; a release that gains
1350
+ * a task or a stage can fall back, and is shown as it is.
1351
+ */
1352
+ export function releaseProgress(r , pipeline ) {
1353
+ const counted = r.tasks.filter((t) => t.state !== "cancelled");
1354
+ const stages = pipeline && pipeline.release_id === r.release_id ? pipelineProgress(pipeline) : null;
1355
+ const total = counted.length + (stages?.kind === "measured" ? stages.total : 0);
1356
+ if (total === 0) return { kind: "indeterminate" };
1357
+ const done = counted.filter((t) => t.state === "done").length + (stages?.kind === "measured" ? stages.done : 0);
1358
+ return { kind: "measured", done, total, unit: "items" };
1359
+ }
1360
+
1361
+ /** The roadmap's "expected done" column: an ETA, or the release it waits for, or nothing. */
1362
+
1363
+ export function taskExpectation(t , release ) {
1364
+ if (isEndedTask(t.state)) return { view: "none" };
1365
+ if (t.eta?.kind === "estimate") return { view: "eta", remaining_s: t.eta.remaining_s };
1366
+ const after = t.after_release ?? release.after_release;
1367
+ return after ? { view: "after_release", release_id: after } : { view: "none" };
1368
+ }
1369
+
1370
+ // ---- packages/remote-protocol/src/live.ts
1371
+ /**
1372
+ * THE LIVE FEED: WHICH AGENTS RUN ON THIS COMPUTER NOW (owner, 2026-11-07: "In Live you see the active agents and how far
1373
+ * testing of a release is"). One sealed, device-wide `agents.active` body: every running remote session, the release and
1374
+ * task it runs for (null for a session the phone started by itself), its activity, its progress (the agent's own plan as
1375
+ * a measured count, else its steps), the session's tokens as reported (null is "not reported", never 0), when its turn
1376
+ * started, its open subagents, and the computer's slots (the session cap, how many run, how many tasks wait).
1377
+ *
1378
+ * Coalesced like agent.usage: at most one per two seconds (USAGE_MIN_INTERVAL_MS, the latest wins), and at once when a
1379
+ * session starts or ends, so the relay learns no more than the timing it already sees. Nothing here is computed for the
1380
+ * surface: a percentage comes from progressPercent over `progress`, elapsed time from elapsedMs over `started_at`.
1381
+ */
1382
+
1383
+ export const MAX_ACTIVE_SESSIONS = 32;
1384
+ export const MAX_ACTIVE_SUBAGENTS = 20;
1385
+
1386
+ export const ACTIVE_SUBAGENT_SPEC = object({
1387
+ subagent_id: id("sag"),
1388
+ parent_id: nullable(id("sag")),
1389
+ label: nullable(text(500, 1)),
1390
+ state: oneOf(SUBAGENT_STATES),
1391
+ tokens_total: nullable(int(0)),
1392
+ });
1393
+
1394
+ export const ACTIVE_SESSION_SPEC = object({
1395
+ session_id: id("ses"),
1396
+ project_id: nullable(id("prj")),
1397
+ release_id: nullable(id("rel")),
1398
+ task_id: nullable(id("tsk")),
1399
+ adapter: oneOf(ADAPTER_IDS),
1400
+ activity: oneOf(ACTIVITIES),
1401
+ progress: PROGRESS_SPEC,
1402
+ tokens: TOKEN_COUNTS_SPEC,
1403
+ started_at: nullable(int(0)),
1404
+ subagents: list(ACTIVE_SUBAGENT_SPEC, MAX_ACTIVE_SUBAGENTS),
1405
+ subagents_cut: bool(),
1406
+ });
1407
+
1408
+ export const AGENTS_ACTIVE_SPEC = object({
1409
+ sessions: list(ACTIVE_SESSION_SPEC, MAX_ACTIVE_SESSIONS),
1410
+ slots: object({ cap: int(1, 64), running: int(0), queued: int(0) }),
1411
+ /** Pipelines running now (their pipeline.updated carries the stages). */
1412
+ pipelines: list(id("plr"), 16),
1413
+ });
1414
+
1415
+ export function agentsActiveRule(a ) {
1416
+ if (new Set(a.sessions.map((s) => s.session_id)).size !== a.sessions.length) return "a session twice";
1417
+ for (const s of a.sessions) {
1418
+ const bad = progressRule(s.progress );
1419
+ if (bad) return `session ${s.session_id}: ${bad}`;
1420
+ if ((s.release_id === null) !== (s.task_id === null)) return `session ${s.session_id}: a release exactly with its task`;
1421
+ }
1422
+ return null;
1423
+ }
1424
+
1425
+ // ---- packages/remote-protocol/src/latency.ts
1426
+ /**
1427
+ * HOW LONG EACH HOP TOOK (owner, 2026-11-07: a prompt sent while the agent is busy waits, and the app must show it).
1428
+ * Each hop is measured on ONE clock, never across two: the phone's own clock from sending to the relay's acknowledgement
1429
+ * arriving, and the computer's clock from the command's arrival (`received_at`, sealed in command.agent_accepted) to its
1430
+ * acceptance (that event's `occurred_at`). The phone and the computer clocks differ, so the time between the relay and
1431
+ * the computer is not derived; a surface shows the two hops it has and "waiting on the computer" while command.queued
1432
+ * stands. Null where a reading is missing or a clock went backwards. No percentage and no bar from time.
1433
+ */
1434
+
1435
+ const span = (from , to ) =>
1436
+ from !== null && to !== null && Number.isSafeInteger(from) && Number.isSafeInteger(to) && to >= from ? to - from : null;
1437
+
1438
+ export function deliveryHops(r ) {
1439
+ return { to_relay_ms: span(r.sent_at, r.relay_ack_seen_at), on_computer_ms: span(r.received_at, r.accepted_at) };
1440
+ }
1441
+
1442
+ // ---- packages/remote-protocol/src/transfer.ts
1443
+ /**
1444
+ * FILES FROM THE PHONE, AND A LOCAL PREVIEW BACK (owner, 2026-11-07 22:50). docs/remote-agents/PROTOCOL.md "Attachments"
1445
+ * and "Local preview". Everything here is sealed: the relay sees the types, their timing and size classes, never a name,
1446
+ * a byte of a file or of a picture.
1447
+ *
1448
+ * ATTACHMENTS. An image, a PDF or a document travels in chunks of at most 512 KiB (`attachment.put`), each naming the whole
1449
+ * file's size, its chunk count and its SHA-256; the computer keeps the chunks apart, joins them when all arrived, checks the
1450
+ * hash and that the bytes are what the type says (a PNG starts like a PNG), and only then writes ONE file into the
1451
+ * session's project at `.worktrust/inbox/<session_id>/<safe name>` (mode 0600, never executable). `attachment.stored`
1452
+ * answers every chunk with the count received (a measured progress) and, once whole, the file's path relative to the
1453
+ * project, which a later `agent.start` / `agent.prompt` names by its id (`attachments`), so the agent is told to read it.
1454
+ * Caps: 25 MB a file, 100 MB a session. `attachment.clear` deletes the session's inbox.
1455
+ *
1456
+ * LOCAL PREVIEW. The phone's "Deploy" segment is a LOCAL preview, never a production deploy: `preview.render` asks the
1457
+ * computer to render a page of a dev server on 127.0.0.1 at a port the person granted for that project at the keyboard
1458
+ * (`worktrust remote preview allow <port>`), or a built HTML file in the project the person granted, at a phone, tablet or
1459
+ * desktop viewport, with the person's own installed Chrome or Chromium (headless; nothing is installed). The answer is a
1460
+ * PNG in chunks (`preview.image`) and its record (`preview.rendered`: the page's title and HTTP status as the computer saw
1461
+ * them). `preview.targets` lists what is granted and whether something listens. Never a URL the phone writes, never
1462
+ * another host, never a port forward.
1463
+ */
1464
+
1465
+ export const ATTACHMENT_CHUNK_BYTES = 524_288;
1466
+ export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
1467
+ export const MAX_SESSION_ATTACHMENT_BYTES = 100 * 1024 * 1024;
1468
+ export const MAX_ATTACHMENT_CHUNKS = Math.ceil(MAX_ATTACHMENT_BYTES / ATTACHMENT_CHUNK_BYTES);
1469
+ export const ATTACHMENT_TYPES = [
1470
+ "image/png", "image/jpeg", "image/heic", "image/webp", "application/pdf", "text/plain", "text/markdown", "text/csv",
1471
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1472
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1473
+ ] ;
1474
+
1475
+ export const MAX_ATTACHMENTS_PER_PROMPT = 20;
1476
+
1477
+ export const PREVIEW_VIEWPORTS = { mobile: { width: 390, height: 844 }, tablet: { width: 820, height: 1180 }, desktop: { width: 1440, height: 900 } } ;
1478
+ export const PREVIEW_CHUNK_BYTES = 524_288;
1479
+ export const MAX_PREVIEW_BYTES = 8 * 1024 * 1024;
1480
+ export const MAX_PREVIEW_CHUNKS = Math.ceil(MAX_PREVIEW_BYTES / PREVIEW_CHUNK_BYTES);
1481
+ /** A path on the granted dev server: starts with one slash, URL characters only, never `//` (another host). */
1482
+ export const PREVIEW_PATH = /^\/(?!\/)[A-Za-z0-9._~!$&'()*+,;=:@%\/?#-]{0,299}$/;
1483
+
1484
+ export const TRANSFER_COMMAND_SPECS = {
1485
+ "attachment.put": object({
1486
+ attachment_id: id("att"),
1487
+ name: text(200, 1),
1488
+ content_type: oneOf(ATTACHMENT_TYPES),
1489
+ size: int(1, MAX_ATTACHMENT_BYTES),
1490
+ sha256: b64({ exact: 32 }),
1491
+ chunk: int(0, MAX_ATTACHMENT_CHUNKS - 1),
1492
+ chunks: int(1, MAX_ATTACHMENT_CHUNKS),
1493
+ data: b64({ max: ATTACHMENT_CHUNK_BYTES }),
1494
+ }),
1495
+ "attachment.clear": object({}),
1496
+ "preview.targets": object({ project_id: id("prj") }),
1497
+ "preview.render": object({
1498
+ preview_id: id("pvw"),
1499
+ project_id: id("prj"),
1500
+ target: oneOf(["port", "file"]),
1501
+ port: nullable(int(1, 65_535)),
1502
+ /** For a port: the path on that server ("/" by default). For a file: its path inside the project. */
1503
+ path: text(300, 1),
1504
+ viewport: oneOf(["mobile", "tablet", "desktop"]),
1505
+ full_page: bool(),
1506
+ }),
1507
+ } ;
1508
+
1509
+ export const TRANSFER_EVENT_SPECS = {
1510
+ "attachment.stored": object({
1511
+ attachment_id: id("att"),
1512
+ received: int(0, MAX_ATTACHMENT_CHUNKS),
1513
+ chunks: int(1, MAX_ATTACHMENT_CHUNKS),
1514
+ /** Once whole and checked: the file's path relative to the project; null while chunks are still coming. */
1515
+ path: nullable(text(400, 1)),
1516
+ size: int(1, MAX_ATTACHMENT_BYTES),
1517
+ content_type: oneOf(ATTACHMENT_TYPES),
1518
+ }),
1519
+ "attachment.cleared": object({ removed: int(0) }),
1520
+ "preview.targets": object({
1521
+ project_id: id("prj"),
1522
+ ports: list(object({ port: int(1, 65_535), listening: bool() }), 20),
1523
+ files: list(text(300, 1), 50),
1524
+ browser: bool(),
1525
+ }),
1526
+ "preview.image": object({ preview_id: id("pvw"), chunk: int(0, MAX_PREVIEW_CHUNKS - 1), chunks: int(1, MAX_PREVIEW_CHUNKS), data: b64({ max: PREVIEW_CHUNK_BYTES }) }),
1527
+ "preview.rendered": object({
1528
+ preview_id: id("pvw"),
1529
+ project_id: id("prj"),
1530
+ viewport: oneOf(["mobile", "tablet", "desktop"]),
1531
+ width: int(1, 4096),
1532
+ height: int(1, 16_384),
1533
+ /** The page's own <title>, or null. */
1534
+ title: nullable(text(300, 1)),
1535
+ /** The dev server's HTTP status as the computer read it; null for a file. */
1536
+ http_status: nullable(int(100, 599)),
1537
+ bytes: int(1, MAX_PREVIEW_BYTES),
1538
+ sha256: b64({ exact: 32 }),
1539
+ chunks: int(1, MAX_PREVIEW_CHUNKS),
1540
+ }),
1541
+ } ;
1542
+
1543
+ export const attachmentRule = (a ) =>
1544
+ a.chunk >= a.chunks ? "a chunk past the count" : a.chunks !== Math.ceil(a.size / ATTACHMENT_CHUNK_BYTES) ? "a chunk count that is not the size's" : null;
1545
+ export const previewRule = (r ) =>
1546
+ r.target === "port" ? (r.port === null || !PREVIEW_PATH.test(r.path) ? "a port and a path on it" : null) : r.port !== null || !/^(?!\/)(?!.*\.\.)[A-Za-z0-9._/-]+\.html?$/.test(r.path) ? "a project file, an .html one, and no port" : null;
1547
+
1548
+ // ---- packages/remote-protocol/src/state-machine.ts
1549
+ /**
1550
+ * DELIVERY AND EXECUTION, AS A PURE FUNCTION. One command's state, from the phone's draft to its end:
1551
+ *
1552
+ * DRAFT_LOCAL -> SUBMITTED_TO_RELAY -> RELAY_ACKNOWLEDGED -> DEVICE_RECEIVED -> AGENT_ACCEPTED -> RUNNING
1553
+ * -> COMPLETED | FAILED | CANCELLED
1554
+ * RUNNING <-> WAITING_APPROVAL, RUNNING <-> PAUSED
1555
+ * EXPIRED (it was never delivered in time), REJECTED (the relay or the computer refused it),
1556
+ * UNKNOWN_DELIVERY (sent, and no receipt came; it may or may not have arrived)
1557
+ *
1558
+ * THE RULES, each proven by property tests in scripts/test-remote-protocol.mjs:
1559
+ * 1. Rank never goes down. Receipts are cumulative: a device receipt that overtakes the relay's acknowledgement
1560
+ * moves the state to DEVICE_RECEIVED, and the late acknowledgement changes nothing.
1561
+ * 2. Final states are final. Nothing leaves COMPLETED, FAILED, CANCELLED, EXPIRED or REJECTED.
1562
+ * 3. A missing receipt is UNKNOWN_DELIVERY, never a failure and never a success. The phone resends the SAME
1563
+ * envelope (same command_id, same idempotency_key, same bytes); a timeout never mints a new id.
1564
+ * 4. The phone's own clock passing `expires_at` proves nothing about the computer, so it gives UNKNOWN_DELIVERY.
1565
+ * EXPIRED comes only from a party that knows: the relay dropping an undelivered command, or the computer
1566
+ * refusing one that arrived late.
1567
+ * 5. Only evidence moves a state. A terminal adapter's typed prompt is AGENT_ACCEPTED only once the agent's state
1568
+ * was seen to change; the computer sends command.agent_accepted then, not when the keys went out.
1569
+ */
1570
+ export const DELIVERY_STATES = [
1571
+ "DRAFT_LOCAL",
1572
+ "SUBMITTED_TO_RELAY",
1573
+ "UNKNOWN_DELIVERY",
1574
+ "RELAY_ACKNOWLEDGED",
1575
+ "DEVICE_RECEIVED",
1576
+ "AGENT_ACCEPTED",
1577
+ "RUNNING",
1578
+ "WAITING_APPROVAL",
1579
+ "PAUSED",
1580
+ "COMPLETED",
1581
+ "FAILED",
1582
+ "CANCELLED",
1583
+ "EXPIRED",
1584
+ "REJECTED",
1585
+ ] ;
1586
+
1587
+ export const DELIVERY_RANK = {
1588
+ DRAFT_LOCAL: 0,
1589
+ SUBMITTED_TO_RELAY: 1,
1590
+ UNKNOWN_DELIVERY: 1,
1591
+ RELAY_ACKNOWLEDGED: 2,
1592
+ DEVICE_RECEIVED: 3,
1593
+ AGENT_ACCEPTED: 4,
1594
+ RUNNING: 5,
1595
+ WAITING_APPROVAL: 5,
1596
+ PAUSED: 5,
1597
+ COMPLETED: 6,
1598
+ FAILED: 6,
1599
+ CANCELLED: 6,
1600
+ EXPIRED: 6,
1601
+ REJECTED: 6,
1602
+ };
1603
+
1604
+ export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "CANCELLED", "EXPIRED", "REJECTED"]);
1605
+ export const isTerminal = (state ) => TERMINAL_STATES.has(state);
1606
+
1607
+ const stay = (state , ignored ) => ({ state, changed: false, ignored });
1608
+ const move = (from , to ) =>
1609
+ from === to ? stay(from, null) : { state: to, changed: true, ignored: null };
1610
+
1611
+ /** Move up to `to`, or stay when that would be a step down (a receipt overtaken by a stronger one). */
1612
+ const upTo = (from , to ) =>
1613
+ DELIVERY_RANK[to] < DELIVERY_RANK[from] ? stay(from, "stale") : move(from, to);
1614
+
1615
+ export function transition(state , input ) {
1616
+ if (isTerminal(state)) return stay(state, "terminal");
1617
+ if (state === "DRAFT_LOCAL" && input.kind !== "submitted") return stay(state, "not_submitted");
1618
+ const rank = DELIVERY_RANK[state];
1619
+ switch (input.kind) {
1620
+ case "submitted":
1621
+ return state === "DRAFT_LOCAL" ? move(state, "SUBMITTED_TO_RELAY") : stay(state, null);
1622
+ case "receipt_timeout":
1623
+ case "deadline_passed":
1624
+ // Only before the relay confirmed. Once it did, it holds the command and owes either a delivery or a
1625
+ // relay_expired; a timeout then is not news, and UNKNOWN_DELIVERY would be a step down.
1626
+ return state === "SUBMITTED_TO_RELAY" ? move(state, "UNKNOWN_DELIVERY") : stay(state, "not_applicable");
1627
+ case "relay_acknowledged":
1628
+ return upTo(state, "RELAY_ACKNOWLEDGED");
1629
+ case "relay_refused":
1630
+ return rank <= 2 ? move(state, "REJECTED") : stay(state, "stale");
1631
+ case "relay_expired":
1632
+ return rank <= 2 ? move(state, "EXPIRED") : stay(state, "stale");
1633
+ case "device_received":
1634
+ return upTo(state, "DEVICE_RECEIVED");
1635
+ case "agent_accepted":
1636
+ return upTo(state, "AGENT_ACCEPTED");
1637
+ case "device_rejected":
1638
+ return rank <= 4 ? move(state, input.expired ? "EXPIRED" : "REJECTED") : stay(state, "stale");
1639
+ case "running":
1640
+ return rank <= 4 || state === "RUNNING" ? move(state, "RUNNING") : stay(state, "not_applicable");
1641
+ case "waiting_approval":
1642
+ return rank <= 5 ? move(state, "WAITING_APPROVAL") : stay(state, "not_applicable");
1643
+ case "approval_resolved":
1644
+ return state === "WAITING_APPROVAL" ? move(state, "RUNNING") : stay(state, "not_applicable");
1645
+ case "paused":
1646
+ return rank <= 5 ? move(state, "PAUSED") : stay(state, "not_applicable");
1647
+ case "resumed":
1648
+ return state === "PAUSED" ? move(state, "RUNNING") : stay(state, "not_applicable");
1649
+ case "completed":
1650
+ return move(state, "COMPLETED");
1651
+ case "failed":
1652
+ return move(state, "FAILED");
1653
+ case "cancelled":
1654
+ return move(state, "CANCELLED");
1655
+ case "reconciled":
1656
+ if (input.state === "DRAFT_LOCAL") return stay(state, "stale");
1657
+ if (state === "UNKNOWN_DELIVERY" || isTerminal(input.state)) return move(state, input.state);
1658
+ return DELIVERY_RANK[input.state] >= rank ? move(state, input.state) : stay(state, "stale");
1659
+ }
1660
+ }
1661
+
1662
+ /** Apply inputs in order. */
1663
+ export const replayTransitions = (start , inputs ) =>
1664
+ inputs.reduce((state, input) => transition(state, input).state, start);
1665
+
1666
+ /**
1667
+ * The strongest state anyone confirmed, for the UI: the highest rank, and among equals the latest observed. A list
1668
+ * of receipts that arrived in any order gives the state the person should see.
1669
+ */
1670
+ export function strongestConfirmed(states ) {
1671
+ let best = "DRAFT_LOCAL";
1672
+ for (const s of states) if (DELIVERY_RANK[s] >= DELIVERY_RANK[best]) best = s;
1673
+ return best;
1674
+ }
1675
+
1676
+ /** Who has confirmed what, in one word for the receipt line under a message. */
1677
+ export function confirmationOf(state ) {
1678
+ if (isTerminal(state)) return "final";
1679
+ switch (state) {
1680
+ case "DRAFT_LOCAL":
1681
+ return "local";
1682
+ case "SUBMITTED_TO_RELAY":
1683
+ return "sent";
1684
+ case "UNKNOWN_DELIVERY":
1685
+ return "unknown";
1686
+ case "RELAY_ACKNOWLEDGED":
1687
+ return "relay";
1688
+ case "DEVICE_RECEIVED":
1689
+ return "computer";
1690
+ default:
1691
+ return "agent";
1692
+ }
1693
+ }
1694
+
1695
+ /** Whether the phone resends the same envelope now: only while no receipt beyond the relay's came and it is in time. */
1696
+ export const shouldResend = (state , now , expiresAt ) =>
1697
+ (state === "SUBMITTED_TO_RELAY" || state === "UNKNOWN_DELIVERY") && now < expiresAt;
1698
+
1699
+ // ---- packages/remote-protocol/src/control.ts
1700
+ /**
1701
+ * PAUSE, RESUME AND STOP, AS ASKED AND AS SEEN. A control request is not its effect: "pause requested" is what the
1702
+ * phone did, "paused" is what the computer reported. The UI shows the one it knows.
1703
+ *
1704
+ * none -> pause_requested -> paused | unable_to_pause
1705
+ * paused -> resume_requested -> none
1706
+ * any (but stopped) -> stop_requested -> stopped
1707
+ *
1708
+ * Stop wins: once requested, a pause or a resume is not offered and a late `paused` does not hide the stop.
1709
+ * `unable_to_pause` is the computer saying this agent cannot pause (command.rejected for agent.pause); it is shown,
1710
+ * and stop is still offered.
1711
+ */
1712
+
1713
+ export const CONTROL_STATES = ["none", "pause_requested", "paused", "resume_requested", "stop_requested", "stopped", "unable_to_pause"] ;
1714
+
1715
+ export function controlTransition(state , input ) {
1716
+ if (state === "stopped") return state;
1717
+ const stopping = state === "stop_requested";
1718
+ switch (input) {
1719
+ case "stop_sent":
1720
+ return "stop_requested";
1721
+ case "stopped_observed":
1722
+ return "stopped";
1723
+ case "pause_sent":
1724
+ return state === "none" || state === "unable_to_pause" ? "pause_requested" : state;
1725
+ case "paused_observed":
1726
+ return stopping ? state : "paused";
1727
+ case "pause_refused":
1728
+ return state === "pause_requested" ? "unable_to_pause" : state;
1729
+ case "resume_sent":
1730
+ return state === "paused" ? "resume_requested" : state;
1731
+ case "resumed_observed":
1732
+ return stopping ? state : "none";
1733
+ case "resume_refused":
1734
+ return state === "resume_requested" ? "paused" : state;
1735
+ case "run_ended":
1736
+ return stopping ? state : "none";
1737
+ }
1738
+ }
1739
+
1740
+ /** Which control buttons exist right now: the adapter's own capabilities, the run's state and the control state. */
1741
+ export function controlsOffered(actions , delivery , control ) {
1742
+ const live = !isTerminal(delivery) && DELIVERY_RANK[delivery] >= DELIVERY_RANK.RELAY_ACKNOWLEDGED;
1743
+ const stopping = control === "stop_requested" || control === "stopped";
1744
+ const running = delivery === "RUNNING" || delivery === "WAITING_APPROVAL";
1745
+ return {
1746
+ pause: actions.pause && live && !stopping && running && (control === "none"),
1747
+ resume: actions.resume && live && !stopping && (delivery === "PAUSED" || control === "paused"),
1748
+ stop: actions.stop && live && !stopping,
1749
+ };
1750
+ }
1751
+
1752
+ // ---- packages/remote-protocol/src/commands.ts
1753
+ /**
1754
+ * THE COMMANDS A PHONE MAY SEND, AND NOTHING ELSE. A fixed list, each with a sealed payload schema. A computer refuses
1755
+ * a type it does not know (command.rejected, `unknown_type`), so a type can be added behind a version bump without
1756
+ * an older computer guessing at it. There is no command that runs a shell line, reads a file, or switches an agent's
1757
+ * approvals off, and none that sends raw keystrokes: the phone steers an agent; it does not operate the computer.
1758
+ *
1759
+ * SCOPE. A session command names an agent session (`session_id`); a device command names none (`session_id: null`)
1760
+ * and acts on the computer as a whole: its inventory, its settings.
1761
+ *
1762
+ * Every payload below is SEALED: the relay sees the type and the sizes, never a prompt, a model name or a key.
1763
+ */
1764
+
1765
+ export const MAX_PROMPT_CHARS = 65_536;
1766
+
1767
+ /**
1768
+ * A NEW PROJECT'S FOLDER NAME (owner, 2026-11-07: the phone's "New session" sheet, project New). One path segment of
1769
+ * [A-Za-z0-9._-], 1 to 100 characters, never starting with a dot (no hidden folder, no `.` or `..`). The computer creates
1770
+ * exactly that one empty folder inside a root the person added at the keyboard, and nothing else.
1771
+ */
1772
+ export const PROJECT_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/;
1773
+ export const projectNameOk = (name ) => typeof name === "string" && PROJECT_NAME.test(name);
1774
+ export const MAX_SESSION_NAME = 100;
1775
+
1776
+ export const COMMAND_PAYLOAD_SPECS = {
1777
+ /**
1778
+ * Start an agent in a project, from a closed set of options validated again on the computer: the adapter, a model
1779
+ * the computer listed (null: the agent's own default), a permission mode the adapter reported, and `resume`, the
1780
+ * agent's OWN session id to continue (Claude Code's --resume id, a Codex thread id), sealed so the relay never
1781
+ * learns which agent session is which. `prompt: null` opens it idle. No free arguments.
1782
+ */
1783
+ "agent.start": object({
1784
+ adapter: oneOf(ADAPTER_IDS),
1785
+ model: nullable(text(128, 1)),
1786
+ permission_mode: oneOf(PERMISSION_MODES),
1787
+ resume: nullable(text(256, 1)),
1788
+ prompt: nullable(text(MAX_PROMPT_CHARS, 1)),
1789
+ /** The session's name on the phone's project tree (2026-11-07), sealed; renameable with session.rename. */
1790
+ name: optional(nullable(text(MAX_SESSION_NAME, 1))),
1791
+ }),
1792
+ /**
1793
+ * A new turn for an agent that waits for input. Sent while a turn runs, it waits (command.queued) and runs when the turn
1794
+ * ends; with `interrupt: true` (only where the adapter reports interrupt) the computer ends the running turn first and
1795
+ * runs this prompt next (2026-11-07).
1796
+ */
1797
+ "agent.prompt": object({ text: text(MAX_PROMPT_CHARS, 1), interrupt: optional(bool()), attachments: optional(list(id("att"), MAX_ATTACHMENTS_PER_PROMPT)) }),
1798
+ /**
1799
+ * Words for an agent in the middle of a turn: redirect without stopping. Where the adapter reports steer_mode `live`
1800
+ * they enter the running turn (accepted with `landed: "running_turn"` once the agent read them); `queued`, they run as
1801
+ * the next turn (command.queued until then); `none` is refused `unsupported`.
1802
+ */
1803
+ "agent.steer": object({ text: text(MAX_PROMPT_CHARS, 1) }),
1804
+ "agent.pause": object({}),
1805
+ "agent.resume": object({}),
1806
+ /** Stop the current turn. The session stays; session.close ends it. */
1807
+ "agent.stop": object({}),
1808
+ /** A signed decision (crypto/approval.ts) for one pending approval. */
1809
+ "approval.decision": object({ approval_id: id("apr"), decision_token: token(4096) }),
1810
+ /** An answer to an agent's question: free text or one of the offered options, exactly one of the two. */
1811
+ "question.answer": object({
1812
+ question_id: id("qst"),
1813
+ text: nullable(text(MAX_PROMPT_CHARS, 1)),
1814
+ option: nullable(int(0, 63)),
1815
+ /**
1816
+ * The answers to an agent.question `form` (owner, 2026-11-08), one per question in its order: the chosen options by
1817
+ * index (several for a multiple-choice question), or the person's own words ("Other"). Then `text` and `option` are
1818
+ * both null.
1819
+ */
1820
+ answers: optional(list(object({ options: list(int(0, 63), 64), text: nullable(text(MAX_PROMPT_CHARS, 1)) }), 4)),
1821
+ }),
1822
+ /** Ask for a status.report: of one session, or of the whole computer (then a device.inventory too). */
1823
+ "status.get": object({ scope: oneOf(["session", "device"]) }),
1824
+ /** Join a session started at the desk, which the computer listed in its inventory. */
1825
+ "session.attach": object({}),
1826
+ /** Bring the session to the front on the computer's own screen ("show it on my desk"). Moves the view only. */
1827
+ "session.focus": object({}),
1828
+ /** End the session and its agent. */
1829
+ "session.close": object({}),
1830
+ /** A new name for the session (2026-11-07); answered with device.inventory, which lists every session by name. */
1831
+ "session.rename": object({ name: text(MAX_SESSION_NAME, 1) }),
1832
+ /** The last lines of a terminal session's screen, answered with agent.screen. */
1833
+ "screen.read": object({ lines: int(1, 2000) }),
1834
+ /** Ask for a device.inventory; `refresh_models` runs the agents' own model listers first. */
1835
+ "inventory.get": object({ refresh_models: bool() }),
1836
+ /** This computer's remote settings, each optional. Pausing from the phone is soft; `worktrust remote disable` at the
1837
+ * desk is the hard off, which no message can undo. */
1838
+ "device.configure": object({
1839
+ remote_enabled: optional(bool()),
1840
+ default_adapter: optional(nullable(oneOf(ADAPTER_IDS))),
1841
+ default_model: optional(nullable(text(128, 1))),
1842
+ }),
1843
+ /** This phone disconnects itself from this computer (owner, 2026-11-07): the computer drops the phone from its
1844
+ * confirmed list and its channels, as `worktrust remote phones remove` does at the keyboard. Sent sealed and signed
1845
+ * just before the phone's `unpair` frame, whose relay event (device.revoked) reaches a computer that was offline. */
1846
+ "pairing.revoke": object({}),
1847
+ /** Files from the phone and a local preview back (transfer.ts, 2026-11-07). */
1848
+ ...TRANSFER_COMMAND_SPECS,
1849
+ /**
1850
+ * One new, empty project folder named `name` inside the root `root_id` (2026-11-07), granted as a project; `git init`
1851
+ * in it only when the person enabled that for the root at the keyboard. Answered with project.created.
1852
+ */
1853
+ "project.create": object({ name: text(100, 1), root_id: id("rot") }),
1854
+ /** A release: a bundle of tasks in one project (release.ts). Ids are minted by the phone, once. */
1855
+ "release.create": object({
1856
+ release_id: id("rel"),
1857
+ title: text(MAX_RELEASE_TITLE, 1),
1858
+ /** Its own short name ("CLI 0.11.0") and its creator's estimate for the whole of it (2026-11-08), both optional. */
1859
+ label: optional(text(MAX_RELEASE_LABEL, 1)),
1860
+ estimate: optional(RELEASE_ESTIMATE_SPEC),
1861
+ project_id: id("prj"),
1862
+ after_release: nullable(id("rel")),
1863
+ parallel: int(1, MAX_RELEASE_PARALLEL),
1864
+ }),
1865
+ "release.add_task": object({
1866
+ release_id: id("rel"),
1867
+ task_id: id("tsk"),
1868
+ prompt: text(MAX_PROMPT_CHARS, 1),
1869
+ label: nullable(text(MAX_TASK_LABEL, 1)),
1870
+ adapter: oneOf(ADAPTER_IDS),
1871
+ model: nullable(text(128, 1)),
1872
+ permission_mode: oneOf(PERMISSION_MODES),
1873
+ after_release: nullable(id("rel")),
1874
+ follow_up_of: nullable(id("tsk")),
1875
+ }),
1876
+ /** The new order of one release's queued tasks, or of the computer's releases (every one not yet ended). */
1877
+ "release.reorder": object({
1878
+ what: oneOf(["tasks", "releases"]),
1879
+ /** tasks: the release whose queued tasks are reordered; releases: null. */
1880
+ release_id: nullable(id("rel")),
1881
+ task_ids: list(id("tsk"), MAX_RELEASE_TASKS),
1882
+ release_ids: list(id("rel"), MAX_REORDER_RELEASES),
1883
+ }),
1884
+ /** A queued task leaves the queue; a running one is stopped (its session's agent.stop) and ends cancelled. */
1885
+ "release.cancel_task": object({ release_id: id("rel"), task_id: id("tsk") }),
1886
+ /** planned -> in_progress: its tasks join the queue. */
1887
+ "release.start": object({ release_id: id("rel") }),
1888
+ /** One page of the backlog, newest first, answered with release.page; project_id null lists every project. */
1889
+ "release.list": object({ project_id: nullable(id("prj")), before_number: nullable(int(1)), limit: int(1, MAX_RELEASE_PAGE) }),
1890
+ /** Run the release's reviewed pipeline now (or again). Never a deploy or publish stage: those stay at the desk. */
1891
+ "pipeline.start": object({ release_id: id("rel") }),
1892
+ "pipeline.cancel": object({ pipeline_run_id: id("plr") }),
1893
+ } ;
1894
+
1895
+ export const COMMAND_TYPES = Object.keys(COMMAND_PAYLOAD_SPECS) ;
1896
+
1897
+ export const RELEASE_COMMANDS = new Set (["release.create", "release.add_task", "release.reorder", "release.cancel_task", "release.start", "release.list", "pipeline.start", "pipeline.cancel"]);
1898
+ export const DEVICE_COMMANDS = new Set (["inventory.get", "device.configure", "pairing.revoke", "project.create", "preview.targets", "preview.render", ...RELEASE_COMMANDS]);
1899
+ export const commandScope = (type ) => (DEVICE_COMMANDS.has(type) ? "device" : "session");
1900
+
1901
+ /** Commands whose acceptance starts a run with steps, approvals and an end (state-machine.ts follows those through
1902
+ * RUNNING); every other command ends at AGENT_ACCEPTED followed by its own effect or a rejection. */
1903
+ export const RUN_COMMANDS = new Set (["agent.start", "agent.prompt", "question.answer"]);
1904
+
1905
+ const MINUTE = 60_000;
1906
+ /**
1907
+ * How long a command stays deliverable. A stop that arrives an hour late would stop the wrong turn, so control
1908
+ * commands live a minute or two; a prompt may wait an hour for a sleeping laptop. Never above MAX_COMMAND_TTL_MS.
1909
+ */
1910
+ export const COMMAND_TTL_MS = {
1911
+ "agent.start": 60 * MINUTE,
1912
+ "agent.prompt": 60 * MINUTE,
1913
+ "agent.steer": 5 * MINUTE,
1914
+ "agent.pause": 2 * MINUTE,
1915
+ "agent.resume": 2 * MINUTE,
1916
+ "agent.stop": 2 * MINUTE,
1917
+ "approval.decision": 5 * MINUTE,
1918
+ "question.answer": 30 * MINUTE,
1919
+ "status.get": 2 * MINUTE,
1920
+ "session.attach": 5 * MINUTE,
1921
+ "session.focus": 1 * MINUTE,
1922
+ "session.close": 5 * MINUTE,
1923
+ "session.rename": 5 * MINUTE,
1924
+ "project.create": 10 * MINUTE,
1925
+ "attachment.put": 60 * MINUTE,
1926
+ "attachment.clear": 10 * MINUTE,
1927
+ "preview.targets": 1 * MINUTE,
1928
+ "preview.render": 2 * MINUTE,
1929
+ "screen.read": 1 * MINUTE,
1930
+ "inventory.get": 5 * MINUTE,
1931
+ "device.configure": 10 * MINUTE,
1932
+ "pairing.revoke": 24 * 60 * MINUTE,
1933
+ "release.create": 60 * MINUTE,
1934
+ "release.add_task": 60 * MINUTE,
1935
+ "release.reorder": 5 * MINUTE,
1936
+ "release.cancel_task": 2 * MINUTE,
1937
+ "release.start": 10 * MINUTE,
1938
+ "release.list": 1 * MINUTE,
1939
+ "pipeline.start": 10 * MINUTE,
1940
+ "pipeline.cancel": 2 * MINUTE,
1941
+ };
1942
+
1943
+ export const isCommandType = (value ) =>
1944
+ typeof value === "string" && Object.hasOwn(COMMAND_PAYLOAD_SPECS, value);
1945
+
1946
+ /** The payload's schema, then the rules between fields. */
1947
+ export function validateCommandPayload (type , value ) {
1948
+ const spec = COMMAND_PAYLOAD_SPECS[type];
1949
+ const checked = check(spec, value, "$payload") ;
1950
+ if (!checked.ok) return checked;
1951
+ const payload = checked.value ;
1952
+ if (type === "question.answer") {
1953
+ const a = payload ;
1954
+ if (a.answers !== undefined) {
1955
+ if (a.text !== null || a.option !== null) return refuse("payload", "$payload: answers, or one of text and option, never both");
1956
+ if (a.answers.length === 0) return refuse("payload", "$payload.answers: at least one");
1957
+ for (const x of a.answers) if ((x.text === null) === (x.options.length === 0)) return refuse("payload", "$payload.answers: each is options or words, exactly one");
1958
+ } else if ((a.text === null) === (a.option === null)) return refuse("payload", "$payload: exactly one of text and option");
1959
+ }
1960
+ if (type === "device.configure" && Object.keys(payload).length === 0) return refuse("payload", "$payload: names no setting");
1961
+ if (type === "attachment.put") { const bad = attachmentRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
1962
+ if (type === "preview.render") { const bad = previewRule(payload ); if (bad) return refuse("payload", `$payload: ${bad}`); }
1963
+ if (type === "project.create" && !projectNameOk((payload ).name))
1964
+ return refuse("payload", "$payload.name: one folder name of [A-Za-z0-9._-], not starting with a dot");
1965
+ if (type === "release.reorder") {
1966
+ const r = payload ;
1967
+ const ids = r.what === "tasks" ? r.task_ids : r.release_ids;
1968
+ const other = r.what === "tasks" ? r.release_ids : r.task_ids;
1969
+ if (ids.length === 0 || other.length > 0 || (r.what === "tasks") !== (r.release_id !== null)) return refuse("payload", "$payload: tasks of one release, or releases, never both");
1970
+ if (new Set(ids).size !== ids.length) return refuse("payload", "$payload: an id twice in the order");
1971
+ }
1972
+ if (type === "release.create" || type === "release.add_task") {
1973
+ const r = payload ;
1974
+ if (r.after_release === r.release_id) return refuse("payload", "$payload.after_release: a release never waits for itself");
1975
+ if (r.task_id !== undefined && r.follow_up_of === r.task_id) return refuse("payload", "$payload.follow_up_of: a task never follows itself");
1976
+ }
1977
+ return checked;
1978
+ }
1979
+
1980
+ // ---- packages/remote-protocol/src/crypto/approval-action.ts
1981
+ /**
1982
+ * WHAT AN APPROVAL IS FOR. The computer describes the action an agent wants to take; the phone shows it; the decision
1983
+ * the phone signs names the action by its hash. A decision for "run the tests" cannot approve "delete the branch":
1984
+ * the hash differs and the computer refuses it (crypto/approval.ts). Sealed: the relay never sees the action.
1985
+ *
1986
+ * WHAT A PHONE MAY APPROVE AT ALL (owner decision 6). The computer's own policy (tools/worktrust-cli, remote-policy)
1987
+ * puts each action in one class. Two classes are approvable from a phone: an edit to files inside the project, and a
1988
+ * command from a short reviewed list. Everything else is decided at the keyboard or not at all: installs from the
1989
+ * network, git push, deploys, deleting outside the project, reading secret paths, and any "always allow" rule. The
1990
+ * phone shows Approve only for an approvable class, and the computer refuses a signed approval of any other class
1991
+ * however valid its signature. An unclassified action is `other`, which is not approvable: unknown fails closed.
1992
+ *
1993
+ * AN OUTWARD MESSAGE (owner, 2026-11-07): an e-mail or another message an agent sends through a connector it has MAY be
1994
+ * approved from a phone, as its own class, `outward_message`, and only with the whole message in the action: the channel,
1995
+ * every recipient (to, cc, bcc), the subject, the full text and the attachment names. The action hash covers all of it,
1996
+ * so a changed recipient or a changed word is another action that needs its own approval. One message per approval,
1997
+ * never batched, never "always allow".
1998
+ */
1999
+
2000
+ export const ACTION_KINDS = ["command", "edit", "write", "delete", "network", "message", "tool", "other"] ;
2001
+
2002
+ /** The whole outward message, shown and hashed as it would be sent. */
2003
+ export const OUTWARD_MESSAGE_SPEC = object({
2004
+ channel: text(128, 1),
2005
+ to: list(text(320, 1), 100, 1),
2006
+ cc: list(text(320, 1), 100),
2007
+ bcc: list(text(320, 1), 100),
2008
+ subject: nullable(text(998)),
2009
+ text: text(65_536),
2010
+ attachments: list(text(4096, 1), 50),
2011
+ });
2012
+
2013
+ export const APPROVAL_CLASSES = [
2014
+ "project_edit",
2015
+ "reviewed_command",
2016
+ "network_install",
2017
+ "git_push",
2018
+ "deploy",
2019
+ "delete_outside_project",
2020
+ "secret_read",
2021
+ "persistent_rule",
2022
+ "outward_message",
2023
+ "other",
2024
+ ] ;
2025
+
2026
+ export const REMOTE_APPROVABLE_CLASSES = new Set (["project_edit", "reviewed_command", "outward_message"]);
2027
+ export const isRemoteApprovable = (cls ) => REMOTE_APPROVABLE_CLASSES.has(cls);
2028
+
2029
+ export const APPROVAL_ACTION_SPEC = object({
2030
+ kind: oneOf(ACTION_KINDS),
2031
+ class: oneOf(APPROVAL_CLASSES),
2032
+ adapter: oneOf(ADAPTER_IDS),
2033
+ /** The tool's own name as the agent called it (Bash, Edit, apply_patch). */
2034
+ tool: text(128, 1),
2035
+ /** The exact input: the command line, the patch summary, the tool's arguments. Shown as it is, not as the agent
2036
+ * described it: a repository can write a convincing description. */
2037
+ input: text(16_384, 1),
2038
+ files: list(text(4096, 1), 100),
2039
+ /** The agent's own one-line rationale, shown below the exact input and marked as the agent's words. */
2040
+ rationale: nullable(text(500, 1)),
2041
+ /** Present exactly for the outward_message class. */
2042
+ message: optional(OUTWARD_MESSAGE_SPEC),
2043
+ });
2044
+
2045
+ const ACTION_DOMAIN = utf8Encode("worktrust-remote/v1/approval-action\n");
2046
+
2047
+ /** base64url(SHA-256(domain || canonical {approval_id, session_id, project_id, adapter, action})). */
2048
+ export function actionHash(scope , action ) {
2049
+ const body = { approval_id: scope.approval_id, session_id: scope.session_id, project_id: scope.project_id, adapter: scope.adapter, action };
2050
+ return toBase64Url(sha256(concatBytes(ACTION_DOMAIN, canonicalBytes(body))));
2051
+ }
2052
+
2053
+ // ---- packages/remote-protocol/src/events.ts
2054
+ /**
2055
+ * THE EVENTS A COMPUTER SENDS, SEALED. Each type has a body schema; the relay sees the type, the sequence number, the
2056
+ * time and the size, never a step label, a file name or a line of output. Three more events come from the relay itself
2057
+ * and carry no body at all (envelopes.ts, RELAY_EVENT_SPECS): presence.changed, command.relay_ack and
2058
+ * connection.reconciliation_required. The relay holds no key, so it cannot write a sealed event, and an endpoint never
2059
+ * treats a relay event as evidence about the agent: "the relay has it" is all command.relay_ack can mean.
2060
+ */
2061
+
2062
+ export const REJECT_REASONS = [
2063
+ "expired", // arrived after expires_at
2064
+ "unknown_type", // a type this computer does not know
2065
+ "unsupported", // the adapter cannot do this (a pause it cannot pause is control state unable_to_pause)
2066
+ "unknown_model", // a model the adapter did not list
2067
+ "agent_blocked", // a dialog is on screen; a prompt would land in it
2068
+ "not_found", // no such session, question or project here
2069
+ "remote_paused", // remote control is paused on this computer
2070
+ "approval_invalid", // the signed decision did not verify; the action stays unapproved
2071
+ "conflict", // a command id reused for different bytes
2072
+ "busy", // the agent is mid-turn and the command needs it idle (a release: its tasks still run, or no slot for a pipeline)
2073
+ "unreviewed", // the project's pipeline file was not reviewed at the keyboard, or changed since (2026-11-07)
2074
+ ] ;
2075
+
2076
+ export const FAIL_REASONS = ["agent_exited", "adapter_error", "not_ready", "timeout", "internal"] ;
2077
+ export const STEP_KINDS = ["read", "edit", "command", "test", "search", "think", "tool", "other"] ;
2078
+ export const SESSION_ORIGINS = ["phone", "desk"] ;
2079
+ /** A listed session: its turn runs, it waits for a prompt (and resumes by the agent's id), or it was closed. */
2080
+ export const SESSION_LIST_STATES = ["running", "idle", "closed"] ;
2081
+
2082
+ const label = (max ) => text(max, 1);
2083
+ /** The most questions one ask carries (Claude Code's AskUserQuestion takes up to four). */
2084
+ export const MAX_FORM_QUESTIONS = 4;
2085
+
2086
+ /**
2087
+ * WHAT A TURN PRODUCED, SEALED (owner, 2026-11-07: the phone shows the model's reply and the code, so the person knows how
2088
+ * to steer). The full final answer, the files the turn changed with a bounded unified diff each, and the outcome of each
2089
+ * test run the agent made. Every part has a cap and says when it was cut; a binary file is named, never shown. `source`
2090
+ * says how the files were found: `vcs` (the repository's working tree against a snapshot taken when the turn began),
2091
+ * `agent_tools` (the agent's own edit tools, outside a repository), or `none`.
2092
+ */
2093
+ export const MAX_ANSWER_CHARS = 262_144;
2094
+ export const MAX_DIFF_CHARS_PER_FILE = 32_768;
2095
+ export const MAX_DIFF_CHARS_PER_RESULT = 262_144;
2096
+ export const MAX_RESULT_FILES = 200;
2097
+ export const TURN_RESULT_SPEC = object({
2098
+ answer: nullable(text(MAX_ANSWER_CHARS, 1)),
2099
+ answer_cut: bool(),
2100
+ source: oneOf(["vcs", "agent_tools", "none"]),
2101
+ files: list(object({
2102
+ path: label(4096),
2103
+ change: oneOf(["added", "modified", "deleted", "renamed"]),
2104
+ binary: bool(),
2105
+ diff: nullable(text(MAX_DIFF_CHARS_PER_FILE, 1)),
2106
+ diff_cut: bool(),
2107
+ }), MAX_RESULT_FILES),
2108
+ files_cut: bool(),
2109
+ tests: list(object({
2110
+ command: label(500),
2111
+ outcome: oneOf(["passed", "failed", "unknown"]),
2112
+ passed: nullable(int(0)),
2113
+ failed: nullable(int(0)),
2114
+ total: nullable(int(0)),
2115
+ }), 20),
2116
+ });
2117
+
2118
+ export const EVENT_BODY_SPECS = {
2119
+ "session.created": object({
2120
+ adapter: oneOf(ADAPTER_IDS),
2121
+ model: nullable(label(128)),
2122
+ origin: oneOf(SESSION_ORIGINS),
2123
+ title: nullable(label(200)),
2124
+ project_label: nullable(label(256)),
2125
+ /** The name the phone gave it (agent.start's name, a release task's label), or null. */
2126
+ name: optional(nullable(label(100))),
2127
+ }),
2128
+ "command.device_received": object({}),
2129
+ /** started_at: the computer's clock when the acceptance began a turn (usage.ts); absent for any other acceptance. */
2130
+ "command.agent_accepted": object({
2131
+ started_at: optional(int(0)),
2132
+ /** The computer's clock when the command arrived (2026-11-07): accepted minus received is the wait on the computer. */
2133
+ received_at: optional(int(0)),
2134
+ /** Where the words went: a new turn, or (a live steer) into the turn that was running. */
2135
+ landed: optional(oneOf(["new_turn", "running_turn"])),
2136
+ }),
2137
+ /**
2138
+ * The command waits on the computer (2026-11-07: "a message sent while the agent is busy is picked up minutes later"):
2139
+ * `position` 1 runs next. Sent when it starts waiting and again whenever its place changes; it ends with
2140
+ * command.agent_accepted (or command.rejected, agent.stopped). Not a delivery state: the command stays DEVICE_RECEIVED.
2141
+ */
2142
+ "command.queued": object({ position: int(1, 1000), reason: oneOf(["turn_running", "interrupting"]) }),
2143
+ "command.rejected": object({ reason: oneOf(REJECT_REASONS) }),
2144
+ /** plan_item_id: the plan item in progress when the step began (plan.ts); subagent_id: the subagent that took it. */
2145
+ "agent.step_started": object({
2146
+ step_id: id("stp"), label: label(500), kind: oneOf(STEP_KINDS), progress: PROGRESS_SPEC,
2147
+ plan_item_id: optional(id("pli")), subagent_id: optional(id("sag")),
2148
+ }),
2149
+ "agent.step_completed": object({ step_id: id("stp"), outcome: oneOf(["ok", "failed", "skipped"]), progress: PROGRESS_SPEC, duration_ms: optional(int(0)) }),
2150
+ "agent.output_delta": object({ stream: oneOf(["assistant", "tool"]), offset: int(0), text: label(65_536) }),
2151
+ "agent.approval_required": object({
2152
+ approval_id: id("apr"),
2153
+ action: APPROVAL_ACTION_SPEC,
2154
+ action_hash: b64({ exact: 32 }),
2155
+ expires_at: int(0),
2156
+ }),
2157
+ "agent.question": object({
2158
+ question_id: id("qst"),
2159
+ text: label(4000),
2160
+ options: list(label(500), 64),
2161
+ /**
2162
+ * THE AGENT'S WHOLE ASK, as its tool put it (owner, 2026-11-08: Claude Code's AskUserQuestion): the set's header, each
2163
+ * question with its own options, each option's description, single or multiple choice. Sealed like every body here;
2164
+ * absent on an agent that asks one plain question (`text` and `options` then). Answered by question.answer `answers`.
2165
+ */
2166
+ form: optional(object({
2167
+ header: nullable(label(100)),
2168
+ questions: list(object({
2169
+ question: label(4000),
2170
+ header: nullable(label(100)),
2171
+ options: list(object({ label: label(500), description: nullable(label(1000)) }), 64),
2172
+ multi: bool(),
2173
+ }), MAX_FORM_QUESTIONS),
2174
+ })),
2175
+ }),
2176
+ "agent.paused": object({}),
2177
+ "agent.resumed": object({}),
2178
+ /**
2179
+ * `session_active_ms` (optional, 2026-11-08, owner: the session's details on the phone): the session's turns so far,
2180
+ * each from its start to its end by the computer's clock (the span `duration_ms` reports), summed by the computer that
2181
+ * ran them; absent when one of its turns had no measured span, so a part is never shown as the whole.
2182
+ */
2183
+ "agent.stopped": object({ session_active_ms: optional(int(0)) }),
2184
+ "agent.completed": object({ summary: nullable(label(4000)), progress: PROGRESS_SPEC, result: optional(TURN_RESULT_SPEC), started_at: optional(int(0)), duration_ms: optional(int(0)), session_active_ms: optional(int(0)) }),
2185
+ "agent.failed": object({ reason: oneOf(FAIL_REASONS), message: nullable(label(4000)), started_at: optional(int(0)), duration_ms: optional(int(0)), session_active_ms: optional(int(0)) }),
2186
+ /** The agent's own plan, whole, on every change (plan.ts): the one source of a percentage besides a measured count. */
2187
+ "agent.plan": PLAN_BODY_SPEC,
2188
+ /** One subagent's current record (agent-map.ts). */
2189
+ "agent.subagent": SUBAGENT_BODY_SPEC,
2190
+ /** Tokens as reported, the turn and the session (usage.ts); at most one per two seconds while a turn runs. */
2191
+ "agent.usage": USAGE_BODY_SPEC,
2192
+ "agent.attention": ATTENTION_SPEC,
2193
+ "agent.screen": object({ lines: list(text(1000), 2000), cut: bool() }),
2194
+ "status.report": object({
2195
+ state: oneOf(DELIVERY_STATES),
2196
+ control: oneOf(CONTROL_STATES),
2197
+ attention: nullable(ATTENTION_SPEC),
2198
+ last_event_seq: int(0),
2199
+ progress: PROGRESS_SPEC,
2200
+ eta: ETA_SPEC,
2201
+ pending_approvals: list(id("apr"), 16),
2202
+ commands: list(object({ command_id: id("cmd"), state: oneOf(DELIVERY_STATES) }), 100),
2203
+ }),
2204
+ "device.inventory": object({
2205
+ remote_enabled: bool(),
2206
+ default_adapter: nullable(oneOf(ADAPTER_IDS)),
2207
+ default_model: nullable(label(128)),
2208
+ adapters: list(ADAPTER_REPORT_SPEC, 16),
2209
+ /** `main`: the main repository's folder when this project's folder is a git worktree of it (2026-11-08); absent otherwise. */
2210
+ projects: list(object({ project_id: id("prj"), label: label(256), path: label(4096), last_used_at: nullable(int(0)), root_id: optional(nullable(id("rot"))), main: optional(label(4096)) }), 30),
2211
+ /** Where a phone may create a new project (project.create), each added at the keyboard (2026-11-07). */
2212
+ roots: optional(list(object({ root_id: id("rot"), label: label(256), git_init: bool() }), 20)),
2213
+ sessions: list(
2214
+ object({
2215
+ session_id: id("ses"),
2216
+ project_id: nullable(id("prj")),
2217
+ adapter: oneOf(ADAPTER_IDS),
2218
+ origin: oneOf(SESSION_ORIGINS),
2219
+ attention: ATTENTION_SPEC,
2220
+ title: nullable(label(200)),
2221
+ /** The project tree (2026-11-07): the session's name, agent model, state and last event time, and its release task. */
2222
+ name: optional(nullable(label(100))),
2223
+ model: optional(nullable(label(128))),
2224
+ state: optional(oneOf(SESSION_LIST_STATES)),
2225
+ last_activity_at: optional(nullable(int(0))),
2226
+ release_id: optional(nullable(id("rel"))),
2227
+ task_id: optional(nullable(id("tsk"))),
2228
+ /** Background jobs its agent reports still running (2026-11-08: "ready, but a job is still running"); absent when it cannot tell. */
2229
+ background_jobs: optional(int(0, 99)),
2230
+ }),
2231
+ 100,
2232
+ ),
2233
+ }),
2234
+ /** The folder project.create made and granted (2026-11-07), answering that command: device-wide, sealed. */
2235
+ "project.created": object({ project_id: id("prj"), label: label(256), path: label(4096), root_id: id("rot"), git: bool() }),
2236
+ /** A release's whole current record (release.ts), on every change: device-wide, sealed. */
2237
+ "release.updated": RELEASE_BODY_SPEC,
2238
+ /** One page of the backlog, newest first, answering release.list. */
2239
+ "release.page": RELEASE_PAGE_SPEC,
2240
+ /** One pipeline run's stages and what their parsers read (pipeline.ts); coalesced to one per two seconds while it runs. */
2241
+ "pipeline.updated": PIPELINE_BODY_SPEC,
2242
+ /** The live feed (live.ts): the running sessions across releases, coalesced like agent.usage. */
2243
+ "agents.active": AGENTS_ACTIVE_SPEC,
2244
+ /** Attachments (session) and the local preview (device), transfer.ts. */
2245
+ ...TRANSFER_EVENT_SPECS,
2246
+ } ;
2247
+
2248
+ export const DEVICE_EVENT_TYPES = Object.keys(EVENT_BODY_SPECS) ;
2249
+
2250
+ /** The one device event about the computer as a whole; every other names a session. */
2251
+ export const DEVICE_SCOPED_EVENTS = new Set (["device.inventory", "project.created", "preview.targets", "preview.image", "preview.rendered", "release.updated", "release.page", "pipeline.updated", "agents.active"]);
2252
+ /** Events that answer one command, so their envelope names it (command_id is required). */
2253
+ export const COMMAND_RECEIPT_EVENTS = new Set ([
2254
+ "command.device_received",
2255
+ "command.agent_accepted",
2256
+ "command.rejected",
2257
+ "command.queued",
2258
+ ]);
2259
+
2260
+ export const isDeviceEventType = (value ) =>
2261
+ typeof value === "string" && Object.hasOwn(EVENT_BODY_SPECS, value);
2262
+
2263
+ /** The body's schema, then the rules between fields. */
2264
+ export function validateEventBody (type , value ) {
2265
+ const spec = EVENT_BODY_SPECS[type];
2266
+ const checked = check(spec, value, "$body") ;
2267
+ if (!checked.ok) return checked;
2268
+ const body = checked.value ;
2269
+ const progress = body.progress ;
2270
+ if (progress) {
2271
+ const bad = progressRule(progress);
2272
+ if (bad) return refuse("payload", `$body.progress: ${bad}`);
2273
+ }
2274
+ if (type === "agent.approval_required") {
2275
+ const action = (checked.value ).action;
2276
+ if ((action.class === "outward_message") !== (action.message !== undefined) || (action.class === "outward_message" && action.kind !== "message"))
2277
+ return refuse("payload", "$body.action.message: present exactly for an outward message, which is a message");
2278
+ }
2279
+ if (type === "agent.completed") {
2280
+ const result = (checked.value ).result;
2281
+ if (result && result.files.reduce((n, f) => n + (f.diff?.length ?? 0), 0) > MAX_DIFF_CHARS_PER_RESULT) return refuse("payload", "$body.result: diffs above the per-result cap");
2282
+ if (result?.files.some((f) => f.binary && f.diff !== null)) return refuse("payload", "$body.result: a binary file is named, never shown");
2283
+ }
2284
+ if (type === "agent.plan") {
2285
+ const bad = planRule(checked.value );
2286
+ if (bad) return refuse("payload", `$body: ${bad}`);
2287
+ }
2288
+ if (type === "agent.subagent") {
2289
+ const bad = subagentRule(checked.value );
2290
+ if (bad) return refuse("payload", `$body: ${bad}`);
2291
+ }
2292
+ if (type === "release.updated") {
2293
+ const bad = releaseRule(checked.value );
2294
+ if (bad) return refuse("payload", `$body: ${bad}`);
2295
+ }
2296
+ if (type === "release.page") {
2297
+ const page = checked.value ;
2298
+ for (const r of page.releases) { const bad = releaseRule(r); if (bad) return refuse("payload", `$body.releases: ${bad}`); }
2299
+ if (page.releases.some((r, n) => n > 0 && r.number >= page.releases[n - 1] .number)) return refuse("payload", "$body.releases: newest first, each number once");
2300
+ if (page.next_before !== null && page.next_before !== page.releases.at(-1)?.number) return refuse("payload", "$body.next_before: the last number of this page");
2301
+ }
2302
+ if (type === "pipeline.updated") {
2303
+ const bad = pipelineRule(checked.value );
2304
+ if (bad) return refuse("payload", `$body: ${bad}`);
2305
+ }
2306
+ if (type === "agents.active") {
2307
+ const bad = agentsActiveRule(checked.value );
2308
+ if (bad) return refuse("payload", `$body: ${bad}`);
2309
+ }
2310
+ if (type === "agent.attention") {
2311
+ const a = validateAttention(value, "$body");
2312
+ if (!a.ok) return refuse("payload", a.detail);
2313
+ }
2314
+ if (type === "device.inventory") {
2315
+ const inv = checked.value ;
2316
+ for (const report of inv.adapters) {
2317
+ const r = validateAdapterReport(report);
2318
+ if (!r.ok) return refuse("payload", `$body.adapters: ${r.detail}`);
2319
+ }
2320
+ if (new Set(inv.adapters.map((a) => a.adapter)).size !== inv.adapters.length) return refuse("payload", "$body.adapters: an adapter twice");
2321
+ }
2322
+ return checked;
2323
+ }
2324
+
2325
+ /** The state-machine input a device event means for the command it answers, or null when it means none. */
2326
+ export function deliveryInputFor (type , body ) {
2327
+ switch (type) {
2328
+ case "command.device_received":
2329
+ return { kind: "device_received" };
2330
+ case "command.agent_accepted":
2331
+ return { kind: "agent_accepted" };
2332
+ case "command.rejected":
2333
+ return { kind: "device_rejected", expired: (body ).reason === "expired" };
2334
+ case "agent.step_started":
2335
+ case "agent.step_completed":
2336
+ case "agent.output_delta":
2337
+ return { kind: "running" };
2338
+ case "agent.approval_required":
2339
+ case "agent.question":
2340
+ return { kind: "waiting_approval" };
2341
+ case "agent.paused":
2342
+ return { kind: "paused" };
2343
+ case "agent.resumed":
2344
+ return { kind: "resumed" };
2345
+ case "agent.stopped":
2346
+ return { kind: "cancelled" };
2347
+ case "agent.completed":
2348
+ return { kind: "completed" };
2349
+ case "agent.failed":
2350
+ return { kind: "failed" };
2351
+ case "status.report": {
2352
+ const report = body ;
2353
+ return { kind: "reconciled", state: report.state };
2354
+ }
2355
+ default:
2356
+ return null;
2357
+ }
2358
+ }
2359
+
2360
+ // ---- packages/remote-protocol/src/envelopes.ts
2361
+ /**
2362
+ * WHAT THE RELAY MAY READ. Every message that crosses the relay is one of the outer shapes below, and RELAY_VISIBLE
2363
+ * lists them all. The relay routes and refuses on these fields alone: ids (prefixed random strings), closed types,
2364
+ * integer times, sequence numbers, counters, fixed-size keys, signatures and hashes, and the sealed box. No field here
2365
+ * can carry a sentence: there is no `text` kind outside a sealed body, a base64 field has an exact size, and the one
2366
+ * compact token (a key binding) is signed by the Passport issuer and verified by both ends.
2367
+ *
2368
+ * scripts/check-remote-protocol.mjs reads RELAY_VISIBLE and refuses a field that could carry content, a type in code
2369
+ * without a schema, and a sealed-only field name in an outer shape.
2370
+ *
2371
+ * Every outer field is also the AEAD's associated data (crypto/channel.ts): a relay that moves a sealed body to
2372
+ * another command, session, type or sequence number breaks the tag, and the receiving end refuses it.
2373
+ */
2374
+
2375
+ const version = int(1, 1000);
2376
+ const time = int(0);
2377
+
2378
+ export const COMMAND_ENVELOPE_SPEC = object({
2379
+ protocol_version: version,
2380
+ command_id: id("cmd"),
2381
+ idempotency_key: id("idk"),
2382
+ session_id: nullable(id("ses")),
2383
+ /** The computer the command is for. */
2384
+ device_id: id("dev"),
2385
+ /** The phone that sent it, whose bound key signed `authorization`. */
2386
+ sender_device_id: id("dev"),
2387
+ project_id: nullable(id("prj")),
2388
+ type: oneOf(COMMAND_TYPES),
2389
+ issued_at: time,
2390
+ expires_at: time,
2391
+ payload_ciphertext: sealed(),
2392
+ /** Ed25519 by the sender's remote key over every other field (crypto/channel.ts, commandSigningBytes). */
2393
+ authorization: b64({ exact: 64 }),
2394
+ });
2395
+
2396
+ export const EVENT_ENVELOPE_SPEC = object({
2397
+ protocol_version: version,
2398
+ session_id: nullable(id("ses")),
2399
+ /** The computer that wrote it. */
2400
+ device_id: id("dev"),
2401
+ /** Monotonic per (device, session) stream, from 1; the endpoint's own number, bound into the AEAD. */
2402
+ event_seq: int(1),
2403
+ type: oneOf(DEVICE_EVENT_TYPES),
2404
+ occurred_at: time,
2405
+ command_id: nullable(id("cmd")),
2406
+ /** The content-free push hint (attention.ts). */
2407
+ notify: oneOf(NOTIFY_HINTS),
2408
+ body_ciphertext: sealed(),
2409
+ });
2410
+
2411
+ export const PRESENCE_STATES = ["online", "offline", "remote_paused"] ;
2412
+ export const RELAY_REFUSALS = ["unauthorized", "device_unknown", "signature", "too_large", "version", "rate_limited", "conflict", "remote_paused"] ;
2413
+ export const RECONCILIATION_REASONS = ["retention", "buffer_overflow", "device_reset"] ;
2414
+ /** Why the relay says a device is gone: a phone disconnected itself (`unpaired`), or the Passport revoked it (`revoked`). */
2415
+ export const DEVICE_REVOKED_REASONS = ["unpaired", "revoked"] ;
2416
+
2417
+ /** Events the relay writes itself. It holds no key, so they have no sealed body, and they are the relay's word only. */
2418
+ export const RELAY_EVENT_SPECS = {
2419
+ "presence.changed": object({
2420
+ protocol_version: version,
2421
+ relay_seq: int(1),
2422
+ type: oneOf(["presence.changed"]),
2423
+ occurred_at: time,
2424
+ device_id: id("dev"),
2425
+ presence: oneOf(PRESENCE_STATES),
2426
+ }),
2427
+ "command.relay_ack": object({
2428
+ protocol_version: version,
2429
+ relay_seq: int(1),
2430
+ type: oneOf(["command.relay_ack"]),
2431
+ occurred_at: time,
2432
+ device_id: id("dev"),
2433
+ command_id: id("cmd"),
2434
+ outcome: oneOf(["accepted", "refused", "expired_undelivered"]),
2435
+ reason: nullable(oneOf(RELAY_REFUSALS)),
2436
+ }),
2437
+ "connection.reconciliation_required": object({
2438
+ protocol_version: version,
2439
+ relay_seq: int(1),
2440
+ type: oneOf(["connection.reconciliation_required"]),
2441
+ occurred_at: time,
2442
+ device_id: id("dev"),
2443
+ session_id: nullable(id("ses")),
2444
+ from_seq: int(1),
2445
+ to_seq: int(1),
2446
+ reason: oneOf(RECONCILIATION_REASONS),
2447
+ }),
2448
+ /**
2449
+ * The relay will carry nothing more between you and `device_id`: a phone disconnected itself from this computer, or
2450
+ * the Passport app revoked one of the two. Content-free, and the relay's word only: an endpoint may act on it to
2451
+ * drop a peer (that only ever lowers what the peer may do), never to add one.
2452
+ */
2453
+ "device.revoked": object({
2454
+ protocol_version: version,
2455
+ relay_seq: int(1),
2456
+ type: oneOf(["device.revoked"]),
2457
+ occurred_at: time,
2458
+ device_id: id("dev"),
2459
+ reason: oneOf(DEVICE_REVOKED_REASONS),
2460
+ }),
2461
+ } ;
2462
+
2463
+ export const RELAY_EVENT_TYPES = Object.keys(RELAY_EVENT_SPECS) ;
2464
+
2465
+ export const HANDSHAKE_HELLO_SPEC = object({
2466
+ protocol_version: version,
2467
+ versions: list(version, 8, 1),
2468
+ channel_id: id("chn"),
2469
+ from_device_id: id("dev"),
2470
+ to_device_id: id("dev"),
2471
+ binding: token(4096),
2472
+ ephemeral_pub: b64({ exact: 32 }),
2473
+ issued_at: time,
2474
+ /** Only in the first contact after a scanned QR invite (crypto/pairing.ts): proof of the invite's secret. */
2475
+ pair_proof: optional(b64({ exact: 32 })),
2476
+ signature: b64({ exact: 64 }),
2477
+ });
2478
+
2479
+ export const HANDSHAKE_WELCOME_SPEC = object({
2480
+ protocol_version: version,
2481
+ versions: list(version, 8, 1),
2482
+ channel_id: id("chn"),
2483
+ from_device_id: id("dev"),
2484
+ to_device_id: id("dev"),
2485
+ binding: token(4096),
2486
+ ephemeral_pub: b64({ exact: 32 }),
2487
+ hello_hash: b64({ exact: 32 }),
2488
+ issued_at: time,
2489
+ /** The computer's answer to a hello's pair_proof (crypto/pairing.ts). */
2490
+ pair_proof: optional(b64({ exact: 32 })),
2491
+ signature: b64({ exact: 64 }),
2492
+ });
2493
+
2494
+ /** Every shape the relay can read, by name. The checker's input, and the tests'. */
2495
+ export const RELAY_VISIBLE = {
2496
+ CommandEnvelope: COMMAND_ENVELOPE_SPEC,
2497
+ EventEnvelope: EVENT_ENVELOPE_SPEC,
2498
+ HandshakeHello: HANDSHAKE_HELLO_SPEC,
2499
+ HandshakeWelcome: HANDSHAKE_WELCOME_SPEC,
2500
+ ...Object.fromEntries(Object.entries(RELAY_EVENT_SPECS).map(([type, spec]) => [`RelayEvent:${type}`, spec])),
2501
+ };
2502
+
2503
+ /** Outer fields that may be a compact token, each verified by its own rules (crypto/binding.ts). */
2504
+ export const RELAY_VISIBLE_TOKENS = ["binding"];
2505
+
2506
+ export function validateCommandEnvelope(value ) {
2507
+ const checked = validate(COMMAND_ENVELOPE_SPEC, value, "$command");
2508
+ if (!checked.ok) return checked;
2509
+ const e = checked.value;
2510
+ if ((commandScope(e.type ) === "device") !== (e.session_id === null))
2511
+ return refuse("shape", "$command.session_id: a session command names a session, a device command none");
2512
+ // A device command names no project on the outside either: a release's or a new project's project lives in the sealed
2513
+ // payload, so the relay never learns which folder it is about (review 2026-11-07, P3-7).
2514
+ if (commandScope(e.type ) === "device" && e.project_id !== null)
2515
+ return refuse("shape", "$command.project_id: a device command names no project outside the box");
2516
+ if (e.expires_at <= e.issued_at) return refuse("shape", "$command.expires_at: not after issued_at");
2517
+ if (e.expires_at - e.issued_at > MAX_COMMAND_TTL_MS) return refuse("lifetime", "$command.expires_at: beyond the longest lifetime");
2518
+ if (e.device_id === e.sender_device_id) return refuse("wrong_device", "$command: a device does not command itself");
2519
+ return checked;
2520
+ }
2521
+
2522
+ export function validateEventEnvelope(value ) {
2523
+ const checked = validate(EVENT_ENVELOPE_SPEC, value, "$event");
2524
+ if (!checked.ok) return checked;
2525
+ const e = checked.value;
2526
+ const type = e.type ;
2527
+ // A receipt follows its command's scope: a device command's (inventory.get, release.create …) names no session. Found
2528
+ // 2026-11-07: the rule refused those receipts at sealing, so a phone never saw a device command received or accepted.
2529
+ if (!COMMAND_RECEIPT_EVENTS.has(type) && DEVICE_SCOPED_EVENTS.has(type) !== (e.session_id === null))
2530
+ return refuse("shape", "$event.session_id: a session event names a session, a device event none");
2531
+ if (COMMAND_RECEIPT_EVENTS.has(type) && e.command_id === null) return refuse("shape", "$event.command_id: a receipt names its command");
2532
+ return checked;
2533
+ }
2534
+
2535
+ export function validateRelayEvent(value ) {
2536
+ const type = typeof value === "object" && value !== null ? (value ).type : undefined;
2537
+ if (typeof type !== "string" || !Object.hasOwn(RELAY_EVENT_SPECS, type)) return refuse("shape", "$relay.type: not a relay event");
2538
+ const checked = check(RELAY_EVENT_SPECS[type ], value, "$relay") ;
2539
+ if (!checked.ok) return checked;
2540
+ const e = checked.value;
2541
+ if (e.type === "command.relay_ack" && (e.outcome === "refused") !== (e.reason !== null))
2542
+ return refuse("shape", "$relay.reason: given exactly when refused");
2543
+ if (e.type === "connection.reconciliation_required" && e.to_seq < e.from_seq) return refuse("shape", "$relay: an empty gap");
2544
+ return checked;
2545
+ }
2546
+
2547
+ /** What a relay acknowledgement means for the command's state. Never more than "the relay has it". */
2548
+ export function relayDeliveryInput(event ) {
2549
+ if (event.outcome === "accepted") return { kind: "relay_acknowledged" };
2550
+ if (event.outcome === "expired_undelivered") return { kind: "relay_expired" };
2551
+ return { kind: "relay_refused" };
2552
+ }
2553
+
2554
+ // ---- packages/remote-protocol/src/ledger.ts
2555
+ /**
2556
+ * AT MOST ONCE, AND NO LOST NEWS. Two pure tools, used the same way on the relay and on the computer.
2557
+ *
2558
+ * THE COMMAND LEDGER. A command is admitted once. The same command_id with the same bytes again is a DUPLICATE: the
2559
+ * caller answers with the state it already has (the computer re-sends its receipts) and never executes it again. The
2560
+ * same command_id with different bytes is a CONFLICT and refused. The same idempotency key from the same sender under
2561
+ * a new command_id is a duplicate of the first command too: a well-behaved phone never does this (a timeout resends
2562
+ * the same envelope; it never mints a new id), so a second id for one key is a retry gone wrong, and executing it
2563
+ * would be the double action the key exists to prevent. The computer writes the entry BEFORE it invokes the agent.
2564
+ *
2565
+ * THE SEQUENCE CURSOR. Events of one stream carry event_seq 1, 2, 3 and so on. The phone delivers them in order,
2566
+ * holds one that arrives early, and names the gap it is waiting for. The relay replays after the phone's last_seen
2567
+ * seq and, when it no longer holds the start of the gap, says so (connection.reconciliation_required) instead of
2568
+ * pretending the stream is whole; the phone then asks the computer for a status.report.
2569
+ */
2570
+
2571
+ export const emptyLedger = () => ({ entries: {}, keys: {} });
2572
+
2573
+ export function admitCommand(ledger , input , initial ) {
2574
+ const found = findCommand(ledger, input);
2575
+ if (found === "conflict") return { verdict: "conflict", ledger, reason: "id_reused" };
2576
+ if (found !== "unknown") return { verdict: "duplicate", ledger, entry: found.duplicate };
2577
+ const entry = { ...input, state: initial };
2578
+ return {
2579
+ verdict: "new",
2580
+ entry,
2581
+ ledger: {
2582
+ entries: { ...ledger.entries, [input.command_id]: entry },
2583
+ keys: { ...ledger.keys, [`${input.sender_device_id} ${input.idempotency_key}`]: input.command_id },
2584
+ },
2585
+ };
2586
+ }
2587
+
2588
+ /**
2589
+ * Look without admitting. The computer asks this BEFORE it opens a command, and admits only after the command opened:
2590
+ * an envelope nobody authenticated must never enter the ledger, or a forged one could take a real command's id and
2591
+ * make the real one a "conflict".
2592
+ */
2593
+ export function findCommand(ledger , input ) {
2594
+ const existing = ledger.entries[input.command_id];
2595
+ if (existing) {
2596
+ const same = existing.digest === input.digest && existing.idempotency_key === input.idempotency_key && existing.sender_device_id === input.sender_device_id;
2597
+ return same ? { duplicate: existing } : "conflict";
2598
+ }
2599
+ const keyed = ledger.keys[`${input.sender_device_id} ${input.idempotency_key}`];
2600
+ const first = keyed === undefined ? undefined : ledger.entries[keyed];
2601
+ return first ? { duplicate: first } : "unknown";
2602
+ }
2603
+
2604
+ /** Apply one state-machine input to a ledger entry. An unknown id leaves the ledger as it was. */
2605
+ export function advanceCommand(ledger , commandId , input ) {
2606
+ const entry = ledger.entries[commandId];
2607
+ if (!entry) return ledger;
2608
+ const next = transition(entry.state, input);
2609
+ if (!next.changed) return ledger;
2610
+ return { ...ledger, entries: { ...ledger.entries, [commandId]: { ...entry, state: next.state } } };
2611
+ }
2612
+
2613
+ export const MAX_HELD_EVENTS = 1024;
2614
+
2615
+ export const startCursor = (lastSeen = 0) => ({ last_seen: lastSeen, held: [] });
2616
+
2617
+ export function receiveSeq(cursor , seq ) {
2618
+ if (!Number.isSafeInteger(seq) || seq < 1) throw new RangeError("event_seq starts at 1");
2619
+ if (seq <= cursor.last_seen || cursor.held.includes(seq))
2620
+ return { cursor, deliver: [], duplicate: true, missing: missingOf(cursor), overflow: false };
2621
+ const held = [...cursor.held, seq].sort((a, b) => a - b);
2622
+ const deliver = [];
2623
+ let last = cursor.last_seen;
2624
+ while (held.length > 0 && held[0] === last + 1) {
2625
+ last = held.shift() ;
2626
+ deliver.push(last);
2627
+ }
2628
+ const next = { last_seen: last, held };
2629
+ return { cursor: next, deliver, duplicate: false, missing: missingOf(next), overflow: held.length > MAX_HELD_EVENTS };
2630
+ }
2631
+
2632
+ const missingOf = (cursor ) =>
2633
+ cursor.held.length === 0 ? null : { from: cursor.last_seen + 1, to: cursor.held[0] - 1 };
2634
+
2635
+ /**
2636
+ * The relay's replay: what it holds after `lastSeen`, in order, and the gap it can no longer fill (its oldest
2637
+ * retained seq is above lastSeen + 1). A gap is said, never skipped silently.
2638
+ */
2639
+ export function replayAfter (
2640
+ retained ,
2641
+ lastSeen ,
2642
+ ) {
2643
+ const events = retained.filter((e) => e.event_seq > lastSeen).sort((a, b) => a.event_seq - b.event_seq);
2644
+ const first = events[0];
2645
+ const gap = first !== undefined && first.event_seq > lastSeen + 1 ? { from: lastSeen + 1, to: first.event_seq - 1 } : null;
2646
+ return { events, gap };
2647
+ }
2648
+
2649
+ // ---- packages/remote-protocol/src/start-options.ts
2650
+ /**
2651
+ * A START IS CHECKED TWICE. The phone offers only what the computer reported; the computer checks again on receipt,
2652
+ * against its own current report, because a report the phone saw may be old and a phone may be wrong. A start that
2653
+ * names a model the adapter did not list, a permission mode it does not offer, or a resume id where the adapter
2654
+ * cannot resume, is refused (command.rejected) and nothing is started.
2655
+ */
2656
+
2657
+ export function checkStart(payload , report ) {
2658
+ if (!report || report.adapter !== payload.adapter || !report.installed || !report.capabilities.start) return "unsupported";
2659
+ if (!isModelReported(report, payload.model)) return "unknown_model";
2660
+ if (!report.capabilities.permission_modes.includes(payload.permission_mode)) return "unsupported";
2661
+ if (payload.resume !== null && !report.capabilities.resume_by_id) return "unsupported";
2662
+ return null;
2663
+ }
2664
+
2665
+ // ---- packages/remote-protocol/src/steered.ts
2666
+ /**
2667
+ * REMOTE-STEERED SESSIONS ARE MARKED, NEVER COUNTED AS A PERSON'S AI HOURS BY THEMSELVES. The agents the daemon runs
2668
+ * write their ordinary logs, which the measurement readers read. So the daemon keeps a local ledger of the agent
2669
+ * sessions it started or steered, `~/.worktrust/remote/steered.jsonl` (mode 0600, one record per line, ids and times
2670
+ * only), and the session readers mark a session found in it `steered: "remote"`, the field they already set for
2671
+ * sessions driven from a chat app. How a remote-steered session counts is the owner's decision; this file only fixes
2672
+ * the record's shape so that the daemon and the readers agree on it.
2673
+ *
2674
+ * Nothing in a record is content. `agent_session_ref` is the agent's own session id (Claude Code's session uuid, a
2675
+ * Codex thread id), which is how the reader finds the log; it is never sent to the relay or to WorkTrust.
2676
+ */
2677
+
2678
+ export const STEERED_RECORD_VERSION = 1;
2679
+
2680
+ export const STEERED_RECORD_SPEC = object({
2681
+ v: int(1, 1),
2682
+ steered: oneOf(["remote"]),
2683
+ adapter: oneOf(ADAPTER_IDS),
2684
+ /** The agent's own session id; [A-Za-z0-9._:-] only, so a path or a sentence cannot be stored here. */
2685
+ agent_session_ref: text(256, 1),
2686
+ remote_session_id: id("ses"),
2687
+ project_id: nullable(id("prj")),
2688
+ /** The remote session began from the phone, or the phone attached to a desk session. */
2689
+ how: oneOf(["started", "attached"]),
2690
+ first_steered_at: int(0),
2691
+ last_steered_at: int(0),
2692
+ });
2693
+
2694
+ /**
2695
+ * A PIPELINE RUN IS NOT AGENT WORK (owner, 2026-11-07). The daemon marks each pipeline run it starts in the same ledger,
2696
+ * `steered: "pipeline"`, `agent: false`, with its window and no agent session: the stages run builds, tests and scanners,
2697
+ * not an agent, and a release or a pipeline is never Passport hours. The readers know the record and skip it (it is not
2698
+ * an unreadable line, and it names no session a reader could match); an older reader that does not know it counts it as
2699
+ * unreadable and skips it too, so neither can turn it into hours.
2700
+ */
2701
+ export const PIPELINE_LEDGER_SPEC = object({
2702
+ v: int(1, 1),
2703
+ steered: oneOf(["pipeline"]),
2704
+ agent: bool(),
2705
+ pipeline_run_id: id("plr"),
2706
+ release_id: nullable(id("rel")),
2707
+ project_id: nullable(id("prj")),
2708
+ started_at: int(0),
2709
+ ended_at: nullable(int(0)),
2710
+ });
2711
+
2712
+ export function validatePipelineLedgerRecord(value ) {
2713
+ const checked = validate(PIPELINE_LEDGER_SPEC, value, "$pipeline");
2714
+ if (!checked.ok) return checked;
2715
+ if (checked.value.agent !== false) return refuse("shape", "$pipeline.agent: a pipeline is never agent work");
2716
+ if (checked.value.ended_at !== null && checked.value.ended_at < checked.value.started_at) return refuse("shape", "$pipeline: ended before it started");
2717
+ return checked;
2718
+ }
2719
+
2720
+ /** One pipeline line of the ledger, canonical, newline-terminated. */
2721
+ export function pipelineLedgerLine(record ) {
2722
+ const checked = validatePipelineLedgerRecord(record);
2723
+ if (!checked.ok) throw new TypeError(checked.detail);
2724
+ return `${canonicalJson(record)}\n`;
2725
+ }
2726
+
2727
+ const REF = /^[A-Za-z0-9._:-]{1,256}$/;
2728
+
2729
+ export function validateSteeredRecord(value ) {
2730
+ const checked = validate(STEERED_RECORD_SPEC, value, "$steered");
2731
+ if (!checked.ok) return checked;
2732
+ if (!REF.test(checked.value.agent_session_ref)) return refuse("shape", "$steered.agent_session_ref: not a bare id");
2733
+ if (checked.value.last_steered_at < checked.value.first_steered_at) return refuse("shape", "$steered: last before first");
2734
+ return checked;
2735
+ }
2736
+
2737
+ /** One line of the ledger, canonical, newline-terminated. */
2738
+ export function steeredLine(record ) {
2739
+ const checked = validateSteeredRecord(record);
2740
+ if (!checked.ok) throw new TypeError(checked.detail);
2741
+ return `${canonicalJson(record)}\n`;
2742
+ }
2743
+
2744
+ /**
2745
+ * Read a ledger file's text: every valid record by agent_session_ref, the latest last_steered_at winning. A malformed
2746
+ * line is skipped and counted, so a reader marks what it can and says how many lines it could not read.
2747
+ */
2748
+ export function readSteeredLedger(textValue ) {
2749
+ const byRef = new Map ();
2750
+ let unreadable = 0;
2751
+ let pipelines = 0;
2752
+ for (const line of textValue.split("\n")) {
2753
+ if (line.trim() === "") continue;
2754
+ const value = parseJson(line);
2755
+ if (validatePipelineLedgerRecord(value).ok) {
2756
+ pipelines += 1; // not agent work: never a session a reader matches
2757
+ continue;
2758
+ }
2759
+ const checked = validateSteeredRecord(value);
2760
+ if (!checked.ok) {
2761
+ unreadable += 1;
2762
+ continue;
2763
+ }
2764
+ const prior = byRef.get(checked.value.agent_session_ref);
2765
+ if (!prior || prior.last_steered_at <= checked.value.last_steered_at) byRef.set(checked.value.agent_session_ref, checked.value);
2766
+ }
2767
+ return { byRef, unreadable, pipelines };
2768
+ }
2769
+
2770
+ // ---- packages/remote-protocol/src/crypto/keys.ts
2771
+ /**
2772
+ * REMOTE DEVICE KEYS. Each computer and each phone install has its own pair: Ed25519 to sign, X25519 to agree keys.
2773
+ * They are NOT the computer's measurement key: a different key, a different store entry, a different audience. A
2774
+ * stolen remote key cannot sign a measurement, and a measurement key cannot steer an agent; every signature here is
2775
+ * also domain-separated ("worktrust-remote/v1/..."), so a signature made for one purpose verifies for no other.
2776
+ *
2777
+ * A FINGERPRINT FOR PEOPLE. 80 bits of SHA-256 over both public keys, as sixteen Crockford base32 characters in four
2778
+ * groups (no I, L, O or U to misread). Shown on the computer's screen and on the phone when a phone is confirmed at
2779
+ * the computer's keyboard, so a compromised issuer cannot slip in a key of its own unnoticed.
2780
+ */
2781
+
2782
+ export function generateDeviceKeys(random ) {
2783
+ return { ed25519: random(KEY_BYTES), x25519: random(KEY_BYTES) };
2784
+ }
2785
+
2786
+ export function publicKeysOf(secret ) {
2787
+ return { ed25519_pub: toBase64Url(ed25519PublicKey(secret.ed25519)), x25519_pub: toBase64Url(x25519PublicKey(secret.x25519)) };
2788
+ }
2789
+
2790
+ /** For a store that holds strings (expo-secure-store, the CLI's credential store). */
2791
+ export const exportSecretKeys = (secret ) => ({
2792
+ ed25519: toBase64Url(secret.ed25519),
2793
+ x25519: toBase64Url(secret.x25519),
2794
+ });
2795
+
2796
+ export function importSecretKeys(stored ) {
2797
+ const ed = fromBase64Url(stored.ed25519);
2798
+ const x = fromBase64Url(stored.x25519);
2799
+ return ed?.length === KEY_BYTES && x?.length === KEY_BYTES ? { ed25519: ed, x25519: x } : null;
2800
+ }
2801
+
2802
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2803
+ const FINGERPRINT_DOMAIN = utf8Encode("worktrust-remote/v1/fingerprint\n");
2804
+
2805
+ function base32Groups(bytes ) {
2806
+ let bits = 0;
2807
+ let acc = 0;
2808
+ let out = "";
2809
+ for (const b of bytes) {
2810
+ acc = (acc << 8) | b;
2811
+ bits += 8;
2812
+ while (bits >= 5) {
2813
+ bits -= 5;
2814
+ out += CROCKFORD[(acc >> bits) & 31] ;
2815
+ }
2816
+ acc &= (1 << bits) - 1;
2817
+ }
2818
+ return out.match(/.{1,4}/g) .join("-");
2819
+ }
2820
+
2821
+ function decodeKey(text ) {
2822
+ const bytes = fromBase64Url(text);
2823
+ if (bytes?.length !== KEY_BYTES) throw new TypeError("a public key is 32 bytes of base64url");
2824
+ return bytes;
2825
+ }
2826
+
2827
+ /** "ABCD-EFGH-JKMN-PQRS" for one device's public keys. */
2828
+ export function deviceFingerprint(keys ) {
2829
+ const digest = sha256(concatBytes(FINGERPRINT_DOMAIN, decodeKey(keys.ed25519_pub), decodeKey(keys.x25519_pub)));
2830
+ return base32Groups(digest.subarray(0, 10));
2831
+ }
2832
+
2833
+ // ---- packages/remote-protocol/src/crypto/jws.ts
2834
+ /**
2835
+ * COMPACT SIGNED TOKENS: JWS (RFC 7515) with EdDSA over Ed25519 (RFC 8037), so the gateway can verify an assertion
2836
+ * with any standard library, and so can the phone and the computer with this package. Three token types, told apart
2837
+ * by `typ` and never interchangeable:
2838
+ * wt-remote-binding+jwt the Passport app binds a device's remote keys to an account
2839
+ * wt-remote-auth+jwt the Passport app authorizes one device at the gateway for five minutes
2840
+ * wt-remote-approval+jwt a phone decides one pending approval
2841
+ * The verifier fixes alg, typ and the key set before it looks at the token: a token cannot choose how it is checked.
2842
+ * Header and payload are canonical JSON, so one claim set has one signing input.
2843
+ */
2844
+
2845
+ export const TOKEN_TYPES = ["wt-remote-binding+jwt", "wt-remote-auth+jwt", "wt-remote-approval+jwt"] ;
2846
+
2847
+ export const MAX_TOKEN_CHARS = 4096;
2848
+
2849
+ /** Public keys by key id: the issuer's keys (pinned in the app and CLI builds), or a phone's bound key. */
2850
+
2851
+ export function signToken(typ , kid , claims , secret ) {
2852
+ const header = toBase64Url(utf8Encode(canonicalJson({ alg: "EdDSA", kid, typ })));
2853
+ const payload = toBase64Url(utf8Encode(canonicalJson(claims)));
2854
+ const signature = ed25519Sign(utf8Encode(`${header}.${payload}`), secret);
2855
+ return `${header}.${payload}.${toBase64Url(signature)}`;
2856
+ }
2857
+
2858
+ const decodeJson = (part ) => {
2859
+ const bytes = fromBase64Url(part);
2860
+ const text = bytes === null ? null : utf8Decode(bytes);
2861
+ return text === null ? undefined : parseJson(text);
2862
+ };
2863
+
2864
+ export function verifyToken(token , typ , keys ) {
2865
+ if (token.length > MAX_TOKEN_CHARS) return refuse("shape", "token: too long");
2866
+ const parts = token.split(".");
2867
+ if (parts.length !== 3) return refuse("shape", "token: not three parts");
2868
+ const [h, p, s] = parts ;
2869
+ const header = decodeJson(h);
2870
+ if (typeof header !== "object" || header === null || Array.isArray(header)) return refuse("shape", "token: header");
2871
+ const hd = header ;
2872
+ if (Object.keys(hd).sort().join(",") !== "alg,kid,typ") return refuse("shape", "token: header fields");
2873
+ if (hd.alg !== "EdDSA") return refuse("shape", "token: alg");
2874
+ if (hd.typ !== typ) return refuse("shape", "token: typ");
2875
+ if (typeof hd.kid !== "string" || !Object.hasOwn(keys, hd.kid)) return refuse("unknown_key", "token: kid");
2876
+ const key = keys[hd.kid] ;
2877
+ const signature = fromBase64Url(s);
2878
+ if (key.length !== KEY_BYTES || signature === null) return refuse("signature", "token: signature encoding");
2879
+ if (!ed25519Verify(signature, utf8Encode(`${h}.${p}`), key)) return refuse("signature", "token: signature");
2880
+ const claims = decodeJson(p);
2881
+ if (typeof claims !== "object" || claims === null || Array.isArray(claims)) return refuse("shape", "token: payload");
2882
+ // The signed bytes must BE the canonical encoding, so one claim set has exactly one valid token form.
2883
+ if (toBase64Url(utf8Encode(canonicalJson(claims))) !== p) return refuse("shape", "token: payload not canonical");
2884
+ if (toBase64Url(utf8Encode(canonicalJson(hd))) !== h) return refuse("shape", "token: header not canonical");
2885
+ return accept({ kid: hd.kid, claims: claims });
2886
+ }
2887
+
2888
+ /** iat/exp checks shared by every token kind; seconds, with the protocol's skew. */
2889
+ export function checkTimes(iat , exp , nowMs , maxLifetimeS , skewMs ) {
2890
+ if (exp <= iat) return refuse("lifetime", "token: exp not after iat");
2891
+ if (exp - iat > maxLifetimeS) return refuse("lifetime", "token: lives too long");
2892
+ if (iat * 1000 > nowMs + skewMs) return refuse("not_yet_valid", "token: issued in the future");
2893
+ if (exp * 1000 + skewMs < nowMs) return refuse("expired", "token: expired");
2894
+ return accept(true);
2895
+ }
2896
+
2897
+ // ---- packages/remote-protocol/src/crypto/binding.ts
2898
+ /**
2899
+ * A REMOTE KEY BINDING: the Passport app's signed word that these public keys belong to this device of this account.
2900
+ * The person approves the device in app.worktrust.io, signed in with a second factor; the app signs
2901
+ * { iss, aud, sub, device_id, kind, ed25519_pub, x25519_pub, iat, exp, jti }
2902
+ * with a WorkTrust issuer key. `sub` is an opaque account reference for the remote system (an HMAC of the owner id
2903
+ * under a Passport secret, prefixed usr_), never the Passport owner id, so the relay's records join to nothing else.
2904
+ *
2905
+ * Endpoints verify bindings against the issuer's public keys PINNED in the app and CLI builds, never against a key the
2906
+ * relay hands them. The relay cannot forge a binding. The issuer alone cannot add a controller either: a new phone is
2907
+ * pending on the computer until the person confirms its fingerprint at the computer's keyboard (handshake.ts).
2908
+ */
2909
+
2910
+ export const DEVICE_KINDS = ["phone", "computer"] ;
2911
+
2912
+ export const BINDING_CLAIMS_SPEC = object({
2913
+ iss: oneOf([PASSPORT_ISSUER]),
2914
+ aud: oneOf([GATEWAY_AUDIENCE]),
2915
+ sub: id("usr"),
2916
+ device_id: id("dev"),
2917
+ kind: oneOf(DEVICE_KINDS),
2918
+ ed25519_pub: b64({ exact: 32 }),
2919
+ x25519_pub: b64({ exact: 32 }),
2920
+ iat: int(0),
2921
+ exp: int(0),
2922
+ jti: id("jti"),
2923
+ });
2924
+
2925
+ /** For the Passport app: validate, then sign. */
2926
+ export function issueBinding(claims , issuerSecret , kid ) {
2927
+ const checked = validate(BINDING_CLAIMS_SPEC, claims, "$binding");
2928
+ if (!checked.ok) throw new TypeError(checked.detail);
2929
+ if (claims.exp - claims.iat > MAX_BINDING_LIFETIME_S || claims.exp <= claims.iat) throw new RangeError("binding lifetime");
2930
+ return signToken("wt-remote-binding+jwt", kid, claims, issuerSecret);
2931
+ }
2932
+
2933
+ export function verifyBinding(token , expect ) {
2934
+ const verified = verifyToken(token, "wt-remote-binding+jwt", expect.issuerKeys);
2935
+ if (!verified.ok) return refuse(verified.code === "shape" ? "binding" : verified.code, verified.detail);
2936
+ const shaped = validate(BINDING_CLAIMS_SPEC, verified.value.claims, "$binding");
2937
+ if (!shaped.ok) return refuse("binding", shaped.detail);
2938
+ const b = shaped.value;
2939
+ const times = checkTimes(b.iat, b.exp, expect.now, MAX_BINDING_LIFETIME_S, CLOCK_SKEW_MS);
2940
+ if (!times.ok) return times;
2941
+ if (expect.kind !== undefined && b.kind !== expect.kind) return refuse("binding", "$binding.kind: not the expected kind");
2942
+ if (expect.deviceId !== undefined && b.device_id !== expect.deviceId) return refuse("wrong_device", "$binding.device_id");
2943
+ if (expect.sub !== undefined && b.sub !== expect.sub) return refuse("account_mismatch", "$binding.sub");
2944
+ if (expect.isRevoked?.(b)) return refuse("revoked", "$binding: revoked");
2945
+ return accept(b);
2946
+ }
2947
+
2948
+ /** The signing key a verified binding names, as bytes. */
2949
+ export const bindingSigningKey = (b ) => fromBase64Url(b.ed25519_pub) ;
2950
+ export const bindingAgreementKey = (b ) => fromBase64Url(b.x25519_pub) ;
2951
+ export const bindingFingerprint = (b ) =>
2952
+ deviceFingerprint({ ed25519_pub: b.ed25519_pub, x25519_pub: b.x25519_pub });
2953
+
2954
+ // ---- packages/remote-protocol/src/crypto/assertion.ts
2955
+ /**
2956
+ * THE GATEWAY'S ADMISSION TICKET. The gateway holds no Passport credential and reads no Passport database: it trusts
2957
+ * one thing, an assertion the Passport app signed for one device, for five minutes at most, used once:
2958
+ * { iss: app.worktrust.io, aud: remote.worktrust.io, sub, device_id, kind, capabilities, iat, exp, jti }
2959
+ *
2960
+ * Capabilities are written `area:verb`, so none can be mistaken for a protocol message type.
2961
+ *
2962
+ * CAPABILITIES ARE CAPPED BY KIND, here and not only at the issuer. A computer's assertion can hold a computer's
2963
+ * capabilities and nothing else: receive commands, send events, publish presence. It can never send a command, so a
2964
+ * stolen computer key cannot schedule work on another computer. A phone's can send commands and receive events. An
2965
+ * assertion that names a capability its kind may not hold is refused whole, however valid its signature: a bug at the
2966
+ * issuer must not become a privilege at the gateway.
2967
+ */
2968
+
2969
+ export const ASSERTION_CAPABILITIES = [
2970
+ "relay:connect",
2971
+ "commands:send",
2972
+ "commands:receive",
2973
+ "events:send",
2974
+ "events:receive",
2975
+ "presence:publish",
2976
+ "push:register",
2977
+ ] ;
2978
+
2979
+ export const CAPABILITIES_BY_KIND = {
2980
+ phone: new Set (["relay:connect", "commands:send", "events:receive", "push:register"]),
2981
+ computer: new Set (["relay:connect", "commands:receive", "events:send", "presence:publish"]),
2982
+ };
2983
+
2984
+ export const ASSERTION_CLAIMS_SPEC = object({
2985
+ iss: oneOf([PASSPORT_ISSUER]),
2986
+ aud: oneOf([GATEWAY_AUDIENCE]),
2987
+ sub: id("usr"),
2988
+ device_id: id("dev"),
2989
+ kind: oneOf(DEVICE_KINDS),
2990
+ capabilities: list(oneOf(ASSERTION_CAPABILITIES), ASSERTION_CAPABILITIES.length, 1),
2991
+ iat: int(0),
2992
+ exp: int(0),
2993
+ jti: id("jti"),
2994
+ });
2995
+
2996
+ function rules(a ) {
2997
+ if (new Set(a.capabilities).size !== a.capabilities.length) return refuse("shape", "$assertion.capabilities: a capability twice");
2998
+ const allowed = CAPABILITIES_BY_KIND[a.kind];
2999
+ if (!a.capabilities.every((c) => allowed.has(c))) return refuse("capability", "$assertion.capabilities: beyond what the kind may hold");
3000
+ return accept(a);
3001
+ }
3002
+
3003
+ /** For the Passport app: validate, then sign. */
3004
+ export function issueAssertion(claims , issuerSecret , kid ) {
3005
+ const shaped = validate(ASSERTION_CLAIMS_SPEC, claims, "$assertion");
3006
+ if (!shaped.ok) throw new TypeError(shaped.detail);
3007
+ const ruled = rules(shaped.value);
3008
+ if (!ruled.ok) throw new TypeError(ruled.detail);
3009
+ if (claims.exp <= claims.iat || claims.exp - claims.iat > MAX_ASSERTION_LIFETIME_S) throw new RangeError("assertion lifetime");
3010
+ return signToken("wt-remote-auth+jwt", kid, claims, issuerSecret);
3011
+ }
3012
+
3013
+ export function verifyAssertion(token , expect ) {
3014
+ const verified = verifyToken(token, "wt-remote-auth+jwt", expect.issuerKeys);
3015
+ if (!verified.ok) return verified;
3016
+ const claims = verified.value.claims;
3017
+ if (claims.iss !== PASSPORT_ISSUER) return refuse("issuer", "$assertion.iss");
3018
+ if (claims.aud !== GATEWAY_AUDIENCE) return refuse("audience", "$assertion.aud");
3019
+ const shaped = validate(ASSERTION_CLAIMS_SPEC, claims, "$assertion");
3020
+ if (!shaped.ok) return shaped;
3021
+ const ruled = rules(shaped.value);
3022
+ if (!ruled.ok) return ruled;
3023
+ const a = ruled.value;
3024
+ const times = checkTimes(a.iat, a.exp, expect.now, MAX_ASSERTION_LIFETIME_S, CLOCK_SKEW_MS);
3025
+ if (!times.ok) return times;
3026
+ if (!expect.needs.every((c) => a.capabilities.includes(c))) return refuse("capability", "$assertion: lacks a needed capability");
3027
+ if (expect.spendJti(a.jti, a.exp) === "seen") return refuse("replay", "$assertion.jti: already used");
3028
+ return accept(a);
3029
+ }
3030
+
3031
+ // ---- packages/remote-protocol/src/crypto/approval.ts
3032
+ /**
3033
+ * A SIGNED APPROVAL DECISION, SINGLE USE, FAIL CLOSED. The phone signs, with its own bound remote key,
3034
+ * { iss: phone device, aud: computer device, approval_id, session_id, action_hash, decision, iat, exp, jti }
3035
+ * and seals it inside approval.decision. The computer acts on it only if every check passes: the key is a CONFIRMED
3036
+ * controller of this computer, the approval is pending and was never decided, the hash is the pending action's own,
3037
+ * the decision is in time (five minutes at most, and never past the request's expiry), and, for an approval, the
3038
+ * action's class may be approved from a phone at all (approval-action.ts). Any refusal leaves the action unapproved;
3039
+ * no decision before the request expires is a denial. A deny needs the same signature but no approvable class: a
3040
+ * refusal is always safe to honour.
3041
+ *
3042
+ * Push is a notification, never the approval: nothing about a push can approve anything.
3043
+ */
3044
+
3045
+ export const DECISION_CLAIMS_SPEC = object({
3046
+ iss: id("dev"),
3047
+ aud: id("dev"),
3048
+ approval_id: id("apr"),
3049
+ session_id: id("ses"),
3050
+ action_hash: b64({ exact: 32 }),
3051
+ decision: oneOf(["approve", "deny"]),
3052
+ iat: int(0),
3053
+ exp: int(0),
3054
+ jti: id("jti"),
3055
+ });
3056
+
3057
+ /** What the computer remembers about an approval it asked for. */
3058
+
3059
+ /** For the phone: sign one decision with the phone's own remote key; kid is the phone's device id. */
3060
+ export function signApprovalDecision(decision , phoneSecret ) {
3061
+ const shaped = validate(DECISION_CLAIMS_SPEC, decision, "$decision");
3062
+ if (!shaped.ok) throw new TypeError(shaped.detail);
3063
+ return signToken("wt-remote-approval+jwt", decision.iss, decision, phoneSecret);
3064
+ }
3065
+
3066
+ export function verifyApprovalDecision(token , expect ) {
3067
+ const verified = verifyToken(token, "wt-remote-approval+jwt", expect.controllers);
3068
+ if (!verified.ok) return verified;
3069
+ const shaped = validate(DECISION_CLAIMS_SPEC, verified.value.claims, "$decision");
3070
+ if (!shaped.ok) return shaped;
3071
+ const d = shaped.value;
3072
+ if (d.iss !== verified.value.kid) return refuse("signature", "$decision.iss: not the signing device");
3073
+ if (expect.decided.has(d.approval_id)) return refuse("already_decided", "$decision.approval_id");
3074
+ const pending = expect.pending.get(d.approval_id);
3075
+ if (!pending) return refuse("not_pending", "$decision.approval_id");
3076
+ if (d.aud !== pending.computer_device_id) return refuse("wrong_device", "$decision.aud");
3077
+ if (d.session_id !== pending.session_id) return refuse("action_mismatch", "$decision.session_id");
3078
+ const ours = fromBase64Url(pending.action_hash);
3079
+ const theirs = fromBase64Url(d.action_hash);
3080
+ if (!ours || !theirs || !equalBytes(ours, theirs)) return refuse("action_mismatch", "$decision.action_hash");
3081
+ const times = checkTimes(d.iat, d.exp, expect.now, MAX_APPROVAL_LIFETIME_S, CLOCK_SKEW_MS);
3082
+ if (!times.ok) return times;
3083
+ // The request's own expiry is the computer's clock and gets no skew: late is denied.
3084
+ if (expect.now > pending.expires_at) return refuse("expired", "$decision: the request expired");
3085
+ if (d.exp * 1000 > pending.expires_at + CLOCK_SKEW_MS) return refuse("lifetime", "$decision.exp: past the request");
3086
+ if (d.decision === "approve" && !isRemoteApprovable(pending.class)) return refuse("not_approvable", "$decision: class");
3087
+ return accept(d);
3088
+ }
3089
+
3090
+ /** Spend the approval: one decision per approval, ever. */
3091
+ export const recordDecision = (decided , approvalId ) =>
3092
+ new Set([...decided, approvalId]);
3093
+
3094
+ // ---- packages/remote-protocol/src/crypto/channel.ts
3095
+ /**
3096
+ * THE SEALED CHANNEL between one phone and one computer, after a handshake (handshake.ts) gave both the same two keys.
3097
+ *
3098
+ * SEALING. XChaCha20-Poly1305 under the sender's direction key, a fresh random 24-byte nonce per message, and as
3099
+ * associated data every relay-visible field of the envelope plus the box's channel id and counter. Change any outer
3100
+ * field and the tag fails: the relay cannot move a body to another command, session, type, time or sequence number.
3101
+ * Random nonces (192 bits) stay safe even if a device restores an old counter from a backup; the counter's job is
3102
+ * replay protection, not nonce uniqueness.
3103
+ *
3104
+ * PADDING. The plaintext is its 4-byte length, the canonical JSON, and zeros up to a bucket: 256 bytes, then powers of
3105
+ * two to 64 KiB, then multiples of 64 KiB. The relay learns a size class, not the length of a prompt.
3106
+ *
3107
+ * REPLAY. Each direction counts from 1. The receiver keeps the highest counter and which of the last 128 it has seen;
3108
+ * a repeat is refused, and so is a counter that fell below the window. Order within the window is free, because the
3109
+ * relay may reorder; ordering is the event stream's job (event_seq, ledger.ts).
3110
+ *
3111
+ * COMMANDS ARE ALSO SIGNED by the phone's remote key over the whole envelope (`authorization`), so the relay can refuse
3112
+ * a command no confirmed phone made, and the computer has a per-command proof of who sent it.
3113
+ */
3114
+
3115
+ const DOMAIN = {
3116
+ commandAad: utf8Encode("worktrust-remote/v1/command-aad\n"),
3117
+ commandSig: utf8Encode("worktrust-remote/v1/command-sig\n"),
3118
+ eventAad: utf8Encode("worktrust-remote/v1/event-aad\n"),
3119
+ digest: utf8Encode("worktrust-remote/v1/envelope-digest\n"),
3120
+ };
3121
+
3122
+ export function checkReplay(window , counter ) {
3123
+ if (counter > window.highest) return "fresh";
3124
+ if (counter <= window.highest - REPLAY_WINDOW) return "too_old";
3125
+ return window.seen.includes(counter) ? "replay" : "fresh";
3126
+ }
3127
+
3128
+ export function markSeen(window , counter ) {
3129
+ const highest = Math.max(window.highest, counter);
3130
+ return { highest, seen: [...window.seen, counter].filter((c) => c > highest - REPLAY_WINDOW).sort((a, b) => a - b) };
3131
+ }
3132
+
3133
+ export function padPlaintext(data ) {
3134
+ const total = 4 + data.length;
3135
+ let size = 256;
3136
+ if (total > 65_536) size = Math.ceil(total / 65_536) * 65_536;
3137
+ else while (size < total) size *= 2;
3138
+ const out = new Uint8Array(size);
3139
+ out.set(u32be(data.length), 0);
3140
+ out.set(data, 4);
3141
+ return out;
3142
+ }
3143
+
3144
+ export function unpadPlaintext(padded ) {
3145
+ if (padded.length < 4) return null;
3146
+ const length = readU32be(padded, 0);
3147
+ if (length > padded.length - 4) return null;
3148
+ for (let i = 4 + length; i < padded.length; i += 1) if (padded[i] !== 0) return null;
3149
+ return padded.subarray(4, 4 + length);
3150
+ }
3151
+
3152
+ /** The associated data: the outer fields, and the box without its ciphertext. */
3153
+ const commandAad = (draft , channelId , counter , nonce ) =>
3154
+ concatBytes(DOMAIN.commandAad, canonicalBytes({ ...draft, payload_ciphertext: { channel_id: channelId, counter, nonce } }));
3155
+ const eventAad = (draft , channelId , counter , nonce ) =>
3156
+ concatBytes(DOMAIN.eventAad, canonicalBytes({ ...draft, body_ciphertext: { channel_id: channelId, counter, nonce } }));
3157
+
3158
+ export const commandSigningBytes = (envelope ) =>
3159
+ concatBytes(DOMAIN.commandSig, canonicalBytes(envelope));
3160
+
3161
+ /** The id of an envelope's exact bytes: the ledger's duplicate test (ledger.ts). */
3162
+ export const envelopeDigest = (envelope ) =>
3163
+ toBase64Url(sha256(concatBytes(DOMAIN.digest, canonicalBytes(envelope))));
3164
+
3165
+ function seal(key , aad , value , random ) {
3166
+ const plain = canonicalBytes(value);
3167
+ if (plain.length > MAX_PLAINTEXT_BYTES) return null;
3168
+ const nonceBytes = random(NONCE_BYTES);
3169
+ const nonce = toBase64Url(nonceBytes);
3170
+ return { nonce, ciphertext: toBase64Url(aeadSeal(key, nonceBytes, aad(nonce), padPlaintext(plain))) };
3171
+ }
3172
+
3173
+ function open(key , aad , nonce , ciphertext ) {
3174
+ const n = fromBase64Url(nonce);
3175
+ const c = fromBase64Url(ciphertext);
3176
+ if (!n || !c) return refuse("shape", "box: encoding");
3177
+ const padded = aeadOpen(key, n, aad, c);
3178
+ if (!padded) return refuse("decrypt", "box: the tag did not verify");
3179
+ const plain = unpadPlaintext(padded);
3180
+ if (!plain) return refuse("padding", "box: padding");
3181
+ const text = utf8Decode(plain);
3182
+ const value = text === null ? undefined : parseJson(text);
3183
+ return value === undefined ? refuse("payload", "box: not JSON") : accept(value);
3184
+ }
3185
+
3186
+ const nextCounter = (channel ) =>
3187
+ channel.send_counter + 1 > CHANNEL_MAX_MESSAGES ? refuse("lifetime", "channel: re-key before sending more") : accept(channel.send_counter + 1);
3188
+
3189
+ /** Phone side: seal a command and sign the envelope. */
3190
+ export function sealCommand (
3191
+ channel ,
3192
+ draft ,
3193
+ payload ,
3194
+ phoneSigningSecret ,
3195
+ random ,
3196
+ ) {
3197
+ if (channel.role !== "phone") return refuse("wrong_device", "only a phone sends commands");
3198
+ if (draft.sender_device_id !== channel.self_device_id || draft.device_id !== channel.peer_device_id)
3199
+ return refuse("wrong_device", "$command: not this channel's devices");
3200
+ if (draft.protocol_version !== channel.protocol_version) return refuse("version", "$command.protocol_version");
3201
+ const valid = validateCommandPayload(draft.type, payload);
3202
+ if (!valid.ok) return valid;
3203
+ const counter = nextCounter(channel);
3204
+ if (!counter.ok) return counter;
3205
+ const box = seal(channel.send_key, (nonce) => commandAad(draft, channel.channel_id, counter.value, nonce), payload, random);
3206
+ if (!box) return refuse("payload", "$payload: too large");
3207
+ const unsigned = { ...draft, payload_ciphertext: { channel_id: channel.channel_id, counter: counter.value, ...box } };
3208
+ const envelope = { ...unsigned, authorization: toBase64Url(ed25519Sign(commandSigningBytes(unsigned), phoneSigningSecret)) };
3209
+ const shaped = validateCommandEnvelope(envelope);
3210
+ if (!shaped.ok) return shaped;
3211
+ return accept({ envelope, channel: { ...channel, send_counter: counter.value } });
3212
+ }
3213
+
3214
+ /** Signature check alone, for the relay (it knows the phone's bound key, not the channel key). */
3215
+ export function verifyCommandAuthorization(envelope , senderEd25519Pub ) {
3216
+ const { authorization, ...unsigned } = envelope;
3217
+ const signature = fromBase64Url(authorization);
3218
+ return signature !== null && ed25519Verify(signature, commandSigningBytes(unsigned), senderEd25519Pub);
3219
+ }
3220
+
3221
+ /**
3222
+ * Computer side. Run AFTER the ledger said the command_id is new (a duplicate is answered from the ledger and never
3223
+ * opened again). Refuses, in this order: shape, version, channel, devices, signature, time, replay, tag, payload.
3224
+ */
3225
+ export function openCommand(
3226
+ channel ,
3227
+ value ,
3228
+ now ,
3229
+ ) {
3230
+ if (channel.role !== "computer") return refuse("wrong_device", "only a computer receives commands");
3231
+ const shaped = validateCommandEnvelope(value);
3232
+ if (!shaped.ok) return shaped;
3233
+ const e = shaped.value;
3234
+ if (e.protocol_version !== channel.protocol_version) return refuse("downgrade", "$command.protocol_version: not the channel's");
3235
+ const box = e.payload_ciphertext;
3236
+ if (box.channel_id !== channel.channel_id) return refuse("wrong_channel", "$command.payload_ciphertext.channel_id");
3237
+ if (e.device_id !== channel.self_device_id || e.sender_device_id !== channel.peer_device_id) return refuse("wrong_device", "$command");
3238
+ if (!verifyCommandAuthorization(e, fromBase64Url(channel.peer_ed25519_pub) )) return refuse("signature", "$command.authorization");
3239
+ if (e.issued_at > now + CLOCK_SKEW_MS) return refuse("not_yet_valid", "$command.issued_at");
3240
+ if (now > e.expires_at + CLOCK_SKEW_MS) return refuse("expired", "$command.expires_at");
3241
+ const replay = checkReplay(channel.receive, box.counter);
3242
+ if (replay !== "fresh") return refuse(replay, "$command.payload_ciphertext.counter");
3243
+ const { payload_ciphertext: _box, authorization: _sig, ...draft } = e;
3244
+ const opened = open(channel.receive_key, commandAad(draft, box.channel_id, box.counter, box.nonce), box.nonce, box.ciphertext);
3245
+ if (!opened.ok) return opened;
3246
+ const payload = validateCommandPayload(e.type, opened.value);
3247
+ if (!payload.ok) return refuse("payload", payload.detail);
3248
+ if (commandScope(e.type) === "device" && e.session_id !== null) return refuse("shape", "$command.session_id");
3249
+ return accept({ envelope: e, payload: payload.value, channel: { ...channel, receive: markSeen(channel.receive, box.counter) } });
3250
+ }
3251
+
3252
+ /** Computer side: seal one event for one phone's channel. */
3253
+ export function sealEvent (
3254
+ channel ,
3255
+ draft ,
3256
+ body ,
3257
+ random ,
3258
+ ) {
3259
+ if (channel.role !== "computer") return refuse("wrong_device", "only a computer sends device events");
3260
+ if (draft.device_id !== channel.self_device_id) return refuse("wrong_device", "$event.device_id");
3261
+ if (draft.protocol_version !== channel.protocol_version) return refuse("version", "$event.protocol_version");
3262
+ const valid = validateEventBody(draft.type, body);
3263
+ if (!valid.ok) return valid;
3264
+ const counter = nextCounter(channel);
3265
+ if (!counter.ok) return counter;
3266
+ const box = seal(channel.send_key, (nonce) => eventAad(draft, channel.channel_id, counter.value, nonce), body, random);
3267
+ if (!box) return refuse("payload", "$body: too large");
3268
+ const envelope = { ...draft, body_ciphertext: { channel_id: channel.channel_id, counter: counter.value, ...box } };
3269
+ const shaped = validateEventEnvelope(envelope);
3270
+ if (!shaped.ok) return shaped;
3271
+ return accept({ envelope, channel: { ...channel, send_counter: counter.value } });
3272
+ }
3273
+
3274
+ /** Phone side. Ordering by event_seq is the caller's next step (ledger.ts, receiveSeq). */
3275
+ export function openEvent(
3276
+ channel ,
3277
+ value ,
3278
+ ) {
3279
+ if (channel.role !== "phone") return refuse("wrong_device", "only a phone receives device events");
3280
+ const shaped = validateEventEnvelope(value);
3281
+ if (!shaped.ok) return shaped;
3282
+ const e = shaped.value;
3283
+ if (e.protocol_version !== channel.protocol_version) return refuse("downgrade", "$event.protocol_version: not the channel's");
3284
+ const box = e.body_ciphertext;
3285
+ if (box.channel_id !== channel.channel_id) return refuse("wrong_channel", "$event.body_ciphertext.channel_id");
3286
+ if (e.device_id !== channel.peer_device_id) return refuse("wrong_device", "$event.device_id");
3287
+ const replay = checkReplay(channel.receive, box.counter);
3288
+ if (replay !== "fresh") return refuse(replay, "$event.body_ciphertext.counter");
3289
+ const { body_ciphertext: _box, ...draft } = e;
3290
+ const opened = open(channel.receive_key, eventAad(draft, box.channel_id, box.counter, box.nonce), box.nonce, box.ciphertext);
3291
+ if (!opened.ok) return opened;
3292
+ const body = validateEventBody(e.type, opened.value);
3293
+ if (!body.ok) return refuse("payload", body.detail);
3294
+ return accept({ envelope: e, body: body.value, channel: { ...channel, receive: markSeen(channel.receive, box.counter) } });
3295
+ }
3296
+
3297
+ /** Re-key (a new handshake, a new channel id) after a week or 2^31 messages in one direction. */
3298
+ export const needsRekey = (channel , now ) =>
3299
+ now - channel.established_at > CHANNEL_MAX_AGE_MS || channel.send_counter >= CHANNEL_MAX_MESSAGES;
3300
+
3301
+ /** A channel as JSON for the device's secure store. The keys are secrets: store it where the device keys live. */
3302
+
3303
+ export const exportChannel = (channel ) => ({
3304
+ ...channel,
3305
+ send_key: toBase64Url(channel.send_key),
3306
+ receive_key: toBase64Url(channel.receive_key),
3307
+ });
3308
+
3309
+ export function importChannel(stored ) {
3310
+ const send = fromBase64Url(stored.send_key);
3311
+ const receive = fromBase64Url(stored.receive_key);
3312
+ if (send?.length !== 32 || receive?.length !== 32) return null;
3313
+ return { ...stored, send_key: send, receive_key: receive };
3314
+ }
3315
+
3316
+ // ---- packages/remote-protocol/src/crypto/pairing.ts
3317
+ /**
3318
+ * PAIRING BY SCANNING THE COMPUTER'S SCREEN (owner, 2026-11-07). `worktrust remote enable` and `worktrust remote pair` draw
3319
+ * a QR code in the terminal; the WorkTrust app scans it. The QR holds one link:
3320
+ *
3321
+ * https://app.worktrust.io/remote/pair#v=1&g=<gateway origin>&d=<computer device id>&k=<Ed25519 pub>&x=<X25519 pub>
3322
+ * &s=<32-byte one-time secret>&e=<expiry, unix seconds>
3323
+ *
3324
+ * (worktrust://remote/pair#... is the same invite for a phone without the app link). Everything sits in the FRAGMENT, which
3325
+ * a browser never sends: no server, not app.worktrust.io and not the gateway, ever receives the secret. The invite lives five
3326
+ * minutes and is spent by its first use; the computer refuses a second.
3327
+ *
3328
+ * WHY IT CONFIRMS THE PHONE. Whoever scanned the QR saw the computer's screen: that is the keyboard confirmation, done by
3329
+ * the camera. The secret is mixed into the first handshake as a pre-shared key (`pairingPsk`, HKDF over "worktrust-remote-
3330
+ * pair-v1"): the hello carries a proof only a holder of the secret can make, the welcome answers with one, and the channel
3331
+ * keys include it, so a relay cannot stand in the middle of the first contact even though both bindings are checked too.
3332
+ * The phone pins the computer's keys from the QR itself (k, x). The computer still checks that the phone's binding names
3333
+ * the same account as its own.
3334
+ *
3335
+ * THE TYPED FALLBACK, for a phone that cannot scan: an 8-character code (Crockford base32, 40 random bits) that only names
3336
+ * the computer to the gateway. It carries no secret, so a phone that pairs by code stays pending until the person confirms
3337
+ * its fingerprint at the computer's keyboard (`worktrust remote phones`).
3338
+ */
3339
+
3340
+ export const PAIRING_INVITE_VERSION = 1;
3341
+ export const PAIRING_INVITE_LIFETIME_S = 300;
3342
+ export const PAIRING_LINK_BASE = "https://app.worktrust.io/remote/pair";
3343
+ export const PAIRING_APP_LINK_BASE = "worktrust://remote/pair";
3344
+
3345
+ export const PAIRING_INVITE_SPEC = object({
3346
+ v: int(1, 1),
3347
+ /** The gateway's origin, wss://host[:port] (ws:// only on this computer's loopback, for the dev relay). */
3348
+ g: text(256, 8),
3349
+ d: id("dev"),
3350
+ k: b64({ exact: 32 }),
3351
+ x: b64({ exact: 32 }),
3352
+ s: b64({ exact: 32 }),
3353
+ e: int(0),
3354
+ });
3355
+
3356
+ const ORDER = ["v", "g", "d", "k", "x", "s", "e"] ;
3357
+ const LOOPBACK = new Set(["127.0.0.1", "[::1]", "localhost"]);
3358
+
3359
+ /** wss://host[:port] with nothing after it; ws:// only for a loopback host. */
3360
+ export function isGatewayOrigin(value ) {
3361
+ // No URL class here: the package runs on Hermes too. Lower-case host names only, a port at most, nothing after.
3362
+ const m = /^(wss?):\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[::1\])(?::([1-9][0-9]{0,4}))?$/.exec(value);
3363
+ if (!m || (m[3] !== undefined && Number(m[3]) > 65535)) return false;
3364
+ return m[1] === "wss" || LOOPBACK.has(m[2] );
3365
+ }
3366
+
3367
+ function checkInvite(value , nowMs ) {
3368
+ const shaped = validate(PAIRING_INVITE_SPEC, value, "$invite");
3369
+ if (!shaped.ok) return shaped;
3370
+ const invite = shaped.value;
3371
+ if (!isGatewayOrigin(invite.g)) return refuse("shape", "$invite.g: not a gateway origin");
3372
+ if (invite.e * 1000 + CLOCK_SKEW_MS < nowMs) return refuse("expired", "$invite.e");
3373
+ if (invite.e * 1000 > nowMs + PAIRING_INVITE_LIFETIME_S * 1000 + CLOCK_SKEW_MS) return refuse("lifetime", "$invite.e: lives too long");
3374
+ return accept(invite);
3375
+ }
3376
+
3377
+ /** The computer: a fresh invite for its own keys, five minutes. */
3378
+ export function createPairingInvite(input ) {
3379
+ const invite = { v: PAIRING_INVITE_VERSION, g: input.gateway, d: input.deviceId, k: input.ed25519_pub, x: input.x25519_pub, s: toBase64Url(input.random(32)), e: Math.floor(input.nowMs / 1000) + PAIRING_INVITE_LIFETIME_S };
3380
+ const checked = checkInvite(invite, input.nowMs);
3381
+ if (!checked.ok) throw new TypeError(checked.detail);
3382
+ return checked.value;
3383
+ }
3384
+
3385
+ export function encodePairingInvite(invite , base = PAIRING_LINK_BASE) {
3386
+ if (base !== PAIRING_LINK_BASE && base !== PAIRING_APP_LINK_BASE) throw new TypeError("not a WorkTrust pairing link");
3387
+ const shaped = validate(PAIRING_INVITE_SPEC, invite, "$invite");
3388
+ if (!shaped.ok || !isGatewayOrigin(invite.g)) throw new TypeError(shaped.ok ? "$invite.g: not a gateway origin" : shaped.detail);
3389
+ return `${base}#${ORDER.map((key) => `${key}=${encodeURIComponent(String(invite[key]))}`).join("&")}`;
3390
+ }
3391
+
3392
+ /** The phone: a scanned link, or a refusal. Only the two bases, no query string, exactly the seven keys once each. */
3393
+ export function decodePairingInvite(link , nowMs ) {
3394
+ if (typeof link !== "string" || link.length > 1024) return refuse("shape", "$link");
3395
+ const hash = link.indexOf("#");
3396
+ if (hash < 0) return refuse("shape", "$link: no fragment");
3397
+ const base = link.slice(0, hash);
3398
+ if (base !== PAIRING_LINK_BASE && base !== PAIRING_APP_LINK_BASE) return refuse("shape", "$link: not a WorkTrust pairing link");
3399
+ const raw = {};
3400
+ for (const part of link.slice(hash + 1).split("&")) {
3401
+ const eq = part.indexOf("=");
3402
+ if (eq < 1) return refuse("shape", "$link: a malformed pair");
3403
+ const key = part.slice(0, eq);
3404
+ if (!(ORDER ).includes(key) || Object.hasOwn(raw, key)) return refuse("shape", "$link: an unknown or repeated key");
3405
+ try { raw[key] = decodeURIComponent(part.slice(eq + 1)); } catch { return refuse("shape", "$link: encoding"); }
3406
+ }
3407
+ if (!/^(0|[1-9][0-9]{0,15})$/.test(raw.v ?? "") || !/^(0|[1-9][0-9]{0,15})$/.test(raw.e ?? "")) return refuse("shape", "$link: v and e are integers");
3408
+ return checkInvite({ ...raw, v: Number(raw.v), e: Number(raw.e) }, nowMs);
3409
+ }
3410
+
3411
+ const PSK_INFO = utf8Encode("worktrust-remote-pair-v1");
3412
+ const PROOF = { hello: utf8Encode("worktrust-remote/v1/pair-proof/hello\n"), welcome: utf8Encode("worktrust-remote/v1/pair-proof/welcome\n") };
3413
+
3414
+ /** The pre-shared key both ends derive from the invite's secret. */
3415
+ export function pairingPsk(secret ) {
3416
+ const bytes = typeof secret === "string" ? fromBase64Url(secret) : secret;
3417
+ if (bytes?.length !== 32) throw new TypeError("a pairing secret is 32 bytes");
3418
+ return hkdfSha256(bytes, new Uint8Array(0), PSK_INFO, 32);
3419
+ }
3420
+
3421
+ /** A proof over a handshake message's other fields (its signature and its own proof left out). */
3422
+ export function pairProof(psk , role , unsigned ) {
3423
+ return toBase64Url(hkdfSha256(psk, sha256(concatBytes(PROOF[role], canonicalBytes(unsigned))), PROOF[role], 32));
3424
+ }
3425
+ export function pairProofValid(psk , role , unsigned , proof ) {
3426
+ const theirs = fromBase64Url(proof);
3427
+ const ours = fromBase64Url(pairProof(psk, role, unsigned));
3428
+ return theirs !== null && ours !== null && equalBytes(theirs, ours);
3429
+ }
3430
+
3431
+ const CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3432
+ /** The typed fallback: 8 characters, 40 random bits. It names the computer to the gateway and proves nothing. */
3433
+ export function generatePairingCode(random ) {
3434
+ let acc = 0;
3435
+ for (const b of random(5)) acc = acc * 256 + b; // 40 bits: exact in a double
3436
+ let out = "";
3437
+ for (let i = 7; i >= 0; i -= 1) out += CODE_ALPHABET[Math.floor(acc / 32 ** i) % 32] ;
3438
+ return out;
3439
+ }
3440
+ export const isPairingCode = (value ) => typeof value === "string" && /^[0-9A-HJKMNP-TV-Z]{8}$/.test(value);
3441
+
3442
+ // ---- packages/remote-protocol/src/crypto/handshake.ts
3443
+ /**
3444
+ * THE HANDSHAKE: a phone and a computer agree two keys the relay cannot know.
3445
+ *
3446
+ * phone -> computer hello { versions, channel_id, ids, phone binding, ephemeral e_p, issued_at, signature }
3447
+ * computer -> phone welcome { chosen version, versions, channel_id, ids, computer binding, ephemeral e_c,
3448
+ * hello_hash, issued_at, signature }
3449
+ *
3450
+ * Each side verifies the other's binding against the PINNED issuer keys (same account, the right kind, this device id,
3451
+ * not revoked) and the message's Ed25519 signature under the bound key. The computer also requires the phone to be
3452
+ * CONFIRMED at its keyboard (`worktrust remote phones`, the phone's fingerprint shown on both screens): the issuer
3453
+ * alone cannot add a controller. The phone checks the computer's fingerprint against the one it pinned when paired.
3454
+ *
3455
+ * KEYS (Noise KK's pattern, with signatures on top): ikm = X25519(e_p, e_c) || X25519(e_p, S_c) || X25519(S_p, e_c).
3456
+ * The ephemeral-ephemeral term gives forward secrecy (a key stolen later opens no earlier channel); the two static
3457
+ * terms bind the channel to both bound keys. HKDF-SHA-256 with the transcript hash as salt and the version, channel
3458
+ * and both device ids as info yields two 32-byte keys, one per direction.
3459
+ *
3460
+ * PAIRING (crypto/pairing.ts). In the first contact after a scanned QR invite the hello carries `pair_proof` and the
3461
+ * welcome answers with one; both are made with the invite's pre-shared key, which is also appended to the key material
3462
+ * (ikm || psk). A phone that proves the secret needs no keyboard confirmation: it saw the computer's screen. A hello
3463
+ * without a proof is the ordinary path and needs a confirmed phone.
3464
+ *
3465
+ * DOWNGRADE. Both version lists are signed. The computer must choose the highest version both list; the phone checks
3466
+ * that it did. A relay that strikes a version out breaks a signature.
3467
+ */
3468
+
3469
+ const D = {
3470
+ hello: utf8Encode("worktrust-remote/v1/hello\n"),
3471
+ welcome: utf8Encode("worktrust-remote/v1/welcome\n"),
3472
+ helloHash: utf8Encode("worktrust-remote/v1/hello-hash\n"),
3473
+ transcript: utf8Encode("worktrust-remote/v1/transcript\n"),
3474
+ keys: "worktrust-remote/v1/channel-keys\n",
3475
+ };
3476
+
3477
+ /** This end: its secret keys, its own binding token and that binding's verified claims. */
3478
+
3479
+ const sorted = (versions ) => [...new Set(versions)].sort((a, b) => b - a);
3480
+ const highestCommon = (a , b ) => sorted(a.filter((v) => b.includes(v)))[0] ?? null;
3481
+ const helloHash = (hello ) => sha256(concatBytes(D.helloHash, canonicalBytes(hello)));
3482
+ const sign = (domain , body , secret ) => toBase64Url(ed25519Sign(concatBytes(domain, canonicalBytes(body)), secret));
3483
+ const verifySig = (domain , body , signature , publicKey ) => {
3484
+ const sig = fromBase64Url(signature);
3485
+ return sig !== null && ed25519Verify(sig, concatBytes(domain, canonicalBytes(body)), publicKey);
3486
+ };
3487
+
3488
+ export function createHello(input
3489
+
3490
+ ) {
3491
+ if (input.self.claims.kind !== "phone") throw new TypeError("a phone opens the handshake");
3492
+ const versions = sorted(input.versions ?? SUPPORTED_PROTOCOL_VERSIONS);
3493
+ const ephemeralSecret = input.random(KEY_BYTES);
3494
+ const unsigned = {
3495
+ protocol_version: versions[0] ,
3496
+ versions,
3497
+ channel_id: mintId("chn", input.random),
3498
+ from_device_id: input.self.claims.device_id,
3499
+ to_device_id: input.peerDeviceId,
3500
+ binding: input.self.binding,
3501
+ ephemeral_pub: toBase64Url(x25519PublicKey(ephemeralSecret)),
3502
+ issued_at: input.now,
3503
+ };
3504
+ const proven = input.psk ? { ...unsigned, pair_proof: pairProof(input.psk, "hello", unsigned) } : unsigned;
3505
+ const hello = { ...proven, signature: sign(D.hello, proven, input.self.secret.ed25519) };
3506
+ return { hello, ephemeralSecret, self: input.self, ...(input.psk ? { psk: input.psk } : {}) };
3507
+ }
3508
+
3509
+ /**
3510
+ * Verify a hello without answering it: the phone's binding, its signature, its age. The computer uses this to list a
3511
+ * PENDING phone with its fingerprint for the person to confirm at the keyboard.
3512
+ */
3513
+ export function inspectHello(value , self , v ) {
3514
+ const shaped = validate(HANDSHAKE_HELLO_SPEC, value, "$hello");
3515
+ if (!shaped.ok) return shaped;
3516
+ const hello = shaped.value;
3517
+ if (hello.to_device_id !== self.claims.device_id) return refuse("wrong_device", "$hello.to_device_id");
3518
+ if (hello.issued_at > v.now + MAX_HANDSHAKE_AGE_MS) return refuse("not_yet_valid", "$hello.issued_at");
3519
+ if (v.now - hello.issued_at > MAX_HANDSHAKE_AGE_MS) return refuse("expired", "$hello.issued_at");
3520
+ const phone = verifyBinding(hello.binding, { ...v, kind: "phone", deviceId: hello.from_device_id, sub: self.claims.sub });
3521
+ if (!phone.ok) return phone;
3522
+ const { signature, ...unsigned } = hello;
3523
+ if (!verifySig(D.hello, unsigned, signature, bindingSigningKey(phone.value))) return refuse("signature", "$hello.signature");
3524
+ return accept({ hello, phone: phone.value, fingerprint: bindingFingerprint(phone.value) });
3525
+ }
3526
+
3527
+ function deriveKeys(ikm , hello , welcome ) {
3528
+ const salt = sha256(concatBytes(D.transcript, canonicalBytes(hello), canonicalBytes(welcome)));
3529
+ const info = utf8Encode(
3530
+ D.keys +
3531
+ JSON.stringify([welcome.protocol_version, hello.channel_id, hello.from_device_id, hello.to_device_id]),
3532
+ );
3533
+ const okm = hkdfSha256(ikm, salt, info, 64);
3534
+ return { p2c: okm.slice(0, 32), c2p: okm.slice(32, 64) };
3535
+ }
3536
+
3537
+ export function acceptHello(input
3538
+
3539
+ ) {
3540
+ if (input.self.claims.kind !== "computer") return refuse("wrong_device", "a computer answers the handshake");
3541
+ const inspected = inspectHello(input.hello, input.self, input);
3542
+ if (!inspected.ok) return inspected;
3543
+ const { hello, phone, fingerprint } = inspected.value;
3544
+ if (input.knownChannels.has(hello.channel_id)) return refuse("channel_known", "$hello.channel_id");
3545
+ const { signature: _sig, pair_proof: proof, ...withoutProof } = hello;
3546
+ const paired = proof !== undefined;
3547
+ if (paired && (!input.psk || !pairProofValid(input.psk, "hello", withoutProof, proof))) return refuse("not_confirmed", "$hello.pair_proof: no invite of this computer");
3548
+ if (!paired && !input.confirmedPhones.has(fingerprint)) return refuse("not_confirmed", "$hello: phone not confirmed at this computer");
3549
+ if (hello.protocol_version !== sorted(hello.versions)[0]) return refuse("downgrade", "$hello.protocol_version: not its own highest");
3550
+ const ours = sorted(input.versions ?? SUPPORTED_PROTOCOL_VERSIONS);
3551
+ const chosen = highestCommon(hello.versions, ours);
3552
+ if (chosen === null) return refuse("version", "$hello.versions: none in common");
3553
+ if (chosen < MIN_PROTOCOL_VERSION) return refuse("downgrade", "$hello.versions: below the minimum");
3554
+ const ePhone = fromBase64Url(hello.ephemeral_pub) ;
3555
+ const eSecret = input.random(KEY_BYTES);
3556
+ const ee = x25519Shared(eSecret, ePhone);
3557
+ const es = x25519Shared(input.self.secret.x25519, ePhone);
3558
+ const se = x25519Shared(eSecret, bindingAgreementKey(phone));
3559
+ if (!ee || !es || !se) return refuse("key_agreement", "$hello: a low-order key");
3560
+ const unsigned = {
3561
+ protocol_version: chosen,
3562
+ versions: ours,
3563
+ channel_id: hello.channel_id,
3564
+ from_device_id: input.self.claims.device_id,
3565
+ to_device_id: hello.from_device_id,
3566
+ binding: input.self.binding,
3567
+ ephemeral_pub: toBase64Url(x25519PublicKey(eSecret)),
3568
+ hello_hash: toBase64Url(helloHash(hello)),
3569
+ issued_at: input.now,
3570
+ };
3571
+ const proven = paired ? { ...unsigned, pair_proof: pairProof(input.psk , "welcome", unsigned) } : unsigned;
3572
+ const welcome = { ...proven, signature: sign(D.welcome, proven, input.self.secret.ed25519) };
3573
+ const keys = deriveKeys(paired ? concatBytes(ee, es, se, input.psk ) : concatBytes(ee, es, se), hello, welcome);
3574
+ const channel = {
3575
+ channel_id: hello.channel_id,
3576
+ protocol_version: chosen,
3577
+ role: "computer",
3578
+ self_device_id: input.self.claims.device_id,
3579
+ peer_device_id: phone.device_id,
3580
+ peer_ed25519_pub: phone.ed25519_pub,
3581
+ send_key: keys.c2p,
3582
+ receive_key: keys.p2c,
3583
+ send_counter: 0,
3584
+ receive: { highest: 0, seen: [] },
3585
+ established_at: input.now,
3586
+ peer_fingerprint: fingerprint,
3587
+ };
3588
+ return accept({ welcome, channel, phone, paired });
3589
+ }
3590
+
3591
+ export function completeHandshake(input
3592
+
3593
+ ) {
3594
+ const shaped = validate(HANDSHAKE_WELCOME_SPEC, input.welcome, "$welcome");
3595
+ if (!shaped.ok) return shaped;
3596
+ const welcome = shaped.value;
3597
+ const { hello, self, ephemeralSecret, psk } = input.pending;
3598
+ if (welcome.channel_id !== hello.channel_id) return refuse("wrong_channel", "$welcome.channel_id");
3599
+ if (welcome.from_device_id !== hello.to_device_id || welcome.to_device_id !== hello.from_device_id) return refuse("wrong_device", "$welcome");
3600
+ if (welcome.hello_hash !== toBase64Url(helloHash(hello))) return refuse("signature", "$welcome.hello_hash: not our hello");
3601
+ if (Math.abs(input.now - welcome.issued_at) > MAX_HANDSHAKE_AGE_MS) return refuse("expired", "$welcome.issued_at");
3602
+ const computer = verifyBinding(welcome.binding, { ...input, kind: "computer", deviceId: welcome.from_device_id, sub: self.claims.sub });
3603
+ if (!computer.ok) return computer;
3604
+ const { signature, ...unsigned } = welcome;
3605
+ if (!verifySig(D.welcome, unsigned, signature, bindingSigningKey(computer.value))) return refuse("signature", "$welcome.signature");
3606
+ const { pair_proof: proof, ...withoutProof } = unsigned;
3607
+ if ((psk !== undefined) !== (proof !== undefined)) return refuse("not_confirmed", "$welcome.pair_proof: the pairing was not answered");
3608
+ if (psk && !pairProofValid(psk, "welcome", withoutProof, proof )) return refuse("not_confirmed", "$welcome.pair_proof");
3609
+ const fingerprint = bindingFingerprint(computer.value);
3610
+ if (input.pinnedFingerprint !== null && input.pinnedFingerprint !== fingerprint) return refuse("not_confirmed", "$welcome: the computer's key changed");
3611
+ const expected = highestCommon(hello.versions, welcome.versions);
3612
+ if (expected === null || welcome.protocol_version !== expected) return refuse("downgrade", "$welcome.protocol_version: not the highest common");
3613
+ if (expected < MIN_PROTOCOL_VERSION) return refuse("downgrade", "$welcome.protocol_version: below the minimum");
3614
+ const eComputer = fromBase64Url(welcome.ephemeral_pub) ;
3615
+ const ee = x25519Shared(ephemeralSecret, eComputer);
3616
+ const es = x25519Shared(ephemeralSecret, bindingAgreementKey(computer.value));
3617
+ const se = x25519Shared(self.secret.x25519, eComputer);
3618
+ if (!ee || !es || !se) return refuse("key_agreement", "$welcome: a low-order key");
3619
+ const keys = deriveKeys(psk ? concatBytes(ee, es, se, psk) : concatBytes(ee, es, se), hello, welcome);
3620
+ return accept({
3621
+ computer: computer.value,
3622
+ channel: {
3623
+ channel_id: hello.channel_id,
3624
+ protocol_version: welcome.protocol_version,
3625
+ role: "phone",
3626
+ self_device_id: self.claims.device_id,
3627
+ peer_device_id: computer.value.device_id,
3628
+ peer_ed25519_pub: computer.value.ed25519_pub,
3629
+ send_key: keys.p2c,
3630
+ receive_key: keys.c2p,
3631
+ send_counter: 0,
3632
+ receive: { highest: 0, seen: [] },
3633
+ established_at: input.now,
3634
+ peer_fingerprint: fingerprint,
3635
+ },
3636
+ });
3637
+ }
3638
+
3639
+ // ---- packages/remote-protocol/src/crypto/revocation.ts
3640
+ /**
3641
+ * THE REVOCATION LIST: how a revocation in the Passport app reaches the gateway at once, without the gateway holding a
3642
+ * Passport credential and without the Passport holding a socket to the gateway (2026-11-07, docs/remote-agents/ISSUER.md
3643
+ * §7). The Passport app publishes ONE signed document (GET /api/remote/revocations); the gateway fetches it every few
3644
+ * seconds, verifies it against the issuer keys pinned in its own configuration, and cuts every live socket and channel of
3645
+ * a device it names. A phone and a computer may read the same list.
3646
+ *
3647
+ * It names nothing. An entry is a 16-byte hash of the revoked id under a fixed domain, never the id: the list is public,
3648
+ * and a reader learns that some device was revoked only if it already knows that device's id.
3649
+ *
3650
+ * device the device id: every binding of that device is refused, whenever issued.
3651
+ * account the account's opaque `usr_` reference: every binding ISSUED AT OR BEFORE `at` is refused ("revoke all remote
3652
+ * keys"); a device the person pairs afterwards is a new binding and works.
3653
+ *
3654
+ * Signed as `{ ...claims, kid, signature }`, the signature an Ed25519 by an issuer key over
3655
+ * "worktrust-remote/v1/revocations\n" || canonicalJson(claims). Not a JWS: a list can outgrow a compact token. It lives
3656
+ * at most fifteen minutes; a reader keeps the newest valid list (a lower `iat` never replaces a higher one, so an old list
3657
+ * cannot be replayed to un-revoke), and a reader whose list has expired fails closed (the gateway admits nobody new).
3658
+ */
3659
+
3660
+ export const REVOCATION_KINDS = ["device", "account"] ;
3661
+
3662
+ export const MAX_REVOCATION_ENTRIES = 50_000;
3663
+ export const MAX_REVOCATION_LIST_LIFETIME_S = 900;
3664
+
3665
+ export const REVOCATION_ENTRY_SPEC = object({ k: oneOf(REVOCATION_KINDS), h: b64({ exact: 16 }), at: int(0) });
3666
+ export const REVOCATION_LIST_SPEC = object({
3667
+ v: int(1, 1),
3668
+ iss: oneOf([PASSPORT_ISSUER]),
3669
+ aud: oneOf([GATEWAY_AUDIENCE]),
3670
+ iat: int(0),
3671
+ exp: int(0),
3672
+ entries: list(REVOCATION_ENTRY_SPEC, MAX_REVOCATION_ENTRIES),
3673
+ });
3674
+
3675
+ const REVOCATION_LIST_DOMAIN = utf8Encode("worktrust-remote/v1/revocations\n");
3676
+ const REVOCATION_ENTRY_DOMAIN = "worktrust-remote/v1/revoked\n";
3677
+ const REVOCATION_KID = /^[A-Za-z0-9._-]{1,64}$/;
3678
+
3679
+ /** The hash an entry carries for a device id or an account reference. */
3680
+ export const revocationHash = (kind , value ) =>
3681
+ toBase64Url(sha256(utf8Encode(`${REVOCATION_ENTRY_DOMAIN}${kind}\n${value}`)).subarray(0, 16));
3682
+
3683
+ export const revocationListBytes = (claims ) => concatBytes(REVOCATION_LIST_DOMAIN, canonicalBytes(claims));
3684
+
3685
+ /** For the Passport app: validate, then sign. */
3686
+ export function signRevocationList(claims , issuerSecret , kid ) {
3687
+ const checked = validate(REVOCATION_LIST_SPEC, claims, "$revocations");
3688
+ if (!checked.ok) throw new TypeError(checked.detail);
3689
+ if (claims.exp <= claims.iat || claims.exp - claims.iat > MAX_REVOCATION_LIST_LIFETIME_S) throw new RangeError("revocation list lifetime");
3690
+ if (!REVOCATION_KID.test(kid)) throw new TypeError("kid");
3691
+ return { ...claims, kid, signature: toBase64Url(ed25519Sign(revocationListBytes(claims), issuerSecret)) };
3692
+ }
3693
+
3694
+ export function verifyRevocationList(doc , expect ) {
3695
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return refuse("shape", "$revocations: not an object");
3696
+ const { kid, signature, ...claims } = doc ;
3697
+ if (typeof kid !== "string" || !REVOCATION_KID.test(kid) || !Object.hasOwn(expect.issuerKeys, kid)) return refuse("unknown_key", "$revocations.kid");
3698
+ const sig = typeof signature === "string" ? fromBase64Url(signature) : null;
3699
+ const shaped = validate(REVOCATION_LIST_SPEC, claims, "$revocations");
3700
+ if (!shaped.ok) return shaped;
3701
+ if (!sig || !ed25519Verify(sig, revocationListBytes(shaped.value), expect.issuerKeys[kid] )) return refuse("signature", "$revocations.signature");
3702
+ const l = shaped.value;
3703
+ if (l.exp <= l.iat || l.exp - l.iat > MAX_REVOCATION_LIST_LIFETIME_S) return refuse("lifetime", "$revocations: lives too long");
3704
+ if (l.iat * 1000 > expect.now + CLOCK_SKEW_MS) return refuse("not_yet_valid", "$revocations.iat");
3705
+ if (l.exp * 1000 + CLOCK_SKEW_MS < expect.now) return refuse("expired", "$revocations.exp");
3706
+ return accept(l);
3707
+ }
3708
+
3709
+ export function compileRevocations(l ) {
3710
+ const devices = new Set ();
3711
+ const accounts = new Map ();
3712
+ for (const e of l.entries) {
3713
+ if (e.k === "device") devices.add(e.h);
3714
+ else accounts.set(e.h, Math.max(accounts.get(e.h) ?? 0, e.at));
3715
+ }
3716
+ return { iat: l.iat, exp: l.exp, devices, accounts };
3717
+ }
3718
+
3719
+ /** True when the list revokes this binding: its device, or its account at or after the binding was issued. */
3720
+ export function isBindingRevoked(list , binding ) {
3721
+ if (list.devices.has(revocationHash("device", binding.device_id))) return true;
3722
+ const cutoff = list.accounts.get(revocationHash("account", binding.sub));
3723
+ return cutoff !== undefined && binding.iat <= cutoff;
3724
+ }
3725
+
3726
+ // ---- packages/remote-protocol/src/crypto/issuer-requests.ts
3727
+ /**
3728
+ * WHAT A DEVICE SIGNS WHEN IT ASKS THE ISSUER FOR SOMETHING (docs/remote-agents/ISSUER.md). One writer and one reader
3729
+ * for each request, here, so the CLI, the phone, the Passport app's issuer routes and the tests sign and check the same
3730
+ * bytes. Every signature is by the device's REMOTE Ed25519 key and domain-separated, so a signature made for one request
3731
+ * opens no other, and none is a measurement signature.
3732
+ *
3733
+ * pair-request the new key's proof that the client holds it (POST /api/remote/pair)
3734
+ * phone-bind a phone's proof, under the app's own session (POST /api/remote/phone)
3735
+ * renew a fresh binding for the same keys (POST /api/remote/renew)
3736
+ * assertion-request a five-minute gateway assertion (POST /api/remote/assertion)
3737
+ * self-revoke a device ends its own binding (POST /api/remote/revoke), e.g. the app's sign-out
3738
+ * relay-auth the answer to the gateway's challenge (gateway.ts), bound to that gateway's origin
3739
+ */
3740
+
3741
+ const requestDomain = (name ) => utf8Encode(`worktrust-remote/v1/${name}\n`);
3742
+ const REQ_PAIR = requestDomain("pair-request");
3743
+ const REQ_PHONE = requestDomain("phone-bind");
3744
+ const REQ_RENEW = requestDomain("renew");
3745
+ const REQ_ASSERT = requestDomain("assertion-request");
3746
+ const REQ_RELAY = requestDomain("relay-auth");
3747
+ const REQ_SELF_REVOKE = requestDomain("self-revoke");
3748
+
3749
+ export const pairRequestBytes = (b ) =>
3750
+ concatBytes(REQ_PAIR, canonicalBytes({ code_challenge: b.code_challenge, ed25519_pub: b.ed25519_pub, kind: b.kind, x25519_pub: b.x25519_pub }));
3751
+ export const phoneBindBytes = (b ) =>
3752
+ concatBytes(REQ_PHONE, canonicalBytes({ ed25519_pub: b.ed25519_pub, iat: b.iat, kind: "phone", x25519_pub: b.x25519_pub }));
3753
+ export const renewRequestBytes = (b ) =>
3754
+ concatBytes(REQ_RENEW, canonicalBytes({ binding_jti: b.binding_jti, device_id: b.device_id, iat: b.iat }));
3755
+ export const assertionRequestBytes = (b ) =>
3756
+ concatBytes(REQ_ASSERT, canonicalBytes({ device_id: b.device_id, iat: b.iat, nonce: b.nonce }));
3757
+ export const selfRevokeBytes = (b ) =>
3758
+ concatBytes(REQ_SELF_REVOKE, canonicalBytes({ device_id: b.device_id, iat: b.iat }));
3759
+ export const relayAuthBytes = (b ) =>
3760
+ concatBytes(REQ_RELAY, canonicalBytes({ device_id: b.device_id, nonce: b.nonce, origin: b.origin }));
3761
+
3762
+ /** A device signs one of the requests above with its remote Ed25519 secret: base64url, 64 bytes. */
3763
+ export const deviceSign = (bytes , secret ) => toBase64Url(ed25519Sign(bytes, secret));
3764
+
3765
+ /** A device's signature (base64url, 64 bytes) under its bound public key (base64url, 32 bytes). False on any malformed part. */
3766
+ export function deviceSignatureValid(bytes , signature , publicKey ) {
3767
+ if (typeof signature !== "string" || typeof publicKey !== "string") return false;
3768
+ const sig = fromBase64Url(signature), pub = fromBase64Url(publicKey);
3769
+ if (sig?.length !== SIGNATURE_BYTES || pub?.length !== KEY_BYTES) return false;
3770
+ return ed25519Verify(sig, bytes, pub);
3771
+ }
3772
+
3773
+ /** A request's own time (milliseconds) within a minute of the issuer's clock. */
3774
+ export const requestTimeValid = (iat , nowMs ) =>
3775
+ typeof iat === "number" && Number.isSafeInteger(iat) && Math.abs(nowMs - iat) <= CLOCK_SKEW_MS;
3776
+
3777
+ // ---- packages/remote-protocol/src/gateway.ts
3778
+ /**
3779
+ * THE GATEWAY'S OWN FRAMES (2026-11-07, docs/remote-agents/GATEWAY.md). Every WebSocket message between a device and the
3780
+ * Remote Gateway (apps/worktrust/remote) is one JSON object with a `frame` word and the fields below, nothing else. The
3781
+ * protocol's own shapes travel inside them unchanged (a hello, a welcome, a command or event envelope, a relay event),
3782
+ * and these frames add only ids, integers, fixed-size keys and the three verified tokens. They are relay-visible by
3783
+ * nature, so they are part of RELAY_VISIBLE and scripts/check-remote-protocol.mjs walks them like every other shape.
3784
+ *
3785
+ * The connection opens with the gateway's `challenge`. The device answers with `auth`: its binding (the issuer's word on
3786
+ * its keys), a five-minute assertion (the issuer's word that the device is still approved, spent once), and its remote
3787
+ * key's signature over the nonce, its device id and the gateway's origin (relayAuthBytes), so a stolen assertion is
3788
+ * worthless without the key and a signature made for one gateway opens no other. `ready` follows; before it, nothing
3789
+ * else is read. Before the assertion ends the gateway sends a new `challenge` on the same socket; a device that does not
3790
+ * answer it is closed with REAUTH_REQUIRED and reconnects.
3791
+ */
3792
+
3793
+ /** The largest frame either side reads, in characters: a sealed body of 1 MiB plus padding, inflated by base64. */
3794
+ export const MAX_GATEWAY_FRAME_CHARS = 2 * 1024 * 1024;
3795
+
3796
+ export const GATEWAY_ERRORS = [
3797
+ "unauthorized", "device_unknown", "signature", "too_large", "rate_limited", "not_paired", "shape", "limit", "unavailable",
3798
+ ] ;
3799
+ export const CLOSING_REASONS = ["shutdown", "revoked", "reauth", "replaced", "rate_limited", "unavailable"] ;
3800
+
3801
+ /** WebSocket close codes. REVOKED and PROTOCOL stop a device's reconnects: the person acts at the keyboard. */
3802
+ export const GATEWAY_CLOSE = {
3803
+ NORMAL: 1000,
3804
+ GOING_AWAY: 1001,
3805
+ RESTART: 1012,
3806
+ REVOKED: 4001,
3807
+ REPLACED: 4002,
3808
+ PROTOCOL: 4003,
3809
+ UNAUTHORIZED: 4004,
3810
+ REAUTH_REQUIRED: 4008,
3811
+ TOO_LARGE: 4009,
3812
+ RATE_LIMITED: 4029,
3813
+ } ;
3814
+ export const GATEWAY_STOP_CODES = new Set([GATEWAY_CLOSE.REVOKED, GATEWAY_CLOSE.PROTOCOL]);
3815
+
3816
+ const gwWord = (w ) => oneOf([w] );
3817
+ const gwDev = id("dev");
3818
+ const gwTime = int(0);
3819
+ const gwTicket = token(8);
3820
+
3821
+ /** What a device sends. */
3822
+ export const GATEWAY_INBOUND_SPECS = {
3823
+ auth: object({ frame: gwWord("auth"), device_id: gwDev, binding: token(4096), assertion: token(4096), nonce: b64({ exact: 32 }), signature: b64({ exact: 64 }) }),
3824
+ ping: object({ frame: gwWord("ping") }),
3825
+ hello: object({ frame: gwWord("hello"), hello: HANDSHAKE_HELLO_SPEC }),
3826
+ welcome: object({ frame: gwWord("welcome"), welcome: HANDSHAKE_WELCOME_SPEC }),
3827
+ command: object({ frame: gwWord("command"), envelope: COMMAND_ENVELOPE_SPEC }),
3828
+ event: object({ frame: gwWord("event"), envelope: EVENT_ENVELOPE_SPEC }),
3829
+ /** A phone: what the gateway still holds of one computer's session after event_seq `after`. */
3830
+ replay: object({ frame: gwWord("replay"), device_id: gwDev, session_id: nullable(id("ses")), after: int(0) }),
3831
+ /** A phone: push for this session of that computer, or stop. */
3832
+ follow: object({ frame: gwWord("follow"), device_id: gwDev, session_id: id("ses"), on: bool() }),
3833
+ /** A phone: disconnect from one computer, or (null) from every computer. */
3834
+ unpair: object({ frame: gwWord("unpair"), device_id: nullable(gwDev) }),
3835
+ /** A computer: the typed pairing code names it for five minutes, and proves nothing. */
3836
+ pair_ticket: object({ frame: gwWord("pair_ticket"), ticket: gwTicket, expires_at: gwTime }),
3837
+ /** A phone: which computer a typed code names (the same account only, once). */
3838
+ resolve_ticket: object({ frame: gwWord("resolve_ticket"), ticket: gwTicket }),
3839
+ } ;
3840
+
3841
+ /** What the gateway sends. */
3842
+ export const GATEWAY_OUTBOUND_SPECS = {
3843
+ challenge: object({ frame: gwWord("challenge"), nonce: b64({ exact: 32 }) }),
3844
+ ready: object({ frame: gwWord("ready"), device_id: gwDev, kind: oneOf(DEVICE_KINDS), heartbeat_ms: int(1000, 600_000), reauth_at: gwTime }),
3845
+ pong: object({ frame: gwWord("pong") }),
3846
+ hello: GATEWAY_INBOUND_SPECS.hello,
3847
+ welcome: GATEWAY_INBOUND_SPECS.welcome,
3848
+ command: GATEWAY_INBOUND_SPECS.command,
3849
+ event: GATEWAY_INBOUND_SPECS.event,
3850
+ relay: object({ frame: gwWord("relay"), event: union("type", RELAY_EVENT_SPECS) }),
3851
+ ticket: object({ frame: gwWord("ticket"), ticket: gwTicket, device_id: gwDev }),
3852
+ error: object({ frame: gwWord("error"), reason: oneOf(GATEWAY_ERRORS) }),
3853
+ /** Said before the gateway closes a socket on purpose, with when to come back. */
3854
+ closing: object({ frame: gwWord("closing"), reason: oneOf(CLOSING_REASONS), retry_after_ms: int(0, 3_600_000) }),
3855
+ } ;
3856
+
3857
+ /** The outer tokens these frames carry, each verified by its own rules: the binding and the assertion by the issuer's
3858
+ * signature (crypto/binding.ts, crypto/assertion.ts), a ticket by isPairingCode. */
3859
+ export const GATEWAY_TOKENS = ["binding", "assertion", "ticket"];
3860
+
3861
+ function validateGatewayFrame (specs , value , path ) {
3862
+ const name = typeof value === "object" && value !== null ? (value ).frame : undefined;
3863
+ if (typeof name !== "string" || !Object.hasOwn(specs, name)) return refuse("shape", `${path}.frame: not a gateway frame`);
3864
+ const spec = specs[name] ;
3865
+ const checked = check(spec, value, path);
3866
+ if (!checked.ok) return checked;
3867
+ const frame = checked.value ;
3868
+ if ("ticket" in frame && !isPairingCode(frame.ticket)) return refuse("shape", `${path}.ticket: not a pairing code`);
3869
+ return { ok: true, value: { name, frame } };
3870
+ }
3871
+
3872
+ /** A device's frame, by its exact shape, or a refusal. The envelopes inside still get their own validators' rules. */
3873
+ export const validateInboundFrame = (value ) => validateGatewayFrame(GATEWAY_INBOUND_SPECS, value, "$frame") ;
3874
+ export const validateOutboundFrame = (value ) => validateGatewayFrame(GATEWAY_OUTBOUND_SPECS, value, "$frame") ;
3875
+
3876
+ /** The push registration a phone POSTs to the gateway (not a frame: an HTTP body with its assertion, `push:register`).
3877
+ * The platform's raw device token is the one value here that is not opaque to the gateway, and it is no content: it
3878
+ * addresses the phone, which is what it is for. The gateway keeps it encrypted at rest. */
3879
+ export const PUSH_PLATFORMS = ["ios", "android"] ;
3880
+ export const isPushToken = (platform , value ) =>
3881
+ typeof value === "string" && (platform === "ios" ? /^[0-9a-f]{64,200}$/.test(value) : /^[A-Za-z0-9_:-]{32,4096}$/.test(value));