@rarog/server 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +18 -5
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +64 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  6. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  7. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  8. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  9. package/node_modules/@rarog/shared/src/protocol.js +20 -47
  10. package/node_modules/@rarog/shared/src/rest.js +106 -12
  11. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  12. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +21 -0
  14. package/package.json +3 -3
  15. package/server/src/auth/admin.js +3 -1
  16. package/server/src/bootstrap/consent.js +99 -2
  17. package/server/src/bootstrap/folder-gate.js +55 -0
  18. package/server/src/bootstrap/http.js +3 -2
  19. package/server/src/bootstrap/inbox.js +29 -4
  20. package/server/src/bootstrap/sse.js +2 -1
  21. package/server/src/cli/doctor-no-hook.js +162 -0
  22. package/server/src/cli/doctor.js +2 -0
  23. package/server/src/cli/service-log.js +27 -0
  24. package/server/src/cli/service.js +5 -2
  25. package/server/src/cli/templates/launchd.plist +1 -1
  26. package/server/src/cli/templates/rarog.service +1 -1
  27. package/server/src/cli/update-channel.js +100 -0
  28. package/server/src/cli/update-provenance.js +37 -19
  29. package/server/src/cli/update-registry.js +160 -62
  30. package/server/src/cli/update.js +13 -3
  31. package/server/src/companion/turns-settle.js +4 -1
  32. package/server/src/companion/turns.js +36 -5
  33. package/server/src/config/files.js +32 -0
  34. package/server/src/config/flags.js +10 -1
  35. package/server/src/config/protected-dirs.js +2 -0
  36. package/server/src/config/roots.js +13 -8
  37. package/server/src/config/work-area.js +36 -12
  38. package/server/src/config-env.js +33 -0
  39. package/server/src/config.js +22 -2
  40. package/server/src/demo/control.js +9 -1
  41. package/server/src/demo/files.js +49 -0
  42. package/server/src/demo/inbox.js +73 -0
  43. package/server/src/demo/review-routes.js +6 -1
  44. package/server/src/device-effects.js +3 -1
  45. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  46. package/server/src/drivers/herdr/consent-no-hook.js +411 -0
  47. package/server/src/drivers/herdr/refusals.js +226 -0
  48. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  49. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  50. package/server/src/drivers/herdr-driver.js +193 -295
  51. package/server/src/files/file-index.js +248 -0
  52. package/server/src/files/ignored.js +119 -0
  53. package/server/src/files/listing.js +82 -0
  54. package/server/src/files/path-rule.js +199 -0
  55. package/server/src/files/refusals.js +50 -0
  56. package/server/src/files/send-file.js +115 -0
  57. package/server/src/files/session-download.js +51 -0
  58. package/server/src/files/session-files.js +38 -0
  59. package/server/src/files/session-gate.js +53 -0
  60. package/server/src/folder-gate/client.js +314 -0
  61. package/server/src/folder-gate/disk.js +455 -0
  62. package/server/src/folder-gate/folders.js +23 -0
  63. package/server/src/folder-gate/gate.js +220 -0
  64. package/server/src/folder-gate/helper.js +118 -0
  65. package/server/src/folder-gate/install.js +27 -0
  66. package/server/src/folder-gate/relay-worker.js +147 -0
  67. package/server/src/folder-gate/types.js +115 -0
  68. package/server/src/folder-gate/wire.js +170 -0
  69. package/server/src/fs-browse.js +55 -23
  70. package/server/src/fs-mkdir.js +3 -1
  71. package/server/src/git-status.js +16 -7
  72. package/server/src/git-watch.js +130 -19
  73. package/server/src/git-work-tree.js +3 -3
  74. package/server/src/herdr/audit.js +1 -1
  75. package/server/src/herdr/client.js +2 -2
  76. package/server/src/herdr/commands/discover.js +21 -9
  77. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  78. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  79. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  80. package/server/src/herdr/dialogs/index.js +12 -2
  81. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  82. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +166 -86
  83. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  84. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  85. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  86. package/server/src/herdr/dialogs/no-hook.js +63 -0
  87. package/server/src/herdr/dialogs/router.js +21 -6
  88. package/server/src/herdr/dialogs/screen/block.js +10 -0
  89. package/server/src/herdr/dialogs/screen/parse.js +33 -3
  90. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  91. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  92. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  93. package/server/src/herdr/jsonl-follow.js +55 -14
  94. package/server/src/herdr/jsonl-pending.js +25 -1
  95. package/server/src/herdr/provenance.js +3 -3
  96. package/server/src/herdr/socket.js +25 -28
  97. package/server/src/herdr/supervisor.js +13 -10
  98. package/server/src/herdr/transcript-path.js +36 -0
  99. package/server/src/herdr/trust.js +11 -8
  100. package/server/src/herdr/uploads-registry.js +3 -2
  101. package/server/src/herdr/uploads.js +170 -47
  102. package/server/src/inbox/card.js +18 -9
  103. package/server/src/inbox/dialogs.js +40 -12
  104. package/server/src/inbox/heads.js +55 -0
  105. package/server/src/inbox/inbox.js +24 -2
  106. package/server/src/inbox/index.js +3 -1
  107. package/server/src/index.js +44 -21
  108. package/server/src/install/repair.js +8 -0
  109. package/server/src/iroh/listener.js +3 -0
  110. package/server/src/iroh/log-budget.js +1 -0
  111. package/server/src/iroh/socket.js +2 -1
  112. package/server/src/log-timestamps.js +9 -4
  113. package/server/src/notes/store.js +3 -2
  114. package/server/src/router.js +20 -2
  115. package/server/src/routes/devices.js +2 -2
  116. package/server/src/routes/inbox.js +91 -0
  117. package/server/src/routes/projects.js +5 -1
  118. package/server/src/routes/sessions.js +145 -18
  119. package/server/src/routes/system.js +9 -4
  120. package/server/src/safe-read.js +86 -1
  121. package/server/src/sessions/companion-scope.js +16 -7
  122. package/server/src/sessions/demo-modules.js +16 -0
  123. package/server/src/sessions/diff-measure.js +30 -0
  124. package/server/src/sessions/done-retention.js +57 -0
  125. package/server/src/sessions/launch-gate.js +2 -2
  126. package/server/src/sessions/manager.js +78 -190
  127. package/server/src/sessions/project-scan.js +9 -3
  128. package/server/src/sessions/ring-buffer.js +5 -3
  129. package/server/src/sessions/seen-marks.js +9 -6
  130. package/server/src/sessions/session-git.js +31 -2
  131. package/server/src/sessions/session-scope.js +30 -0
  132. package/server/src/sessions/session.js +19 -0
  133. package/server/src/sessions/state-sentences.js +1 -1
  134. package/server/src/sessions/waiting-line.js +72 -0
  135. package/server/src/sse.js +143 -10
  136. package/server/src/term/herdr-backend.js +2 -2
  137. package/server/src/term/index.js +2 -15
  138. package/server/src/term/registry.js +4 -3
  139. package/server/src/term/ws.js +9 -1
  140. package/server/src/version.js +30 -0
