@dr-co/dsh-secret-form 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/i18n.mjs CHANGED
@@ -38,11 +38,19 @@ const MESSAGES = Object.freeze({
38
38
  save: 'Save',
39
39
  cancel: 'Cancel',
40
40
  field: 'Value',
41
+ fileField: 'File',
41
42
  mismatch: 'This value does not look like the expected format. You can still save it.',
42
43
  note: 'One-time link: it works once and stops accepting input {time}.',
43
44
  remainingSoon: 'in less than a minute',
44
45
  remaining: (count) => (count === 1 ? 'in 1 minute' : `in ${count} minutes`),
46
+ shareNote: 'This link can be opened again, but the button works exactly once. It stops working {time}.',
47
+ revealSecret: 'Show the secret',
48
+ copy: 'Copy',
49
+ copied: 'Copied',
50
+ burnNote: 'Shown once. This link no longer works.',
45
51
  errors: {
52
+ nofile: 'No file was received.',
53
+ upload: 'The file could not be stored: {detail}',
46
54
  action: 'The form was submitted without a recognised action.',
47
55
  empty: 'This field cannot be empty.',
48
56
  busy: 'This form is already being submitted.',
@@ -50,6 +58,14 @@ const MESSAGES = Object.freeze({
50
58
  },
51
59
  mismatchNote: 'Saved, but the value did not match the expected format.',
52
60
  notices: {
61
+ uploaded: {
62
+ title: 'File received',
63
+ text: 'The file is stored on the host; its name, size and checksum were passed to the model. You can close this tab.',
64
+ },
65
+ revealed: {
66
+ title: 'Secret already shown',
67
+ text: 'This link was used once and the secret has been deleted. Ask for a new link if you need it again.',
68
+ },
53
69
  saved: {
54
70
  title: 'Saved',
55
71
  text: 'The value has been stored on the host. It is not shown here and was not sent to the chat; you can close this tab.',
@@ -83,11 +99,19 @@ const MESSAGES = Object.freeze({
83
99
  save: 'Сохранить',
84
100
  cancel: 'Отмена',
85
101
  field: 'Значение',
102
+ fileField: 'Файл',
86
103
  mismatch: 'Не похоже на ожидаемый формат. Сохранить всё равно можно.',
87
104
  note: 'Ссылка одноразовая: она срабатывает один раз и перестаёт принимать ввод {time}.',
88
105
  remainingSoon: 'меньше чем через минуту',
89
106
  remaining: (count) => `через ${count} ${RUSSIAN_MINUTES[russianForm(count)]}`,
107
+ shareNote: 'Ссылку можно открыть снова, но кнопка срабатывает ровно один раз. Ссылка перестанет работать {time}.',
108
+ revealSecret: 'Показать секрет',
109
+ copy: 'Скопировать',
110
+ copied: 'Скопировано',
111
+ burnNote: 'Секрет показан один раз. Ссылка больше не работает.',
90
112
  errors: {
113
+ nofile: 'Файл не пришёл.',
114
+ upload: 'Не удалось сохранить файл: {detail}',
91
115
  action: 'Форма отправлена без понятного действия.',
92
116
  empty: 'Поле не может быть пустым.',
93
117
  busy: 'Эта форма уже отправляется.',
@@ -95,6 +119,14 @@ const MESSAGES = Object.freeze({
95
119
  },
96
120
  mismatchNote: 'Сохранено, но значение не совпало с ожидаемым форматом.',
97
121
  notices: {
122
+ uploaded: {
123
+ title: 'Файл получен',
124
+ text: 'Файл сохранён на хосте, имя, размер и контрольная сумма переданы модели. Вкладку можно закрыть.',
125
+ },
126
+ revealed: {
127
+ title: 'Секрет уже показан',
128
+ text: 'Ссылка сработала один раз, секрет удалён. Если он нужен снова, попроси новую ссылку.',
129
+ },
98
130
  saved: {
99
131
  title: 'Сохранено',
100
132
  text: 'Значение сохранено на хосте. Здесь оно не показывается и в чат не отправлялось; вкладку можно закрыть.',
@@ -128,11 +160,19 @@ const MESSAGES = Object.freeze({
128
160
  save: 'Speichern',
129
161
  cancel: 'Abbrechen',
130
162
  field: 'Wert',
163
+ fileField: 'Datei',
131
164
  mismatch: 'Der Wert sieht nicht wie das erwartete Format aus. Du kannst ihn trotzdem speichern.',
132
165
  note: 'Einmal-Link: er funktioniert genau einmal und nimmt {time} keine Eingabe mehr an.',
133
166
  remainingSoon: 'in weniger als einer Minute',
134
167
  remaining: (count) => (count === 1 ? 'in 1 Minute' : `in ${count} Minuten`),
168
+ shareNote: 'Der Link lässt sich erneut öffnen, der Knopf funktioniert aber genau einmal. Er läuft {time} ab.',
169
+ revealSecret: 'Geheimnis anzeigen',
170
+ copy: 'Kopieren',
171
+ copied: 'Kopiert',
172
+ burnNote: 'Einmal angezeigt. Dieser Link funktioniert nicht mehr.',
135
173
  errors: {
174
+ nofile: 'Es kam keine Datei an.',
175
+ upload: 'Die Datei konnte nicht gespeichert werden: {detail}',
136
176
  action: 'Das Formular wurde ohne erkennbare Aktion gesendet.',
137
177
  empty: 'Dieses Feld darf nicht leer sein.',
138
178
  busy: 'Dieses Formular wird bereits gesendet.',
@@ -140,6 +180,14 @@ const MESSAGES = Object.freeze({
140
180
  },
141
181
  mismatchNote: 'Gespeichert, aber der Wert entsprach nicht dem erwarteten Format.',
142
182
  notices: {
183
+ uploaded: {
184
+ title: 'Datei erhalten',
185
+ text: 'Die Datei liegt auf dem Host; Name, Größe und Prüfsumme wurden an das Modell übergeben. Du kannst den Tab schließen.',
186
+ },
187
+ revealed: {
188
+ title: 'Geheimnis schon angezeigt',
189
+ text: 'Dieser Link wurde einmal benutzt und das Geheimnis ist gelöscht. Frag nach einem neuen Link, wenn du es wieder brauchst.',
190
+ },
143
191
  saved: {
144
192
  title: 'Gespeichert',
145
193
  text: 'Der Wert liegt jetzt auf dem Host. Er wird hier nicht angezeigt und ging nicht in den Chat; du kannst den Tab schließen.',
@@ -173,11 +221,19 @@ const MESSAGES = Object.freeze({
173
221
  save: 'Enregistrer',
174
222
  cancel: 'Annuler',
175
223
  field: 'Valeur',
224
+ fileField: 'Fichier',
176
225
  mismatch: "Cette valeur ne ressemble pas au format attendu. Tu peux quand même l'enregistrer.",
177
226
  note: "Lien à usage unique : il fonctionne une fois, puis n'accepte plus de saisie {time}.",
178
227
  remainingSoon: "dans moins d'une minute",
179
228
  remaining: (count) => (count === 1 ? 'dans 1 minute' : `dans ${count} minutes`),
229
+ shareNote: "Le lien peut être rouvert, mais le bouton ne fonctionne qu'une seule fois. Il cesse de marcher {time}.",
230
+ revealSecret: 'Afficher le secret',
231
+ copy: 'Copier',
232
+ copied: 'Copié',
233
+ burnNote: 'Affiché une seule fois. Ce lien ne fonctionne plus.',
180
234
  errors: {
235
+ nofile: "Aucun fichier n'est arrivé.",
236
+ upload: "Impossible d'enregistrer le fichier : {detail}",
181
237
  action: 'Le formulaire a été envoyé sans action reconnue.',
182
238
  empty: 'Ce champ ne peut pas être vide.',
183
239
  busy: "Ce formulaire est déjà en cours d'envoi.",
@@ -185,6 +241,14 @@ const MESSAGES = Object.freeze({
185
241
  },
186
242
  mismatchNote: 'Enregistré, mais la valeur ne correspondait pas au format attendu.',
187
243
  notices: {
244
+ uploaded: {
245
+ title: 'Fichier reçu',
246
+ text: "Le fichier est stocké sur l'hôte ; son nom, sa taille et son empreinte ont été transmis au modèle. Tu peux fermer cet onglet.",
247
+ },
248
+ revealed: {
249
+ title: 'Secret déjà affiché',
250
+ text: "Ce lien a servi une fois et le secret a été supprimé. Demande un nouveau lien s'il te le faut encore.",
251
+ },
188
252
  saved: {
189
253
  title: 'Enregistré',
190
254
  text: "La valeur est stockée sur l'hôte. Elle n'est pas affichée ici et n'a pas été envoyée dans le chat ; tu peux fermer cet onglet.",
@@ -218,11 +282,19 @@ const MESSAGES = Object.freeze({
218
282
  save: 'Guardar',
219
283
  cancel: 'Cancelar',
220
284
  field: 'Valor',
285
+ fileField: 'Archivo',
221
286
  mismatch: 'Este valor no parece tener el formato esperado. Aun así puedes guardarlo.',
222
287
  note: 'Enlace de un solo uso: funciona una vez y deja de aceptar datos {time}.',
223
288
  remainingSoon: 'en menos de un minuto',
224
289
  remaining: (count) => (count === 1 ? 'en 1 minuto' : `en ${count} minutos`),
290
+ shareNote: 'El enlace se puede abrir de nuevo, pero el botón funciona una sola vez. Deja de funcionar {time}.',
291
+ revealSecret: 'Mostrar el secreto',
292
+ copy: 'Copiar',
293
+ copied: 'Copiado',
294
+ burnNote: 'Mostrado una sola vez. Este enlace ya no funciona.',
225
295
  errors: {
296
+ nofile: 'No llegó ningún archivo.',
297
+ upload: 'No se pudo guardar el archivo: {detail}',
226
298
  action: 'El formulario se envió sin una acción reconocida.',
227
299
  empty: 'Este campo no puede estar vacío.',
228
300
  busy: 'Este formulario ya se está enviando.',
@@ -230,6 +302,14 @@ const MESSAGES = Object.freeze({
230
302
  },
231
303
  mismatchNote: 'Guardado, pero el valor no coincidía con el formato esperado.',
232
304
  notices: {
305
+ uploaded: {
306
+ title: 'Archivo recibido',
307
+ text: 'El archivo está guardado en el host; el nombre, el tamaño y la suma de control se pasaron al modelo. Puedes cerrar esta pestaña.',
308
+ },
309
+ revealed: {
310
+ title: 'Secreto ya mostrado',
311
+ text: 'Este enlace se usó una vez y el secreto se ha borrado. Pide un enlace nuevo si lo necesitas otra vez.',
312
+ },
233
313
  saved: {
234
314
  title: 'Guardado',
235
315
  text: 'El valor se ha guardado en el host. No se muestra aquí y no se envió al chat; puedes cerrar esta pestaña.',
@@ -263,11 +343,19 @@ const MESSAGES = Object.freeze({
263
343
  save: 'Salvar',
264
344
  cancel: 'Cancelar',
265
345
  field: 'Valor',
346
+ fileField: 'Arquivo',
266
347
  mismatch: 'Este valor não parece estar no formato esperado. Você ainda pode salvá-lo.',
267
348
  note: 'Link de uso único: funciona uma vez e para de aceitar dados {time}.',
268
349
  remainingSoon: 'em menos de um minuto',
269
350
  remaining: (count) => (count === 1 ? 'em 1 minuto' : `em ${count} minutos`),
351
+ shareNote: 'O link pode ser aberto de novo, mas o botão funciona uma única vez. Ele para de funcionar {time}.',
352
+ revealSecret: 'Mostrar o segredo',
353
+ copy: 'Copiar',
354
+ copied: 'Copiado',
355
+ burnNote: 'Mostrado uma única vez. Este link não funciona mais.',
270
356
  errors: {
357
+ nofile: 'Nenhum arquivo chegou.',
358
+ upload: 'Não foi possível salvar o arquivo: {detail}',
271
359
  action: 'O formulário foi enviado sem uma ação reconhecida.',
272
360
  empty: 'Este campo não pode ficar vazio.',
273
361
  busy: 'Este formulário já está sendo enviado.',
@@ -275,6 +363,14 @@ const MESSAGES = Object.freeze({
275
363
  },
276
364
  mismatchNote: 'Salvo, mas o valor não correspondia ao formato esperado.',
277
365
  notices: {
366
+ uploaded: {
367
+ title: 'Arquivo recebido',
368
+ text: 'O arquivo está salvo no host; nome, tamanho e checksum foram passados ao modelo. Você pode fechar esta aba.',
369
+ },
370
+ revealed: {
371
+ title: 'Segredo já mostrado',
372
+ text: 'Este link foi usado uma vez e o segredo foi apagado. Peça um novo link se precisar dele de novo.',
373
+ },
278
374
  saved: {
279
375
  title: 'Salvo',
280
376
  text: 'O valor foi guardado no host. Ele não aparece aqui e não foi enviado ao chat; você pode fechar esta aba.',
@@ -308,11 +404,19 @@ const MESSAGES = Object.freeze({
308
404
  save: '保存',
309
405
  cancel: '取消',
310
406
  field: '值',
407
+ fileField: '文件',
311
408
  mismatch: '看起来不是预期的格式,不过仍然可以保存。',
312
409
  note: '一次性链接:只能用一次,{time}就会停止接受输入。',
313
410
  remainingSoon: '不到一分钟后',
314
411
  remaining: (count) => `${count} 分钟后`,
412
+ shareNote: '链接可以再次打开,但按钮只能按一次。{time}后失效。',
413
+ revealSecret: '显示密钥',
414
+ copy: '复制',
415
+ copied: '已复制',
416
+ burnNote: '仅显示一次,此链接已失效。',
315
417
  errors: {
418
+ nofile: '没有收到文件。',
419
+ upload: '无法保存文件:{detail}',
316
420
  action: '表单提交时没有可识别的操作。',
317
421
  empty: '这一栏不能为空。',
318
422
  busy: '这个表单正在提交中。',
@@ -320,6 +424,14 @@ const MESSAGES = Object.freeze({
320
424
  },
321
425
  mismatchNote: '已保存,但值与预期格式不符。',
322
426
  notices: {
427
+ uploaded: {
428
+ title: '已收到文件',
429
+ text: '文件已保存在主机上,名称、大小和校验和已交给模型。可以关闭此页面。',
430
+ },
431
+ revealed: {
432
+ title: '密钥已显示',
433
+ text: '此链接已使用过一次,密钥已删除。如果还需要,请再要一个新链接。',
434
+ },
323
435
  saved: {
324
436
  title: '已保存',
325
437
  text: '值已保存到主机上。这里不显示它,也没有发送到聊天;你可以关闭这个标签页。',
@@ -353,11 +465,19 @@ const MESSAGES = Object.freeze({
353
465
  save: '保存',
354
466
  cancel: 'キャンセル',
355
467
  field: '値',
468
+ fileField: 'ファイル',
356
469
  mismatch: '期待する形式と違うようです。このまま保存してもかまいません。',
357
470
  note: '1回だけ使えるリンクです。{time}に入力を受け付けなくなります。',
358
471
  remainingSoon: '1分以内',
359
472
  remaining: (count) => `${count}分後`,
473
+ shareNote: 'リンクは何度でも開けますが、ボタンが使えるのは一度だけです。{time}に失効します。',
474
+ revealSecret: 'シークレットを表示',
475
+ copy: 'コピー',
476
+ copied: 'コピーしました',
477
+ burnNote: '一度だけ表示されました。このリンクは使えません。',
360
478
  errors: {
479
+ nofile: 'ファイルが届きませんでした。',
480
+ upload: 'ファイルを保存できませんでした:{detail}',
361
481
  action: 'フォームが不明な操作で送信されました。',
362
482
  empty: 'この欄は空にできません。',
363
483
  busy: 'このフォームは送信中です。',
@@ -365,6 +485,14 @@ const MESSAGES = Object.freeze({
365
485
  },
366
486
  mismatchNote: '保存しましたが、値は期待する形式と一致しませんでした。',
367
487
  notices: {
488
+ uploaded: {
489
+ title: 'ファイルを受け取りました',
490
+ text: 'ファイルはホストに保存され、名前・サイズ・チェックサムがモデルに渡されました。このタブは閉じてかまいません。',
491
+ },
492
+ revealed: {
493
+ title: 'シークレットは表示済みです',
494
+ text: 'このリンクは一度使われ、シークレットは削除されました。もう一度必要なら新しいリンクを依頼してください。',
495
+ },
368
496
  saved: {
369
497
  title: '保存しました',
370
498
  text: '値はホストに保存されました。ここには表示されず、チャットにも送られていません。このタブは閉じてかまいません。',
package/lib/notify.mjs ADDED
@@ -0,0 +1,234 @@
1
+ // The note that wakes the session which created a form.
2
+ //
3
+ // A form is filled in by a human in a browser, minutes after the model asked
4
+ // for it — usually after that session's turn has ended. Leaving the model to
5
+ // poll `secret_result` is wasteful and slow, so the plugin places a durable
6
+ // one-shot reminder on the session, exactly the way the graceful-restart plugin
7
+ // wakes a session after the host comes back:
8
+ //
9
+ // schedule.create(sessionId, { title, prompt, after_seconds: 1 })
10
+ //
11
+ // `ScheduleService` owns the timer, resumes the session itself and retries on
12
+ // its own terms. The rows in the `note` table are the outbox: a note survives a
13
+ // restart, a session that is not there is retried, and one that can never be
14
+ // delivered is dropped with a log line rather than blocking the queue.
15
+ const NOTE_KIND = Object.freeze({
16
+ formSaved: 'form-saved',
17
+ formUploaded: 'form-uploaded',
18
+ formCancelled: 'form-cancelled',
19
+ shareRevealed: 'share-revealed',
20
+ });
21
+
22
+ export const NOTE_KINDS = NOTE_KIND;
23
+
24
+ /** Longest a single note keeps trying before it goes back to the outbox. */
25
+ const DEFAULT_DEADLINE_MS = 15_000;
26
+ const DEFAULT_POLL_MS = 250;
27
+ const DEFAULT_RETRY_MS = 2_000;
28
+ /** How many times a note is tried across restarts before it is dropped. */
29
+ const MAX_ATTEMPTS = 8;
30
+
31
+ const DICTS = {
32
+ en: {
33
+ formSaved: {
34
+ title: 'Secret received',
35
+ prompt: 'The secret for "{label}" ({ref}) was saved to {target}. The form uuid={uuid} is closed. Continue the work: secret_result({uuid}) reports the status.',
36
+ },
37
+ formUploaded: {
38
+ title: 'File received',
39
+ prompt: 'The file {fileName} ({size} bytes) for "{label}" was saved to {path}, sha256={sha256}. The form uuid={uuid} is closed. Continue the work.',
40
+ },
41
+ formCancelled: {
42
+ title: 'Form cancelled',
43
+ prompt: 'The human cancelled the form "{label}" ({ref}), uuid={uuid}. Nothing was saved: decide whether a new link or another route is needed.',
44
+ },
45
+ shareRevealed: {
46
+ title: 'Secret collected',
47
+ prompt: 'The secret "{label}" (uuid={uuid}) was shown to the human once; the link is burnt and the key with the ciphertext are deleted. secret_result({uuid}) confirms the state.',
48
+ },
49
+ },
50
+ ru: {
51
+ formSaved: {
52
+ title: 'Секрет получен',
53
+ prompt: 'Секрет для «{label}» ({ref}) сохранён: {target}. Форма uuid={uuid} закрыта. Продолжай работу: secret_result(uuid="{uuid}") покажет статус.',
54
+ },
55
+ formUploaded: {
56
+ title: 'Файл получен',
57
+ prompt: 'Файл {fileName} ({size} байт) для «{label}» сохранён в {path}, sha256={sha256}. Форма uuid={uuid} закрыта. Продолжай работу.',
58
+ },
59
+ formCancelled: {
60
+ title: 'Форма отменена',
61
+ prompt: 'Человек отменил форму «{label}» ({ref}), uuid={uuid}. Ничего не сохранено: реши, нужна ли новая ссылка или другой путь.',
62
+ },
63
+ shareRevealed: {
64
+ title: 'Секрет забрали',
65
+ prompt: 'Секрет «{label}» (uuid={uuid}) показан человеку один раз: ссылка погашена, ключ и шифртекст удалены. secret_result(uuid="{uuid}") подтвердит состояние.',
66
+ },
67
+ },
68
+ zh: {
69
+ formSaved: {
70
+ title: '已收到密钥',
71
+ prompt: '“{label}”({ref})的值已保存到 {target}。表单 uuid={uuid} 已关闭。继续工作:secret_result({uuid}) 可查看状态。',
72
+ },
73
+ formUploaded: {
74
+ title: '已收到文件',
75
+ prompt: '“{label}”的文件 {fileName}({size} 字节)已保存到 {path},sha256={sha256}。表单 uuid={uuid} 已关闭。继续工作。',
76
+ },
77
+ formCancelled: {
78
+ title: '表单已取消',
79
+ prompt: '用户取消了表单“{label}”({ref}),uuid={uuid}。没有保存任何内容:请判断是否需要新链接或其他方式。',
80
+ },
81
+ shareRevealed: {
82
+ title: '密钥已被取走',
83
+ prompt: '“{label}”的密钥(uuid={uuid})已向用户展示一次:链接作废,密钥与密文已删除。secret_result({uuid}) 可确认状态。',
84
+ },
85
+ },
86
+ };
87
+
88
+ /** The wording for one note in one language; English when the tag is unknown. */
89
+ export function noteText(kind, variables, language = 'en') {
90
+ const dict = DICTS[String(language ?? '').trim().toLowerCase().split(/[-_]/)[0]] ?? DICTS.en;
91
+ // Stored kinds are hyphenated (`form-saved`), dictionary keys are camelCase.
92
+ const key = String(kind).replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
93
+ const entry = dict[key] ?? DICTS.en[key];
94
+ if (entry === undefined) throw new TypeError(`dsh-secret-form: unknown note kind ${JSON.stringify(kind)}`);
95
+ const fill = (text) => String(text).replace(/\{(\w+)\}/g, (slot, key) => (key in variables ? String(variables[key]) : slot));
96
+ return { title: fill(entry.title), prompt: fill(entry.prompt) };
97
+ }
98
+
99
+ function sleep(ms) {
100
+ return new Promise((resolve) => {
101
+ const timer = setTimeout(resolve, ms);
102
+ timer.unref?.();
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Build the outbox.
108
+ * @param input - `db`, `getSchedule` (lazy lookup of the schedule service),
109
+ * `language`, `logger`, and the test knobs `deadlineMs`/`pollMs`/`retryMs`.
110
+ */
111
+ export function createNotifier({
112
+ db,
113
+ getSchedule = () => undefined,
114
+ language = 'en',
115
+ logger,
116
+ now = Date.now,
117
+ deadlineMs = DEFAULT_DEADLINE_MS,
118
+ pollMs = DEFAULT_POLL_MS,
119
+ retryMs = DEFAULT_RETRY_MS,
120
+ } = {}) {
121
+ if (db === undefined || typeof db.prepare !== 'function') {
122
+ throw new TypeError('dsh-secret-form: the notifier needs an open database');
123
+ }
124
+ const sql = {
125
+ insert: db.prepare('INSERT INTO note (uuid, kind, session_id, title, prompt, created_at) VALUES (?, ?, ?, ?, ?, ?)'),
126
+ all: db.prepare('SELECT * FROM note ORDER BY id'),
127
+ bump: db.prepare('UPDATE note SET attempts = ?, last_error = ? WHERE id = ?'),
128
+ drop: db.prepare('DELETE FROM note WHERE id = ?'),
129
+ count: db.prepare('SELECT COUNT(*) AS n FROM note'),
130
+ };
131
+
132
+ let draining = null;
133
+ let retryTimer;
134
+
135
+ const log = (level, text) => {
136
+ const writer = logger?.[level] ?? logger?.info;
137
+ try {
138
+ if (typeof writer === 'function') writer.call(logger, text);
139
+ } catch {}
140
+ };
141
+
142
+ /**
143
+ * Put one note on the session, retrying while the schedule service is either
144
+ * absent or refusing.
145
+ * @returns true when the note is placed, false when it has to wait.
146
+ */
147
+ async function place(note) {
148
+ const schedule = getSchedule();
149
+ if (schedule === undefined || typeof schedule.create !== 'function') return false;
150
+ const deadline = Date.now() + deadlineMs;
151
+ let refusal;
152
+ while (Date.now() < deadline) {
153
+ try {
154
+ await schedule.create(note.session_id, {
155
+ title: note.title,
156
+ prompt: note.prompt,
157
+ after_seconds: 1,
158
+ });
159
+ return true;
160
+ } catch (error) {
161
+ refusal = String(error?.message ?? error);
162
+ // A delegated child has no delivery path at all: retrying forever would
163
+ // only hide that fact.
164
+ if (/subagent/i.test(refusal)) throw error;
165
+ await sleep(retryMs);
166
+ }
167
+ }
168
+ throw new Error(refusal ?? 'the schedule service did not accept the note in time');
169
+ }
170
+
171
+ async function drain() {
172
+ for (const note of sql.all.all()) {
173
+ try {
174
+ const placed = await place(note);
175
+ if (!placed) {
176
+ log('info', `note ${note.kind} for session ${note.session_id} waits for the schedule service`);
177
+ break;
178
+ }
179
+ sql.drop.run(note.id);
180
+ log('info', `note ${note.kind} placed on session ${note.session_id}`);
181
+ } catch (error) {
182
+ const attempts = note.attempts + 1;
183
+ const message = String(error?.message ?? error);
184
+ sql.bump.run(attempts, message, note.id);
185
+ if (attempts >= MAX_ATTEMPTS) {
186
+ sql.drop.run(note.id);
187
+ log('warn', `note ${note.kind} for session ${note.session_id} dropped after ${attempts} attempts: ${message}`);
188
+ continue;
189
+ }
190
+ log('info', `note ${note.kind} not placed yet (${attempts}/${MAX_ATTEMPTS}): ${message}`);
191
+ }
192
+ }
193
+ if (sql.count.get().n > 0) {
194
+ clearTimeout(retryTimer);
195
+ retryTimer = setTimeout(() => void kick(), Math.max(1000, retryMs * 5));
196
+ retryTimer.unref?.();
197
+ }
198
+ }
199
+
200
+ /** Try to deliver everything in the outbox; safe to call at any time. */
201
+ function kick() {
202
+ if (draining !== null) return draining;
203
+ draining = drain().finally(() => {
204
+ draining = null;
205
+ });
206
+ return draining;
207
+ }
208
+
209
+ return {
210
+ /** Queue a note and start delivering it. */
211
+ queue({ kind, uuid, sessionId, variables = {} }) {
212
+ if (typeof sessionId !== 'string' || sessionId === '') {
213
+ log('info', `no session to tell about ${kind} ${uuid}: the note is skipped`);
214
+ return undefined;
215
+ }
216
+ const { title, prompt } = noteText(kind, { uuid, ...variables }, language);
217
+ sql.insert.run(uuid, kind, sessionId, title, prompt, now());
218
+ void kick();
219
+ return { uuid, kind, sessionId, title, prompt };
220
+ },
221
+
222
+ /** Deliver what is waiting (start-up, and again when the service appears). */
223
+ kick,
224
+
225
+ /** How many notes are still undelivered. */
226
+ get pending() {
227
+ return sql.count.get().n;
228
+ },
229
+
230
+ stop() {
231
+ clearTimeout(retryTimer);
232
+ },
233
+ };
234
+ }
package/lib/page.mjs CHANGED
@@ -129,6 +129,35 @@ button { font: inherit; cursor: pointer; }
129
129
  }
130
130
  .save { background: var(--accent); color: var(--accent-fg); }
131
131
  .cancel { background: transparent; color: var(--fg); border-color: var(--line) !important; }
132
+ input[type=file] {
133
+ padding: 10px;
134
+ border-style: dashed;
135
+ background: var(--bg);
136
+ }
137
+ pre.secret {
138
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
139
+ font-size: 15px;
140
+ line-height: 1.45;
141
+ white-space: pre-wrap;
142
+ word-break: break-all;
143
+ background: var(--card);
144
+ border: 1px solid var(--line);
145
+ border-radius: 10px;
146
+ padding: 12px;
147
+ margin: 0 0 12px;
148
+ max-height: 60vh;
149
+ overflow: auto;
150
+ }
151
+ .copy {
152
+ min-height: 46px;
153
+ padding: 10px 18px;
154
+ font-size: 15px;
155
+ font-weight: 600;
156
+ color: var(--accent);
157
+ background: transparent;
158
+ border: 1px solid var(--accent);
159
+ border-radius: 10px;
160
+ }
132
161
  .notice { border-left: 3px solid var(--accent); padding: 2px 0 2px 12px; }
133
162
  .err { color: var(--danger); }
134
163
  .warn { background: var(--warn-bg); color: var(--warn-fg); border-radius: 10px; padding: 12px; font-size: 15px; }
@@ -198,9 +227,12 @@ function remainingText(messages, remainingSeconds) {
198
227
  */
199
228
  export function renderFormView(form, { actionPath, remainingSeconds, error, warning, locale } = {}) {
200
229
  const { locale: lang, messages } = localized(locale);
230
+ const isFile = form.kind === 'file';
201
231
  const name = form.ref;
202
232
  const required = form.allowEmpty ? '' : ' required';
203
- const field = form.kind === 'single'
233
+ const field = isFile
234
+ ? `<input type="file" id="value" name="file"${required}>`
235
+ : form.kind === 'single'
204
236
  ? `<div class="field"><textarea id="value" name="value" rows="1" class="single masked" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" wrap="off" autofocus${required}></textarea><div class="mask" id="mask" aria-hidden="true" hidden></div></div>`
205
237
  : `<textarea id="value" name="value" rows="8" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" autofocus${required}></textarea>`;
206
238
  const reveal = form.kind === 'single'
@@ -230,9 +262,9 @@ export function renderFormView(form, { actionPath, remainingSeconds, error, warn
230
262
  });
231
263
  })();`);
232
264
  }
233
- if (form.expect !== undefined) {
265
+ if (form.expectSource !== undefined && !isFile) {
234
266
  scripts.push(`(function () {
235
- var pattern = new RegExp(${scriptLiteral(form.expect.source)});
267
+ var pattern = new RegExp(${scriptLiteral(form.expectSource)});
236
268
  var field = document.getElementById('value');
237
269
  var box = document.getElementById('expect-warning');
238
270
  if (!field || !box) return;
@@ -249,16 +281,16 @@ export function renderFormView(form, { actionPath, remainingSeconds, error, warn
249
281
  form.description === undefined ? '' : `<p class="hint">${escapeHtml(form.description)}</p>`,
250
282
  error === undefined ? '' : `<p class="err">${escapeHtml(error)}</p>`,
251
283
  warning === undefined ? '' : `<p class="warn">${escapeHtml(warning)}</p>`,
252
- `<form method="post" action="${escapeHtml(actionPath)}" autocomplete="off">`,
284
+ `<form method="post" action="${escapeHtml(actionPath)}"${isFile ? ' enctype="multipart/form-data"' : ''} autocomplete="off">`,
253
285
  // The ref is an identifier such as OPENAI_API_KEY: it is shown as is, next
254
286
  // to the translated word for the thing being filled in.
255
- `<label for="value">${escapeHtml(messages.field)} <span class="hint">${escapeHtml(name)}</span></label>`,
287
+ `<label for="value">${escapeHtml(isFile ? messages.fileField : messages.field)} <span class="hint">${escapeHtml(name)}</span></label>`,
256
288
  // The locale travels with the post so the outcome page answers in the
257
289
  // language the form was read in, whatever the next request's header says.
258
290
  `<input type="hidden" name="lang" value="${escapeHtml(lang)}">`,
259
291
  field,
260
292
  reveal,
261
- form.expect === undefined
293
+ form.expectSource === undefined || isFile
262
294
  ? ''
263
295
  : `<p class="warn" id="expect-warning" hidden>${escapeHtml(messages.mismatch)}</p>`,
264
296
  `<div class="actions">`,
@@ -294,6 +326,81 @@ export function renderNotice(kind, note, { locale } = {}) {
294
326
  return shell({ title: notice.title, body: body.join('\n'), locale: lang });
295
327
  }
296
328
 
329
+ /**
330
+ * Render the page of an outbound secret: a link that may be opened any number of
331
+ * times, and a button that works exactly once.
332
+ * @param share - pending share.
333
+ * @param options - `actionPath` is where the reveal posts, `remainingSeconds`
334
+ * feeds the expiry line, `error` and `warning` are page-level messages,
335
+ * `locale` picks the wording.
336
+ */
337
+ export function renderShareView(share, { actionPath, remainingSeconds, error, warning, locale } = {}) {
338
+ const { locale: lang, messages } = localized(locale);
339
+ const remaining = remainingText(messages, remainingSeconds);
340
+ const body = [
341
+ `<h1>${escapeHtml(share.label)}</h1>`,
342
+ share.description === undefined ? '' : `<p class="hint">${escapeHtml(share.description)}</p>`,
343
+ error === undefined ? '' : `<p class="err">${escapeHtml(error)}</p>`,
344
+ warning === undefined ? '' : `<p class="warn">${escapeHtml(warning)}</p>`,
345
+ `<form method="post" action="${escapeHtml(actionPath)}" autocomplete="off">`,
346
+ `<input type="hidden" name="lang" value="${escapeHtml(lang)}">`,
347
+ `<div class="actions">`,
348
+ `<button class="save" type="submit" name="action" value="reveal">${escapeHtml(messages.revealSecret)}</button>`,
349
+ `</div>`,
350
+ `</form>`,
351
+ remaining === '' ? '' : `<p class="meta">${escapeHtml(format(messages.shareNote, { time: remaining }))}</p>`,
352
+ ].filter((part) => part !== '');
353
+ return shell({
354
+ title: share.label,
355
+ body: body.join('\n'),
356
+ locale: lang,
357
+ });
358
+ }
359
+
360
+ /**
361
+ * Render the one page that ever shows an outbound secret. It is produced once,
362
+ * after the reveal burned the link, and carries the copy button.
363
+ * @param share - the share that was just revealed.
364
+ * @param options - `value` is the decrypted secret, `locale` picks the wording.
365
+ */
366
+ export function renderRevealedView(share, { value, locale } = {}) {
367
+ const { locale: lang, messages } = localized(locale);
368
+ const script = `(function () {
369
+ var button = document.getElementById('copy');
370
+ var box = document.getElementById('secret');
371
+ if (!button || !box) return;
372
+ var done = function () { button.textContent = ${scriptLiteral(messages.copied)}; };
373
+ var fallback = function () {
374
+ var range = document.createRange();
375
+ range.selectNodeContents(box);
376
+ var selection = window.getSelection();
377
+ if (!selection) return;
378
+ selection.removeAllRanges();
379
+ selection.addRange(range);
380
+ try { document.execCommand('copy'); done(); } catch (error) {}
381
+ };
382
+ button.addEventListener('click', function () {
383
+ if (navigator.clipboard && navigator.clipboard.writeText) {
384
+ navigator.clipboard.writeText(box.textContent || '').then(done, fallback);
385
+ return;
386
+ }
387
+ fallback();
388
+ });
389
+ })();`;
390
+ const body = [
391
+ `<h1>${escapeHtml(share.label)}</h1>`,
392
+ `<pre class="secret" id="secret">${escapeHtml(value)}</pre>`,
393
+ `<button class="copy" type="button" id="copy">${escapeHtml(messages.copy)}</button>`,
394
+ `<p class="meta">${escapeHtml(messages.burnNote)}</p>`,
395
+ ].filter((part) => part !== '');
396
+ return shell({
397
+ title: share.label,
398
+ body: body.join('\n'),
399
+ script,
400
+ locale: lang,
401
+ });
402
+ }
403
+
297
404
  /** Send an HTML response with the security headers and an exact length. */
298
405
  export function sendHtml(res, status, html, { head = false } = {}) {
299
406
  const body = Buffer.from(html, 'utf8');