@rarog/server 1.0.1 → 1.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +4 -3
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +49 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  6. package/node_modules/@rarog/shared/src/protocol.js +16 -17
  7. package/node_modules/@rarog/shared/src/rest.js +106 -12
  8. package/node_modules/@rarog/shared/src/sentences/rest.js +13 -0
  9. package/package.json +3 -3
  10. package/server/src/bootstrap/consent.js +88 -2
  11. package/server/src/bootstrap/http.js +3 -2
  12. package/server/src/bootstrap/inbox.js +29 -4
  13. package/server/src/bootstrap/sse.js +2 -1
  14. package/server/src/cli/doctor-no-hook.js +162 -0
  15. package/server/src/cli/doctor.js +2 -0
  16. package/server/src/cli/update-channel.js +100 -0
  17. package/server/src/cli/update-registry.js +160 -62
  18. package/server/src/cli/update.js +13 -3
  19. package/server/src/companion/turns-settle.js +4 -1
  20. package/server/src/companion/turns.js +36 -5
  21. package/server/src/config/files.js +32 -0
  22. package/server/src/config/flags.js +10 -1
  23. package/server/src/config-env.js +24 -0
  24. package/server/src/config.js +6 -2
  25. package/server/src/demo/files.js +49 -0
  26. package/server/src/demo/inbox.js +73 -0
  27. package/server/src/demo/review-routes.js +6 -1
  28. package/server/src/device-effects.js +3 -1
  29. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  30. package/server/src/drivers/herdr/consent-no-hook.js +316 -0
  31. package/server/src/drivers/herdr/refusals.js +226 -0
  32. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  33. package/server/src/drivers/herdr-driver.js +116 -287
  34. package/server/src/files/file-index.js +246 -0
  35. package/server/src/files/ignored.js +119 -0
  36. package/server/src/files/listing.js +76 -0
  37. package/server/src/files/path-rule.js +145 -0
  38. package/server/src/files/refusals.js +36 -0
  39. package/server/src/files/send-file.js +115 -0
  40. package/server/src/files/session-download.js +51 -0
  41. package/server/src/files/session-files.js +38 -0
  42. package/server/src/files/session-gate.js +48 -0
  43. package/server/src/git-status.js +3 -2
  44. package/server/src/herdr/audit.js +1 -1
  45. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  46. package/server/src/herdr/dialogs/index.js +6 -1
  47. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +132 -59
  48. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  49. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  50. package/server/src/herdr/dialogs/no-hook.js +63 -0
  51. package/server/src/herdr/dialogs/screen/block.js +10 -0
  52. package/server/src/herdr/dialogs/screen/parse.js +10 -1
  53. package/server/src/herdr/jsonl-pending.js +25 -1
  54. package/server/src/inbox/card.js +18 -9
  55. package/server/src/inbox/dialogs.js +40 -12
  56. package/server/src/inbox/heads.js +55 -0
  57. package/server/src/inbox/inbox.js +24 -2
  58. package/server/src/inbox/index.js +3 -1
  59. package/server/src/index.js +22 -18
  60. package/server/src/install/repair.js +8 -0
  61. package/server/src/log-timestamps.js +9 -4
  62. package/server/src/router.js +7 -1
  63. package/server/src/routes/devices.js +2 -2
  64. package/server/src/routes/inbox.js +91 -0
  65. package/server/src/routes/sessions.js +135 -14
  66. package/server/src/routes/system.js +5 -4
  67. package/server/src/safe-read.js +86 -1
  68. package/server/src/sessions/companion-scope.js +6 -2
  69. package/server/src/sessions/demo-modules.js +16 -0
  70. package/server/src/sessions/diff-measure.js +30 -0
  71. package/server/src/sessions/manager.js +64 -152
  72. package/server/src/sessions/ring-buffer.js +18 -3
  73. package/server/src/sessions/seen-marks.js +9 -6
  74. package/server/src/sessions/session-scope.js +30 -0
  75. package/server/src/sessions/session.js +20 -1
  76. package/server/src/sessions/waiting-line.js +72 -0
  77. package/server/src/sse.js +40 -6
  78. package/server/src/version.js +30 -0
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # Rarog
2
2
 