@@ -1,3 +1,4 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
1
2
  import { MAX_TRANSCRIPT_MESSAGES } from '@rarog/shared';
2
3
  import { isServerSentence, say } from '@rarog/shared/sentences';
3
4
  import { MAX_MESSAGE_BYTES, RING_MAX_BYTES, RingBuffer, jsonBytes } from './ring-buffer.js';
@@ -493,6 +494,11 @@ export class Session {
493
494
  #messages = [];
494
495
  /** Suma wag wiadomości w `#messages` — drugi sufit transkryptu (bajty, nie sztuki). */
495
496
  #messageBytes = 0;
497
+ /**
498
+ * Random name of this memory of the session for {@link readMark}: a card made again under the same id (a pane that
499
+ * resumes the same conversation) numbers its messages from 1 again.
500
+ */
501
+ #memoryId = randomBytes(6).toString('base64url');
496
502
  /**
497
503
  * Ring `seq` of the newest event when the pane last moved to another engine conversation (`/clear`, `/resume`); `0`
498
504
  * before any move. A message in memory with a higher `seq` belongs to the conversation the session writes now
@@ -718,6 +724,19 @@ export class Session {
718
724
  const last = this.#messages.at(-1);
719
725
  return last !== undefined && (last.seq ?? 0) > this.conversationStartSeq ? last : undefined;
720
726
  }
727
+ /**
728
+ * Opaque name of what this memory of the session holds, the voice agent's read mark: the random name of this memory
729
+ * (`#memoryId`), the ring `seq` of the newest message (`0` before the first one) and a digest of {@link stateSince}.
730
+ * Every message added to the transcript ({@link appendMessage}: a prompt, an agent message, a notice, imported
731
+ * history) gives another one, and so does every new `stateSince` (a state change, a history import that moves it
732
+ * back). Frames sent while the state stands and seen marks leave it as it is. The state stamp is there because
733
+ * the messages reach the memory from the conversation file while herdr reports a turn's states on its own: a turn
734
+ * can end before its messages arrive. 37 characters at most (8 + 1 + 16 digits of a safe integer + 1 + 11).
735
+ */
736
+ get readMark() {
737
+ const stamp = createHash('sha256').update(this.stateSince).digest('base64url').slice(0, 11);
738
+ return `${this.#memoryId}.${String(this.#messages.at(-1)?.seq ?? 0)}.${stamp}`;
739
+ }
721
740
  get messageCount() {
722
741
  return this.#messages.length;
723
742
  }
@@ -413,7 +413,7 @@ export const HERDR_OUT_OF_SCOPE_MESSAGE = say('session.out-of-scope');
413
413
  * bramki zasięgu (patrz {@link HERDR_CODEX_GIT_MESSAGE}).
414
414
  */
415
415
  export const HERDR_OUT_OF_SCOPE_DIFF_MESSAGE = say('session.out-of-scope-diff');
416
- /** 400 na wysyłkę przy zamkniętym kanale zapisu (`RAROG_HERDR_SEND=0` albo nieznany protokół). */
416
+ /** 400 for a send while the write channel is closed (`RAROG_HERDR_SEND=0`). */
417
417
  export const HERDR_READ_ONLY_MESSAGE = say('session.herdr-read-only');
418
418
  /** 429 na wysyłkę odrzuconą przez throttle. */
419
419
  export const HERDR_THROTTLED_MESSAGE = say('session.send-throttled');
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The one line of a pending decision on the list card (`SessionSummary.waitingFor.text`): the text of a permission
3
+ * request or a question, cut to its first line and to `WAITING_TEXT_MAX` code points. Pure functions; the manager
4
+ * calls them when it builds `waitingFor`.
5
+ */
6
+ import { EXIT_PLAN_MODE_TOOL, WAITING_TEXT_MAX } from '@rarog/shared';
7
+ // Ta sama etykieta, którą dostaje wiersz tool-calla w transkrypcie — patrz `decisionText`.
8
+ import { summarizeToolInput } from '../drivers/tool-summary.js';
9
+ /**
10
+ * Treść decyzji do JEDNEJ linii karty listy: pierwsza linia, przycięta do `WAITING_TEXT_MAX`.
11
+ *
12
+ * Pierwsza linia, a nie „pierwsze 120 znaków całości": heredoc, wypisana treść `.env` i plan
13
+ * z trzema akapitami mają się tu nie zmieścić Z DEFINICJI. Cięcie po znakach jest wtedy tylko
14
+ * sufitem na długi jednolinijkowiec, a nie jedyną obroną przed wklejeniem pół pliku w sidebar.
15
+ * Wielokropek dokładamy WYŁĄCZNIE tam, gdzie faktycznie uciął — inaczej linia obiecuje ciąg
16
+ * dalszy, którego nie ma.
17
+ */
18
+ export function waitingText(raw) {
19
+ const first = raw.split('\n', 1)[0]?.trim() ?? '';
20
+ /*
21
+ * Cięcie po PUNKTACH KODOWYCH, nie po jednostkach UTF-16: `slice(0, 120)` na linii
22
+ * z emoji na 120. znaku rozcina parę surogatów, `trimEnd()` samotnego surogata nie usuwa
23
+ * (to nie biały znak) i na karcie staje „�…". Grafem z modyfikatorem (flaga, odcień skóry)
24
+ * może się tu jeszcze rozpaść na dwa znaki, ale każdy z nich jest wtedy PEŁNY — żaden
25
+ * nie jest połówką kodu, więc przeglądarka rysuje litery, a nie znak zastępczy.
26
+ */
27
+ const points = [...first];
28
+ if (points.length <= WAITING_TEXT_MAX)
29
+ return first;
30
+ return `${points.slice(0, WAITING_TEXT_MAX).join('').trimEnd()}…`;
31
+ }
32
+ /**
33
+ * Treść ZGODY do jednej linii karty listy — z `displayText`, ale nie zawsze dosłownie.
34
+ *
35
+ * `displayText` jest jednolinijkowy tylko dla narzędzi z polem `command`. Dla całej reszty
36
+ * (`Edit`, `Write`, `Read`, `Task`, `WebFetch`…) `toolInputText` oddaje pretty-printowany JSON,
37
+ * więc PIERWSZĄ linią jest sama klamra — i karta mówiła „zgoda: Edit · {". Z takiego opisu
38
+ * bierzemy dokładnie to, co bierze etykieta tool-calla w transkrypcie (`summarizeToolInput`:
39
+ * `file_path`, `path`, `pattern`, `url`, `query`), a gdy nie ma czego wziąć — nic: „zgoda: Edit"
40
+ * jest uczciwe, klamra nie. Rozpoznanie idzie po PIERWSZEJ LINII, a nie po `startsWith('{')`,
41
+ * bo komenda Basha też umie zacząć się klamrą (`{ echo a; }` — grupa powłoki).
42
+ *
43
+ * Dwa `displayText` nie są treścią decyzji i tu nie wchodzą wcale:
44
+ *
45
+ * - PLAN (`ExitPlanMode`): treścią jest CAŁY plan, a jego nagłówek („# Plan") nie mówi nic
46
+ * ponad samo słowo „plan", które karta i tak stawia. Kanał globalny nie ma powodu wozić
47
+ * danych, których nikt nie rysuje (kontrakt `WaitingFor.text`),
48
+ * - karta ZDEGRADOWANA (`canAllow === false`, `DEGRADED_DISPLAY_TEXT`): tam stoi zdanie
49
+ * O RAROGU („nie potwierdziłem, czego dotyczy ten dialog"), a nie o decyzji. Powód
50
+ * degradacji niesie karta sesji (`herdrDialogReason`), nie wiersz listy.
51
+ */
52
+ export function decisionText(permission) {
53
+ if (permission.toolName === EXIT_PLAN_MODE_TOOL)
54
+ return '';
55
+ if (permission.canAllow === false)
56
+ return '';
57
+ const display = permission.displayText;
58
+ const first = display.split('\n', 1)[0]?.trim() ?? '';
59
+ if (first !== '{' && first !== '{}' && first !== '[')
60
+ return display;
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(display);
64
+ }
65
+ catch {
66
+ // Opis przycięty do 20 kB ma na końcu stopkę, więc nie jest już poprawnym JSON-em.
67
+ return '';
68
+ }
69
+ const summary = summarizeToolInput(permission.toolName, parsed);
70
+ // Bez trafionego klucza `summarizeToolInput` oddaje NAZWĘ narzędzia — a ta stoi już obok.
71
+ return summary === permission.toolName ? '' : summary;
72
+ }
package/server/src/sse.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { HELLO_HEARTBEAT_MS, MAX_IMAGE_DATA_URL_BYTES } from '@rarog/shared';
2
2
  import { say } from '@rarog/shared/sentences';
