@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
@@ -4,10 +4,19 @@ import { historyWithoutEcho, readHistoryTail, readRange, sizeOf } from '../herdr
4
4
  import { HISTORY_MAX_BYTES } from '../herdr/jsonl-follow.js';
5
5
  import { locateTranscript } from '../herdr/transcript-path.js';
6
6
  import { RING_MAX_BYTES, jsonBytes } from '../sessions/ring-buffer.js';
7
- import { transcriptMessage } from '../sessions/session.js';
7
+ import { MESSAGE_TRIMMED_MARK, transcriptMessage } from '../sessions/session.js';
8
8
  import { conversationToken } from './conversation.js';
9
9
  /** First window of the tail read: enough for three turns of most sessions; it doubles up to the history ceiling. */
10
10
  export const TURNS_FIRST_WINDOW = 256 * 1024;
11
+ /**
12
+ * `readMark` of an answer that did not read the session's result: an answer with no messages (a failed read, i.e. no
13
+ * file, a lookup that throws, a size or a first read that fails, and a conversation with nothing to read alike) and an
14
+ * answer with a message trimmed to the per-message ceiling ({@link hasTrimmedMessage}). The mark names no read: it has
15
+ * no dot, while `Session.readMark` always has three dot-separated parts, so the voice agent's pick-up built from it
16
+ * never meets the session's mark and gets the 409. Inside the 1–64 character bound of the turns answer and of the
17
+ * pick-up body.
18
+ */
19
+ export const NO_READ_MARK = 'no-read';
11
20
  /**
12
21
  * Whether a message opens a turn, by the rule of the app's projection: a human message, not a harness notice and not
13
22
  * a blocked prompt, with text outside the server's own sentences, an image block or an attachment. A command output,
@@ -49,6 +58,21 @@ function wireHistory(entries, now) {
49
58
  seq: index + 1,
50
59
  }));
51
60
  }
61
+ /**
62
+ * Whether a returned message lost its end: `transcriptMessage` keeps the start of a message over the per-message
63
+ * ceiling and closes it with {@link MESSAGE_TRIMMED_MARK}, a server sentence known by its `ref` (a text from the file
64
+ * never carries one). The history merges consecutive agent entries into one message, while the server's memory of a
65
+ * live session got them one by one, so the newest result can be in the memory and lost in the answer. Any trimmed
66
+ * message counts, also one of an older returned turn: the answer is what the agent relays as the session's last turns.
67
+ * The other cuts of the read (the window, the message limit, the cut to turns and the byte ceiling) drop from the old
68
+ * end and keep the newest message.
69
+ */
70
+ function hasTrimmedMessage(messages) {
71
+ return messages.some((m) => {
72
+ const last = m.blocks.at(-1);
73
+ return last?.type === 'text' && last.ref?.code === MESSAGE_TRIMMED_MARK.ref.code;
74
+ });
75
+ }
52
76
  /** Byte ceiling of the session's transcript (`Session.appendMessage`): the oldest messages drop first. */