3
- Rarog is an iPhone and iPad app plus a server on your Mac or Linux machine for the Claude Code sessions that run in
4
- [herdr](https://herdr.dev), a terminal multiplexer. From the phone you follow every session, answer its permission
5
- prompts and questions, and send it prompts, photos and files.
3
+ Rarog is a free, open-source (MIT) iPhone and iPad app, plus a server on your Mac or Linux machine, that shows the
4
+ Claude Code sessions running in Herdr TUI and lets you drive them. Herdr ([herdr.dev](https://herdr.dev)) is
5
+ a terminal multiplexer. From the phone you follow every session, answer its permission prompts and questions, and
6
+ send it prompts, photos and files.
6
7
 
7
8
  ## What it is
8
9
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rarog/shared",
3
- "version": "1.0.1",
3
+ "version": "1.1.0-beta.1",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,7 +22,7 @@
22
22
  * złotych ramek (`shared/test/sse-fixtures.test.ts` sprawdza nim `degrades`, które czyta Swift).
23
23
  */
24
24
  import { z } from 'zod';
25
- import { activityEventSchema, activitySchema, backgroundTaskSchema, blockSchema, contextLimitStateSchema, deltaEventSchema, gitFileDetailSchema, gitStatusEventSchema, helloEventSchema, herdrStatusEventSchema, messageAttachmentSchema, messageEventSchema, notesEventSchema, parseServerEvent, permissionPendingEventSchema, permissionRequestObjectSchema, permissionRequestSchema, permissionResolvedEventSchema, permissionSettledEventSchema, questionOptionSchema, questionPendingEventSchema, questionRequestSchema, questionSchema, questionResolvedEventSchema, sessionChangedEventSchema, sessionPullRequestSchema, sessionsSnapshotEventSchema, sessionSummarySchema, stateEventSchema, transcriptMessageSchema, transcriptNoticeSchema, transcriptSnapshotEventSchema, usageEventSchema, toolCallBlockObjectSchema, waitingForSchema, withDetailTruncation, withDisplayTextTruncation, } from './protocol.js';
25
+ import { activityEventSchema, activitySchema, backgroundTaskSchema, blockSchema, contextLimitStateSchema, deltaEventSchema, gitFileDetailSchema, gitStatusEventSchema, helloEventSchema, herdrStatusEventSchema, inboxCardKindSchema, inboxDialogKindSchema, inboxEventSchemas, inboxHeadSchemaOf, messageAttachmentSchema, messageEventSchema, notesEventSchema, parseServerEvent, permissionPendingEventSchema, permissionRequestObjectSchema, permissionRequestSchema, permissionResolvedEventSchema, permissionSettledEventSchema, questionOptionSchema, questionPendingEventSchema, questionRequestSchema, questionSchema, questionResolvedEventSchema, sessionChangedEventSchema, sessionPullRequestSchema, sessionStateSchema, sessionsSnapshotEventSchema, sessionSummarySchema, stateEventSchema, transcriptMessageSchema, transcriptNoticeSchema, transcriptSnapshotEventSchema, usageEventSchema, toolCallBlockObjectSchema, waitingForSchema, withDetailTruncation, withDisplayTextTruncation, } from './protocol.js';
26
26
  /**
27
27
  * Wartownik „ta wersja klienta tego nie zna". Zarezerwowany w KLIENCIE: serwer go nie nadaje
28
28
  * i nie zna (schematy ścisłe), więc w polu stanu nie pomyli się z żadną prawdziwą wartością.
@@ -111,6 +111,12 @@ export const DEGRADATIONS = {
111
111
  'pullRequests.state': undefined,
112
112
  /** `SessionSummary.seenBy`: an unknown picker drops the field, so the received result reads as a human's. */
113
113
  seenBy: undefined,
114
+ /**
115
+ * An `inbox-heads` head with an unknown `kind`, `state` or `dialog`: that head drops out of the list and the other
116
+ * heads stay, so a card kind added later does not empty an older app's Inbox. A single `inbox-head` with such a
117
+ * value is one item with nothing left to show and is ignored whole.
118
+ */
119
+ 'inbox.head': undefined,
114
120
  };
115
121
  /**
116
122
  * Znacznik widoku surowego: ta wartość przeszła GAŁĄŹ ZAPASOWĄ. Zgłaszany zawsze, bez porównania
@@ -123,6 +129,16 @@ class Unknown {
123
129
  this.value = value;
124
130
  }
125
131
  }
132
+ /**
133
+ * A list element the client cannot read. The result drops it from its list; the raw view keeps it in place, wrapped,
134
+ * so {@link collect} reports its markers at the input index and pairs the elements after it with the right result.
135
+ */
136
+ class Dropped {
137
+ value;
138
+ constructor(value) {
139
+ this.value = value;
140
+ }
141
+ }
126
142
  /**
127
143
  * Schematy tolerancyjne, zbudowane ze ścisłych przez `.extend` pól wyliczeniowych.
128
144
  *
@@ -234,6 +250,20 @@ function buildSchemas(raw) {
234
250
  channel: lenientOpt(questionRequestSchema.shape.channel, undefined),
235
251
  questions: z.array(questionSchema.extend({ options: z.array(option) })),
236
252
  });
253
+ /*
254
+ * `inbox-heads`: a head with an unknown string in `kind`, `state` or `dialog` drops out and the rest of the list
255
+ * stays. Any other broken head (`null`, a missing field, an empty `version`) still rejects the frame, also next to
256
+ * an unknown value.
257
+ */
258
+ const [inboxHeadsEvent, inboxHeadEvent, inboxRemovedEvent] = inboxEventSchemas(sessionStateSchema);
259
+ const inboxHead = inboxHeadSchemaOf(sessionStateSchema);
260
+ const unreadableHead = inboxHead.extend({
261
+ kind: lenient(inboxCardKindSchema, undefined),
262
+ state: lenient(sessionStateSchema, undefined),
263
+ dialog: lenientOpt(inboxDialogKindSchema.optional(), undefined),
264
+ }).transform((head) => new Dropped(head));
265
+ const inboxHeads = z.array(z.union([inboxHead, unreadableHead]))
266
+ .transform((heads) => (raw ? heads : heads.filter((head) => !(head instanceof Dropped))));
237
267
  return z.discriminatedUnion('type', [
238
268
  helloEventSchema,
239
269
  sessionsSnapshotEventSchema.extend({ sessions: z.array(summary) }),
@@ -270,6 +300,10 @@ function buildSchemas(raw) {
270
300
  usageEventSchema,
271
301
  herdrStatusEventSchema,
272
302
  notesEventSchema,
303
+ inboxHeadsEvent.extend({ heads: inboxHeads }),
304
+ // One head is one item: an unknown value ignores the frame, and the next head or `GET /api/inbox` mends it.
305
+ inboxHeadEvent,
306
+ inboxRemovedEvent,
273
307
  ]);
274
308
  }
275
309
  /** Budowane przy PIERWSZEJ ramce spoza ścisłego kontraktu — ścieżka szybka ich nie potrzebuje. */
@@ -287,13 +321,25 @@ function collect(raw, out, path, acc) {
287
321
  acc.push({ path, value: raw.value });
288
322
  return;
289
323
  }
324
+ if (raw instanceof Dropped) {
325
+ collect(raw.value, undefined, path, acc);
326
+ return;
327
+ }
290
328
  if (typeof raw !== 'object' || raw === null)
291
329
  return;
292
330
  const target = typeof out === 'object' && out !== null ? out : undefined;
331
+ // A dropped element exists only in the raw view, so every later element sits that many places earlier in `out`.
332
+ let dropped = 0;
293
333
  for (const [key, value] of Object.entries(raw)) {
294
- const next = target?.[key];
334
+ if (value instanceof Dropped) {
335
+ dropped += 1;
336
+ collect(value, undefined, `${path}/${key}`, acc);
337
+ continue;
338
+ }
339
+ const outKey = dropped === 0 ? key : String(Number(key) - dropped);
340
+ const next = target?.[outKey];
295
341
  if (next === undefined)
296
- delete target?.[key];
342
+ delete target?.[outKey];
297
343
  collect(value, next, `${path}/${key}`, acc);
298
344
  }
299
345
  }
@@ -0,0 +1,33 @@
1
+ /** Most entries one listing carries; a directory with more comes cut, with `truncated: true`. */
2
+ export const MAX_FILE_ENTRIES = 1000;
3
+ /** Kinds of a listing entry. Symlinks and special files (FIFO, socket, device) are never listed. */
4
+ export const FILE_ENTRY_KINDS = ['dir', 'file'];
5
+ /**
6
+ * Order of a listing: directories before files, then by name without letter case (`toLowerCase`), then by the name
7
+ * itself, both compared by UTF-16 code units (no locale), so every client sorts the same way.
8
+ */
9
+ export function compareFileEntries(a, b) {
10
+ if (a.kind !== b.kind)
11
+ return a.kind === 'dir' ? -1 : 1;
12
+ return byCodeUnits(a.name.toLowerCase(), b.name.toLowerCase()) || byCodeUnits(a.name, b.name);
13
+ }
14
+ function byCodeUnits(a, b) {
15
+ if (a === b)
16
+ return 0;
17
+ return a < b ? -1 : 1;
18
+ }
19
+ /* Codes of the refusals of both file routes (field `error` of a 4xx body). */
20
+ /** 400: the path failed the shape check (empty segment, `.` or `..`, a leading or trailing `/`, NUL, over 4096 B). */
21
+ export const FILES_BAD_PATH_ERROR = 'bad-path';
22
+ /** 400: the session's directory is outside the work area, or the session has no pane: its files stay on the server. */
23
+ export const FILES_OUT_OF_SCOPE_ERROR = 'out-of-scope';
24
+ /** 400: a Codex entry, which Rarog only observes. */
25
+ export const FILES_CODEX_ERROR = 'codex';
26
+ /**
27
+ * 404: nothing to list or send under this path: it does not exist, or the server never shows it (a segment that
28
+ * starts with a dot, `node_modules`, a symlink, a special file, a file with more than one hard link, a path outside
29
+ * the session directory or the work area). The app reads it as "this directory or file is gone".
30
+ */
31
+ export const FILES_NOT_FOUND_ERROR = 'not-found';
32
+ /** 413: the file is larger than `maxBytes`; refused before the first byte, the body is {@link FileTooLargeBody}. */
33
+ export const FILE_TOO_LARGE_ERROR = 'file-too-large';
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Protocol contract, Inbox area: the heads of Inbox cards on the global stream, without the card text.
3
+ *
4
+ * A stream gets them only when it asks with `inbox=1` (`GET /api/stream?inbox=1`): `inbox-heads` right after
5
+ * `sessions-snapshot`, then `inbox-head` when a visible card changes and `inbox-removed` when it leaves the visible
6
+ * cards. The text comes from `GET /api/inbox` (`rest.ts`). The head carries the protocol's `SessionState`, which an
7
+ * area file does not import: the types and schemas take it as a parameter, and `protocol.ts` binds it.
8
+ *
9
+ * Re-exported unchanged by `shared/src/protocol.ts`; code imports the names from there.
10
+ */
11
+ import { z } from 'zod';
12
+ /** `result`: the turn ended with a result; `decision`: the turn waits for a person; `failed`: the turn stopped. */
13
+ export const INBOX_CARD_KINDS = ['result', 'decision', 'failed'];
14
+ export const inboxCardKindSchema = z.enum(INBOX_CARD_KINDS);
15
+ /** What a `decision` card waits for: a permission card, a question card, or a dialog in the pane without a card. */
16
+ export const INBOX_DIALOG_KINDS = ['permission', 'question', 'panel'];
17
+ export const inboxDialogKindSchema = z.enum(INBOX_DIALOG_KINDS);
18
+ /** The head schema over the protocol's session state schema. */
19
+ export function inboxHeadSchemaOf(state) {
20
+ return z.object({
21
+ sessionId: z.string().min(1),
22
+ turnId: z.string().min(1),
23
+ version: z.string().min(1),
24
+ kind: inboxCardKindSchema,
25
+ state,
26
+ at: z.string(),
27
+ dialog: inboxDialogKindSchema.optional(),
28
+ });
29
+ }
30
+ /** The three event schemas, in the order of {@link InboxEventOf}, for the protocol's event union. */
31
+ export function inboxEventSchemas(state) {
32
+ const head = inboxHeadSchemaOf(state);
33
+ return [
34
+ z.object({ type: z.literal('inbox-heads'), heads: z.array(head) }),
35
+ z.object({ type: z.literal('inbox-head'), head }),
36
+ z.object({ type: z.literal('inbox-removed'), sessionId: z.string().min(1), turnId: z.string().min(1) }),
37
+ ];
38
+ }
@@ -5,9 +5,8 @@
5
5
  * `null`, a klient loguje i ignoruje zdarzenie. Dzięki temu starszy klient przeżyje nowszy
6
6
  * serwer bez wysypywania strumienia SSE.
7
7
  *
8
- * Types and schemas of separate areas live in `./protocol/`, one file per area. This file re-exports every
9
- * name from them, so code imports the contract from `protocol.ts` (`@rarog/shared`) only. An area file does
10
- * not import this file.
8
+ * Types and schemas of separate areas live in `./protocol/`, one file per area, re-exported here, so code imports
9
+ * the contract from `protocol.ts` (`@rarog/shared`) only. An area file does not import this file.
11
10
  */
12
11
  import { z } from 'zod';
13
12
  import { say, sentenceRefSchema } from './sentences/index.js';
@@ -17,6 +16,7 @@ import { backgroundTaskSchema, sessionArtifactSchema, sessionPullRequestSchema,
17
16
  import { consentAlwaysEntrySchema, SCREEN_UNAVAILABLE_REASONS, } from './protocol/consent.js';
18
17
  import { gitCommitSchema, gitFileDetailSchema, gitFileKindsSchema, } from './protocol/git.js';
19
18
  import { herdrModeSchema, herdrStatusSchema } from './protocol/herdr.js';
19
+ import { inboxEventSchemas } from './protocol/inbox.js';
20
20
  import { effortLevelSchema, modelIdSchema } from './protocol/model.js';
21
21
  export * from './protocol/activity.js';
22
22
  export * from './protocol/attachments.js';
@@ -26,8 +26,10 @@ export * from './protocol/consent.js';
26
26
  export * from './protocol/dictation.js';
27
27
  export * from './protocol/diff.js';
28
28
  export * from './protocol/directories.js';
29
+ export * from './protocol/files.js';
29
30
  export * from './protocol/git.js';
30
31
  export * from './protocol/herdr.js';
32
+ export * from './protocol/inbox.js';
31
33
  export * from './protocol/model.js';
32
34
  export * from './protocol/notes.js';
33
35
  export * from './protocol/resume.js';
@@ -211,7 +213,7 @@ export const WAITING_TEXT_MAX = 120;
211
213
  * z przyciskami; nikt jeszcze o nic nie prosił, więc nie ma żądania, na które odpowiedzieć;
212
214
  * - **decyzja** (`multi-select` … `send-failed`) — człowiek tapnął, a klawisz nie wyszedł;
213
215
  * - **blokada** (`in-flight`) — powstaje w MANAGERZE, nie w driverze: decyzja o tej karcie
214
- * właśnie leci z drugiego urządzenia. Do dziennika audytu nie trafia nigdy (`#auditRefusal`
216
+ * właśnie leci z drugiego urządzenia. Do dziennika audytu nie trafia nigdy (`auditRefusal`
215
217
  * woła wyłącznie driver), więc obietnicy „wpisy się SUMUJĄ" nie narusza.
216
218
  *
217
219
  * Lista stoi PRZED sekcją schematów, bo `sessionSummarySchema.herdrDialogReason` jej używa,
@@ -567,10 +569,7 @@ export const herdrStatusEventSchema = z.object({
567
569
  detail: z.string().optional(),
568
570
  detailRef: sentenceRefSchema.optional(),
569
571
  });
570
- /**
571
- * Zmiana notatek projektu. Katalog i bit „pusty po zapisie", zero treści — powód przy
572
- * wariancie w {@link ServerEvent}.
573
- */
572
+ /** Project notes changed: the directory and the "empty after the write" bit, no content ({@link ServerEvent}). */
574
573
  export const notesEventSchema = z.object({
575
574
  type: z.literal('notes'),
576
575
  cwd: z.string().min(1),
@@ -594,6 +593,7 @@ export const serverEventSchema = z.discriminatedUnion('type', [
594
593
  usageEventSchema,
595
594
  herdrStatusEventSchema,
596
595
  notesEventSchema,
596
+ ...inboxEventSchemas(sessionStateSchema),
597
597
  ]);
598
598
  const _schemaMatchesType = true;
599
599
  const _typeMatchesSchema = true;
@@ -793,21 +793,20 @@ export const decisionRefusedBodySchema = z.object({
793
793
  export const INTERRUPT_DELIVERY = ['yes', 'no', 'pending'];
794
794
  export const interruptDeliverySchema = z.enum(INTERRUPT_DELIVERY);
795
795
  /**
796
- * Odpowiedź `POST /api/sessions/:id/interrupt` — **202**.
797
- *
798
- * `session` niesie ŚWIEŻE `SessionSummary`: stan przestawia się
799
- * synchronicznie, więc odpowiedź na POST-a naprawia widok także wtedy, gdy `EventSource`
800
- * umarł po cichu i nie zgłosił błędu.
796
+ * Answer of `POST /api/sessions/:id/interrupt`: **202**.
801
797
  *
802
- * Oba pola poza `ok` są OPCJONALNE i to nie jest asekuracja: `session` odpada przy odpowiedzi
803
- * starszego serwera, a `delivered` — dopóki endpoint nie czeka na obietnicę drivera. Klient
804
- * bez `delivered` degraduje się do dwóch gałęzi (sukces / wyjątek) — i to jest jedyna dozwolona
805
- * reakcja na jego brak.
798
+ * `session` carries a FRESH `SessionSummary`: the state changes synchronously, so the answer fixes the view even when
799
+ * `EventSource` died silently. Every field but `ok` is OPTIONAL: `session` is absent from an older server, `delivered`
800
+ * from a route that does not wait for the driver; a client without `delivered` has two branches (success, exception),
801
+ * the only allowed reaction. `returnedPrompt` stands only after a delivered key whose Esc put the interrupted turn's
802
+ * prompt back into Claude Code's prompt field (CLI 2.1.329), proven by the whole field equal to that prompt; it is the
803
+ * prompt as the server sent or read it. Absent: no hand-back was proven.
806
804
  */
807
805
  export const interruptResponseSchema = z.object({
808
806
  ok: z.literal(true),
809
807
  session: sessionSummarySchema.optional(),
810
808
  delivered: interruptDeliverySchema.optional(),
809
+ returnedPrompt: z.string().min(1).optional(),
811
810
  });
812
811
  export const clientLogBodySchema = z.object({
813
812
  events: z.array(z.object({
@@ -20,7 +20,7 @@
20
20
  import { z } from 'zod';
21
21
  import { IROH_ENDPOINT_ID_RE, PAIRING_CODE_RE, irohRelayUrl } from './pairing-link.js';
22
22
  import { sentenceRefSchema } from './sentences/index.js';
23
- import { MAX_ANSWER_TEXT_CHARS, MAX_FILES_PER_MESSAGE, MAX_IMAGES_PER_MESSAGE, MAX_MESSAGE_TEXT_CHARS, PUSH_LABEL_MAX_CHARS, TERM_ID_RE, fileAttachmentSchema, imageDataUrlSchema, sessionSummarySchema, termListResponseSchema, transcriptMessageSchema, } from './protocol.js';
23
+ import { FILE_ENTRY_KINDS, FILE_TOO_LARGE_ERROR, MAX_ANSWER_TEXT_CHARS, MAX_FILES_PER_MESSAGE, MAX_IMAGES_PER_MESSAGE, MAX_MESSAGE_TEXT_CHARS, PUSH_LABEL_MAX_CHARS, TERM_ID_RE, fileAttachmentSchema, imageDataUrlSchema, inboxHeadSchemaOf, knownDialogIdSchema, refuseReasonSchema, sessionStateSchema, sessionSummarySchema, termListResponseSchema, transcriptMessageSchema, waitingForSchema, } from './protocol.js';
24
24
  /*
25
25
  * REST terminala dla apki natywnej: schematy istnieją w `protocol.ts`, tu tylko re-eksport — jedno miejsce
26
26
  * kontraktu REST dla klienta w innym języku, zero kopii.
@@ -76,25 +76,26 @@ export const messageBodySchema = z.object({
76
76
  });
77
77
  /**
78
78
  * `POST /api/sessions/:id/seen`. Without fields (`{}`, as the app sends it) a human viewed the result. `by:
79
- * "voice-agent"` with `stateSince` and `conversation` is the voice agent across sessions picking up the result it
80
- * read: `stateSince` and `conversation` (the token of `GET /api/companion/sessions` and of the turns route) come from
81
- * that read. The server accepts it only for a result standing in `waiting-input` with no decision card over it, whose
82
- * `stateSince` is the session's current one, in the engine conversation the session writes and its pane runs;
83
- * otherwise a 409 (`session.seen-result-changed`) and nothing changes. All three or none: a part is a 400, as is
84
- * another value of `by`.
79
+ * "voice-agent"` with `conversation` and `readMark` is the voice agent across sessions picking up the result it read:
80
+ * both come from one answer of the turns route (`companionTurnsSchema`). The server accepts it only for a result
81
+ * standing in `waiting-input` with no decision card over it, in the engine conversation the session writes and its
82
+ * pane runs, while the session's memory holds no message newer than the read and its `stateSince` is the one of the
83
+ * read; otherwise a 409
84
+ * (`session.seen-result-changed`) and nothing changes. All three or none: a part is a 400, as is another value of
85
+ * `by`. Other keys are dropped, as in every body schema that is not strict.
85
86
  *
86
87
  * With `RAROG_COMPANION_SESSIONS` off (or the voice agent off), a body with the three fields is a 503 like the other
87
88
  * routes of the mode across sessions (`docs/companion.md`, "Picking up a result").
88
89
  */
89
90
  export const seenBodySchema = z.object({
90
91
  by: z.literal('voice-agent').optional(),
91
- stateSince: z.string().min(1).max(64).optional(),
92
92
  conversation: z.string().min(1).max(64).optional(),
93
+ readMark: z.string().min(1).max(64).optional(),
93
94
  }).refine((body) => {
94
- const given = [body.by, body.stateSince, body.conversation].filter((field) => field !== undefined).length;
95
+ const given = [body.by, body.conversation, body.readMark].filter((field) => field !== undefined).length;
95
96
  return given === 0 || given === 3;
96
97
  }, {
97
- message: 'by, stateSince and conversation come all three or none',
98
+ message: 'by, conversation and readMark come all three or none',
98
99
  });
99
100
  /**
100
101
  * Sufit JEDNEJ notatki do odpowiedzi, w jednostkach UTF-16 (`string.length`): sufit Raroga,
@@ -723,13 +724,17 @@ export const companionTurnsCountSchema = z.string().regex(/^[1-9]$/u).transform(
723
724
  * messages of this response from 1 and is not the stream's `seq`). A turn starts at a human message that the app
724
725
  * shows as a turn. `conversation` is an opaque token of that conversation: the same while the server runs, another
725
726
  * for another conversation and after a server restart; it is not the engine's id. `stateSince` is the session's
726
- * `stateSince` at the read. `complete: false` = the read window starts inside the oldest returned turn, so its prompt
727
- * and its first messages are missing.
727
+ * `stateSince` at the read. `readMark` is an opaque name of the newest message the server's memory of the session held
728
+ * and of the session's `stateSince` when the route took the session for this read, before the file was read; the voice
729
+ * agent's pick-up of the result sends it back (`seenBodySchema`). An answer with no messages, or with a message cut
730
+ * to its start by the size limit, carries a mark that names no read, which no pick-up matches. `complete: false` =
731
+ * the read window starts inside the oldest returned turn, so its prompt and its first messages are missing.
728
732
  */
729
733
  export const companionTurnsSchema = z.object({
730
734
  messages: z.array(transcriptMessageSchema),
731
735
  conversation: z.string().min(1),
732
736
  stateSince: z.string(),
737
+ readMark: z.string().min(1).max(64),
733
738
  complete: z.boolean(),
734
739
  });
735
740
  /** 503: the voice agent works, but the mode across sessions is off (`RAROG_COMPANION_SESSIONS`). */
@@ -802,3 +807,92 @@ export const COMPANION_SPEECH_UNCONFIGURED_ERROR = 'companion-speech-unconfigure
802
807
  export const COMPANION_SPEECH_THROTTLED_ERROR = 'companion-speech-throttled';
803
808
  /** 502: Soniox did not give a key (5xx, timeout, no connection, a reply without a key). */
804
809
  export const COMPANION_SPEECH_UPSTREAM_ERROR = 'companion-speech-upstream';
810
+ // ---------------------------------------------------------------------------
811
+ // Inbox: the cards with their text (`docs/implementation-spec.md`, "Inbox")
812
+ // ---------------------------------------------------------------------------
813
+ /**
814
+ * The decision a `decision` card waits for, as the session summary carries it: a permission or question card
815
+ * (`waitingFor`, and `requestId`, the `permId` or `qId` of that card in the session stream) or a dialog in the pane
816
+ * without a card (`herdrDialog`, `herdrDialogReason`). The pending card itself comes with the session stream.
817
+ */
818
+ export const inboxCardDialogSchema = z.discriminatedUnion('kind', [
819
+ z.object({
820
+ kind: z.literal('permission'), waitingFor: waitingForSchema.optional(), requestId: z.string().min(1).optional(),
821
+ }),
822
+ z.object({
823
+ kind: z.literal('question'), waitingFor: waitingForSchema.optional(), requestId: z.string().min(1).optional(),
824
+ }),
825
+ z.object({
826
+ kind: z.literal('panel'), herdrDialog: knownDialogIdSchema.optional(),
827
+ herdrDialogReason: refuseReasonSchema.optional(),
828
+ }),
829
+ ]);
830
+ /**
831
+ * One visible Inbox card with its text: the head of `inbox-head` (`protocol/inbox.ts`), whose `dialog` here is the
832
+ * whole {@link inboxCardDialogSchema} instead of its kind, plus `text`, the last message of the agent's turn (at most
833
+ * 12 000 Unicode scalars), and `truncated` when the text lost its start to that ceiling.
834
+ */
835
+ export const inboxCardSchema = inboxHeadSchemaOf(sessionStateSchema).extend({
836
+ text: z.string(),
837
+ truncated: z.boolean(),
838
+ dialog: inboxCardDialogSchema.optional(),
839
+ });
840
+ /** 200 of `GET /api/inbox`: every visible card, newest first. */
841
+ export const inboxListSchema = z.object({ cards: z.array(inboxCardSchema) });
842
+ /** 200 of `GET /api/inbox/:sessionId`: the session's visible card; no `card` = the session has none now. */
843
+ export const inboxCardResponseSchema = z.object({ card: inboxCardSchema.optional() });
844
+ /**
845
+ * `POST /api/inbox/:sessionId/remove` and `/restore`: the turn and the version of the card the device shows (from its
846
+ * head). Another turn or version is a 409 {@link INBOX_CARD_CHANGED_ERROR} without effect.
847
+ */
848
+ export const inboxActionBodySchema = z.object({
849
+ turnId: z.string().min(1).max(64),
850
+ version: z.string().min(1).max(64),
851
+ });
852
+ /**
853
+ * 200 of remove and restore. `changed: false` = the card already was removed (restored), nothing happened again.
854
+ * `receipt: "skipped"` = the card is removed (restored), but the receipt of the result it would give (remove) or take
855
+ * back (restore) did not happen, because no read confirmed the card's turn or the session moved meanwhile.
856
+ */
857
+ export const inboxActionResponseSchema = z.object({
858
+ ok: z.literal(true),
859
+ changed: z.boolean(),
860
+ receipt: z.literal('skipped').optional(),
861
+ });
862
+ /** 409 of remove and restore: the session has no card of that turn and version now; nothing happened. */
863
+ export const INBOX_CARD_CHANGED_ERROR = 'inbox-card-changed';
864
+ /** 503 of every Inbox route: the Inbox is off on the server (`RAROG_INBOX=0`). */
865
+ export const INBOX_DISABLED_ERROR = 'inbox-disabled';
866
+ // ---------------------------------------------------------------------------
867
+ // Session files: the listing of one directory, the index and the refusal of a file over the limit (`protocol/files.ts`)
868
+ // ---------------------------------------------------------------------------
869
+ /** One entry of {@link fileListingSchema}: `size` for files only, `ignored` only as `true`. */
870
+ export const fileEntrySchema = z.object({
871
+ name: z.string().min(1),
872
+ kind: z.enum(FILE_ENTRY_KINDS),
873
+ size: z.number().int().nonnegative().optional(),
874
+ ignored: z.literal(true).optional(),
875
+ });
876
+ /** 200 of `GET /api/sessions/:id/files?dir=<rel>` ({@link FileListing}). */
877
+ export const fileListingSchema = z.object({
878
+ dir: z.string(),
879
+ entries: z.array(fileEntrySchema),
880
+ truncated: z.boolean(),
881
+ maxBytes: z.number().int().positive(),
882
+ });
883
+ /** 200 of `GET /api/sessions/:id/files/index` ({@link FileIndex}). */
884
+ export const fileIndexSchema = z.object({
885
+ paths: z.array(z.string().min(1)),
886
+ truncated: z.boolean(),
887
+ maxBytes: z.number().int().positive(),
888
+ });
889
+ /** 413 `file-too-large` of `GET /api/sessions/:id/files/raw?path=<rel>` ({@link FileTooLargeBody}). */
890
+ export const fileTooLargeBodySchema = z.object({
891
+ error: z.literal(FILE_TOO_LARGE_ERROR),
892
+ message: z.string(),
893
+ messageRef: sentenceRefSchema.optional(),
894
+ size: z.number().int().nonnegative(),
895
+ maxBytes: z.number().int().positive(),
896
+ });
897
+ const _fileContract = [true, true, true, true, true, true, true, true];
898
+ void _fileContract;
@@ -85,7 +85,20 @@ export const REST_SENTENCES = {
85
85
  'rest.diff-file-not-found': { en: "That file isn't in the list of changes. The list may have changed." },
86
86
  'rest.diff-git-failed': { en: "Git didn't respond. Try again." },
87
87
  'rest.endpoint-not-found': { en: "That endpoint doesn't exist." },
88
+ 'rest.file-too-large': {
89
+ en: 'This file has {size} MB. The server sends files up to {limit} MB (RAROG_FILES_MAX_MB).',
90
+ args: ['size:int', 'limit:int'],
91
+ },
92
+ 'rest.files-codex': { en: "Rarog only observes the Codex pane, so it doesn't show the files in its directory." },
93
+ 'rest.files-no-pane': { en: "This session has no herdr pane, so Rarog doesn't show the files in its directory." },
94
+ 'rest.files-not-found': { en: "That file or directory isn't there, or Rarog doesn't show it." },
95
+ 'rest.files-out-of-scope': {
96
+ en: 'The pane is outside RAROG_HERDR_ROOTS. Rarog shows its state but not the files in its directory.',
97
+ },
88
98
  'rest.image-not-found': { en: "That photo doesn't exist." },
99
+ 'rest.inbox-card-changed': { en: 'This Inbox card changed in the meantime, so nothing happened.' },
100
+ 'rest.inbox-disabled': { en: 'The Inbox is turned off on the server (RAROG_INBOX).' },
101
+ 'rest.inbox-save-failed': { en: "Couldn't save the change to the Inbox." },
89
102
  'rest.login-retired': { en: 'Token sign-in no longer exists. Pair the device (rarog pair).' },
90
103
  'rest.method-not-allowed': { en: 'Method not allowed.' },
91
104
  'rest.mkdir-busy': { en: 'Another directory is being created. Try again in a moment.' },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rarog/server",
3
- "version": "1.0.1",
4
- "description": "Server for Rarog, the iPhone and iPad app for Claude Code sessions running in herdr",
3
+ "version": "1.1.0-beta.1",
4
+ "description": "Rarog is a free, open-source (MIT) iPhone and iPad app, plus a server on your Mac or Linux machine, that shows the Claude Code sessions running in Herdr TUI and lets you drive them.",
5
5
  "keywords": [
6
6
  "claude-code",
7
7
  "herdr",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@number0/iroh": "1.2.0",
37
- "@rarog/shared": "1.0.1",
37
+ "@rarog/shared": "1.1.0-beta.1",
38
38
  "qrcode": "1.5.4",
39
39
  "ws": "8.21.3",
40
40
  "zod": "4.4.3"
@@ -5,13 +5,16 @@
5
5
  * itself starts there, after `listen`.
6
6
  */
7
7
  import { stat } from 'node:fs/promises';
8
- import { basename, dirname } from 'node:path';
8
+ import { basename, dirname, join } from 'node:path';
9
9
  import { createConsentHandler, redact, startConsentSocket } from '../auth/index.js';
10
10
  import { defaultStoreRoot } from '../cli-store.js';
11
+ import { inWorkAreaOnDisk } from '../config/work-area.js';
12
+ import { hookChildRunning, statuslineFreshness } from '../drivers/herdr/consent-no-hook-io.js';
11
13
  import { createConsentEvidenceReview, createConsentEvidenceScanner } from '../herdr/consent-evidence.js';
12
14
  import { consentStep } from '../herdr/consent-step.js';
13
15
  import { consentChannelOpen } from '../herdr/dialogs/hook/contract.js';
14
- import { CONSENT_HOLDING_STATES } from '../herdr/dialogs/layer1/contract.js';
16
+ import { createSessionFacts } from '../herdr/dialogs/layer1/hook-list/session-facts.js';
17
+ import { CONSENT_HOLDING_STATES, CONSENT_POOL_MAX } from '../herdr/dialogs/layer1/contract.js';
15
18
  import { createConsentCycle } from '../herdr/dialogs/layer1/cycle.js';
16
19
  // Osobny import: strażnik wspólnej obserwacji (`layer1-obserwacja`) czyta linię importu `observeConsentSession`.
17
20
  import { observeConsentSession } from '../herdr/dialogs/layer1/observe.js';
@@ -20,7 +23,10 @@ import { recoverThenSweepConsent } from '../herdr/dialogs/layer1/records.js';
20
23
  import { retireRunningAfterRecover } from '../herdr/dialogs/layer1/frames.js';
21
24
  import { consentRegistrationWanted, consentRegistryScopeOf, createConsentRegistry, } from '../herdr/dialogs/layer1/registry.js';
22
25
  import { createRefusalDumper } from '../herdr/dialogs/refusals.js';
26
+ import { scanCallDumps, scanMarkers } from '../herdr/dialogs/shadow/files.js';
23
27
  import { psLiveness } from '../herdr/dialogs/shadow/liveness.js';
28
+ import { HOOK_INSTALLED_SCRIPT_REL, hookCommand } from '../herdr/hook-commands.js';
29
+ import { defaultStatuslineRoot } from '../herdr/statusline.js';
24
30
  import { TRANSCRIPT_EXT, locateTranscript } from '../herdr/transcript-path.js';
25
31
  /**
26
32
  * Chwila przyjęcia najnowszej żywej rejestracji sesji, której klucz nie ma jeszcze karty kanału (w żadnym stanie), albo
@@ -72,6 +78,86 @@ export async function observeConsent(link, dataDir, liveness, request, subagents
72
78
  ...(subagents === null || hidden === null ? {} : { hidden }),
73
79
  }));
74
80
  }
81
+ /**
82
+ * The session process of an engine session for the session hook list: the one live entry of the CLI registry (pid and
83
+ * start); `null` without a registry read, with an unreadable pid, an unlisted session or more than one entry.
84
+ */
85
+ export function consentSessionEntry(cliVersionReader) {
86
+ return async (engineSessionId) => {
87
+ const read = await cliVersionReader({ registryOnly: true });
88
+ if (read.registry === null || (read.unreadablePids ?? 0) > 0)
89
+ return null;
90
+ if (read.unlistedSessions?.has(engineSessionId) === true)
91
+ return null;
92
+ const entries = read.registry.get(engineSessionId);
93
+ const entry = entries?.length === 1 ? entries[0] : undefined;
94
+ return entry === undefined ? null
95
+ : { pid: entry.pid, ...(entry.startedAt === undefined ? {} : { startedAt: entry.startedAt }) };
96
+ };
97
+ }
98
+ /** Record states of a request the hook still waits on: anything later is answered or settled. */
99
+ const CONSENT_UNSETTLED_STATES = new Set(['pending', 'deciding', 'sent']);
100
+ /**
101
+ * Whether a trace of Rarog's `PermissionRequest` hook stands for the session (the consent-without-hook detector,
102
+ * `drivers/herdr/consent-no-hook.ts`): a live registration accepted at or after `since` (ms of the epoch, the end of
103
+ * the previous dialog episode), a channel card holding a dialog, a request of the channel pool (dump or request
104
+ * marker) without an exit whose record is not settled, a pool past its cap, a per-call dump on disk whose record is
105
+ * not settled (the hook deletes it on every exit, so it stands while the hook lives), or a request marker on disk the
106
+ * pool has not taken whose record is not settled; an incomplete read of the dumps or markers counts too. Settled
107
+ * records, and dumps and requests under them, are no trace. Throws on a read error of the dump or marker directory.
108
+ */
109
+ export function consentHookTrace(link, dataDir, sessionId, since) {
110
+ const { cycle, registry } = link;
111
+ if (registry?.entries().some((entry) => entry.sessionId === sessionId && entry.acceptedAt >= since) === true) {
112
+ return true;
113
+ }
114
+ // Without the cycle there is no record to settle a request: every request counts.
115
+ const open = (key) => {
116
+ const record = cycle?.record(sessionId, key) ?? null;
117
+ return record === null || CONSENT_UNSETTLED_STATES.has(record.state);
118
+ };
119
+ if (cycle !== null) {
120
+ if (cycle.cards(sessionId).some((card) => CONSENT_HOLDING_STATES.includes(card.state))) {
121
+ return true;
122
+ }
123
+ const pool = cycle.pool(sessionId);
124
+ if (pool.overflow)
125
+ return true;
126
+ if (pool.candidates.some((candidate) => candidate.exitAt === null && open(candidate.dump.key)))
127
+ return true;
128
+ }
129
+ const dumps = scanCallDumps(dataDir, sessionId);
130
+ if (!dumps.complete || dumps.dumps.some((dump) => open(dump.key)))
131
+ return true;
132
+ // Request markers the pool has not taken yet (written after the last channel observation). A marker under a dump
133
+ // key or a name the pool knows is decided above; a marker without a call key has no record that settles it.
134
+ const dumpKeys = new Set(dumps.dumps.map((dump) => dump.key));
135
+ const markers = scanMarkers(dataDir, sessionId, (name) => dumpKeys.has(name) || cycle?.poolKnows(sessionId, name) === true, CONSENT_POOL_MAX);
136
+ return !markers.complete || markers.markers.some((marker) => marker.key === null || open(marker.key));
137
+ }
138
+ /** The sources of the consent-without-hook detector, shared by every driver of the process. */
139
+ export function consentNoHookSources(options) {
140
+ const script = join(options.home, HOOK_INSTALLED_SCRIPT_REL);
141
+ const statuslineRoot = defaultStatuslineRoot();
142
+ // One instance per process, with the cache of its own; it reads like the session hook list and logs nothing.
143
+ const facts = createSessionFacts({ home: options.home, accepted: [hookCommand(options.home)], entry: options.entry });
144
+ return {
145
+ hookTrace: (sessionId, since) => {
146
+ try {
147
+ return consentHookTrace(options.link, options.dataDir, sessionId, since);
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ },
153
+ facts,
154
+ hookRunning: (pid) => hookChildRunning(pid, script),
155
+ // The hook's rule (`scripts/hooks/work-area.mjs`): the text, then the path resolved one segment at a time.
156
+ outsideWorkArea: (cwd) => !inWorkAreaOnDisk(cwd, options.roots, options.home),
157
+ statusline: (sessionId) => statuslineFreshness(statuslineRoot, sessionId, Date.now()),
158
+ proofRules: (sessionId) => options.proofGate.current(sessionId),
159
+ };
160
+ }
75
161
  /**
76
162
  * Wpisy rejestru sekretów, których proces hooka nie żyje według `ps` (pid i czas startu z rejestracji), idą do cyklu
77
163
  * sygnałem `dead`: karta klucza (jeśli jest) przechodzi jak przy martwym hooku, a wpis znika z rejestru. Dotyczy też
@@ -9,7 +9,7 @@ import { devicePairedNotifier } from '../device-effects.js';
9
9
  import { createRouter } from '../router.js';
10
10
  import { tailnetReader } from '../tailnet.js';
11
11
  export function buildRouter(assembly) {
12
- const { config, manager, hub, serverStartId, startedAtMs, log, health, system, macStats, demoUsage, demoVoice, demoNotes, term, companion, notifier, presence, apns, loginLimiter, irohPair, devices, pairing, reviewConstants, demoHost, } = assembly;
12
+ const { config, manager, hub, serverStartId, startedAtMs, log, health, system, macStats, demoUsage, demoVoice, demoNotes, term, companion, notifier, presence, apns, loginLimiter, irohPair, devices, pairing, reviewConstants, demoHost, inbox, fileDownloads, } = assembly;
13
13
  /*
14
14
  * Nazwa tailnetu dla nagłówka AGENCI. Czytana LENIWIE i z terminem
15
15
  * ważności — `tailnetReader` spawnuje `tailscale status` najwyżej raz na minutę i nigdy
@@ -22,7 +22,7 @@ export function buildRouter(assembly) {
22
22
  const tailnet = reviewConstants !== null ? undefined
23
23
  : demoHost !== null ? () => Promise.resolve(demoHost.tailnet) : tailnetReader();
24
24
  return createRouter({
25
- config, manager, hub, serverStartId, startedAtMs, logger: log, health, system,
25
+ config, manager, hub, serverStartId, startedAtMs, logger: log, health, system, fileDownloads,
26
26
  ...(tailnet === undefined ? {} : { tailnet }),
27
27
  mac: () => macStats.current(),
28
28
  ...(demoUsage === undefined ? {} : { usage: demoUsage }),
@@ -35,6 +35,7 @@ export function buildRouter(assembly) {
35
35
  // APNs) — bez kanału nie ma czego bramkować, a beacon staje się no-opem (patrz `RouterDeps`).
36
36
  ...(notifier !== null ? { presence } : {}),
37
37
  ...(apns !== undefined ? { apns } : {}),
38
+ ...(inbox === null || inbox === undefined ? {} : { inbox }),
38
39
  loginLimiter,
39
40
  iroh: irohPair,
40
41
  devices: {