3
3
  import { constants as zlibConstants, createGzip } from 'node:zlib';
4
+ import { folderGate as processFolderGate } from './folder-gate/install.js';
5
+ import { RING_MAX_BYTES } from './sessions/ring-buffer.js';
4
6
  /**
5
7
  * Default heartbeat interval (SSE comment plus a `ping` event) in ms. Every stream gets it, and `hello` announces it
6
8
  * as `heartbeatMs`, so a client can tell a stream that stopped without an error from a quiet one.
@@ -38,6 +40,22 @@ export const REPLAY_SNAPSHOT_LOG = 'sse: replay';
38
40
  * dziennie.
39
41
  */
40
42
  export const SNAPSHOT_IMAGE_BUDGET_BYTES = MAX_IMAGE_DATA_URL_BYTES;
43
+ /**
44
+ * Backlog a stream may hold unsent on top of twice its largest frame: the socket buffer of the response plus the
45
+ * compressor input.
46
+ *
47
+ * A single valid frame has no fixed upper size (a snapshot carries every pending consent card besides a full ring
48
+ * ({@link RING_MAX_BYTES}) and the image budget), and with compression it sits in the compressor input while its
49
+ * output already fills the socket buffer, so the allowance grows with the largest frame the stream was sent and one
50
+ * frame never cuts a healthy client. A stream above the ceiling is a client that stopped reading, and its bytes would
51
+ * otherwise stay in server memory until the socket times out.
52
+ */
53
+ export const SSE_WRITE_BUFFER_MAX = 2 * (RING_MAX_BYTES + SNAPSHOT_IMAGE_BUDGET_BYTES);
54
+ /**
55
+ * Phrase of the log line of a stream cut at the ceiling:
56
+ * `sse: write buffer over ceiling <MiB> MiB, stream closed (global|session <id>[, device <id>])`.
57
+ */
58
+ export const WRITE_BUFFER_CUT_LOG = 'sse: write buffer over ceiling';
41
59
  /**
42
60
  * Podmienny data URL dla obrazka poza budżetem: przezroczysty PNG 1×1.
43
61
  *
@@ -170,6 +188,12 @@ export class SseHub {
170
188
  notesFor;
171
189
  logger;
172
190
  onClientCount;
191
+ inbox;
192
+ folderGateOption;
193
+ /** The enabled gate the hub listens to since `start()`; `undefined` = no `folder-access` frames. */
194
+ folderGate;
195
+ /** The closed folders as JSON, as the streams last heard them: a change that keeps the list sends nothing. */
196
+ folderBlocked = '';
173
197
  gzipEnabled;
