your-attention 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +2 -0
  2. package/bin/your-attention.js +6 -2
  3. package/dist/src/adapters/files.js +66 -0
  4. package/dist/src/adapters/mdns.js +53 -0
  5. package/dist/src/adapters/mermaid.js +50 -0
  6. package/dist/src/adapters/openui-body.js +40 -0
  7. package/dist/src/adapters/openui-library.js +3 -0
  8. package/dist/src/adapters/sqlite.js +68 -0
  9. package/dist/src/cli.js +814 -0
  10. package/dist/src/client.js +459 -0
  11. package/dist/src/cloudflare/collector.js +53 -0
  12. package/dist/src/cloudflare/inbox-object.js +338 -0
  13. package/dist/src/cloudflare/storage.js +151 -0
  14. package/dist/src/cloudflare/worker.js +189 -0
  15. package/dist/src/core/crypto.js +23 -0
  16. package/dist/src/core/diagrams.js +225 -0
  17. package/dist/src/core/expr.js +125 -0
  18. package/dist/src/core/file-links.js +48 -0
  19. package/dist/src/core/hooks.js +74 -0
  20. package/dist/src/core/http.js +651 -0
  21. package/dist/src/core/inbox.js +2463 -0
  22. package/dist/src/core/pin.js +234 -0
  23. package/dist/src/core/sealed.js +167 -0
  24. package/dist/src/core/session-link.js +13 -0
  25. package/dist/src/core/socket.js +88 -0
  26. package/dist/src/core/storage.js +102 -0
  27. package/dist/src/core/summary.js +149 -0
  28. package/dist/src/core/telemetry.js +221 -0
  29. package/dist/src/core/types.js +470 -0
  30. package/dist/src/core/version.js +2 -0
  31. package/dist/src/core/widgets.js +128 -0
  32. package/dist/src/extensions/triage.js +232 -0
  33. package/dist/src/integrations/claude/ask-hook.js +84 -0
  34. package/dist/src/integrations/claude/channel-flag.js +102 -0
  35. package/dist/src/integrations/claude/channel.js +276 -0
  36. package/dist/src/integrations/claude/session-name.js +32 -0
  37. package/dist/src/integrations/claude/turn-end-hook.js +84 -0
  38. package/dist/src/integrations/herdr/approve.js +71 -0
  39. package/dist/src/integrations/herdr/blocked.js +210 -0
  40. package/dist/src/integrations/herdr/dialog.js +64 -0
  41. package/dist/src/integrations/herdr/focus.js +31 -0
  42. package/dist/src/integrations/herdr/place.js +22 -0
  43. package/dist/src/integrations/images.js +43 -0
  44. package/dist/src/integrations/opencode/install.js +24 -0
  45. package/dist/src/integrations/opencode/plugin.js +157 -0
  46. package/dist/src/integrations/pi/extension.js +166 -0
  47. package/dist/src/integrations/run-tool.js +157 -0
  48. package/dist/src/integrations/secrets.js +63 -0
  49. package/dist/src/integrations/tags.js +27 -0
  50. package/dist/src/integrations/tools.js +147 -0
  51. package/dist/src/node/home.js +20 -0
  52. package/dist/src/node/install.js +225 -0
  53. package/dist/src/node/links.js +249 -0
  54. package/dist/src/node/pin-prompt.js +125 -0
  55. package/dist/src/node/server.js +320 -0
  56. package/dist/src/node/service.js +74 -0
  57. package/dist/src/node/telemetry.js +127 -0
  58. package/dist/src/owner-watch.js +49 -0
  59. package/dist/src/tui/api.js +203 -0
  60. package/dist/src/tui/app.js +586 -0
  61. package/dist/src/tui/body.js +727 -0
  62. package/dist/src/tui/cardview.js +453 -0
  63. package/dist/src/tui/doc.js +157 -0
  64. package/dist/src/tui/edit.js +119 -0
  65. package/dist/src/tui/input.js +192 -0
  66. package/dist/src/tui/md.js +196 -0
  67. package/dist/src/tui/screen.js +225 -0
  68. package/dist/src/tui/terminal.js +130 -0
  69. package/dist/src/tui/text.js +103 -0
  70. package/dist/src/tui/theme.js +105 -0
  71. package/dist/src/tui/view.js +314 -0
  72. package/dist/src/watch.js +104 -0
  73. package/dist/web/age.js +16 -0
  74. package/dist/web/answers.js +485 -0
  75. package/dist/web/app.js +739 -0
  76. package/dist/web/body-faults.js +69 -0
  77. package/dist/web/components.js +923 -0
  78. package/dist/web/copy.js +118 -0
  79. package/dist/web/details.js +59 -0
  80. package/dist/web/env.js +97 -0
  81. package/dist/web/favicon-waiting.svg +1 -0
  82. package/dist/web/favicon.svg +1 -0
  83. package/dist/web/index.html +16 -0
  84. package/dist/web/library-spec.js +33 -0
  85. package/dist/web/markdown.js +142 -0
  86. package/dist/web/paste-images.js +193 -0
  87. package/dist/web/pin-key.js +125 -0
  88. package/dist/web/pin.js +126 -0
  89. package/dist/web/queue.js +97 -0
  90. package/dist/web/sealed.js +13 -0
  91. package/dist/web/search.js +70 -0
  92. package/dist/web/stories/cards.stories.js +144 -0
  93. package/dist/web/stories/page.stories.js +54 -0
  94. package/dist/web/stories/render.js +16 -0
  95. package/dist/web/style.css +417 -0
  96. package/package.json +4 -2
  97. package/src/core/version.ts +1 -1