53
77
  function capBytes(messages) {
54
78
  let bytes = messages.reduce((sum, m) => sum + jsonBytes(m), 0);
@@ -66,13 +90,16 @@ export function createCompanionTurns(opts) {
66
90
  const maxBytes = Math.max(firstWindow, opts.maxBytes ?? HISTORY_MAX_BYTES);
67
91
  return {
68
92
  async read(target, count) {
69
- const base = { conversation: token(target.agentSessionId), stateSince: target.stateSince };
93
+ const conversation = token(target.agentSessionId);
94
+ const nothing = {
95
+ messages: [], conversation, stateSince: target.stateSince, readMark: NO_READ_MARK, complete: true,
96
+ };
70
97
  const file = target.agentSessionId === undefined
71
98
  ? null
72
99
  : await opts.locate(target.cwd, target.agentSessionId).catch(() => null);
73
100
  const size = file === null ? null : await sizeOf(file);
74
101
  if (file === null || size === null)
75
- return { messages: [], ...base, complete: true };
102
+ return nothing;
76
103
  const at = now();
77
104
  // One turn start more than asked: the oldest wanted turn then lies whole inside the window.
78
105
  const tail = await readHistoryTail(readRange, file, size, {
@@ -80,13 +107,17 @@ export function createCompanionTurns(opts) {
80
107
  enough: (entries) => wireHistory(entries, at).filter(isTurnStart).length > count,
81
108
  });
82
109
  if (tail === null)
83
- return { messages: [], ...base, complete: true };
110
+ return nothing;
84
111
  const wholeFile = tail.start === 0 && tail.messages.length < HERDR_HISTORY_MESSAGES;
85
112
  const turns = lastTurns(wireHistory(tail.messages, at), count, wholeFile);
86
113
  const capped = capBytes(turns.messages);
114
+ if (capped.messages.length === 0)
115
+ return { ...nothing, complete: turns.complete };
87
116
  return {
88
117
  messages: capped.messages.map((m, index) => ({ ...m, seq: index + 1 })),
89
- ...base,
118
+ conversation,
119
+ stateSince: target.stateSince,
120
+ readMark: hasTrimmedMessage(capped.messages) ? NO_READ_MARK : target.readMark,
90
121
  complete: turns.complete && !capped.dropped,
91
122
  };
92
123
  },
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The session files settings: the switch of the file routes (`RAROG_FILES`) and the largest file the server sends
3
+ * (`RAROG_FILES_MAX_MB`). A value out of range stops the start, so a typo never leaves a limit the owner did not set.
4
+ */
5
+ import { ConfigError, FILES_ENV, FILES_MAX_MB_ENV } from '../config-env.js';
6
+ /** Limit of a sent file in megabytes without the variable. */
7
+ export const DEFAULT_FILES_MAX_MB = 50;
8
+ /** The highest value `RAROG_FILES_MAX_MB` takes. */
9
+ export const FILES_MAX_MB_CEILING = 1024;
10
+ const MIB = 1024 * 1024;
11
+ /** Session files switch; missing, empty or `1` = on, `0` = off, any other value stops the start. */
12
+ export function parseFilesEnabled(raw) {
13
+ const value = raw?.trim() ?? '';
14
+ if (value === '' || value === '1')
15
+ return true;
16
+ if (value === '0')
17
+ return false;
18
+ throw new ConfigError(`${FILES_ENV} takes 1 or 0 (got: ${value}).`);
19
+ }
20
+ /**
21
+ * The largest sent file in bytes, from whole megabytes (`RAROG_FILES_MAX_MB`); missing or empty = 50 MB. Only digits
22
+ * from 1 to 1024: a fraction, an exponent, a hex number or a value out of range stops the start.
23
+ */
24
+ export function parseFilesMaxBytes(raw) {
25
+ const value = raw?.trim() ?? '';
26
+ if (value === '')
27
+ return DEFAULT_FILES_MAX_MB * MIB;
28
+ const mb = /^\d{1,4}$/.test(value) ? Number(value) : Number.NaN;
29
+ if (mb >= 1 && mb <= FILES_MAX_MB_CEILING)
30
+ return mb * MIB;
31
+ throw new ConfigError(`${FILES_MAX_MB_ENV} takes whole megabytes from 1 to ${String(FILES_MAX_MB_CEILING)} (got: ${value}).`);
32
+ }
@@ -4,7 +4,7 @@
4
4
  * status and the consent channel's restart grace. The
5
5
  * consent channel, dialog layer 2 and tall dialog guard flags stay in `server/src/config.ts`.
6
6
  */
7
- import { COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, CONSENT_RESTART_GRACE_ENV, ConfigError, PR_STATUS_ENV, SSE_GZIP_ENV, } from '../config-env.js';
7
+ import { COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, CONSENT_RESTART_GRACE_ENV, ConfigError, INBOX_ENV, PR_STATUS_ENV, SSE_GZIP_ENV, } from '../config-env.js';
8
8
  import { HOOK_RESTART_GRACE_DEFAULT_MS, HOOK_RESTART_GRACE_MAX_MS } from '../herdr/dialogs/hook/contract.js';
9
9
  /**
10
10
  * Restart grace of the consent channel in ms from whole seconds (`RAROG_CONSENT_RESTART_GRACE`); no value = 45 s,
@@ -107,6 +107,15 @@ export function parsePrStatusEnabled(raw) {
107
107
  return false;
108
108
  throw new ConfigError(`${PR_STATUS_ENV} takes 1 or 0 (got: ${value}).`);
109
109
  }
110
+ /** Inbox flag; missing, empty or `1` = on, `0` = off, any other value stops the start. */
111
+ export function parseInboxEnabled(raw) {
112
+ const value = raw?.trim() ?? '';
113
+ if (value === '' || value === '1')
114
+ return true;
115
+ if (value === '0')
116
+ return false;
117
+ throw new ConfigError(`${INBOX_ENV} takes 1 or 0 (got: ${value}).`);
118
+ }
110
119
  /** Voice agent flag; missing or `0` = off, `1` = on, any other value stops the start. */
111
120
  export function parseCompanionEnabled(raw) {
112
121
  const value = raw?.trim() ?? '';
@@ -10,6 +10,8 @@ import path from 'node:path';
10
10
  export const PROTECTED_HOME_DIRS = [
11
11
  'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures',
12
12
  ];
13
+ /** The protected folders where projects usually live: the part of {@link PROTECTED_HOME_DIRS} a folder gate opens. */
14
+ export const OPEN_HOME_DIRS = ['Desktop', 'Documents', 'Downloads'];
13
15
  /**
14
16
  * A name or path folded the way the default macOS disk (APFS, case-insensitive) compares names, so spellings that disk
15
17
  * reads as one name fold alike: decomposed form (NFD), then lower, upper and lower case, then composed form (NFC).
@@ -3,11 +3,11 @@
3
3
  * that every caller uses before Rarog runs anything in a directory. `loadConfig` (`server/src/config.ts`) passes in
4
4
  * the values it read through `readEnv`.
5
5
  */
6
- import { realpathSync, statSync } from 'node:fs';
7
6
  import os from 'node:os';
8
7
  import path from 'node:path';
9
8
  import { say } from '@rarog/shared/sentences';
10
9
  import { ConfigError, HERDR_ROOTS_ENV, PROJECT_ROOTS_ENV } from '../config-env.js';
10
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
11
11
  import { insideWorkArea, isExcludedPath, resolveInWorkArea } from './work-area.js';
12
12
  // ---------------------------------------------------------------------------
13
13
  // Korzenie projektów i walidacja cwd
@@ -85,9 +85,11 @@ export function isInsideAnyRoot(candidate, roots) {
85
85
  return false;
86
86
  return roots.some((root) => isInside(candidate, root));
87
87
  }
88
+ /** `realpathSync` of the work-area disk port: the JavaScript walk, letter case as written. */
89
+ const realpathOnDisk = (candidate) => DIRECT_DISK.sync('realpath', { path: candidate });
88
90
  function realIsDirectory(candidate) {
89
91
  try {
90
- return statSync(candidate).isDirectory();
92
+ return DIRECT_DISK.sync('stat', { path: candidate }).isDirectory();
91
93
  }
92
94
  catch {
93
95
  return false;
@@ -110,7 +112,7 @@ function realIsDirectory(candidate) {
110
112
  * nadrzędnym), odpada. Korzeń, którego nie da się rozwiązać, zostaje w postaci leksykalnej —
111
113
  * nieistniejący korzeń nie może rozszerzać granicy, więc jego „zawężenie" byłoby tylko szumem.
112
114
  */
113
- export function isInsideAnyRootReal(candidate, roots, realPath = realpathSync) {
115
+ export function isInsideAnyRootReal(candidate, roots, realPath = realpathOnDisk) {
114
116
  if (!isInsideAnyRoot(candidate, roots))
115
117
  return false;
116
118
  let resolved;
@@ -172,7 +174,8 @@ function realPathEntersHidden(resolved, realRoots) {
172
174
  * 5. the work area, still text only: a macOS-protected folder of home is refused unless a root lies in it
173
175
  * (`config/work-area.ts`); a read there makes macOS ask for access, and this check is synchronous,
174
176
  * 6. the symlink walk (`resolveInWorkArea`) as the first disk access: it stops before an excluded folder, so
175
- * `<root>/link -> ~/Desktop/x` is refused without a read in `Desktop`; a missing segment is "not found",
177
+ * `<root>/link -> ~/Desktop/x` is refused without a read in `Desktop`; a missing segment is "not found", and a
178
+ * guarded folder the folder gate holds closed gives the sentence of its state (metadata only, no helper call),
176
179
  * 7. musi istnieć i być katalogiem,
177
180
  * 8. i dopiero teraz to samo pytanie po ROZWIĄZANIU dowiązań — kroki 4 i 7 same
178
181
  * przepuszczały `<korzeń>/skrót -> /gdziekolwiek`; the resolved path must also lie outside the excluded folders,
@@ -217,7 +220,7 @@ export function validateProjectCwd(input, roots, opts = {}) {
217
220
  if (!insideWorkArea(cwd, roots, home)) {
218
221
  return { ok: false, sentence: say('rest.cwd-protected') };
219
222
  }
220
- const resolveOne = opts.realPath ?? realpathSync;
223
+ const resolveOne = opts.realPath ?? realpathOnDisk;
221
224
  const onDisk = (entry) => {
222
225
  try {
223
226
  return resolveOne(entry);
@@ -234,8 +237,10 @@ export function validateProjectCwd(input, roots, opts = {}) {
234
237
  const walked = resolveInWorkArea(cwd, realRoots, realHome, opts.walk);
235
238
  if (walked.kind === 'missing')
236
239
  return { ok: false, sentence: say('rest.cwd-not-found') };
237
- if (walked.kind === 'excluded')
238
- return { ok: false, sentence: say('rest.cwd-symlink-escape') };
240
+ if (walked.kind === 'excluded') {
241
+ // A guarded folder the folder gate holds closed: the sentence of its state, not a link that leads out.
242
+ return { ok: false, sentence: walked.closed?.sentence ?? say('rest.cwd-symlink-escape') };
243
+ }
239
244
  resolved = walked.path;
240
245
  }
241
246
  if (!isDirectory(cwd)) {
@@ -243,7 +248,7 @@ export function validateProjectCwd(input, roots, opts = {}) {
243
248
  }
244
249
  if (resolved === null) {
245
250
  try {
246
- resolved = opts.realPath === undefined ? realpathSync(cwd) : opts.realPath(cwd);
251
+ resolved = opts.realPath === undefined ? realpathOnDisk(cwd) : opts.realPath(cwd);
247
252
  }
248
253
  catch {
249
254
  return { ok: false, sentence: say('rest.cwd-symlink-escape') };
@@ -5,10 +5,13 @@
5
5
  * unless a root lies in that folder (`protected-dirs.ts`). `insideWorkArea` judges text only; `resolveInWorkArea`
6
6
  * resolves symlinks one segment at a time and stops before it would touch an excluded folder; `inWorkAreaOnDisk`
7
7
  * puts the two together for a directory that already exists, and `inExcludedOnDisk` asks only about the excluded
8
- * folders, for a directory that may lie outside the roots. The module never lists a directory and never reads a file.
8
+ * folders, for a directory that may lie outside the roots. A guarded folder the folder gate holds closed is out of the
9
+ * work area too, unless the caller asks to ignore the gate (`WalkOptions`). The module never lists a directory and
10
+ * never reads a file.
9
11
  */
10
- import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
11
12
  import path from 'node:path';
13
+ import { DIRECT_DISK, closedFolderOf } from '../folder-gate/disk.js';
14
+ import { FolderGateError } from '../folder-gate/types.js';
12
15
  import { PROTECTED_HOME_DIRS, foldCase, inProtectedFolder, openedByRoot } from './protected-dirs.js';
13
16
  const lower = (value) => value.toLowerCase();
14
17
  /** Whether `candidate` is `root` or lies inside it, by path segments. */
@@ -58,7 +61,14 @@ export function insideWorkArea(cwd, roots, home) {
58
61
  });
59
62
  return inRoot && !isExcludedPath(resolved, roots, home);
60
63
  }
61
- const DISK = { lstat: (file) => lstatSync(file), readlink: (file) => readlinkSync(file) };
64
+ /** The walk's view of the work-area disk port. */
65
+ export function walkDiskOf(disk) {
66
+ return {
67
+ lstat: (file) => disk.sync('lstat', { path: file }),
68
+ readlink: (file) => disk.sync('readlink', { path: file }),
69
+ };
70
+ }
71
+ const DISK = walkDiskOf(DIRECT_DISK);
62
72
  /** Symlinks followed in one walk before it gives up, as `ELOOP` of the system. */
63
73
  const MAX_LINKS = 40;
64
74
  /**
@@ -66,9 +76,13 @@ const MAX_LINKS = 40;
66
76
  * built so far is checked, and one in an excluded folder ends the walk (`excluded`) without a read there. A
67
77
  * symlink's target is walked the same way, so `<root>/link -> ~/Desktop/x` never reaches `Desktop`. An excluded
68
78
  * folder that holds a root (`~/Documents` on the way to the root `~/Documents/Projects`) may be passed.
69
- * `missing`: a segment does not exist, cannot be checked, or the links loop. `roots` and `home` in on-disk form.
79
+ * `missing`: a segment does not exist, cannot be checked, or the links loop. A segment in a guarded folder the folder
80
+ * gate holds closed ends the walk as `excluded` with the refusal in `closed`, before its `lstat`: the folder cannot be
81
+ * entered now, and a missing segment would keep the verdict of the text. The walk asks the port for it
82
+ * (`closedFolderOf`), because metadata passes a closed folder; a disk that refuses a segment with `FolderGateError`
83
+ * ends the walk the same way. With `gate: 'ignore'` the walk does not ask the gate. `roots` and `home` in on-disk form.
70
84
  */
71
- export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
85
+ export function resolveInWorkArea(candidate, roots, home, disk = DISK, options = {}) {
72
86
  if (!path.isAbsolute(candidate))
73
87
  return { kind: 'missing' };
74
88
  // The way to a root compares in lower case, like a root opening a path (`isExcludedPath`).
@@ -90,13 +104,16 @@ export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
90
104
  const next = path.join(current, part);
91
105
  if (blocked(next))
92
106
  return { kind: 'excluded' };
107
+ const closed = options.gate === 'ignore' ? null : closedFolderOf(next);
108
+ if (closed !== null)
109
+ return { kind: 'excluded', closed };
93
110
  let link = null;
94
111
  try {
95
112
  if (disk.lstat(next).isSymbolicLink())
96
113
  link = disk.readlink(next);
97
114
  }
98
- catch {
99
- return { kind: 'missing' };
115
+ catch (error) {
116
+ return error instanceof FolderGateError ? { kind: 'excluded', closed: error } : { kind: 'missing' };
100
117
  }
101
118
  if (link === null) {
102
119
  current = next;
@@ -111,7 +128,11 @@ export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
111
128
  }
112
129
  return { kind: 'resolved', path: current };
113
130
  }
114
- const AREA_DISK = { ...DISK, realpath: (file) => realpathSync(file) };
131
+ /** The area's view of the work-area disk port: `realpath` is the JavaScript walk of `realpathSync`. */
132
+ export function areaDiskOf(disk) {
133
+ return { ...walkDiskOf(disk), realpath: (file) => disk.sync('realpath', { path: file }) };
134
+ }
135
+ const AREA_DISK = areaDiskOf(DIRECT_DISK);
115
136
  /**
116
137
  * Roots and home in on-disk form, the reference points of a walk: a root that is a symlink (`/srv/home -> ~`) counts
117
138
  * where it leads. Only they go through `realpath`, never a folder inside them; one that does not resolve stays as given.
@@ -136,13 +157,15 @@ export function onDiskForms(roots, home, realpath = AREA_DISK.realpath) {
136
157
  * meets the whole rule once more there, so `<root>/link -> ~/Desktop/x`, `<root ~>/visible -> ~/.cache/x` and a root
137
158
  * that is a symlink to home (`/srv/home/Desktop`) stay out without a read in the excluded folder. A path the walk
138
159
  * cannot resolve (deleted, unreadable, a loop of links) keeps the verdict of its text, because nothing can be read
139
- * through it; a link that leads out of every root keeps it too, unless it ends in an excluded folder.
160
+ * through it; a link that leads out of every root keeps it too, unless it ends in an excluded folder. A guarded folder
161
+ * the folder gate holds closed on the way puts the path out of the work area until the folder opens, unless `options`
162
+ * ignore the gate ({@link WalkOptions}).
140
163
  */
141
- export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK) {
164
+ export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK, options = {}) {
142
165
  const real = onDiskForms(roots, home, disk.realpath);
143
166
  if (!insideWorkArea(cwd, [...roots, ...real.roots], home))
144
167
  return false;
145
- const walked = resolveInWorkArea(cwd, real.roots, real.home, disk);
168
+ const walked = resolveInWorkArea(cwd, real.roots, real.home, disk, options);
146
169
  if (walked.kind !== 'resolved')
147
170
  return walked.kind === 'missing';
148
171
  const inRoots = real.roots.some((root) => path.isAbsolute(root) && isWithin(walked.path, path.resolve(root)));
@@ -156,7 +179,8 @@ export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK) {
156
179
  * resolve before the text check, never `cwd`, and a root counts in both forms: one that is a symlink into a protected
157
180
  * folder (`/srv/code -> ~/Desktop/project`) opens the physical path a pane reports. Then the walk
158
181
  * ({@link resolveInWorkArea}), which stops before an excluded folder, and the excluded folders once more on the path
159
- * it resolves to. A path the walk cannot resolve is not excluded: nothing can be read through it.
182
+ * it resolves to. A path the walk cannot resolve is not excluded: nothing can be read through it. A guarded folder
183
+ * the folder gate holds closed on the way counts as excluded, so git does not run there.
160
184
  */
161
185
  export function inExcludedOnDisk(cwd, roots, home, disk = AREA_DISK) {
162
186
  const real = onDiskForms(roots, home, disk.realpath);
@@ -182,6 +182,14 @@ export const CONSENT_RESTART_GRACE_ENV = 'RAROG_CONSENT_RESTART_GRACE';
182
182
  * wysyła, więc to NIE jest szósty killswitch. Flaga kanału zgody jej nie zmienia i odwrotnie.
183
183
  */
184
184
  export const DIALOG_LAYER2_ENV = 'RAROG_DIALOG_LAYER2';
185
+ /**
186
+ * Folder gate kill switch (`docs/macos-folders.md`): missing or empty = on on macOS and off elsewhere, `1` = on,
187
+ * `0` = off; any other value is a config error at start, also in the demo, which never runs the gate. On, a disk call
188
+ * of the work area in Desktop, Documents or Downloads (and any other guarded folder of home) runs in a helper
189
+ * process the server can kill, so a macOS consent window waits there instead of in the server. Off = every call in
190
+ * the server process, without helpers or the relay thread. It approves and sends nothing.
191
+ */
192
+ export const FOLDER_GATE_ENV = 'RAROG_FOLDER_GATE';
185
193
  /**
186
194
  * SSE STREAM COMPRESSION flag: missing, empty or `1` = the server gzips the stream when the client sent
187
195
  * `Accept-Encoding` with `gzip` at a weight above zero; `0` = no compression for any client; any other value is a
@@ -232,6 +240,27 @@ export const WITHDRAWN_ENV_NAMES = ['RAROG_COMPANION_SPEECH'];
232
240
  * killswitch; `docs/security-model.md` describes the channel. Demo mode reads states from a fixed map.
233
241
  */
234
242
  export const PR_STATUS_ENV = 'RAROG_PR_STATUS';
243
+ /**
244
+ * Inbox flag (`docs/server-config.md`): missing, empty or `1` = the server keeps an Inbox card per session
245
+ * (`server/src/inbox/`), sends its heads to a stream opened with `inbox=1`, serves `/api/inbox` and announces the
246
+ * `inbox` capability; `0` = no card tracker, no Inbox event, no capability, and the Inbox routes answer 503;
247
+ * `inbox.json` stays on disk untouched. Any other value is a configuration error at start. It sends nothing to a pane,
248
+ * so NOT a killswitch.
249
+ */
250
+ export const INBOX_ENV = 'RAROG_INBOX';
251
+ /**
252
+ * Session files switch (`docs/server-config.md`): missing, empty or `1` = the server lists a directory of a session
253
+ * (`GET /api/sessions/:id/files`) and announces the `files` capability; `0` = the file routes answer 404 as unknown
254
+ * routes and the capability is absent. Any other value is a configuration error at start. It sends nothing to a pane,
255
+ * so NOT a killswitch.
256
+ */
257
+ export const FILES_ENV = 'RAROG_FILES';
258
+ /**
259
+ * The largest file of a session the server sends, in whole megabytes from 1 to 1024 (`docs/server-config.md`);
260
+ * missing or empty = 50. Every listing announces it in bytes (`maxBytes`), so the app keeps no limit of its own. Any
261
+ * other value is a configuration error at start.
262
+ */
263
+ export const FILES_MAX_MB_ENV = 'RAROG_FILES_MAX_MB';
235
264
  // ---------------------------------------------------------------------------
236
265
  // Dyktowanie i powiadomienia
237
266
  // ---------------------------------------------------------------------------
@@ -371,11 +400,15 @@ export const SERVER_ENV = {
371
400
  [CONSENT_ALWAYS_ENV]: 'plain',
372
401
  [CONSENT_RESTART_GRACE_ENV]: 'plain',
373
402
  [DIALOG_LAYER2_ENV]: 'plain',
403
+ [FOLDER_GATE_ENV]: 'plain',
374
404
  [SSE_GZIP_ENV]: 'plain',
375
405
  [COMPANION_ENV]: 'plain',
376
406
  [COMPANION_SESSIONS_ENV]: 'plain',
377
407
  [COMPANION_MODEL_ENV]: 'plain',
378
408
  [PR_STATUS_ENV]: 'plain',
409
+ [INBOX_ENV]: 'plain',
410
+ [FILES_ENV]: 'plain',
411
+ [FILES_MAX_MB_ENV]: 'plain',
379
412
  [OPENAI_API_KEY_ENV]: 'secret',
380
413
  // Dyktowanie i powiadomienia.
381
414
  [SONIOX_API_KEY_ENV]: 'secret',
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  import { MAX_TRANSCRIPT_MESSAGES } from '@rarog/shared';
16
16
  import { BUNDLE_ID_RE } from '@rarog/shared/rest';
17
17
  import { dataDirConflictMessage, resolveDataDir } from '@rarog/shared/data-dir';
18
- import { AGENT_FILES_ENV, APNS_ENV_NAMES, APNS_KEY_ID_ENV, APNS_KEY_PATH_ENV, APNS_TEAM_ID_ENV, APNS_TOPIC_ENV, CLAUDE_ENV_CLEAR_ENV, ConfigError, CLI_WAITING_ENV, CODEX_STATUS_ENV, COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, COMPANION_ENV_PASSTHROUGH, CONSENT_CHANNEL_ENV, CONSENT_PROOF_ENV, CONSENT_ALWAYS_ENV, CONSENT_RESTART_GRACE_ENV, DEMO_CONTENT_ENV, DEMO_LANG_ENV, DEMO_REVIEW_CODE_ENV, DIALOG_LAYER2_ENV, GIT_ENV_PASSTHROUGH, GIT_ENV_PREFIX, GIT_FILE_DETAILS_ENV, HERDR_BIN_ENV, HERDR_LAUNCH_ENV, HERDR_ROOTS_ENV, HERDR_SEEN_FOCUS_ENV, HERDR_SEND_ENV, HERDR_SOCKET_ENV, HERDR_TAB_LABELS_ENV, IROH_ENV, IROH_KEY_ENV, IROH_PORT_ENV, IROH_RELAY_ENV, MAX_PANES_ENV, MIN_CLIENT_BUILD_ENV, NOTES_ENV, PROJECT_ROOTS_ENV, PROMPT_BLOCK_ENV, PUSH_E2E_ENV, PUSH_ENV, PR_STATUS_ENV, PR_STATUS_ENV_PASSTHROUGH, PUSH_RELAY_URL_ENV, QUEUE_ECHO_ENV, REFUSAL_DUMPS_ENV, SONIOX_API_HOST_ENV, SONIOX_API_KEY_ENV, OPENAI_API_KEY_ENV, SSE_GZIP_ENV, TALL_DIALOG_GUARD_ENV, TERM_ENV, TERM_ENV_PASSTHROUGH, TERM_IDLE_DAYS_ENV, TERM_MAX_ENV, VOICE_ENV, YOLO_ROOTS_ENV, readEnv, } from './config-env.js';
18
+ import { AGENT_FILES_ENV, APNS_ENV_NAMES, APNS_KEY_ID_ENV, APNS_KEY_PATH_ENV, APNS_TEAM_ID_ENV, APNS_TOPIC_ENV, CLAUDE_ENV_CLEAR_ENV, ConfigError, CLI_WAITING_ENV, CODEX_STATUS_ENV, COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, COMPANION_ENV_PASSTHROUGH, CONSENT_CHANNEL_ENV, CONSENT_PROOF_ENV, CONSENT_ALWAYS_ENV, CONSENT_RESTART_GRACE_ENV, DEMO_CONTENT_ENV, DEMO_LANG_ENV, DEMO_REVIEW_CODE_ENV, DIALOG_LAYER2_ENV, FOLDER_GATE_ENV, GIT_ENV_PASSTHROUGH, GIT_ENV_PREFIX, GIT_FILE_DETAILS_ENV, HERDR_BIN_ENV, HERDR_LAUNCH_ENV, HERDR_ROOTS_ENV, HERDR_SEEN_FOCUS_ENV, HERDR_SEND_ENV, HERDR_SOCKET_ENV, HERDR_TAB_LABELS_ENV, INBOX_ENV, FILES_ENV, FILES_MAX_MB_ENV, IROH_ENV, IROH_KEY_ENV, IROH_PORT_ENV, IROH_RELAY_ENV, MAX_PANES_ENV, MIN_CLIENT_BUILD_ENV, NOTES_ENV, PROJECT_ROOTS_ENV, PROMPT_BLOCK_ENV, PUSH_E2E_ENV, PUSH_ENV, PR_STATUS_ENV, PR_STATUS_ENV_PASSTHROUGH, PUSH_RELAY_URL_ENV, QUEUE_ECHO_ENV, REFUSAL_DUMPS_ENV, SONIOX_API_HOST_ENV, SONIOX_API_KEY_ENV, OPENAI_API_KEY_ENV, SSE_GZIP_ENV, TALL_DIALOG_GUARD_ENV, TERM_ENV, TERM_ENV_PASSTHROUGH, TERM_IDLE_DAYS_ENV, TERM_MAX_ENV, VOICE_ENV, YOLO_ROOTS_ENV, readEnv, } from './config-env.js';
19
19
  import { RAROG_VERSION } from './version.js';
20
20
  import { INSTALL_MODE } from './install/mode.js';
21
21
  import { DEVICES_FILENAME, activeDeviceEpochs } from './auth/devices-store.js';
@@ -24,7 +24,8 @@ import { CONSENT_PROOF_RULES } from './herdr/dialogs/layer1/contract.js';
24
24
  import { readAccountDefaultEffort, readAccountDefaultModel } from './config/claude-account.js';
25
25
  import { minClientBuildOf, parseMinClientBuild } from './config/clients.js';
26
26
  import { DEMO_REVIEW_MAX_DEVICES, assertDemoReviewOrigins, demoEnabled, parseDemoContent, parseDemoLang, parseDemoReview, } from './config/demo.js';
27
- import { COMPANION_MODEL_DEFAULT, COMPANION_MODEL_PATTERN, parseAgentFiles, parseCliWaiting, parseCodexStatusEnabled, parseCompanionEnabled, parseCompanionModel, parseCompanionSessionsEnabled, parseConsentRestartGrace, parseGitFileDetails, parseNotesEnabled, parsePrStatusEnabled, parsePromptBlock, parseQueueEcho, parseRefusalDumps, parseSseGzip, } from './config/flags.js';
27
+ import { COMPANION_MODEL_DEFAULT, COMPANION_MODEL_PATTERN, parseAgentFiles, parseCliWaiting, parseCodexStatusEnabled, parseCompanionEnabled, parseCompanionModel, parseCompanionSessionsEnabled, parseConsentRestartGrace, parseGitFileDetails, parseInboxEnabled, parseNotesEnabled, parsePrStatusEnabled, parsePromptBlock, parseQueueEcho, parseRefusalDumps, parseSseGzip, } from './config/flags.js';
28
+ import { parseFilesEnabled, parseFilesMaxBytes } from './config/files.js';
28
29
  import { DEFAULT_MAX_PANES, defaultHerdrSocket, parseHerdrLaunch, parseHerdrSeenFocus, parseHerdrSend, parseHerdrSocket, parseHerdrTabLabels, parseMaxPanes, } from './config/herdr.js';
29
30
  import { DEFAULT_PORT, MAX_BODY_BYTES, RAROG_HOST, assertLoopbackHost, demoOrigins, parseIroh, parseOrigins, parsePort, } from './config/listen.js';
30
31
  import { APPLE_ID_RE, expandHome, parsePushE2e, parsePushEnabled, parsePushRelay, readApnsKeyFile, } from './config/push.js';
@@ -527,6 +528,20 @@ export function parseDialogLayer2(raw) {
527
528
  return true;
528
529
  throw new ConfigError(`${DIALOG_LAYER2_ENV} takes 1 or 0 (got: ${value}).`);
529
530
  }
531
+ /**
532
+ * The folder gate flag: missing or empty = the platform decides (on on macOS, where the consent windows are), `1` = on,
533
+ * `0` = off; any other value stops the start, so a typo never leaves the server in another mode than the owner meant.
534
+ */
535
+ export function parseFolderGate(raw, platform) {
536
+ const value = raw?.trim() ?? '';
537
+ if (value === '')
538
+ return platform === 'darwin';
539
+ if (value === '1')
540
+ return true;
541
+ if (value === '0')
542
+ return false;
543
+ throw new ConfigError(`${FOLDER_GATE_ENV} takes 1 or 0 (got: ${value}).`);
544
+ }
530
545
  /** Strażnik wysokości dialogu; brak wartości = WŁĄCZONY, `0`/`false` wyłącza. */
531
546
  export function parseTallDialogGuard(raw) {
532
547
  if (raw === undefined || raw.trim() === '')
@@ -706,6 +721,8 @@ export function loadConfig(env = process.env, mode = INSTALL_MODE) {
706
721
  consentRestartGraceMs: parseConsentRestartGrace(readEnv(env, CONSENT_RESTART_GRACE_ENV)),
707
722
  // W demo bez skutku (mock nie ma drivera herdr), ale zła wartość zatrzymuje start tak samo.
708
723
  dialogLayer2: parseDialogLayer2(readEnv(env, DIALOG_LAYER2_ENV)),
724
+ // Off in demo unconditionally: the demo reads nothing of the host's folders; a wrong value stops the start there.
725
+ folderGate: parseFolderGate(readEnv(env, FOLDER_GATE_ENV), process.platform) && !demo,
709
726
  sseGzip: parseSseGzip(readEnv(env, SSE_GZIP_ENV)),
710
727
  // Off in demo unconditionally; a wrong value still stops the start there.
711
728
  companionEnabled: parseCompanionEnabled(readEnv(env, COMPANION_ENV)) && !demo,
@@ -715,6 +732,9 @@ export function loadConfig(env = process.env, mode = INSTALL_MODE) {
715
732
  companionModel: parseCompanionModel(readEnv(env, COMPANION_MODEL_ENV)),
716
733
  // On in demo too: the demo has its own fixed source (`bootstrap/pr-status.ts`); a wrong value stops the start.
717
734
  prStatusEnabled: parsePrStatusEnabled(readEnv(env, PR_STATUS_ENV)),
735
+ inboxEnabled: parseInboxEnabled(readEnv(env, INBOX_ENV)),
736
+ filesEnabled: parseFilesEnabled(readEnv(env, FILES_ENV)),
737
+ filesMaxBytes: parseFilesMaxBytes(readEnv(env, FILES_MAX_MB_ENV)),
718
738
  prStatusEnvBase: parsePrStatusEnvBase(env),
719
739
  /*
720
740
  * Terminal jest wyłączony w demo BEZWARUNKOWO: demo nie dotyka dysku ani procesów
@@ -546,7 +546,15 @@ export function createDemoControl(router, config, manager, panels, notes) {
546
546
  return true;
547
547
  }
548
548
  const handler = (req, res) => {
549
- const url = new URL(req.url ?? '/', 'http://127.0.0.1');
549
+ let url;
550
+ try {
551
+ url = new URL(req.url ?? '/', 'http://127.0.0.1');
552
+ }
553
+ catch {
554
+ // A target `URL` rejects would end the process here; the router answers it with its 400.
555
+ router(req, res);
556
+ return;
557
+ }
550
558
  const pathname = url.pathname;
551
559
  if (pathname === '/api/demo/control') {
552
560
  controlChain = controlChain.then(() => control(req, res)).catch(() => {
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The file tree of the demo sessions: one fixed project that every demo session lists through
3
+ * `GET /api/sessions/:id/files` and downloads a file of through `GET /api/sessions/:id/files/raw`, with no disk and
4
+ * no git. It agrees with the demo diff (`DEMO_DIFF_FILES` of the mock driver): the added and the modified file stand
5
+ * in `src`, the deleted one does not.
6
+ */
7
+ import { compareFileEntries } from '@rarog/shared';
8
+ /** Path of every file of the demo project → its text; a directory is every leading part of a path. */
9
+ export const DEMO_FILES = {
10
+ 'README.md': '# notes\n\nA small notes service: write, list and remove notes.\n',
11
+ 'package.json': '{\n "name": "notes",\n "private": true,\n "type": "module"\n}\n',
12
+ 'tsconfig.json': '{\n "compilerOptions": {\n "strict": true,\n "outDir": "dist"\n }\n}\n',
13
+ 'docs/guide.md': '# Guide\n\nRun the tests before every release.\n',
14
+ 'src/index.ts': "export { addNote, listNotes } from './notes.ts';\n",
15
+ 'src/notes.ts': 'export const listNotes = (): string[] => [];\nexport const addNote = (text: string): string => text;\n',
16
+ 'src/notes.test.ts': "import { listNotes } from './notes.ts';\n\nconsole.assert(listNotes().length === 0);\n",
17
+ 'dist/index.js': "export { addNote, listNotes } from './notes.js';\n",
18
+ 'dist/notes.js': 'export const listNotes = () => [];\nexport const addNote = (text) => text;\n',
19
+ };
20
+ /** Directories git ignores in the demo project (its `.gitignore` names `dist/`), with everything under them. */
21
+ const IGNORED_DIRS = ['dist'];
22
+ const isIgnored = (rel) => IGNORED_DIRS.some((dir) => rel === dir || rel.startsWith(`${dir}/`));
23
+ /**
24
+ * The entries of the directory `dir` of the demo project (`''` = the session directory), in the order of a listing;
25
+ * `null` when the project has no such directory.
26
+ */
27
+ export function demoFileEntries(dir) {
28
+ const prefix = dir === '' ? '' : `${dir}/`;
29
+ const entries = new Map();
30
+ for (const [file, text] of Object.entries(DEMO_FILES)) {
31
+ if (!file.startsWith(prefix))
32
+ continue;
33
+ const rest = file.slice(prefix.length);
34
+ const slash = rest.indexOf('/');
35
+ const name = slash === -1 ? rest : rest.slice(0, slash);
36
+ const label = isIgnored(`${prefix}${name}`) ? { ignored: true } : {};
37
+ entries.set(name, slash === -1
38
+ ? { name, kind: 'file', size: Buffer.byteLength(text, 'utf8'), ...label }
39
+ : { name, kind: 'dir', ...label });
40
+ }
41
+ if (entries.size === 0)
42
+ return dir === '' ? [] : null;
43
+ return [...entries.values()].sort(compareFileEntries);
44
+ }
45
+ /** The bytes of the file `rel` of the demo project (its UTF-8 text); `null` when the project has no such file. */
46
+ export function demoFileBytes(rel) {
47
+ const text = Object.hasOwn(DEMO_FILES, rel) ? DEMO_FILES[rel] : undefined;
48
+ return text === undefined ? null : Buffer.from(text, 'utf8');
49
+ }
@@ -0,0 +1,73 @@
1
+ import { segmentByInput } from '../herdr/input-segments.js';
2
+ import { demoBlocks } from './seeds.js';
3
+ /**
4
+ * The session manager with an engine conversation for every demo session in scope: a seed without a live driver
5
+ * (a session that hit its limit, say) has none, and the tracker gives a session without one no card. The made-up
6
+ * conversation is the session id behind a prefix; nothing outside the demo Inbox sees it.
7
+ */
8
+ export function demoInboxManager(manager) {
9
+ return {
10
+ get: manager.get.bind(manager),
11
+ list: manager.list.bind(manager),
12
+ companionTarget: (id) => {
13
+ const target = manager.companionTarget(id);
14
+ return target === null || target.agentSessionId !== undefined
15
+ ? target : { ...target, agentSessionId: `demo-conversation-${id}` };
16
+ },
17
+ markSeen: manager.markSeen.bind(manager),
18
+ markUnseen: manager.markUnseen.bind(manager),
19
+ onEvent: manager.onEvent.bind(manager),
20
+ onConversationChange: manager.onConversationChange.bind(manager),
21
+ eventsSince: manager.eventsSince.bind(manager),
22
+ };
23
+ }
24
+ /** The dialog events of a session stream the tracker folds for the identity of a decision card's dialog. */
25
+ const DIALOG_EVENTS = new Set([
26
+ 'permission-pending', 'permission-settled', 'permission-resolved', 'question-pending', 'question-resolved',
27
+ ]);
28
+ /**
29
+ * Segments of the demo session that writes the engine conversation `agentSessionId`, from the `message` events of
30
+ * its ring. The opening entry of a turn has no file entry id, so a turn is keyed by its time and text: the seeds get
31
+ * new times at every start, so a removal made before a demo restart matches no card after it. A ring that already
32
+ * dropped its first events reads as `unreadable`, and the card keeps the turn it showed.
33
+ */
34
+ export function createDemoSegmentReader(manager) {
35
+ return (_cwd, agentSessionId) => Promise.resolve(readDemoSegments(manager, agentSessionId));
36
+ }
37
+ function readDemoSegments(manager, agentSessionId) {
38
+ const sessionId = manager.list().find((session) => conversationOf(manager, session.id) === agentSessionId)?.id;
39
+ if (sessionId === undefined)
40
+ return { kind: 'no-file' };
41
+ const replay = manager.eventsSince(sessionId, 0);
42
+ if (replay.tooOld)
43
+ return { kind: 'unreadable' };
44
+ const entries = replay.events.flatMap(({ event }) => (event.type === 'message' ? [entryOf(event.message)] : []));
45
+ return { kind: 'read', segments: segmentByInput(agentSessionId, entries).segments, wholeFile: true };
46
+ }
47
+ function conversationOf(manager, sessionId) {
48
+ try {
49
+ return manager.companionTarget(sessionId)?.agentSessionId;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ function entryOf(message) {
56
+ return {
57
+ role: message.role, blocks: demoBlocks(message.blocks), at: message.at,
58
+ ...(message.notice === undefined ? {} : { notice: message.notice }),
59
+ };
60
+ }
61
+ /**
62
+ * Hands the tracker the dialog events already in the rings of the demo sessions: the seeds register their permission
63
+ * cards while the manager is built, before the tracker listens, so without them a demo decision card would have no
64
+ * request id. The ring holds every dialog event in order, so a repeated event folds to the same state.
65
+ */
66
+ export function replayDemoDialogs(manager, inbox) {
67
+ for (const session of manager.list()) {
68
+ for (const { event } of manager.eventsSince(session.id, 0).events) {
69
+ if (DIALOG_EVENTS.has(event.type))
70
+ inbox.noteEvent(session.id, event);
71
+ }
72
+ }
73
+ }
@@ -23,7 +23,7 @@
23
23
  */
24
24
  /** Akcje `/api/sessions/:id/<akcja>` (`segments[3]` w routerze): wszystkie dozwolone, podakcje dziedziczą klasę. */
25
25
  const SESSION_ACTIONS = [
26
- 'answers', 'close', 'commands', 'diff', 'focus', 'interrupt', 'messages', 'mode', 'model', 'permission',
26
+ 'answers', 'close', 'commands', 'diff', 'files', 'focus', 'interrupt', 'messages', 'mode', 'model', 'permission',
27
27
  'permissions', 'queue', 'restart', 'resume', 'seen', 'stream', 'unseen', 'uploads',
28
28
  ];
29
29
  export const REVIEW_ROUTES = [
@@ -57,6 +57,11 @@ export const REVIEW_ROUTES = [
57
57
  { route: '/api/push/live-activity/end', class: 'allow' },
58
58
  { route: '/api/sessions', class: 'allow' },
59
59
  ...SESSION_ACTIONS.map((action) => ({ route: `/api/sessions/:id/${action}`, class: 'allow' })),
60
+ // Inbox cards of the demo sessions; a removal lands in `inbox.json` of the demo data directory.
61
+ { route: '/api/inbox', class: 'allow' },
62
+ { route: '/api/inbox/:id', class: 'allow' },
63
+ { route: '/api/inbox/:id/remove', class: 'allow' },
64
+ { route: '/api/inbox/:id/restore', class: 'allow' },
60
65
  // Kod parowania dla testów UI, który odpina wszystkie urządzenia: w trybie recenzji router go nie wydaje.
61
66
  { route: '/api/demo/pairing', class: 'absent' },
62
67
  // Agent głosowy: demo nie ma pliku rozmowy ani procesu `claude -p`, więc trasy nie ma także dla recenzenta.
@@ -9,6 +9,7 @@ export function attachDeactivation(store, targets) {
9
9
  const streams = targets.hub.closeOwner(id);
10
10
  const sockets = targets.term?.closeOwner(id) ?? 0;
11
11
  const questions = targets.companion?.closeOwner(id) ?? 0;
12
+ const downloads = targets.files?.closeOwner(id) ?? 0;
12
13
  revokeDevice(id);
13
14
  let tokens = 0;
14
15
  const apns = targets.apns;
@@ -20,7 +21,8 @@ export function attachDeactivation(store, targets) {
20
21
  tokens = apns.devices.removeOwnedBy(id).length;
21
22
  }
22
23
  targets.log(`devices: ${id} revoked (${by}) — streams: ${String(streams)},`
23
- + ` consoles: ${String(sockets)}, APNs tokens: ${String(tokens)}, voice agent: ${String(questions)}`);
24
+ + ` consoles: ${String(sockets)}, APNs tokens: ${String(tokens)}, voice agent: ${String(questions)},`
25
+ + ` file downloads: ${String(downloads)}`);
24
26
  }
25
27
  });
26
28
  }