174
198
  createGzipFn;
175
199
  /**
@@ -186,6 +210,13 @@ export class SseHub {
186
210
  heartbeat = null;
187
211
  nextClientId = 1;
188
212
  started = false;
213
+ /**
214
+ * Token of the current {@link start}. The manager offers no way to detach a listener, so the listeners of an earlier
215
+ * start check it and do nothing after {@link closeAll}; the Inbox and folder gate listeners are detached for real.
216
+ */
217
+ subscription = null;
218
+ detachInbox;
219
+ detachFolderGate;
189
220
  constructor(options) {
190
221
  this.manager = options.manager;
191
222
  this.serverStartId = options.serverStartId;
@@ -194,6 +225,8 @@ export class SseHub {
194
225
  this.notesFor = options.notesFor;
195
226
  this.logger = options.logger;
196
227
  this.onClientCount = options.onClientCount;
228
+ this.inbox = options.inbox;
229
+ this.folderGateOption = options.folderGate;
197
230
  this.gzipEnabled = options.gzip ?? false;
198
231
  this.createGzipFn = options.createGzip ?? (() => createGzip());
199
232
  this.heartbeatMs = options.heartbeatMs ?? HEARTBEAT_MS;
@@ -222,7 +255,17 @@ export class SseHub {
222
255
  if (this.started)
223
256
  return;
224
257
  this.started = true;
225
- this.manager.onEvent((scope, seq, ev) => { this.broadcast(scope, seq, ev); });
258
+ const token = {};
259
+ this.subscription = token;
260
+ this.manager.onEvent((scope, seq, ev) => { if (this.subscription === token)
261
+ this.broadcast(scope, seq, ev); });
262
+ this.detachInbox = this.inbox?.onEvent((event) => { this.broadcastInbox(event); });
263
+ const gate = this.folderGateOption ?? processFolderGate();
264
+ if (gate.enabled) {
265
+ this.folderGate = gate;
266
+ this.folderBlocked = JSON.stringify(gate.blocked());
267
+ this.detachFolderGate = gate.onChange(() => { this.broadcastFolderAccess(gate); });
268
+ }
226
269
  if (this.heartbeatMs > 0) {
227
270
  this.heartbeat = this.setIntervalFn(() => { this.sendHeartbeat(); }, this.heartbeatMs);
228
271
  }
@@ -290,6 +333,32 @@ export class SseHub {
290
333
  if (frame !== null && ready.type === 'session-changed')
291
334
  this.announceNewCwd(ready.session.cwd);
292
335
  }
336
+ /**
337
+ * Sends an Inbox event to the global streams opened with `inbox=1`; an older app never asks, so it never gets one.
338
+ * Fleeting like `herdr-status`: no `id:`, nothing to replay, a stream that opens later gets `inbox-heads`.
339
+ */
340
+ broadcastInbox(event) {
341
+ let frame = null;
342
+ for (const client of this.clients.values()) {
343
+ if (!client.inbox)
344
+ continue;
345
+ frame ??= formatSseEvent(event, null, this.serverStartId);
346
+ this.writeRaw(client, frame);
347
+ }
348
+ }
349
+ /**
350
+ * Sends `folder-access` to every global stream when the list of closed folders changed. The gate tells about every
351
+ * change of state, also one the list does not show (unknown to open, a missing folder). Fleeting like `herdr-status`:
352
+ * no `id:`, and a stream that opens later gets the list right after `sessions-snapshot`.
353
+ */
354
+ broadcastFolderAccess(gate) {
355
+ const blocked = gate.blocked();
356
+ const json = JSON.stringify(blocked);
357
+ if (json === this.folderBlocked)
358
+ return;
359
+ this.folderBlocked = json;
360
+ this.broadcast('global', null, { type: 'folder-access', blocked });
361
+ }
293
362
  /**
294
363
  * Dokłada do ramki `sessions-snapshot` pole `notesCwds` i odnotowuje, o czym klient już wie.
295
364
  *
@@ -334,9 +403,12 @@ export class SseHub {
334
403
  /**
335
404
  * Otwiera strumień globalny: `hello` + `sessions-snapshot`, potem live.
336
405
  * `Last-Event-ID` jest tu celowo ignorowany — snapshot listy jest tani i zawsze aktualny.
406
+ * With the folder gate on, `folder-access` follows the list.
407
+ * `inbox`: the client asked for the Inbox heads (`inbox=1`); on a server with an Inbox `inbox-heads` follows the
408
+ * list and the stream gets the Inbox events from then on.
337
409
  */
338
- openGlobal(res, owner, acceptEncoding) {
339
- const client = this.register('global', res, owner, acceptEncoding);
410
+ openGlobal(res, owner, acceptEncoding, inbox = false) {
411
+ const client = this.register('global', res, owner, acceptEncoding, inbox && this.inbox !== undefined);
340
412
  this.send(client, {
341
413
  type: 'hello',
342
414
  protocolVersion: this.protocolVersion,
@@ -363,6 +435,14 @@ export class SseHub {
363
435
  * Liczy to `withNotes`, ta sama metoda co przy ramkach z managera — patrz `broadcast`.
364
436
  */
365
437
  this.send(client, this.withNotes(snapshot), null);
438
+ // The closed macOS folders, also none: an empty list clears a banner the app kept from before the reconnect.
439
+ if (this.folderGate !== undefined) {
440
+ this.send(client, { type: 'folder-access', blocked: this.folderGate.blocked() }, null);
441
+ }
442
+ // The Inbox heads after the list (`inbox=1`), so the app knows every session a head names.
443
+ if (client.inbox && this.inbox !== undefined) {
444
+ this.send(client, { type: 'inbox-heads', heads: this.inbox.heads() }, null);
445
+ }
366
446
  }
367
447
  /**
368
448
  * Otwiera strumień transkryptu sesji.
@@ -435,7 +515,7 @@ export class SseHub {
435
515
  }
436
516
  return closed;
437
517
  }
438
- /** Zamyka wszystkie strumienie i zatrzymuje heartbeat (graceful shutdown). */
518
+ /** Closes every stream, stops the heartbeat and detaches what {@link start} attached (graceful shutdown). */
439
519
  closeAll() {
440
520
  for (const client of this.clients.values())
441
521
  this.endClient(client);
@@ -445,6 +525,13 @@ export class SseHub {
445
525
  this.clearIntervalFn(this.heartbeat);
446
526
  this.heartbeat = null;
447
527
  }
528
+ this.subscription = null;
529
+ this.detachInbox?.();
530
+ this.detachInbox = undefined;
531
+ this.detachFolderGate?.();
532
+ this.detachFolderGate = undefined;
533
+ this.folderGate = undefined;
534
+ this.started = false;
448
535
  }
449
536
  /**
450
537
  * Wysyła `transcript-snapshot` i oddaje ramkę — waga trafia do linii logu powtórki. `onFlushed` dostaje wagę ramki po
@@ -468,10 +555,11 @@ export class SseHub {
468
555
  this.writeChecked(client, frame, onFlushed);
469
556
  return frame;
470
557
  }
471
- register(scope, res, owner, acceptEncoding) {
558
+ register(scope, res, owner, acceptEncoding, inbox = false) {
472
559
  const id = this.nextClientId++;
473
560
  const gzip = this.gzipEnabled && acceptsGzip(acceptEncoding) ? this.createGzipFn() : undefined;
474
- const client = { id, scope, res, owner, gzip, bytesOut: 0, flushedBytes: 0 };
561
+ const client = { id, scope, inbox, res, owner, gzip, bytesOut: 0, flushedBytes: 0, cut: false,
562
+ largestFrame: 0 };
475
563
  res.writeHead(200, {
476
564
  ...SSE_HEADERS,
477
565
  // Przy włączonej kompresji odpowiedź zależy od `Accept-Encoding`; pośrednik nie ma jej podać innemu klientowi.
@@ -485,6 +573,8 @@ export class SseHub {
485
573
  */
486
574
  const sink = res;
487
575
  gzip.on('data', (bytes) => {
576
+ if (client.cut)
577
+ return;
488
578
  client.bytesOut += bytes.length;
489
579
  try {
490
580
  sink.write(bytes);
@@ -493,7 +583,9 @@ export class SseHub {
493
583
  // Zerwane gniazdo: klient znika z rejestru, kompresor się zamyka.
494
584
  this.dropClient(id);
495
585
  gzip.destroy();
586
+ return;
496
587
  }
588
+ this.cutIfOverCeiling(client);
497
589
  });
498
590
  // Błąd kompresora kończy strumień; klient łączy się od nowa.
499
591
  gzip.on('error', () => {
@@ -507,8 +599,11 @@ export class SseHub {
507
599
  });
508
600
  }
509
601
  this.writeRaw(client, `retry: ${RETRY_MS}\n\n`);
510
- this.clients.set(id, client);
511
- this.countChanged();
602
+ // A socket already over the ceiling cuts the stream at its first line; such a client never enters the register.
603
+ if (!client.cut) {
604
+ this.clients.set(id, client);
605
+ this.countChanged();
606
+ }
512
607
  res.on('close', () => {
513
608
  this.dropClient(id);
514
609
  // Rozłączenie: kompresor nie ma już dokąd pisać, więc zamyka się od razu.
@@ -550,11 +645,18 @@ export class SseHub {
550
645
  * (`write()` oddało `false`), `null` = gniazdo zerwane i klient wyrejestrowany.
551
646
  */
552
647
  writeChecked(client, chunk, onFlushed) {
648
+ if (client.cut)
649
+ return null;
650
+ client.largestFrame = Math.max(client.largestFrame, Buffer.byteLength(chunk));
553
651
  try {
554
652
  const gzip = client.gzip;
555
- if (gzip === undefined)
556
- return client.res.write(chunk);
653
+ if (gzip === undefined) {
654
+ const accepted = client.res.write(chunk);
655
+ return this.cutIfOverCeiling(client) ? null : accepted;
656
+ }
557
657
  const accepted = gzip.write(chunk);
658
+ if (this.cutIfOverCeiling(client))
659
+ return null;
558
660
  /*
559
661
  * Opróżnienie bufora po KAŻDYM zapisie (ramka, ping, `retry:`): bez niego gzip trzyma bajty, aż uzbiera blok,
560
662
  * a ping czekałby na następną ramkę. `Z_SYNC_FLUSH` zostawia słownik, więc ramka dalej kompresuje się względem
@@ -574,4 +676,35 @@ export class SseHub {
574
676
  return null;
575
677
  }
576
678
  }
679
+ /**
680
+ * Cuts the stream when its unsent bytes pass {@link SSE_WRITE_BUFFER_MAX} plus twice its largest frame: the response
681
+ * buffer plus, with compression, the compressor input not yet compressed. The connection is destroyed rather than ended, because the
682
+ * stream would never get its bytes out; the client reconnects and gets a snapshot or a replay.
683
+ *
684
+ * @returns `true` = the stream was cut now.
685
+ */
686
+ cutIfOverCeiling(client) {
687
+ if (client.cut)
688
+ return false;
689
+ const buffered = (client.res.writableLength ?? 0) + (client.gzip?.writableLength ?? 0);
690
+ if (buffered <= SSE_WRITE_BUFFER_MAX + 2 * client.largestFrame)
691
+ return false;
692
+ client.cut = true;
693
+ this.dropClient(client.id);
694
+ client.gzip?.destroy();
695
+ try {
696
+ if (client.res.destroy === undefined)
697
+ client.res.end();
698
+ else
699
+ client.res.destroy();
700
+ }
701
+ catch {
702
+ // The client may already be gone.
703
+ }
704
+ const mib = (bytes) => (bytes / (1024 * 1024)).toFixed(1);
705
+ const scope = client.scope === 'global' ? 'global' : `session ${client.scope}`;
706
+ const device = client.owner === undefined ? '' : `, device ${client.owner}`;
707
+ this.logger?.(`${WRITE_BUFFER_CUT_LOG} ${mib(SSE_WRITE_BUFFER_MAX)} MiB, stream closed (${scope}${device})`);
708
+ return true;
709
+ }
577
710
  }
@@ -550,8 +550,8 @@ export function createHerdrBackend(options) {
550
550
  *
551
551
  * Niczego NIE zamyka (rola `lazygit`/`popup` też nie: token mógł zniknąć bez restartu herdr,
552
552
  * a w panelu żyje praca) i niczego nie zakłada. Każda mutacja stoi za `refusal()` i `disposed`,
553
- * sprawdzanymi po każdym `await`; `HerdrReadOnlyError` (nieznany protokół, `SEND=0` po
554
- * stronie gniazda) kończy mutacje przebiegu jedną linią logu.
553
+ * sprawdzanymi po każdym `await`; `HerdrReadOnlyError` (`SEND=0` at the socket, a second line
554
+ * behind `refusal()`) ends the pass's mutations with one log line.
555
555
  */
556
556
  async function reconcilePass() {
557
557
  if (disposed)
@@ -1,20 +1,7 @@
1
- /**
2
- * Terminal PTY — złożenie ficzeru.
3
- *
4
- * Jedno wejście dla `index.ts` i routera: backend trwałej powłoki, żniwiarz bezczynności
5
- * przy starcie, rejestr, transport WS i sprzątanie przy zamknięciu serwera.
6
- *
7
- * **Powłoka mieszka w PANELU herdr**: `RAROG_HERDR_LAUNCH=0` i `RAROG_HERDR_SEND=0` odmawiają
8
- * założenia terminala (`refusal()` w `herdr-backend.ts`, 409 z routera), a żniwa paneli
9
- * chodzą tylko wtedy, gdy wolno je w ogóle zakładać.
10
- *
11
- * WŁASNYM killswitchem terminala jest `RAROG_TERM` i tylko on gasi ficzer w całości.
12
- * Granice spisane w `docs/security-model.md` (sekcja terminala, punkty 1 i 10).
13
- */
14
- import { realpathSync } from 'node:fs';
15
1
  import { redact } from '../auth/index.js';
16
2
  import { TERM_START_RETRY_MS, TERM_TOKEN_REFRESH_MS, validateProjectCwd } from '../config.js';
17
3
  import { DEMO_SERVER_SYSTEM } from '../demo/mac.js';
4
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
18
5
  import { serverSystem } from '../version.js';
19
6
  import { createHerdrBackend } from './herdr-backend.js';
20
7
  import { matchTermId, shouldReap } from './lifecycle.js';
@@ -139,7 +126,7 @@ async function adoptSurvivors(backend, config, registry, log) {
139
126
  continue;
140
127
  let real;
141
128
  try {
142
- real = realpathSync(session.cwd);
129
+ real = DIRECT_DISK.sync('realpath', { path: session.cwd });
143
130
  }
144
131
  catch {
145
132
  continue; // Katalog zniknął — sesja zostaje dla żniwiarza, nie dla rejestru.
@@ -18,9 +18,9 @@
18
18
  * **Zero logowania treści.** Do `server.log` idzie WYŁĄCZNIE cykl życia (id, cwd, spawn,
19
19
  * kill, exit, liczba gniazd). Ani jeden bajt wejścia ani wyjścia powłoki.
20
20
  */
21
- import { realpathSync } from 'node:fs';
22
21
  import { isPopupRole, TERM_SLOTS_MAX } from '@rarog/shared';
23
22
  import { redact } from '../auth/index.js';
23
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
24
24
  import { serverSystem } from '../version.js';
25
25
  import { say } from '@rarog/shared/sentences';
26
26
  import { TermBackendRetryError, TermHandleStaleError, errFrame } from './backend.js';
@@ -88,8 +88,9 @@ export class TermRegistry {
88
88
  constructor(options) {
89
89
  this.config = options.config;
90
90
  this.log = options.logger;
91
- this.realPath = options.realPath ?? realpathSync.native;
92
- this.legacyRealPath = options.legacyRealPath ?? options.realPath ?? realpathSync;
91
+ this.realPath = options.realPath ?? ((candidate) => DIRECT_DISK.sync('realpathNative', { path: candidate }));
92
+ this.legacyRealPath = options.legacyRealPath ?? options.realPath
93
+ ?? ((candidate) => DIRECT_DISK.sync('realpath', { path: candidate }));
93
94
  this.setTimer = options.setTimer ?? ((cb, ms) => setTimeout(cb, ms));
94
95
  this.clearTimer = options.clearTimer ?? ((timer) => { clearTimeout(timer); });
95
96
  this.backend = options.backend;
@@ -40,7 +40,15 @@ export const TERM_PASTE_INTERRUPTED_LOG = 'input in the middle of a paste';
40
40
  * starszy klient nie widzi żadnej zmiany.
41
41
  */
42
42
  export function termAttachFromUrl(rawUrl) {
43
- const url = new URL(rawUrl ?? '/', 'http://127.0.0.1');
43
+ // The HTTP parser lets through targets `URL` rejects (`//:/`); this runs before any credential, and a throw here
44
+ // would end the process, so an unparsable target is a path outside `/api/term/:id`.
45
+ let url;
46
+ try {
47
+ url = new URL(rawUrl ?? '/', 'http://127.0.0.1');
48
+ }
49
+ catch {
50
+ return null;
51
+ }
44
52
  const match = /^\/api\/term\/([^/]+)$/.exec(url.pathname.replace(/\/+$/, ''));
45
53
  const id = match?.[1];
46
54
  if (id === undefined || !TERM_ID_RE.test(id))
@@ -57,6 +57,36 @@ export const RAROG_VERSION = readPackageVersion();
57
57
  export const SERVER_CAPABILITIES = [
58
58
  'device-auth', 'pair', 'pair-from-device', 'push-relay', 'push-e2e-v2', 'companion', 'companion-sessions',
59
59
  ];
60
+ /**
61
+ * `inbox` — the server keeps an Inbox card per session: `GET /api/stream?inbox=1` adds the Inbox heads, and
62
+ * `GET /api/inbox`, `GET /api/inbox/:sessionId` and `POST /api/inbox/:sessionId/remove|restore` answer. A capability of
63
+ * the configuration, unlike the list above: absent with `RAROG_INBOX=0`, and then the app hides its Inbox.
64
+ */
65
+ export const INBOX_CAPABILITY = 'inbox';
66
+ /**
67
+ * `files` — the session file routes answer: `GET /api/sessions/:id/files?dir=` lists a directory of the session and
68
+ * `GET /api/sessions/:id/files/raw?path=` sends one file of it. A capability of the configuration, like the Inbox:
69
+ * absent while the routes are off, and then the app builds its file tree from the changes of `git-status` alone.
70
+ */
71
+ export const FILES_CAPABILITY = 'files';
72
+ /**
73
+ * `file-index` — `GET /api/sessions/:id/files/index` answers with the index of a session's files, which the app
74
+ * searches. Announced with {@link FILES_CAPABILITY} and under the same switch; an app that does not see it searches
75
+ * only the directories it has listed.
76
+ */
77
+ export const FILE_INDEX_CAPABILITY = 'file-index';
78
+ /**
79
+ * The capabilities announced now: {@link SERVER_CAPABILITIES}, plus {@link INBOX_CAPABILITY} when the Inbox is on and
80
+ * {@link FILES_CAPABILITY} with {@link FILE_INDEX_CAPABILITY} when the session file routes answer (missing `files` =
81
+ * they do not).
82
+ */
83
+ export function serverCapabilities(features) {
84
+ return [
85
+ ...SERVER_CAPABILITIES,
86
+ ...(features.inbox ? [INBOX_CAPABILITY] : []),
87
+ ...(features.files === true ? [FILES_CAPABILITY, FILE_INDEX_CAPABILITY] : []),
88
+ ];
89
+ }
60
90
  /**
61
91
  * System maszyny serwera dla `GET /api/version` (`system`): `darwin` → `macos`, `linux` → `linux`, każdy inny
62
92
  * `process.platform` → `other`. Z tego pola apka bierze słowo maszyny („Mac” albo „VPS”).