@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
@@ -44,6 +44,7 @@ export class Inbox {
44
44
  #running = new Map();
45
45
  /** The read of each session asked for while its previous read ran; it starts once that one ends. */
46
46
  #queued = new Map();
47
+ #listeners = new Set();
47
48
  #disposed = false;
48
49
  constructor(config, port) {
49
50
  this.#port = port;
@@ -119,6 +120,14 @@ export class Inbox {
119
120
  this.#schedule(session.id);
120
121
  }
121
122
  }
123
+ /**
124
+ * Listener of changes: called with a session after every card read and every change of its card or removals,
125
+ * also when nothing visible changed (the listener compares). Returns the function that detaches it.
126
+ */
127
+ onChange(listener) {
128
+ this.#listeners.add(listener);
129
+ return () => { this.#listeners.delete(listener); };
130
+ }
122
131
  /** The card of a session, also a removed one; `null` = none. */
123
132
  card(sessionId) {
124
133
  return this.#cards.get(sessionId) ?? null;
@@ -163,6 +172,7 @@ export class Inbox {
163
172
  sessionId, ...key, ...(receipt && session.seen !== true ? { seen: true } : {}),
164
173
  };
165
174
  const stored = await this.#store.add(entry);
175
+ this.#notify(sessionId);
166
176
  if (stored === 'failed')
167
177
  return { kind: 'write-failed' };
168
178
  if (stored === 'present')
@@ -195,6 +205,7 @@ export class Inbox {
195
205
  if (card.version !== ref.version || found.moved)
196
206
  return STALE;
197
207
  const removed = await this.#store.delete(key);
208
+ this.#notify(sessionId);
198
209
  if (removed === 'failed')
199
210
  return { kind: 'write-failed' };
200
211
  if (removed === 'absent')
@@ -270,6 +281,7 @@ export class Inbox {
270
281
  this.#transitions.delete(id);
271
282
  this.#looks.delete(id);
272
283
  this.#states.delete(id);
284
+ this.#notify(id);
273
285
  }
274
286
  }
275
287
  #schedule(sessionId) {
@@ -309,7 +321,10 @@ export class Inbox {
309
321
  this.#log(`inbox: card read failed for session ${sessionId} (${err instanceof Error ? err.message : String(err)})`);
310
322
  return false;
311
323
  })
312
- .finally(() => { this.#running.delete(sessionId); });
324
+ .finally(() => {
325
+ this.#running.delete(sessionId);
326
+ this.#notify(sessionId);
327
+ });
313
328
  this.#running.set(sessionId, read);
314
329
  return read;
315
330
  }
@@ -381,7 +396,7 @@ export class Inbox {
381
396
  turns = { conversation, shown, ended: session.state === 'waiting-input' ? shown : turns.ended };
382
397
  }
383
398
  this.#turns.set(sessionId, turns);
384
- const requestOf = (dialog, waitingFor) => this.#dialogs.current(sessionId, dialog, waitingFor);
399
+ const requestOf = (dialog, waitingFor) => this.#dialogs.request(sessionId, dialog, waitingFor);
385
400
  const card = composeCard(session, working ? turns.ended : turns.shown, requestOf);
386
401
  if (card === null) {
387
402
  this.#cards.delete(sessionId);
@@ -406,6 +421,13 @@ export class Inbox {
406
421
  #forget(sessionId) {
407
422
  this.#cards.delete(sessionId);
408
423
  this.#turns.delete(sessionId);
424
+ this.#notify(sessionId);
425
+ }
426
+ #notify(sessionId) {
427
+ if (this.#disposed)
428
+ return;
429
+ for (const listener of this.#listeners)
430
+ this.#safely(sessionId, 'change listener', () => { listener(sessionId); });
409
431
  }
410
432
  #safely(sessionId, what, step) {
411
433
  try {
@@ -10,10 +10,12 @@
10
10
  * a decision card's dialog;
11
11
  * - `segments.ts`: the read of the conversation file a session writes now, through `readInputSegments`;
12
12
  * - `removals.ts`: `inbox.json`, the removals with their atomic write chain;
13
- * - `inbox.ts`: the tracker that reads cards again after the session manager's events, and remove and restore.
13
+ * - `inbox.ts`: the tracker that reads cards again after the session manager's events, and remove and restore;
14
+ * - `heads.ts`: the heads of the visible cards and the stream events of their changes.
14
15
  */
15
16
  export { cardKindOf, composeCard, removalKeyOf, shownTurnFor } from './card.js';
16
17
  export { PendingDialogs } from './dialogs.js';
18
+ export { InboxHeads, byNewest, headOf } from './heads.js';
17
19
  export { INBOX_DEBOUNCE_MS, INBOX_SLOW_READ_MS, Inbox } from './inbox.js';
18
20
  export { INBOX_CLOSED_LIMIT, INBOX_FILENAME, INBOX_FORMAT } from './removals.js';
19
21
  export { INBOX_FIRST_WINDOW, createSegmentReader } from './segments.js';
@@ -24,14 +24,16 @@ import { gitReadEnv, probeGitSandboxAtStart } from './git-status.js';
24
24
  import { exitAfter } from './shutdown.js';
25
25
  import { consoleLogger } from './router.js';
26
26
  import { readHookHealth } from './health.js';
27
- import { consentAdminControl, consentCardAwaitedAt, consentCardLive, consentManagerPort, consentTranscriptOf, createConsentChannel, observeConsent, startConsentCycle, startConsentRegistration, watchConsentMode, } from './bootstrap/consent.js';
27
+ import { consentAdminControl, consentCardAwaitedAt, consentCardLive, consentForgottenPort, consentManagerPort, consentTranscriptOf, createConsentChannel, observeConsent, startConsentCycle, startConsentRegistration, watchConsentMode, } from './bootstrap/consent.js';
28
28
  import { createAliveSessionsSignal } from './bootstrap/alive-sessions.js';
29
+ import { consentNoHookSources, consentSessionEntry } from './bootstrap/consent.js';
29
30
  import { createDeviceAuth, startDeviceSweep } from './bootstrap/devices.js';
31
+ import { startFolderGate } from './bootstrap/folder-gate.js';
30
32
  import { healthProbes } from './bootstrap/health.js';
31
33
  import { prepareHookFiles } from './bootstrap/hook-files.js';
32
34
  import { loadDemoHerdr } from './bootstrap/herdr.js';
33
35
  import { buildRouter, configureHttpServer } from './bootstrap/http.js';
34
- import { startInbox } from './bootstrap/inbox.js';
36
+ import { assembleInbox } from './bootstrap/inbox.js';
35
37
  import { startServerIroh } from './bootstrap/iroh.js';
36
38
  import { loadSdk, managerConfig } from './bootstrap/manager.js';
37
39
  import { createPush } from './bootstrap/push.js';
@@ -43,6 +45,7 @@ import { consentSubagentsOpen } from './herdr/dialogs/hook/contract.js';
43
45
  import { CONSENT_EVIDENCE_SCAN_MAX_BYTES } from './herdr/dialogs/layer1/contract.js';
44
46
  import { nodeConsentEvidenceIo } from './herdr/consent-evidence.js';
45
47
  import { createSessionHookList } from './herdr/dialogs/layer1/hook-list/hook-list.js';
48
+ import { FileDownloads } from './files/send-file.js';
46
49
  import { consentStep } from './herdr/consent-step.js';
47
50
  import { createSubagentObservation } from './herdr/consent-subagent.js';
48
51
  import { hookCommand } from './herdr/hook-commands.js';
@@ -178,22 +181,18 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
178
181
  topLoss: createConsentTopLoss(),
179
182
  sessionHooks: createSessionHookList({
180
183
  home: homedir(), accepted: [hookCommand(homedir())],
181
- entry: async (engineSessionId) => {
182
- const read = await cliVersionReader({ registryOnly: true });
183
- if (read.registry === null || (read.unreadablePids ?? 0) > 0)
184
- return null;
185
- if (read.unlistedSessions?.has(engineSessionId) === true)
186
- return null;
187
- const entries = read.registry.get(engineSessionId);
188
- const entry = entries?.length === 1 ? entries[0] : undefined;
189
- return entry === undefined ? null
190
- : { pid: entry.pid, ...(entry.startedAt === undefined ? {} : { startedAt: entry.startedAt }) };
191
- },
184
+ entry: consentSessionEntry(cliVersionReader),
192
185
  onVerdict: (engineSessionId, verdict) => {
193
186
  log.info(`consent: session hooks ${engineSessionId} ${verdict.ok ? 'ok' : `no (${verdict.why})`}`);
194
187
  },
195
188
  }),
196
189
  };
190
+ // Consent without a hook (`drivers/herdr/consent-no-hook.ts`): traces, session facts, `ps` and `statusLine`.
191
+ const consentNoHook = cliVersionReader === null ? undefined : consentNoHookSources({
192
+ link: consentLink, dataDir: config.dataDir, home: homedir(), roots: config.herdrRoots,
193
+ entry: consentSessionEntry(cliVersionReader), proofGate: consentProofGate,
194
+ restartGraceMs: config.consentRestartGraceMs, startedAt: Date.now(),
195
+ });
197
196
  const supervisor = herdr.createHerdrSupervisor({
198
197
  socketPath: config.herdrSocket,
199
198
  roots: config.herdrRoots,
@@ -214,7 +213,7 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
214
213
  ...(versionWatch === null ? {} : {
215
214
  onVersion: (version) => { versionWatch.observe('herdr', version); },
216
215
  }),
217
- // The first sessions after the start go to `alive.json` at once (`bootstrap/alive-sessions.ts`).
216
+ // A new session goes to `alive.json` at once (`bootstrap/alive-sessions.ts`).
218
217
  onAgentsChanged: aliveSessions.onAgentsChanged,
219
218
  /*
220
219
  * Fabryka dostaje `HerdrLaunchClient` zbudowany na TYM SAMYM gnieździe co reszta
@@ -316,6 +315,7 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
316
315
  consentCardLive: (engineSessionId) => consentCardLive(consentLink, engineSessionId),
317
316
  // The reason of a consent card without the approve button: what the desk release of its call key kept.
318
317
  consentDeskRelease: (engineSessionId, key) => consentLink.cycle?.deskRelease(engineSessionId, key) ?? null,
318
+ ...(consentNoHook === undefined ? {} : { consentNoHook }),
319
319
  // Karta zgody z ekranu albo jsonl czeka na kartę kanału, póki rejestracja hooka sesji nie ma karty (z sufitem).
320
320
  consentCardAwaited: (engineSessionId) => consentCardAwaitedAt(consentLink, engineSessionId),
321
321
  // The measured "Yes" digit waits for no registration without a card, a subagent's too, of any age.
@@ -443,6 +443,15 @@ async function main() {
443
443
  */
444
444
  const server = http.createServer();
445
445
  const iroh = await startServerIroh(config, server, log);
446
+ /*
447
+ * The folder gate before the first disk call of the work area: calls in a guarded folder of home go to a helper.
448
+ * It stays routed until the process ends: a call in such a folder during shutdown must not fall back to the server
449
+ * process, and the exit hook of the client kills the helpers when the process exits.
450
+ */
451
+ startFolderGate({
452
+ enabled: config.folderGate, home: homedir(), roots: [...config.projectRoots, ...config.herdrRoots],
453
+ log: (line) => { log.info(line); },
454
+ });
446
455
  // Hook files in the data directory, before anything reads them: roots, start cleanup, log rotation.
447
456
  prepareHookFiles(config, log);
448
457
  // Git under `sandbox-exec` on macOS (layer 2): one probe before the first read, one log line without it.
@@ -595,6 +604,7 @@ async function main() {
595
604
  }),
596
605
  // Karty kanału zgód: decyzje i zwolnienie tylko przy otwartym kanale (`main`, `all`), inaczej 410.
597
606
  ...(consentCycle === null ? {} : { consent: consentManagerPort(consentCycle, consentMode, log) }),
607
+ ...(consentCycle === null ? {} : { consentForgotten: consentForgottenPort(consentCycle, log) }),
598
608
  ...(prStatus === null ? {} : { prStatus: prStatus.port }),
599
609
  });
600
610
  managerRef = manager;
@@ -608,11 +618,14 @@ async function main() {
608
618
  manager.onEvent((scope) => { if (scope === 'global')
609
619
  apns.liveActivity.poke(); });
610
620
  }
611
- // Inbox cards from the manager's events and their removals in `inbox.json` (`bootstrap/inbox.ts`); none in the demo.
612
- const inbox = config.demo ? null : startInbox({
613
- manager, ready: manager.ready, dataDir: config.dataDir, promptBlock: config.promptBlock,
614
- log: (line) => { log.info(line); },
621
+ /*
622
+ * Inbox cards from the manager's events, their removals in `inbox.json` and the heads for the stream
623
+ * (`bootstrap/inbox.ts`), the demo over its own sessions; `null` with `RAROG_INBOX=0`.
624
+ */
625
+ const inboxParts = await assembleInbox({
626
+ config, manager, ready: manager.ready, log: (line) => { log.info(line); },
615
627
  });
628
+ const inbox = inboxParts?.inbox ?? null;
616
629
  // Nadzorca podpięty, seedy demo założone — dopiero wtedy wpuszczamy ruch HTTP.
617
630
  await manager.ready;
618
631
  apns?.liveActivity.poke();
@@ -622,6 +635,7 @@ async function main() {
622
635
  : undefined;
623
636
  const hub = createSseHub({
624
637
  config, manager, serverStartId, log, demoNotes,
638
+ ...(inboxParts === null ? {} : { inbox: inboxParts.heads }),
625
639
  // The PR status reads GitHub only while a client is connected.
626
640
  ...(prStatus === null
627
641
  ? {}
@@ -638,9 +652,11 @@ async function main() {
638
652
  */
639
653
  const term = await loadTerm(config, log, { devices, limiter: loginLimiter });
640
654
  const companion = assembleCompanion({ config, manager, log: (line) => { log.info(line); } }); // off in demo
655
+ // Session file downloads in flight by device: the router registers them, an unpair stops them.
656
+ const fileDownloads = new FileDownloads();
641
657
  // Skutki odpięcia urządzenia, pierwszy przebieg wygasania i przebieg co minutę (`bootstrap/devices.ts`).
642
658
  const deviceSweep = startDeviceSweep(devices, {
643
- pairing, hub, term: term ?? undefined, companion, apns, log: (line) => { log.info(line); },
659
+ pairing, hub, term: term ?? undefined, companion, files: fileDownloads, apns, log: (line) => { log.info(line); },
644
660
  });
645
661
  // Sondy `/health` z `bootstrap/health.ts`; pole kanału zgód dokłada `main()`.
646
662
  const health = {
@@ -662,7 +678,7 @@ async function main() {
662
678
  const router = buildRouter({
663
679
  config, manager, hub, serverStartId, startedAtMs, log, health, system, macStats, demoUsage, demoVoice, demoNotes,
664
680
  readUpload: herdr?.readUpload, term, companion, notifier, presence, apns, loginLimiter, irohPair, devices, pairing,
665
- reviewConstants, demoHost,
681
+ reviewConstants, demoHost, inbox, fileDownloads,
666
682
  });
667
683
  // Sterowanie testów UI tylko w zwykłym demo: w trybie recenzji słuchacz `request` to sam router.
668
684
  const demoControl = config.demo && config.demoReview === null && herdr?.scenarioPanels !== undefined
@@ -683,7 +699,14 @@ async function main() {
683
699
  socket.destroy();
684
700
  return;
685
701
  }
686
- term.handleUpgrade(req, socket, head);
702
+ // An exception in an `upgrade` listener is uncaught and would end the process before any credential.
703
+ try {
704
+ term.handleUpgrade(req, socket, head);
705
+ }
706
+ catch (err) {
707
+ log.error(`term: upgrade failed (${err instanceof Error ? err.name : 'non-error'}), socket closed`);
708
+ socket.destroy();
709
+ }
687
710
  });
688
711
  // Timeouty dla strumieni SSE i obsługa błędu `listen` (EADDRINUSE = kod 1), `bootstrap/http.ts`.
689
712
  configureHttpServer(server, config, log);
@@ -127,6 +127,14 @@ export function npmUpdatePackArgs(current, latest, dir) {
127
127
  return ['pack', `${RAROG_PACKAGE_NAME}@>${current} <=${latest}`, '--ignore-scripts', '--json', '--pack-destination',
128
128
  dir];
129
129
  }
130
+ /**
131
+ * Arguments of `npm-cli.js` with which `rarog update --beta` downloads exactly `version`, the target it chose from the
132
+ * dist-tags, into `dir`, with its name and version as JSON. npm's release age gate holds an exact version back as it
133
+ * holds a range: not old enough is `ETARGET`.
134
+ */
135
+ export function npmUpdateExactPackArgs(version, dir) {
136
+ return ['pack', `${RAROG_PACKAGE_NAME}@${version}`, '--ignore-scripts', '--json', '--pack-destination', dir];
137
+ }
130
138
  /**
131
139
  * Arguments of `npm-cli.js` with which `rarog update` installs exactly the tarball `file` it checked: global,
132
140
  * without install scripts (the package needs none, and a release must not run code at install).
@@ -205,6 +205,9 @@ export async function startIroh(config, server, log, deps = {}) {
205
205
  const duplex = new IrohDuplex(stream, { slot, clock });
206
206
  entry.sockets.add(duplex);
207
207
  duplex.once('close', () => { entry.sockets.delete(duplex); });
208
+ // A throw in an `http.Server` listener comes back through the read loop as the socket's `'error'`. Node removes
209
+ // its own `'error'` listener before `'upgrade'`, and an unheard `'error'` would end the process.
210
+ duplex.on('error', ignore);
208
211
  entry.handle.attach(duplex);
209
212
  duplex.setTimeout(idleMs());
210
213
  try {
@@ -26,6 +26,7 @@ export const IROH_REFUSALS = [
26
26
  'origin', // mutation with an `Origin` other than `IROH_ORIGIN`
27
27
  'upgrade-refused', // WebSocket upgrade refused
28
28
  'login', // `/api/login` over iroh
29
+ 'bad-url', // request target that `URL` cannot parse
29
30
  ];
30
31
  /** Budget window. */
31
32
  export const LOG_BUDGET_WINDOW_MS = 60_000;
@@ -8,7 +8,8 @@
8
8
  * authenticated (higher stream limit, no deadline, protection from eviction), and revoking a device
9
9
  * (`revokeDevice`) removes it from all connections at once. The listener gets the state change through `onAuthChange`.
10
10
  *
11
- * HTTP layer refusals on an iroh socket (bad `Origin`, upgrade refusal, `/api/login`) go through
11
+ * HTTP layer refusals on an iroh socket (bad `Origin`, upgrade refusal, `/api/login`, a request target `URL` cannot
12
+ * parse) go through
12
13
  * {@link noteIrohRefusal} to the listener's log budget instead of an ordinary line: before authentication anyone who
13
14
  * knows the server's EndpointId can trigger them as often as they like.
14
15
  *
@@ -9,12 +9,17 @@
9
9
  * w testach i wyjście komend `rarog …` dla człowieka go nie dostają.
10
10
  *
11
11
  * Granica linii to `\n` w bajtach zapisu: zapis wielowierszowy (stos błędu) dostaje prefiks na każdej linii, a linia
12
- * zapisana kilkoma `write` jeden, z czasem pierwszego fragmentu. Czego nie obejmuje: bajtów, które omijają
12
+ * zapisana kilkoma `write` jeden, z czasem pierwszego fragmentu. A line that starts after a newline inside the same
13
+ * write continues one log call (a stack trace, a value with a newline), so its prefix is the time followed by
14
+ * {@link LOG_CONTINUATION_MARK}: after {@link LOG_TIME_PREFIX} it starts with `| `, and a value that carries a whole
15
+ * log line cannot pass for a line the server wrote. Czego nie obejmuje: bajtów, które omijają
13
16
  * `process.stdout.write` / `process.stderr.write` (wydruk niezłapanego wyjątku z samego Node, proces potomny
14
17
  * z odziedziczonym deskryptorem).
15
18
  */
16
19
  /** Prefiks czasu na początku linii logu serwera. Czytelnicy logu przyjmują linię z nim i bez niego (stare pliki). */
17
20
  export const LOG_TIME_PREFIX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /u;
21
+ /** Follows the time on a line that continues the log call of the line above, in the same write. */
22
+ export const LOG_CONTINUATION_MARK = '| ';
18
23
  const NEWLINE = 0x0a;
19
24
  /**
20
25
  * Owija `stream.write`: przed każdą linią wstawia czas z `now()` (raz na zapis, tylko gdy linia się w nim zaczyna).
@@ -38,12 +43,12 @@ export function timestampWrites(stream, now = () => new Date()) {
38
43
  if (bytes.length === 0)
39
44
  return original(chunk, ...rest);
40
45
  const parts = [];
41
- let prefix = null;
46
+ let time = null;
42
47
  let from = 0;
43
48
  while (from < bytes.length) {
44
49
  if (atLineStart) {
45
- prefix ??= Buffer.from(`${now().toISOString()} `, 'utf8');
46
- parts.push(prefix);
50
+ time ??= now().toISOString();
51
+ parts.push(Buffer.from(from === 0 ? `${time} ` : `${time} ${LOG_CONTINUATION_MARK}`, 'utf8'));
47
52
  }
48
53
  const newline = bytes.indexOf(NEWLINE, from);
49
54
  const end = newline === -1 ? bytes.length : newline + 1;
@@ -33,10 +33,11 @@
33
33
  * zapis atomowy. Retencji NIE MA — treść kasuje wyłącznie człowiek.
34
34
  */
35
35
  import { createHash } from 'node:crypto';
36
- import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
36
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
37
37
  import { join } from 'node:path';
38
38
  import { notesEmpty } from '@rarog/shared';
39
39
  import { say, textOf } from '@rarog/shared/sentences';
40
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
40
41
  /**
41
42
  * Katalog plików notatek w `<dataDir>`. Cytują go `docs/security-model.md` (runbook)
42
43
  * i `docs/server-config.md`.
@@ -74,7 +75,7 @@ export class NotesFailure extends Error {
74
75
  export function notesPath(dataDir, cwd) {
75
76
  let real;
76
77
  try {
77
- real = realpathSync(cwd);
78
+ real = DIRECT_DISK.sync('realpath', { path: cwd });
78
79
  }
79
80
  catch {
80
81
  throw new NotesFailure('cwd-not-allowed', say('rest.notes-cwd-not-allowed'));
@@ -13,7 +13,10 @@ import { createUsageProvider } from './usage.js';
13
13
  import { serverSystem } from './version.js';
14
14
  import { COMPANION_SPEECH_KEY, createVoiceMinter } from './voice/soniox.js';
15
15
  import { createCompanionTokenMinter } from './companion/openai-token.js';
16
+ import { SessionFileIndex } from './files/file-index.js';
17
+ import { FileDownloads } from './files/send-file.js';
16
18
  import { handleDemoPairing, routeDevices } from './routes/devices.js';
19
+ import { routeInbox } from './routes/inbox.js';
17
20
  import { routeLimits } from './routes/limits.js';
18
21
  import { routeNotes } from './routes/notes.js';
19
22
  import { routeProjects } from './routes/projects.js';
@@ -391,6 +394,8 @@ export function createRouter(deps) {
391
394
  ?? createUsageProvider({ logger: (line) => { log.info(line); } });
392
395
  const loginLimiter = deps.loginLimiter ?? createLoginLimiter();
393
396
  const interruptWaitMs = deps.interruptWaitMs ?? INTERRUPT_WAIT_MS;
397
+ const fileDownloads = deps.fileDownloads ?? new FileDownloads();
398
+ const fileIndex = deps.fileIndex ?? new SessionFileIndex();
394
399
  const { config, manager, hub, serverStartId, startedAtMs, presence, apns } = deps;
395
400
  const notes = deps.notes ?? fileNotes(config.dataDir);
396
401
  const system = deps.system ?? serverSystem();
@@ -453,10 +458,11 @@ export function createRouter(deps) {
453
458
  const ctx = {
454
459
  deps, config, manager, hub, serverStartId, startedAtMs, presence, apns, notes, system, voice, companionToken,
455
460
  companionAvailable, companionSessionsAvailable, companionTurns, companionSpeechToken, usageProvider,
456
- healthProbes, secrets, log, interruptWaitMs, apnsTestCooldown, loginLimiter,
461
+ healthProbes, secrets, log, interruptWaitMs, apnsTestCooldown, loginLimiter, fileDownloads, fileIndex,
457
462
  };
458
463
  const ROUTE_GROUPS = [
459
464
  routeSystem, routeTerminal, routeNotes, routeDevices, routeProjects, routeLimits, routePush, routeSessions,
465
+ routeInbox,
460
466
  ];
461
467
  /**
462
468
  * Odmowa bramki: brak nagłówka `Authorization` (401 `unauthorized`), nieznany klucz urządzenia
@@ -487,7 +493,19 @@ export function createRouter(deps) {
487
493
  async function handle(req, res) {
488
494
  const method = req.method ?? 'GET';
489
495
  // `req.url` jest ścieżką względną; base jest sztuczny, bierzemy z niego tylko pathname.
490
- const url = new URL(req.url ?? '/', 'http://127.0.0.1');
496
+ // The HTTP parser lets through targets `URL` rejects (`//:/`): a 400 before the Origin check, and on an iroh
497
+ // socket through the log budget, because anyone can send it before any credential.
498
+ let url;
499
+ try {
500
+ url = new URL(req.url ?? '/', 'http://127.0.0.1');
501
+ }
502
+ catch {
503
+ if (!noteIrohRefusal(req.socket, 'bad-url', `${method} ${req.url ?? ''}`)) {
504
+ log.info(`refused ${method}: request target does not parse as a URL`);
505
+ }
506
+ sendError(res, 400, 'bad-request', say('rest.bad-request'));
507
+ return;
508
+ }
491
509
  const pathname = url.pathname.replace(/\/+$/, '') || '/';
492
510
  const segments = pathname.split('/').filter((s) => s !== '');
493
511
  /*
@@ -6,7 +6,7 @@ import { loginPeer, pairingLink, publicUrlOf, redact } from '../auth/index.js';
6
6
  import { isIrohSocket, markAuthenticated, noteIrohRefusal } from '../iroh/socket.js';
7
7
  import { methodNotAllowed, parseBody, readJsonBody, readValidatedBody, sendError, sendJson, sendNoContent, } from '../router.js';
8
8
  import { sanitizeBuild, sanitizeLabel } from '../text.js';
9
- import { SERVER_CAPABILITIES } from '../version.js';
9
+ import { serverCapabilities } from '../version.js';
10
10
  /** Pusty obiekt — ciało `POST /api/pairings` (kod wydaje serwer, klient niczego nie podaje). */
11
11
  const emptyBodySchema = z.strictObject({});
12
12
  /**
@@ -99,7 +99,7 @@ async function handlePair(ctx, req, res, identity) {
99
99
  id: identity.store.serverId,
100
100
  name: identity.serverName,
101
101
  version: config.version,
102
- capabilities: [...SERVER_CAPABILITIES],
102
+ capabilities: serverCapabilities({ inbox: deps.inbox !== undefined, files: config.filesEnabled }),
103
103
  // Serwer iroh — ten sam co w `/api/version`; serwer bez nasłuchu iroh pisze `null`.
104
104
  iroh: deps.iroh ?? null,
105
105
  },
@@ -0,0 +1,91 @@
1
+ import { INBOX_CARD_CHANGED_ERROR, INBOX_DISABLED_ERROR, inboxActionBodySchema, } from '@rarog/shared/rest';
2
+ import { say } from '@rarog/shared/sentences';
3
+ import { methodNotAllowed, readValidatedBody, sendError, sendJson } from '../router.js';
4
+ import { decodeSegment } from './context.js';
5
+ /**
6
+ * The card on the wire, as the tracker composed it: a `decision` card carries the dialog the session summary
7
+ * describes and the id of its card in the session stream, not that pending card. Reading it (`ManagerApi.transcript`,
8
+ * also with `peek`) marks every consent card of the session as shown, also those this answer would not carry; the next
9
+ * change of such a card then goes as `permission-settled`, which a device that never got the card drops, instead of
10
+ * `permission-pending`.
11
+ */
12
+ function wireOf(card) {
13
+ const { dialog, ...head } = card;
14
+ return dialog === undefined ? head : { ...head, dialog };
15
+ }
16
+ function disabled(res) {
17
+ sendError(res, 503, INBOX_DISABLED_ERROR, say('rest.inbox-disabled'));
18
+ return true;
19
+ }
20
+ function unknownSession(res) {
21
+ sendError(res, 404, 'not-found', say('rest.session-not-found'));
22
+ return true;
23
+ }
24
+ async function act(ctx, req, res, inbox, sessionId, action) {
25
+ const body = await readValidatedBody(req, res, ctx.config, inboxActionBodySchema);
26
+ if (body === null)
27
+ return;
28
+ if (ctx.manager.get(sessionId) === undefined) {
29
+ unknownSession(res);
30
+ return;
31
+ }
32
+ const result = action === 'remove' ? await inbox.remove(sessionId, body) : await inbox.restore(sessionId, body);
33
+ if (result.kind === 'stale') {
34
+ sendError(res, 409, INBOX_CARD_CHANGED_ERROR, say('rest.inbox-card-changed'));
35
+ return;
36
+ }
37
+ if (result.kind === 'write-failed') {
38
+ ctx.log.error(`inbox: ${action} of the card of session ${sessionId} not saved`);
39
+ sendError(res, 500, 'internal', say('rest.inbox-save-failed'));
40
+ return;
41
+ }
42
+ const response = {
43
+ ok: true, changed: result.changed, ...(result.receipt === undefined ? {} : { receipt: result.receipt }),
44
+ };
45
+ sendJson(res, 200, response);
46
+ }
47
+ export async function routeInbox(ctx, req, res, rq) {
48
+ const { method, pathname, segments } = rq;
49
+ const inbox = ctx.deps.inbox;
50
+ if (pathname === '/api/inbox') {
51
+ if (method !== 'GET')
52
+ return methodNotAllowed(res, 'GET');
53
+ if (inbox === undefined)
54
+ return disabled(res);
55
+ sendJson(res, 200, { cards: inbox.visibleCards().map(wireOf) });
56
+ return true;
57
+ }
58
+ // /api/inbox/:sessionId[/remove|/restore]
59
+ if (segments[0] === 'api' && segments[1] === 'inbox' && segments.length >= 3) {
60
+ const sessionId = decodeSegment(segments[2] ?? '');
61
+ const action = segments[3];
62
+ if (segments.length === 3) {
63
+ if (method !== 'GET')
64
+ return methodNotAllowed(res, 'GET');
65
+ if (inbox === undefined)
66
+ return disabled(res);
67
+ if (ctx.manager.get(sessionId) === undefined)
68
+ return unknownSession(res);
69
+ const card = inbox.card(sessionId);
70
+ sendJson(res, 200, card === null || inbox.removed(sessionId) ? {} : { card: wireOf(card) });
71
+ return true;
72
+ }
73
+ if (action === 'remove' && segments.length === 4) {
74
+ if (method !== 'POST')
75
+ return methodNotAllowed(res, 'POST');
76
+ if (inbox === undefined)
77
+ return disabled(res);
78
+ await act(ctx, req, res, inbox, sessionId, 'remove');
79
+ return true;
80
+ }
81
+ if (action === 'restore' && segments.length === 4) {
82
+ if (method !== 'POST')
83
+ return methodNotAllowed(res, 'POST');
84
+ if (inbox === undefined)
85
+ return disabled(res);
86
+ await act(ctx, req, res, inbox, sessionId, 'restore');
87
+ return true;
88
+ }
89
+ }
90
+ return false;
91
+ }
@@ -9,6 +9,7 @@ import { MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, makeDirBodySchema } from '@ra
9
9
  import { say } from '@rarog/shared/sentences';
10
10
  import { redact } from '../auth/index.js';
11
11
  import { validateProjectCwd } from '../config.js';
12
+ import { closedFolderOf } from '../folder-gate/disk.js';
12
13
  import { browseDirectory, demoListing } from '../fs-browse.js';
13
14
  import { makeDirectory, mkdirRefusal } from '../fs-mkdir.js';
14
15
  import { managerErrorStatus, methodNotAllowed, readValidatedBody, recheckDevice, sendError, sendFailure, sendJson, } from '../router.js';
@@ -20,6 +21,8 @@ import { managerErrorStatus, methodNotAllowed, readValidatedBody, recheckDevice,
20
21
  * seedów (`/Users/demo/Projects/...`) NIE istnieją na dysku,
21
22
  * - poza demo dowolna inna ścieżka („inna ścieżka…") musi przejść walidację korzeni:
22
23
  * istniejący katalog wewnątrz `RAROG_PROJECT_ROOTS`, bez segmentów ukrytych.
24
+ * Outside the demo a listed directory in a guarded folder the folder gate holds closed is refused with the sentence
25
+ * of the folder's state, judged by its text and without the disk, as `validateProjectCwd` refuses any other path.
23
26
  *
24
27
  * @returns znormalizowany katalog albo zdanie do odesłania w 400.
25
28
  */
@@ -45,7 +48,8 @@ export function checkCwd(cwd, config, manager) {
45
48
  }
46
49
  const target = path.resolve(raw);
47
50
  if (manager.projects().some((p) => path.resolve(p.path) === target)) {
48
- return { ok: true, cwd: target };
51
+ const closed = config.demo ? null : closedFolderOf(target);
52
+ return closed === null ? { ok: true, cwd: target } : { ok: false, sentence: closed.sentence };
49
53
  }
50
54
  if (config.demo) {
51
55
  return { ok: false, sentence: say('rest.cwd-not-in-projects') };