@@ -0,0 +1,234 @@
1
+ // The PIN that a browser tab types before it acts as the owner. The client runs
2
+ // the slow salted hash, PBKDF2, and sends the derived key, never the PIN. The
3
+ // inbox keeps a SHA-256 hash of that key, and a hash of each unlock token it
4
+ // gives a tab. Wrong tries and their lockout live in storage, so a restart
5
+ // keeps them.
6
+ import { randomId, sha256 } from './crypto.js';
7
+
8
+
9
+ /** About 100 ms of PBKDF2-SHA256 on a laptop. The client computes it on every build, with the count GET /v1/pin hands out. */
10
+ export const PIN_ITERATIONS = 800_000;
11
+ /** Wrong tries before a lockout. */
12
+ export const PIN_TRIES = 5;
13
+ /** The first lockout. Each one after it lasts twice as long as the one before, up to a day. */
14
+ export const FIRST_LOCKOUT_MS = 60_000;
15
+ export const MAX_LOCKOUT_MS = 24 * 60 * 60 * 1000;
16
+ /** An unlock token that no request has used for this long ends. */
17
+ export const UNLOCK_IDLE_MS = 12 * 60 * 60 * 1000;
18
+ /** The header that carries a tab's unlock token. */
19
+ export const UNLOCK_HEADER = 'x-your-attention-unlock';
20
+ const MAX_UNLOCKS = 32;
21
+ /** How often a token in use writes its last use, so each request does not write to storage. */
22
+ const TOUCH_MS = 60_000;
23
+
24
+ /** What a client sends for a new PIN: the PBKDF2-SHA256 key it derived, in hex, with the salt and iterations it used. */
25
+
26
+ /** `key` is the SHA-256 of the derived key. An inbox from before the client derived keeps the derived key itself in `hash`. */
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+ const hex = (bytes ) => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
48
+ const unhex = (s ) => new Uint8Array((s.match(/../g) ?? []).map((b) => parseInt(b, 16)));
49
+
50
+ /** The key a client sends for a PIN: PBKDF2-SHA256 over the PIN, 32 bytes in hex. web/pin-key.js computes the same on the page. */
51
+ export async function pinKey(pin , salt , iterations ) {
52
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(pin), 'PBKDF2', false, ['deriveBits']);
53
+ return hex(new Uint8Array(await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt: unhex(salt), iterations }, key, 256)));
54
+ }
55
+
56
+ /** A new PIN's key, with a fresh random 16-byte salt. */
57
+ export async function newPinKey(pin , iterations = PIN_ITERATIONS) {
58
+ if (!validPin(pin)) throw new RangeError('a PIN is 4 digits');
59
+ const salt = hex(crypto.getRandomValues(new Uint8Array(16)));
60
+ return { key: await pinKey(pin, salt, iterations), salt, iterations };
61
+ }
62
+
63
+ /** Two strings of the same length compared in time that does not depend on where they differ. */
64
+ function same(a , b ) {
65
+ if (a.length !== b.length) return false;
66
+ let diff = 0;
67
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
68
+ return diff === 0;
69
+ }
70
+
71
+ export const validPin = (pin ) => typeof pin === 'string' && /^\d{4}$/.test(pin);
72
+ /** A derived key as a client sends it: 32 bytes in lowercase hex. */
73
+ export const validKey = (key ) => typeof key === 'string' && /^[0-9a-f]{64}$/.test(key);
74
+
75
+ /** Why the inbox refuses a new PIN's key, or undefined when it takes it. */
76
+ export function pinKeyError(k , iterations = PIN_ITERATIONS) {
77
+ const v = (k && typeof k === 'object' ? k : {}) ;
78
+ if (!validKey(v.key)) return 'key must be the PIN derived with PBKDF2-SHA256, 32 bytes in lowercase hex';
79
+ if (typeof v.salt !== 'string' || !/^[0-9a-f]{32}$/.test(v.salt)) return 'salt must be 16 random bytes in lowercase hex';
80
+ if (v.iterations !== iterations) return `iterations must be ${iterations}, the newIterations of GET /v1/pin`;
81
+ return undefined;
82
+ }
83
+
84
+ export class PinLock {
85
+ store ;
86
+ now ;
87
+ /** The PBKDF2 iterations a new PIN's key must use. */
88
+ iterations ;
89
+ listeners = new Set ();
90
+
91
+ constructor(store , now = Date.now, iterations = PIN_ITERATIONS) {
92
+ this.store = store;
93
+ this.now = now;
94
+ this.iterations = iterations;
95
+ }
96
+
97
+ record() {
98
+ return this.store.get ('meta', 'pin') ?? {};
99
+ }
100
+
101
+ tries() {
102
+ return this.store.get ('meta', 'pin-tries') ?? { failures: 0, lockouts: 0, until: 0 };
103
+ }
104
+
105
+ isSet() {
106
+ const r = this.record();
107
+ return !!(r.key || r.hash);
108
+ }
109
+
110
+ status() {
111
+ const r = this.record();
112
+ const t = this.tries();
113
+ const locked = t.until > this.now();
114
+ const set = this.isSet();
115
+ return {
116
+ set, salt: set ? r.salt ?? null : null, iterations: set ? r.iterations ?? this.iterations : this.iterations, newIterations: this.iterations,
117
+ neverAsk: r.neverAsk === true, lockedUntil: locked ? t.until : null, triesLeft: locked ? 0 : PIN_TRIES - t.failures,
118
+ };
119
+ }
120
+
121
+ /** Runs after the PIN changes or goes, once every unlock token has ended. */
122
+ onChange(listener ) {
123
+ this.listeners.add(listener);
124
+ return () => this.listeners.delete(listener);
125
+ }
126
+
127
+ /** Set a PIN typed in this process, such as at the laptop's terminal. Clients send the key to setKey instead. */
128
+ async set(pin ) {
129
+ await this.setKey(await newPinKey(pin, this.iterations));
130
+ }
131
+
132
+ /** Set the PIN from the key a client derived. The inbox stores the SHA-256 of the key. */
133
+ async setKey(k ) {
134
+ const error = pinKeyError(k, this.iterations);
135
+ if (error) throw new RangeError(error);
136
+ const key = await sha256(k.key);
137
+ const { neverAsk } = this.record();
138
+ this.store.put ('meta', 'pin', { key, salt: k.salt, iterations: k.iterations, setAt: this.now(), ...(neverAsk !== undefined ? { neverAsk } : {}) });
139
+ this.store.delete('meta', 'pin-tries');
140
+ this.dropUnlocks();
141
+ }
142
+
143
+ clear() {
144
+ const { neverAsk } = this.record();
145
+ this.store.put ('meta', 'pin', neverAsk ? { neverAsk } : {});
146
+ this.store.delete('meta', 'pin-tries');
147
+ this.dropUnlocks();
148
+ }
149
+
150
+ setNeverAsk(neverAsk ) {
151
+ this.store.put ('meta', 'pin', { ...this.record(), neverAsk });
152
+ }
153
+
154
+ /** Check a derived key against the lockout. Each try counts before the hash runs, so tries sent at once all count. */
155
+ async check(key ) {
156
+ const r = this.record();
157
+ if (!this.isSet()) return { ok: false, triesLeft: 0 };
158
+ const now = this.now();
159
+ const t = this.tries();
160
+ if (t.until > now) return { ok: false, lockedUntil: t.until };
161
+ const failures = t.failures + 1;
162
+ const next = failures >= PIN_TRIES
163
+ ? { failures: 0, lockouts: t.lockouts + 1, until: now + Math.min(FIRST_LOCKOUT_MS * 2 ** t.lockouts, MAX_LOCKOUT_MS) }
164
+ : { ...t, failures };
165
+ this.store.put('meta', 'pin-tries', next);
166
+ // An older laptop inbox stored the derived key itself, so its hash is the SHA-256 of that.
167
+ const expected = r.key ?? (await sha256(r.hash ?? ''));
168
+ if (validKey(key) && same(await sha256(key), expected)) {
169
+ this.store.delete('meta', 'pin-tries');
170
+ return { ok: true };
171
+ }
172
+ return next.until > now ? { ok: false, lockedUntil: next.until } : { ok: false, triesLeft: PIN_TRIES - failures };
173
+ }
174
+
175
+ /** Give a tab an unlock token for the owner token it signed in with, when the key is right. */
176
+ async unlock(key , token ) {
177
+ const r = await this.check(key);
178
+ return r.ok ? { ok: true, token: await this.issue(token) } : r;
179
+ }
180
+
181
+ /** A new unlock token for one owner token. The secret is returned once. */
182
+ async issue(token ) {
183
+ const id = randomId(8);
184
+ const secret = `${id}.${randomId(32)}`;
185
+ const live = this.unlocks().sort((a, b) => b.seen - a.seen);
186
+ for (const old of live.slice(MAX_UNLOCKS - 1)) this.store.delete('meta', old.key);
187
+ this.store.put ('meta', `unlock:${id}`, { key: `unlock:${id}`, hash: await sha256(secret), token, seen: this.now() });
188
+ return secret;
189
+ }
190
+
191
+ /** The id of a live unlock token that belongs to this owner token, or undefined. */
192
+ async verifyUnlock(secret , token ) {
193
+ if (!secret) return undefined;
194
+ const id = secret.split('.')[0] ?? '';
195
+ if (!/^[0-9a-f]{16}$/.test(id)) return undefined;
196
+ // Hash before the read, so a PIN change between the read and the touch below cannot bring a dropped token back.
197
+ const hash = await sha256(secret);
198
+ const u = this.store.get ('meta', `unlock:${id}`);
199
+ if (!u || u.token !== token || !same(hash, u.hash)) return undefined;
200
+ const now = this.now();
201
+ if (now - u.seen > UNLOCK_IDLE_MS) { this.store.delete('meta', u.key); return undefined; }
202
+ if (now - u.seen > TOUCH_MS) this.store.put ('meta', u.key, { ...u, seen: now });
203
+ return id;
204
+ }
205
+
206
+ /** Whether an unlock token, by id, is still live. For a connection that unlocked when it opened. */
207
+ live(id ) {
208
+ const u = id ? this.store.get ('meta', `unlock:${id}`) : undefined;
209
+ return !!u && this.now() - u.seen <= UNLOCK_IDLE_MS;
210
+ }
211
+
212
+ /** End one tab's unlock token. */
213
+ async lock(secret ) {
214
+ const id = String(secret).split('.')[0] ?? '';
215
+ const hash = await sha256(String(secret));
216
+ const u = /^[0-9a-f]{16}$/.test(id) ? this.store.get ('meta', `unlock:${id}`) : undefined;
217
+ if (u && same(hash, u.hash)) this.store.delete('meta', u.key);
218
+ }
219
+
220
+ /** End every unlock token, or those of one owner token, such as one that was revoked. */
221
+ dropUnlocks(token ) {
222
+ for (const u of this.unlocks()) if (token === undefined || u.token === token) this.store.delete('meta', u.key);
223
+ for (const l of this.listeners) l();
224
+ }
225
+
226
+ sweep() {
227
+ const now = this.now();
228
+ for (const u of this.unlocks()) if (now - u.seen > UNLOCK_IDLE_MS) this.store.delete('meta', u.key);
229
+ }
230
+
231
+ unlocks() {
232
+ return this.store.list ('meta').filter((m) => typeof m?.key === 'string' && m.key.startsWith('unlock:'));
233
+ }
234
+ }
@@ -0,0 +1,167 @@
1
+ // Sealed secrets: the agent side, a key pair per card and opening what the page sealed with web/sealed.js, and the
2
+ // inbox side, the fields of a card that take only a sealed value. Web Crypto only.
3
+ import { InboxError } from './inbox.js';
4
+
5
+
6
+ export const SEAL_ALG = 'RSA-OAEP-256+A256GCM';
7
+ const RSA = { name: 'RSA-OAEP', hash: 'SHA-256' } ;
8
+ const bytes = (b64 ) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
9
+
10
+ export async function newSealKeys() {
11
+ const pair = (await crypto.subtle.generateKey({ ...RSA, modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]) }, true, ['wrapKey', 'unwrapKey'])) ;
12
+ return { publicKey: (await crypto.subtle.exportKey('jwk', pair.publicKey)) , privateKey: pair.privateKey };
13
+ }
14
+
15
+ export async function openSealed(privateKey , sealed ) {
16
+ if (sealed.alg !== SEAL_ALG) throw new Error(`unknown sealing ${sealed.alg}`);
17
+ const aes = await crypto.subtle.unwrapKey('raw', bytes(sealed.key), privateKey, { name: 'RSA-OAEP' }, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
18
+ const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes(sealed.iv) }, aes, bytes(sealed.data));
19
+ return new TextDecoder().decode(plain);
20
+ }
21
+
22
+ /** Whether a value has the fields of a sealed secret. */
23
+ export function isSealed(v ) {
24
+ if (!v || typeof v !== 'object') return false;
25
+ const s = v ;
26
+ return s['alg'] === SEAL_ALG && ['key', 'iv', 'data'].every((k) => typeof s[k] === 'string');
27
+ }
28
+
29
+ const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
30
+ // The members of an RSA private key in a JWK. A public key has none of them.
31
+ const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth'];
32
+ const LITERALS = 'SecretInput takes two string literals, the field name and the public key. Place it with the secret widget: key = widget secret {"name": "API_KEY"}';
33
+
34
+ // The body as the OpenUI parser reads it, after the steps of @openuidev/lang-core 1.0.1 that decide what is code: the
35
+ // code of its ``` fences when it has any, then without // and # comments. A string can hide a call only the way the
36
+ // parser's own strings do, so a stray quote in prose or in a comment hides nothing.
37
+ function skipDoubleQuoted(input , start ) {
38
+ if (input[start] !== '"') return start;
39
+ let i = start + 1;
40
+ while (i < input.length) {
41
+ if (input[i] === '\\') i += 2;
42
+ else if (input[i] === '"') return i + 1;
43
+ else i++;
44
+ }
45
+ return i;
46
+ }
47
+ function fencedCode(input ) {
48
+ const blocks = [];
49
+ const fenceAt = (i ) => input.startsWith('```', i);
50
+ let i = 0;
51
+ while (i < input.length) {
52
+ let start = -1;
53
+ while (i < input.length) {
54
+ const next = skipDoubleQuoted(input, i);
55
+ if (next > i) { i = next; continue; }
56
+ if (fenceAt(i)) { start = i; break; }
57
+ i++;
58
+ }
59
+ if (start === -1) break;
60
+ let j = input.indexOf('\n', start + 3);
61
+ if (j === -1) { blocks.push(input.slice(start + 3).replace(/^[^\n]*\n?/, '')); break; }
62
+ j++;
63
+ let close = -1;
64
+ let k = j;
65
+ while (k < input.length) {
66
+ const next = skipDoubleQuoted(input, k);
67
+ if (next > k) { k = next; continue; }
68
+ if (fenceAt(k)) { close = k; break; }
69
+ k++;
70
+ }
71
+ blocks.push(input.slice(j, close === -1 ? undefined : close));
72
+ i = close === -1 ? input.length : close + 3;
73
+ }
74
+ // A body that starts with a fence always adds a block above, so lang-core's branch for that case never runs here.
75
+ return blocks.length ? blocks.join('\n') : input;
76
+ }
77
+ function withoutComments(input ) {
78
+ let quote = false;
79
+ return input.split('\n').map((line) => {
80
+ for (let i = 0; i < line.length; i++) {
81
+ const c = line[i];
82
+ if (quote) {
83
+ if (c === '\\' && i + 1 < line.length) { i++; continue; }
84
+ if (c === quote) quote = false;
85
+ continue;
86
+ }
87
+ if (c === '"' || c === "'") { quote = c; continue; }
88
+ if ((c === '/' && line[i + 1] === '/') || c === '#') return line.slice(0, i).trimEnd();
89
+ }
90
+ return line;
91
+ }).join('\n');
92
+ }
93
+
94
+ /** Read the string literal at `i`, as the OpenUI lexer decodes it. Undefined when no string starts there. */
95
+ function stringAt(src , i ) {
96
+ if (src[i] === '"') {
97
+ let j = i + 1;
98
+ let closed = false;
99
+ while (j < src.length) {
100
+ if (src[j] === '\\') j += 2;
101
+ else if (src[j] === '"') { j++; closed = true; break; } else j++;
102
+ }
103
+ const raw = src.slice(i, j);
104
+ try { return { value: String(JSON.parse(closed ? raw : `${raw}"`)), end: j }; } catch { return { value: raw.replace(/^"|"$/g, ''), end: j }; }
105
+ }
106
+ if (src[i] === "'") {
107
+ let j = i + 1;
108
+ let value = '';
109
+ while (j < src.length) {
110
+ if (src[j] === '\\') {
111
+ const esc = src[j + 1];
112
+ if (esc !== undefined) value += esc === 'n' ? '\n' : esc === 't' ? '\t' : esc;
113
+ j += 2;
114
+ } else if (src[j] === "'") { j++; break; } else value += src[j++];
115
+ }
116
+ return { value, end: j };
117
+ }
118
+ return undefined;
119
+ }
120
+
121
+ /** The field names of the SecretInput calls in a body, in order, read with the OpenUI parser's strings, comments and
122
+ * fences. Each call must give its field name and an RSA public key as string literals, so the inbox knows every field
123
+ * that takes only a sealed value. */
124
+ export function secretInputs(body ) {
125
+ const src = withoutComments(fencedCode(body.trim())).trim();
126
+ const names = [];
127
+ const space = (i ) => { while (/\s/.test(src[i] ?? '')) i++; return i; };
128
+ let i = 0;
129
+ while (i < src.length) {
130
+ const str = stringAt(src, i);
131
+ if (str) { i = str.end; continue; }
132
+ const word = /^[A-Za-z_]\w*/.exec(src.slice(i, i + 64))?.[0];
133
+ if (!word) { i++; continue; }
134
+ i += word.length;
135
+ if (word !== 'SecretInput' || src[space(i)] !== '(') continue;
136
+ const first = stringAt(src, space(space(i) + 1));
137
+ const comma = first ? space(first.end) : -1;
138
+ const second = first && src[comma] === ',' ? stringAt(src, space(comma + 1)) : undefined;
139
+ if (!first || !second || src[space(second.end)] !== ')') throw new InboxError(400, LITERALS);
140
+ i = space(second.end) + 1;
141
+ const name = first.value;
142
+ const key = second.value;
143
+ if (!FIELD_NAME.test(name)) throw new InboxError(400, `secret ${JSON.stringify(name)}: the name must be a variable name, such as API_KEY`);
144
+ if (names.includes(name)) throw new InboxError(400, `the card asks for ${name} twice: give each secret its own name`);
145
+ if (!key) throw new InboxError(400, `secret ${name} needs the public key that card_post fills in. Post the card with the card_post tool of a Claude Code, pi or opencode session, which keeps the private key`);
146
+ let jwk ;
147
+ try { jwk = JSON.parse(key) ; } catch { throw new InboxError(400, `secret ${name}: the public key must be an RSA key as JSON Web Key text`); }
148
+ if (!jwk || typeof jwk !== 'object' || jwk['kty'] !== 'RSA' || typeof jwk['n'] !== 'string' || typeof jwk['e'] !== 'string') throw new InboxError(400, `secret ${name}: the public key must be an RSA key as JSON Web Key text`);
149
+ if (PRIVATE_MEMBERS.some((k) => Object.hasOwn(jwk, k))) throw new InboxError(400, `secret ${name}: the key is a private key. The private key never leaves the agent's session: place only the public key`);
150
+ names.push(name);
151
+ }
152
+ return names;
153
+ }
154
+
155
+ /** The answer fields of a card that take only a sealed value. A secret card that an older inbox stored has one, `sealed`. */
156
+ export function sealedFields(card ) {
157
+ return card.secrets ?? (card.kind === 'secret' ? ['sealed'] : []);
158
+ }
159
+
160
+ /** The answer without its sealed fields, nor those of the answers before it, for every reader except the agent stream:
161
+ * hooks and webhooks hold no key. */
162
+ export function withoutSealed(card , answer ) {
163
+ const fields = sealedFields(card);
164
+ if (!fields.length) return answer;
165
+ const strip = (values ) => Object.fromEntries(Object.entries(values).filter(([k]) => !fields.includes(k)));
166
+ return { ...answer, values: strip(answer.values), previous: (answer.previous ?? []).map((p) => ({ ...p, values: strip(p.values ?? {}) })) };
167
+ }
@@ -0,0 +1,13 @@
1
+ // A session link points at another agent's session from inside a card. It uses herdr's own link form,
2
+ // https://herdr.invalid/v1/<kind>/<id>, which agents already write in their terminal replies.
3
+ // A link may carry herdr's session fingerprint before the kind; the inbox ignores it.
4
+
5
+
6
+
7
+ const LINK = /^https:\/\/herdr\.invalid\/v1\/(?:[0-9a-f]{64}\/)?(agent|pane|tab|workspace)\/([A-Za-z0-9][\w:.-]{0,99})$/;
8
+
9
+ /** The session a link points at, or undefined when the address is not a session link. An id never starts with a dash, so herdr cannot read it as a flag. */
10
+ export function parseSessionLink(href ) {
11
+ const m = LINK.exec(href);
12
+ return m ? { kind: m[1] , id: m[2] } : undefined;
13
+ }
@@ -0,0 +1,88 @@
1
+ // One agent connection over a WebSocket, for any platform. The platform calls
2
+ // `message` for each text frame and `close` when the socket closes.
3
+ //
4
+ // Client to inbox: {type: "auth", token} first when the client cannot send an
5
+ // Authorization header, then {type: "ack", card} and {type: "ping"}.
6
+ // Inbox to client: the same events as the stream, and {type: "pong"}.
7
+
8
+
9
+ /** The frames a socket may send in a minute. A socket past it closes, since each frame wakes the inbox. */
10
+ export const FRAMES_PER_MINUTE = 120;
11
+
12
+ /** Counts a socket's frames in the current minute. */
13
+ function frameBudget(now = Date.now) {
14
+ let start = now();
15
+ let count = 0;
16
+ return () => {
17
+ if (now() - start >= 60_000) { start = now(); count = 0; }
18
+ return ++count <= FRAMES_PER_MINUTE;
19
+ };
20
+ }
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ /** `resumed` marks a socket that was already open and signed in before the platform rebuilt it, as a Durable Object does
36
+ * when it wakes: the client keeps the same connection, so it gets no second `hello`. `channelOff` says the session
37
+ * discards channel notifications. */
38
+ export function agentSocket(inbox , agent , ws , caller , instance , resumed = false, channelOff = false) {
39
+ let me = caller;
40
+ let disconnect ;
41
+ const allow = frameBudget();
42
+ const start = (c , quiet ) => {
43
+ me = c;
44
+ disconnect = inbox.connect(c, agent, (ev) => ws.send(JSON.stringify(ev)), instance, { resumed: quiet, channelOff });
45
+ };
46
+ if (me) start(me, resumed);
47
+ return {
48
+ async message(text) {
49
+ if (!allow()) return ws.close(4429, `more than ${FRAMES_PER_MINUTE} frames a minute`);
50
+ let msg ;
51
+ try { msg = JSON.parse(text) ; } catch { return ws.close(1003, 'frames must be JSON'); }
52
+ if (!msg || typeof msg !== 'object') return ws.close(1003, 'frames must be JSON objects');
53
+ if (!me) {
54
+ const token = msg.type === 'auth' ? await inbox.authenticate(msg.token) : undefined;
55
+ if (!token) return ws.close(4401, 'send {type: "auth", token} first');
56
+ return start({ token: token.id, role: token.role }, false);
57
+ }
58
+ if (msg.type === 'ping') return ws.send('{"type":"pong"}');
59
+ if (msg.type === 'ack' && msg.card) {
60
+ try { inbox.ack(me, msg.card); } catch (e) { ws.send(JSON.stringify({ type: 'error', error: (e ).message })); }
61
+ }
62
+ },
63
+ close() {
64
+ disconnect?.();
65
+ disconnect = undefined;
66
+ },
67
+ get authenticated() {
68
+ return me !== undefined;
69
+ },
70
+ get caller() {
71
+ return me;
72
+ },
73
+ };
74
+ }
75
+
76
+ /** The inbox page over a WebSocket, for the owner: the same events as GET /v1/events. The page sends {type: "ping"} and gets {type: "pong"}.
77
+ * A page that signed in with a cookie or a link token passes `guard`, with the unlock token it opened with, so the socket closes when the PIN changes. */
78
+ export function pageSocket(inbox , ws , viewer , guard ) {
79
+ const allow = frameBudget();
80
+ const stop = inbox.subscribePage((ev) => ws.send(JSON.stringify(ev)), viewer, guard ? { unlock: guard.unlock, close: () => ws.close(4423, 'the PIN changed: unlock again') } : undefined);
81
+ return {
82
+ message(text) {
83
+ if (!allow()) return ws.close(4429, `more than ${FRAMES_PER_MINUTE} frames a minute`);
84
+ if (text.includes('"ping"')) ws.send('{"type":"pong"}');
85
+ },
86
+ close: stop,
87
+ };
88
+ }
@@ -0,0 +1,102 @@
1
+ // The storage adapter. Calls are synchronous, like node:sqlite and the SQL API
2
+ // of a Durable Object, so each inbox change runs to completion before the next
3
+ // one starts and needs no lock.
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ /** Storage kept in memory. For tests and for a page that hosts an inbox. */
30
+ export class MemoryStorage {
31
+ data = new Map ();
32
+ text = new Map ();
33
+
34
+ bucket(c ) {
35
+ let b = this.data.get(c);
36
+ if (!b) this.data.set(c, (b = new Map()));
37
+ return b;
38
+ }
39
+
40
+ get (c , id ) {
41
+ const v = this.bucket(c).get(id);
42
+ return v === undefined ? undefined : (JSON.parse(v) );
43
+ }
44
+
45
+ put (c , id , value ) {
46
+ this.bucket(c).set(id, JSON.stringify(value));
47
+ }
48
+
49
+ delete(c , id ) {
50
+ this.bucket(c).delete(id);
51
+ }
52
+
53
+ list (c ) {
54
+ return [...this.bucket(c).values()].map((v) => JSON.parse(v) );
55
+ }
56
+
57
+ first (c , limit ) {
58
+ return [...this.bucket(c).values()].slice(0, limit).map((v) => JSON.parse(v) );
59
+ }
60
+
61
+ count(c ) {
62
+ return this.bucket(c).size;
63
+ }
64
+
65
+ bytes() {
66
+ let n = 0;
67
+ for (const b of this.data.values()) for (const v of b.values()) n += v.length;
68
+ for (const v of this.text.values()) n += v.length;
69
+ return n;
70
+ }
71
+
72
+ index(card , text ) {
73
+ if (text) this.text.set(card, text.toLowerCase());
74
+ else this.text.delete(card);
75
+ }
76
+
77
+ search(query , limit ) {
78
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
79
+ const hits = [];
80
+ for (const [card, text] of this.text) {
81
+ if (words.length && words.every((w) => text.includes(w))) hits.push({ card, rank: 0 });
82
+ }
83
+ return hits.slice(0, limit);
84
+ }
85
+
86
+ close() {}
87
+ }
88
+
89
+ /** Where file bytes go: R2 in the Cloudflare build, files on disk on a laptop.
90
+ * Calls are asynchronous, so the inbox stores the bytes before it commits the card. */
91
+
92
+
93
+
94
+
95
+
96
+
97
+ export class MemoryBlobs {
98
+ data = new Map ();
99
+ async put(key , bytes , type ) { this.data.set(key, { bytes, type }); }
100
+ async get(key ) { return this.data.get(key); }
101
+ async delete(key ) { this.data.delete(key); }
102
+ }