@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
@@ -20,7 +20,7 @@ import { randomUUID } from 'node:crypto';
20
20
  import { renameSync } from 'node:fs';
21
21
  import { homedir } from 'node:os';
22
22
  import { basename, join, resolve } from 'node:path';
23
- import { DEFAULT_MODEL_CHOICE, DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, FALLBACK_MODEL_CHOICES, MAX_ANSWER_TEXT_CHARS, MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, EXIT_PLAN_MODE_TOOL, MAX_RESUMABLE_SESSIONS, MODEL_CHANGE_WARNING, ULTRACODE_CHANGE_NOTE, WAITING_TEXT_MAX, messageAttachments, } from '@rarog/shared';
23
+ import { DEFAULT_MODEL_CHOICE, DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, FALLBACK_MODEL_CHOICES, MAX_ANSWER_TEXT_CHARS, MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, EXIT_PLAN_MODE_TOOL, MAX_RESUMABLE_SESSIONS, MODEL_CHANGE_WARNING, ULTRACODE_CHANGE_NOTE, messageAttachments, } from '@rarog/shared';
24
24
  import { foreign, say, sentenceOfArglessRef, } from '@rarog/shared/sentences';
25
25
  import { isFallbackLabel, nextFallbackLabel } from './fallback-label.js';
26
26
  export { isFallbackLabel, nextFallbackLabel };
@@ -28,11 +28,12 @@ import { MAX_TURNS_DETAIL, transition } from './state-machine.js';
28
28
  import { Session, wireStateDetail } from './session.js';
29
29
  import { BadRequestError, BadStateError, NotFoundError, TooManyRequestsError, } from './errors.js';
30
30
  import { createSendRegistry, sendDigest } from './send-registry.js';
31
- import { DECISION_STATES, DRIVER_ERROR_DETAIL, DRIVER_GONE_DETAIL, HERDR_ALLOW_MESSAGE, HERDR_CODEX_CLOSE_MESSAGE, HERDR_CODEX_GIT_MESSAGE, HERDR_FOCUS_MESSAGE, HERDR_GONE_DETAIL, HERDR_HIDDEN_DETAIL, HERDR_LAUNCHING_DETAIL, HERDR_LAUNCH_OFF_MESSAGE, HERDR_LOST_PROMPT_MESSAGE, HERDR_MODEL_MESSAGE, HERDR_MODE_BYPASS_MESSAGE, HERDR_MODE_MESSAGE, HERDR_NOT_OWNED_MESSAGE, HERDR_NO_DRIVER_INTERRUPT_MESSAGE, HERDR_OUT_OF_SCOPE_DIFF_MESSAGE, HERDR_OUT_OF_SCOPE_MESSAGE, HERDR_READ_ONLY_MESSAGE, HERDR_RESUME_MESSAGE, HERDR_TERMINAL_UNAVAILABLE_MESSAGE, HERDR_THROTTLED_MESSAGE, HERDR_TRUST_PROMPT_MESSAGE, INTERRUPT_DETAIL, INTERRUPT_WORKING_GRACE_MS, LATE_TOOL_CALL_MS, LIVE_STATES, MODEL_BUSY_MESSAGE, MODEL_CHANGE_STATES, MODE_BUSY_MESSAGE, PROMPT_BLOCK_MARKER_MS, RESTART_BUSY_MESSAGE, RESTART_CODEX_MESSAGE, RESTART_EXIT_TIMEOUT_MS, RESTART_NO_PANEL_MESSAGE, RESTART_NO_UPDATE_MESSAGE, RESTART_RESEND_STALE_MESSAGE, RESTART_TASKS_MESSAGE, RESTART_UNSUPPORTED_MESSAGE, RESTART_WAITING_AGENT_MESSAGE, RESUME_WITHOUT_ULTRACODE_MESSAGE, SENDABLE_STATES, STREAMING_STATES, TURN_END_STATES, ULTRACODE_CLI_UNKNOWN_MESSAGE, WORKING_STATES, cwdDeniedSentence, herdrLaunchFailedDetail, inTurn, launchThrottledMessage, limitReachedDetail, nextTurnInput, noInputYet, pushStateDetail, restartFailedDetail, restartLaunchingDetail, seedDetailField, startsTurn, tallyTurnInput, toolsDecideSilence, ultracodeCliTooOldMessage, uncertainLaunch, } from './state-sentences.js';
31
+ import { DECISION_STATES, DRIVER_ERROR_DETAIL, DRIVER_GONE_DETAIL, HERDR_ALLOW_MESSAGE, HERDR_CODEX_CLOSE_MESSAGE, HERDR_FOCUS_MESSAGE, HERDR_GONE_DETAIL, HERDR_HIDDEN_DETAIL, HERDR_LAUNCHING_DETAIL, HERDR_LAUNCH_OFF_MESSAGE, HERDR_LOST_PROMPT_MESSAGE, HERDR_MODEL_MESSAGE, HERDR_MODE_BYPASS_MESSAGE, HERDR_MODE_MESSAGE, HERDR_NOT_OWNED_MESSAGE, HERDR_NO_DRIVER_INTERRUPT_MESSAGE, HERDR_OUT_OF_SCOPE_MESSAGE, HERDR_READ_ONLY_MESSAGE, HERDR_RESUME_MESSAGE, HERDR_TERMINAL_UNAVAILABLE_MESSAGE, HERDR_THROTTLED_MESSAGE, HERDR_TRUST_PROMPT_MESSAGE, INTERRUPT_DETAIL, INTERRUPT_WORKING_GRACE_MS, LATE_TOOL_CALL_MS, LIVE_STATES, MODEL_BUSY_MESSAGE, MODEL_CHANGE_STATES, MODE_BUSY_MESSAGE, PROMPT_BLOCK_MARKER_MS, RESTART_BUSY_MESSAGE, RESTART_CODEX_MESSAGE, RESTART_EXIT_TIMEOUT_MS, RESTART_NO_PANEL_MESSAGE, RESTART_NO_UPDATE_MESSAGE, RESTART_RESEND_STALE_MESSAGE, RESTART_TASKS_MESSAGE, RESTART_UNSUPPORTED_MESSAGE, RESTART_WAITING_AGENT_MESSAGE, RESUME_WITHOUT_ULTRACODE_MESSAGE, SENDABLE_STATES, STREAMING_STATES, TURN_END_STATES, ULTRACODE_CLI_UNKNOWN_MESSAGE, WORKING_STATES, cwdDeniedSentence, herdrLaunchFailedDetail, inTurn, launchThrottledMessage, limitReachedDetail, nextTurnInput, noInputYet, pushStateDetail, restartFailedDetail, restartLaunchingDetail, seedDetailField, startsTurn, tallyTurnInput, toolsDecideSilence, ultracodeCliTooOldMessage, uncertainLaunch, } from './state-sentences.js';
32
32
  import { DialogTimings } from './dialog-timing.js';
33
33
  import { ClaimWindows } from './claim-window.js';
34
34
  import * as seenMarks from './seen-marks.js';
35
35
  import * as heldEcho from './held-echo.js';
36
+ import { GIT_DIFF_FILE_LOG, GIT_DIFF_LIST_LOG, measureDiff } from './diff-measure.js';
36
37
  import { heldActivity, holdActivity, stampState } from './activity-clocks.js';
37
38
  import { PendingInteractions } from '../permissions.js';
38
39
  import { classifyRisk } from '../risk.js';
@@ -60,6 +61,9 @@ import { AttachSlots } from './attach-slots.js';
60
61
  import { scanProjectRoots } from './project-scan.js';
61
62
  import { recentProjects } from './recent-projects.js';
62
63
  import * as companionScope from './companion-scope.js';
64
+ import * as sessionScope from './session-scope.js';
65
+ import { openSessionDownload } from '../files/session-download.js';
66
+ import { listSessionFiles } from '../files/session-files.js';
63
67
  // Jedyny wartościowy import z `herdr/*` w tym pliku: czysta funkcja sklejająca prompt ze
64
68
  // ścieżkami załączników. Zero gniazda, zero I/O — patrz komentarz przy re-eksporcie niżej.
65
69
  import { appendAttachmentPaths } from '../herdr/uploads.js';
@@ -79,9 +83,9 @@ import { consentStep } from '../herdr/consent-step.js';
79
83
  import { HerdrCommandRefusedError, ULTRACODE_COMMANDS, commandListOf, promptBlockedField, promptBlockedText, registryCatalog, } from '../herdr/commands/index.js';
80
84
  import { cardShowsAll, permissionSemantics, toolInputText } from '../drivers/tool-text.js';
81
85
  import { onlyWaitingAgents, tasksBlockRestart, tasksHoldingDonePush, waitingOnOwnCommand, } from '../herdr/background/work.js';
82
- // Ta sama etykieta, którą dostaje wiersz tool-calla w transkrypcie — patrz `decisionText`.
83
- import { summarizeToolInput } from '../drivers/tool-summary.js';
86
+ import { decisionText, waitingText } from './waiting-line.js';
84
87
  import { ConsentCards, consentRefusal } from './consent-cards.js';
88
+ import { loadDemoModules } from './demo-modules.js';
85
89
  /** Wynik zwykłej wysyłki (bez `clientMessageId` albo pierwsze przyjęcie) */
86
90
  const NOT_REPLAYED = Object.freeze({ replayed: false });
87
91
  // ---------------------------------------------------------------------------
@@ -96,10 +100,8 @@ export { BadRequestError, BadStateError, GoneError, NotFoundError, TooManyReques
96
100
  export const PROMPT_BLOCKED_LOG = 'rarog: prompt blocked by a hook';
97
101
  /** Defined in `held-echo.ts` with the deferred echo; importers keep this path. */
98
102
  export { HELD_FLUSHED_LOG, HELD_QUEUE_LOG } from './held-echo.js';
99
- /** Fraza linii kosztu listy plików gita czytanej od nowa: `git: diff list <ms> ms`. */
100
- export const GIT_DIFF_LIST_LOG = 'git: diff list';
101
- /** Fraza linii kosztu patcha jednego pliku: `git: diff file <ms> ms`. */
102
- export const GIT_DIFF_FILE_LOG = 'git: diff file';
103
+ /** Defined in `diff-measure.ts` with the line of a diff read; importers keep this path. */
104
+ export { GIT_DIFF_FILE_LOG, GIT_DIFF_LIST_LOG } from './diff-measure.js';
103
105
  /*
104
106
  * 409 na zakładanie sesji po osiągnięciu sufitu paneli Raroga.
105
107
  *
@@ -118,19 +120,6 @@ export { HERDR_PANE_CAP_MESSAGE };
118
120
  export { appendAttachmentPaths };
119
121
  /** Re-exported for `index.ts`, which imports it from the manager; defined in `state-sentences.ts`. */
120
122
  export { RESUME_UNREADABLE_MESSAGE } from './state-sentences.js';
121
- /** Dynamiczny import scenariuszy demo — wołany WYŁĄCZNIE przy `config.demo`; treść z podanego zestawu. */
122
- async function loadDemoModules(content) {
123
- const seeds = await import('../demo/seeds.js');
124
- return {
125
- demoSeeds: (now) => seeds.demoSeeds(content, now),
126
- demoBlocks: seeds.demoBlocks,
127
- demoProjects: () => seeds.demoProjects(content),
128
- demoResumable: (cwd, now) => seeds.demoResumable(content, cwd, now),
129
- demoDiff: () => seeds.demoDiff(content),
130
- demoDiffFiles: seeds.demoDiffFiles,
131
- demoDiffFile: (path) => seeds.demoDiffFile(content, path),
132
- };
133
- }
134
123
  // ---------------------------------------------------------------------------
135
124
  // Etykieta sesji (człon `sesja` w tytule `projekt · sesja`)
136
125
  // ---------------------------------------------------------------------------
@@ -151,6 +140,7 @@ class RarogManager {
151
140
  #pending = new PendingInteractions();
152
141
  #sessions = new Map();
153
142
  #listeners = [];
143
+ #transcriptResets = [];
154
144
  #conversations = new companionScope.ConversationListeners((line) => { this.#config.logger?.(line); });
155
145
  /** Git row of cards: reader, `.git` watcher, `git-status` frames and the cost window in the log. */
156
146
  #git;
@@ -629,6 +619,9 @@ class RarogManager {
629
619
  onEvent(cb) {
630
620
  this.#listeners.push(cb);
631
621
  }
622
+ onTranscriptReset(cb) {
623
+ this.#transcriptResets.push(cb);
624
+ }
632
625
  projects() {
633
626
  const configured = this.#config.projects;
634
627
  if (configured !== undefined) {
@@ -878,11 +871,19 @@ class RarogManager {
878
871
  paneId: handle.paneId,
879
872
  herdrKey: handle.key,
880
873
  launchedByRarog: true,
874
+ ringStartSeq: opts.continuesRing?.lastSeq,
881
875
  });
882
876
  // Etykieta karty → etykieta taba w herdr. Launcher założył tab z nazwą katalogu;
883
877
  // nadzorca przemianuje go, gdy panel dostanie etykietę pochodzenia.
884
878
  this.#setLabel(session, label);
885
879
  this.#sessions.set(session.id, session);
880
+ // A card under an existing id: the open transcript streams get a snapshot before the first frame of the new card.
881
+ for (const listener of opts.continuesRing === undefined ? [] : this.#transcriptResets) {
882
+ try {
883
+ listener(session.id);
884
+ }
885
+ catch { /* A broken listener must not fail the launch. */ }
886
+ }
886
887
  this.#herdrByKey.set(handle.key, session.id);
887
888
  this.#indexEngineSession(session);
888
889
  this.#git.watch(session);
@@ -1547,7 +1548,7 @@ class RarogManager {
1547
1548
  if (outcome.kind === 'refused') {
1548
1549
  /*
1549
1550
  * Rozpoznanie WRACA tylko po `send-failed`: to jedyna odmowa, przy której z Raroga nie
1550
- * wyszedł ani jeden bajt, driver karty nie wycofał (`#refuseSend` świadomie nie woła ani
1551
+ * wyszedł ani jeden bajt, driver karty nie wycofał (`refuseSend` świadomie nie woła ani
1551
1552
  * `#clearActive`, ani `#scheduleEvaluate`) i dialog na pewno stoi dalej na ekranie.
1552
1553
  *
1553
1554
  * Pozostałe powody (`screen-changed`, `no-digit`, `multi-select`, `terminal-only`,
@@ -1656,22 +1657,21 @@ class RarogManager {
1656
1657
  return { outcome: 'ok' };
1657
1658
  }
1658
1659
  /**
1659
- * Esc do sesji. Zwraca obietnicę drivera („klawisz poszedł"), a NIE moment przyjęcia
1660
- * żądania.
1660
+ * Esc to the session. Returns the driver's promise ("the key went"), NOT the moment the request was accepted.
1661
1661
  *
1662
- * Kolejność w tej metodzie jest wiążąca i nie wolno jej przesunąć za dostarczenie:
1663
- * `interruptedAtMs` i przejście `interrupt-requested` lecą SYNCHRONICZNIE, bo na tym stoi
1664
- * odpowiedź POST-a ze świeżym `SessionSummary` — jedyna prawda, gdy
1665
- * `EventSource` umarł po cichu. Metoda nie jest `async` z tego samego powodu, co w driverze:
1666
- * odmowy poniżej mają rzucać na wywołaniu, nie odrzuconą obietnicą.
1667
- *
1668
- * Idempotencja stoi TUTAJ, a nie w kliencie: żądania przychodzą też z drugiego urządzenia
1669
- * i z ponowienia sieciowego klienta, których żaden guard w kliencie nie widzi. Okna są
1670
- * dwa i rozłączne — „w locie" (przed dostarczeniem) i debounce (po), każde na swoim polu.
1662
+ * The order in this method is binding: `interruptedAtMs` and the `interrupt-requested` transition run SYNCHRONOUSLY,
1663
+ * because the POST answer with a fresh `SessionSummary` stands on them, the only truth when `EventSource` died
1664
+ * silently. Not `async` for the same reason as in the driver: the refusals below throw on the call. Idempotency
1665
+ * stands HERE, not in the client: requests also come from a second device and from network retries. The two windows
1666
+ * are disjoint: "in flight" (before delivery) and debounce (after), each on its own field.
1671
1667
  */
1672
1668
  interrupt(id) {
1673
1669
  return this.#sessionRestart.track(id, () => this.#interrupt(id));
1674
1670
  }
1671
+ /** {@link ManagerApi.returnedPrompt}: the driver's field read after the last delivered `escape`. */
1672
+ returnedPrompt(id) {
1673
+ return this.#sessions.get(id)?.driver?.returnedPrompt?.() ?? Promise.resolve(null);
1674
+ }
1675
1675
  #interrupt(id) {
1676
1676
  const session = this.#require(id);
1677
1677
  this.#sessionRestart.assertNotRestarting(id);
@@ -1964,7 +1964,8 @@ class RarogManager {
1964
1964
  const restore = this.#snapshotIndexes(session);
1965
1965
  this.#forgetHerdrSession(session);
1966
1966
  try {
1967
- await this.#launch(opts, slotTaken);
1967
+ // The new card numbers on after the old one; `#launch` sends the open streams of this id a snapshot.
1968
+ await this.#launch({ ...opts, continuesRing: session.ring }, slotTaken);
1968
1969
  }
1969
1970
  catch (error) {
1970
1971
  /*
@@ -1989,9 +1990,9 @@ class RarogManager {
1989
1990
  this.#sessionRestart.assertNotRestarting(id);
1990
1991
  /*
1991
1992
  * „Uruchom ponownie i wyślij”: `seq` i `id` z ciała mają wskazywać blokadę, której przycisk
1992
- * działa — inaczej 409 PRZED rezerwacją i slotem. Sam `seq` nie wystarcza: karta po restarcie numeruje
1993
- * transkrypt od zera, więc spóźnione tapnięcie spod notki sprzed restartu trafiłoby w nową notkę o tym samym
1994
- * numerze.
1993
+ * działa — inaczej 409 PRZED rezerwacją i slotem. The `seq` alone is not enough: numbering starts from 1 again
1994
+ * in a new server process, so a late tap from before a server restart could name a new notice under the same
1995
+ * number. The block `id` decides.
1995
1996
  * Ładunek (tekst dla CLI, dymek, wizytówki) bierzemy z serwera, nigdy z ciała: klient podaje wyłącznie,
1996
1997
  * KTÓRĄ blokadę tapnięto.
1997
1998
  */
@@ -2332,53 +2333,44 @@ class RarogManager {
2332
2333
  // -------------------------------------------------------------------------
2333
2334
  // Git: diff sesji
2334
2335
  // -------------------------------------------------------------------------
2335
- /**
2336
- * Bramka wspólna WSZYSTKICH tras diffa — starej i obu per plik. Oddaje sesję, z której
2337
- * katalogu wolno czytać, albo `null` w demo: tam diff to stały mock, bez odczytu z dysku.
2338
- */
2339
- #diffSession(id) {
2340
- const session = this.#require(id);
2341
- // Bramka zasięgu: diff roboczy to TREŚĆ katalogu, a wpis Codexa obiecuje sam stan. Klient
2342
- // przycisku dla Codexa nie rysuje — to jest druga linia, dla starego klienta i dla `curl`.
2343
- if (session.engine === 'codex')
2344
- throw new BadRequestError(HERDR_CODEX_GIT_MESSAGE);
2345
- // Panel poza zasięgiem: ta sama granica co transkrypt i wycinek ekranu — treść katalogu zostaje na Macu.
2346
- if (session.outOfScope === true)
2347
- throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
2348
- /*
2349
- * Niżej, za gałęzią demo: `outOfScope` mówi o katalogu, w którym panel stoi TERAZ (nadzorca
2350
- * liczy go od nowa po `cd`), a diff czyta `session.cwd` — katalog z chwili pojawienia się
2351
- * panelu, którego reattach nie rusza. Panel, który wystartował poza korzeniami i zrobił `cd` pod korzeń, miał więc zasięg,
2352
- * a diff dalej czytał stary, prywatny katalog. Bramka pyta o TEN
2353
- * katalog, z którego pójdzie odczyt, tą samą funkcją co nadzorca (`scopeOf`).
2354
- */
2355
- // Demo nie ma korzeni ani prawdziwych katalogów: jego diff to stały mock, bez odczytu z dysku.
2356
- if (this.#config.demo)
2357
- return null;
2358
- if (!companionScope.sessionCwdInArea(session, this.#config))
2359
- throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
2360
- return session;
2336
+ /** Port of the diff gate (`diffSession` in `session-scope.ts`): the session lookup and the configuration. */
2337
+ #diffSessionPort() {
2338
+ return { require: (id) => this.#require(id), config: this.#config };
2361
2339
  }
2362
2340
  async diff(id) {
2363
- const session = this.#diffSession(id);
2341
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2364
2342
  if (session === null)
2365
2343
  return this.#requireDemo().demoDiff();
2366
2344
  const runner = this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv);
2367
2345
  return collectDiff(session.cwd, { run: runner });
2368
2346
  }
2369
2347
  async diffFiles(id) {
2370
- const session = this.#diffSession(id);
2348
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2371
2349
  if (session === null)
2372
2350
  return this.#requireDemo().demoDiffFiles();
2373
2351
  const injected = this.#config.diffRunner;
2374
- return this.#measureDiff(GIT_DIFF_LIST_LOG, () => collectDiffList(session.cwd, {
2352
+ return measureDiff(GIT_DIFF_LIST_LOG, this.#diffClock, () => collectDiffList(session.cwd, {
2375
2353
  run: injected ?? spawnGitArgs(this.#gitEnv),
2376
2354
  // Liczniki mają WŁASNY budżet (jak w ramce `git-status`): lista nie czeka na nie dłużej.
2377
2355
  runNumstat: injected ?? spawnGitArgs(this.#gitEnv, GIT_NUMSTAT_BUDGET_MS),
2378
2356
  }));
2379
2357
  }
2358
+ filesPort() {
2359
+ return {
2360
+ ...this.#diffSessionPort(), run: this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv),
2361
+ demoEntries: (rel) => this.#requireDemo().demoFileEntries(rel),
2362
+ };
2363
+ }
2364
+ listFiles(id, dir, maxBytes) {
2365
+ return listSessionFiles(id, dir, maxBytes, this.filesPort());
2366
+ }
2367
+ openFile(id, rel, maxBytes) {
2368
+ return openSessionDownload(id, rel, maxBytes, {
2369
+ ...this.#diffSessionPort(), demoFile: (file) => this.#requireDemo().demoFileBytes(file),
2370
+ });
2371
+ }
2380
2372
  async diffFile(id, path) {
2381
- const session = this.#diffSession(id);
2373
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2382
2374
  // Walidacja wstępna stoi PRZED gałęzią demo: `?path=../x` to 400 także tam, jak na produkcji.
2383
2375
  if (validateDiffPath(path) === null)
2384
2376
  throw new DiffError(DIFF_BAD_PATH_ERROR);
@@ -2389,28 +2381,12 @@ class RarogManager {
2389
2381
  return patch;
2390
2382
  }
2391
2383
  const run = this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv);
2392
- return this.#measureDiff(GIT_DIFF_FILE_LOG, () => collectDiffFile(session.cwd, path, { run }));
2393
- }
2394
- /**
2395
- * Linia `git: diff list|file <ms>` w logu: koszt list gita czytanych od nowa przy każdym
2396
- * żądaniu, czyli liczba, po której zapadnie decyzja o pamięci podręcznej. Niesie czas i — przy
2397
- * odmowie — kod z kontraktu; NIGDY ścieżki ani nazwy pliku.
2398
- */
2399
- async #measureDiff(phrase, read) {
2400
- const startedAt = this.#now();
2401
- const line = (suffix) => {
2402
- this.#config.logger?.(`${phrase} ${String(this.#now() - startedAt)} ms${suffix}`);
2403
- };
2404
- try {
2405
- const result = await read();
2406
- line('');
2407
- return result;
2408
- }
2409
- catch (error) {
2410
- line(` (${error instanceof DiffError ? error.code : 'error'})`);
2411
- throw error;
2412
- }
2384
+ return measureDiff(GIT_DIFF_FILE_LOG, this.#diffClock, () => collectDiffFile(session.cwd, path, { run }));
2413
2385
  }
2386
+ /** Clock and logger of the diff read lines (`diff-measure.ts`), read at the time of each line. */
2387
+ #diffClock = {
2388
+ now: () => this.#now(), log: (line) => { this.#config.logger?.(line); },
2389
+ };
2414
2390
  // -------------------------------------------------------------------------
2415
2391
  // Cykl życia procesu
2416
2392
  // -------------------------------------------------------------------------
@@ -3819,49 +3795,6 @@ class RarogManager {
3819
3795
  function describeError(error) {
3820
3796
  return error instanceof Error ? error.message : String(error);
3821
3797
  }
3822
- /**
3823
- * Treść decyzji do JEDNEJ linii karty listy: pierwsza linia, przycięta do `WAITING_TEXT_MAX`.
3824
- *
3825
- * Pierwsza linia, a nie „pierwsze 120 znaków całości": heredoc, wypisana treść `.env` i plan
3826
- * z trzema akapitami mają się tu nie zmieścić Z DEFINICJI. Cięcie po znakach jest wtedy tylko
3827
- * sufitem na długi jednolinijkowiec, a nie jedyną obroną przed wklejeniem pół pliku w sidebar.
3828
- * Wielokropek dokładamy WYŁĄCZNIE tam, gdzie faktycznie uciął — inaczej linia obiecuje ciąg
3829
- * dalszy, którego nie ma.
3830
- */
3831
- function waitingText(raw) {
3832
- const first = raw.split('\n', 1)[0]?.trim() ?? '';
3833
- /*
3834
- * Cięcie po PUNKTACH KODOWYCH, nie po jednostkach UTF-16: `slice(0, 120)` na linii
3835
- * z emoji na 120. znaku rozcina parę surogatów, `trimEnd()` samotnego surogata nie usuwa
3836
- * (to nie biały znak) i na karcie staje „�…". Grafem z modyfikatorem (flaga, odcień skóry)
3837
- * może się tu jeszcze rozpaść na dwa znaki, ale każdy z nich jest wtedy PEŁNY — żaden
3838
- * nie jest połówką kodu, więc przeglądarka rysuje litery, a nie znak zastępczy.
3839
- */
3840
- const points = [...first];
3841
- if (points.length <= WAITING_TEXT_MAX)
3842
- return first;
3843
- return `${points.slice(0, WAITING_TEXT_MAX).join('').trimEnd()}…`;
3844
- }
3845
- /**
3846
- * Treść ZGODY do jednej linii karty listy — z `displayText`, ale nie zawsze dosłownie.
3847
- *
3848
- * `displayText` jest jednolinijkowy tylko dla narzędzi z polem `command`. Dla całej reszty
3849
- * (`Edit`, `Write`, `Read`, `Task`, `WebFetch`…) `toolInputText` oddaje pretty-printowany JSON,
3850
- * więc PIERWSZĄ linią jest sama klamra — i karta mówiła „zgoda: Edit · {". Z takiego opisu
3851
- * bierzemy dokładnie to, co bierze etykieta tool-calla w transkrypcie (`summarizeToolInput`:
3852
- * `file_path`, `path`, `pattern`, `url`, `query`), a gdy nie ma czego wziąć — nic: „zgoda: Edit"
3853
- * jest uczciwe, klamra nie. Rozpoznanie idzie po PIERWSZEJ LINII, a nie po `startsWith('{')`,
3854
- * bo komenda Basha też umie zacząć się klamrą (`{ echo a; }` — grupa powłoki).
3855
- *
3856
- * Dwa `displayText` nie są treścią decyzji i tu nie wchodzą wcale:
3857
- *
3858
- * - PLAN (`ExitPlanMode`): treścią jest CAŁY plan, a jego nagłówek („# Plan") nie mówi nic
3859
- * ponad samo słowo „plan", które karta i tak stawia. Kanał globalny nie ma powodu wozić
3860
- * danych, których nikt nie rysuje (kontrakt `WaitingFor.text`),
3861
- * - karta ZDEGRADOWANA (`canAllow === false`, `DEGRADED_DISPLAY_TEXT`): tam stoi zdanie
3862
- * O RAROGU („nie potwierdziłem, czego dotyczy ten dialog"), a nie o decyzji. Powód
3863
- * degradacji niesie karta sesji (`herdrDialogReason`), nie wiersz listy.
3864
- */
3865
3798
  /**
3866
3799
  * Przedmiot zgody: wyjście z trybu planu albo zwykłe narzędzie. Jedyne miejsce, w którym
3867
3800
  * nazwa `ExitPlanMode` staje się faktem dla klienta — telefon buduje kartę planu z pola
@@ -3884,27 +3817,6 @@ function withOptionRoles(questions) {
3884
3817
  options: question.options.map((option) => (option.role === undefined ? { ...option, role: 'answer' } : option)),
3885
3818
  }));
3886
3819
  }
3887
- function decisionText(permission) {
3888
- if (permission.toolName === EXIT_PLAN_MODE_TOOL)
3889
- return '';
3890
- if (permission.canAllow === false)
3891
- return '';
3892
- const display = permission.displayText;
3893
- const first = display.split('\n', 1)[0]?.trim() ?? '';
3894
- if (first !== '{' && first !== '{}' && first !== '[')
3895
- return display;
3896
- let parsed;
3897
- try {
3898
- parsed = JSON.parse(display);
3899
- }
3900
- catch {
3901
- // Opis przycięty do 20 kB ma na końcu stopkę, więc nie jest już poprawnym JSON-em.
3902
- return '';
3903
- }
3904
- const summary = summarizeToolInput(permission.toolName, parsed);
3905
- // Bez trafionego klucza `summarizeToolInput` oddaje NAZWĘ narzędzia — a ta stoi już obok.
3906
- return summary === permission.toolName ? '' : summary;
3907
- }
3908
3820
  /**
3909
3821
  * Czy model wolno podać we fladze `--model`?
3910
3822
  *
@@ -4,6 +4,10 @@
4
4
  * Kontrakt ze speca: pojemność 500, `push(t) → seq` monotoniczny od 1, `since(seq) → T[]`,
5
5
  * `tooOld(seq) → boolean`.
6
6
  *
7
+ * A new card under an existing id (restart, "Resume") continues the old card's numbering with `startSeq`: the first
8
+ * push gets `startSeq + 1`, and a cursor at or below `startSeq` is too old, because the events it counts belong to the
9
+ * old card and none of them are in this ring.
10
+ *
7
11
  * Semantyka kursora (taka sama jak w SSE): kursor to `seq` OSTATNIEGO odebranego eventu,
8
12
  * więc `since(seq)` zwraca elementy o `seq > kursor`. Kursor `0` = „nic jeszcze nie widziałem".
9
13
  * `seq` żyje w ramach jednego `serverStartId` — po restarcie backendu kursor jest z definicji
@@ -69,8 +73,10 @@ export class RingBuffer {
69
73
  #size = 0;
70
74
  /** Suma wag elementów aktualnie przechowywanych. */
71
75
  #bytes = 0;
72
- /** Ostatnio przydzielony `seq`; 0 = nic jeszcze nie wrzucono. */
73
- #lastSeq = 0;
76
+ /** Ostatnio przydzielony `seq`; `#floor` = nic jeszcze nie wrzucono. */
77
+ #lastSeq;
78
+ /** The last seq of the ring this one continues; a cursor at or below it is too old (0 = a fresh ring). */
79
+ #floor;
74
80
  constructor(capacity = DEFAULT_RING_CAPACITY, opts = {}) {
75
81
  if (!Number.isInteger(capacity) || capacity < 1) {
76
82
  throw new RangeError(`RingBuffer: pojemność musi być dodatnią liczbą całkowitą, jest ${capacity}`);
@@ -80,6 +86,12 @@ export class RingBuffer {
80
86
  this.#weights = new Array(capacity).fill(0);
81
87
  this.#maxBytes = opts.maxBytes ?? null;
82
88
  this.#weigh = opts.weigh ?? jsonBytes;
89
+ const startSeq = opts.startSeq ?? 0;
90
+ if (!Number.isInteger(startSeq) || startSeq < 0) {
91
+ throw new RangeError(`RingBuffer: startSeq must be a non-negative integer, is ${String(startSeq)}`);
92
+ }
93
+ this.#floor = startSeq;
94
+ this.#lastSeq = startSeq;
83
95
  }
84
96
  get capacity() {
85
97
  return this.#capacity;
@@ -145,13 +157,16 @@ export class RingBuffer {
145
157
  *
146
158
  * `true`, gdy:
147
159
  * - część eventów po kursorze została już wyparta z bufora (kursor za stary), albo
148
- * - kursor wskazuje na `seq` z przyszłości / z innego `serverStartId` (kursor niespójny).
160
+ * - kursor wskazuje na `seq` z przyszłości / z innego `serverStartId` (kursor niespójny), albo
161
+ * - the cursor counts events of the ring this one continues (`startSeq`).
149
162
  */
150
163
  tooOld(seq) {
151
164
  if (!Number.isFinite(seq))
152
165
  return true;
153
166
  if (seq > this.#lastSeq)
154
167
  return true;
168
+ if (this.#floor > 0 && seq <= this.#floor)
169
+ return true;
155
170
  return seq < this.oldestServableCursor;
156
171
  }
157
172
  /**
@@ -91,20 +91,23 @@ export function markSeen(session, deps, pickUp) {
91
91
  * so a receipt taken there would cover the turn's real result;
92
92
  * - no decision card waits on it: a permission card or a question that comes after the turn end moves no state, so it
93
93
  * can stand over the result in `waiting-input`;
94
- * - the `stateSince` is the session's current one. Equality, not order: a history import can move `stateSince` back,
95
- * and the agent read another result then;
96
94
  * - the session is in the engine conversation the agent read ({@link inReadConversation}): `/clear` and `/resume`
97
95
  * change it with no change of state or `stateSince`. A session without a conversation yet has no result the agent
98
- * could have read.
96
+ * could have read;
97
+ * - the session's memory holds no message newer than the read and its `stateSince` is the one of the read
98
+ * (`Session.readMark` equals the pick-up's). A short turn whose `working` herdr's grace drops ends with no change of
99
+ * state or `stateSince`, and only its messages tell its result from the one the agent read. A turn whose `working`
100
+ * reaches the session can end before its messages reach the memory, and only its state stamps tell it. A turn that
101
+ * adds no message (a context compaction alone) moves the stamp too, so the agent reads the session again.
99
102
  */
100
103
  function pickUpMeetsResult(session, deps, pickUp) {
101
104
  if (session.state !== 'waiting-input' || deps.decisionStands(session))
102
105
  return false;
103
- if (pickUp.stateSince !== session.stateSince)
104
- return false;
105
106
  if (session.engineSessionId === undefined || session.engineSessionId === '')
106
107
  return false;
107
- return inReadConversation(session, pickUp.conversation);
108
+ if (!inReadConversation(session, pickUp.conversation))
109
+ return false;
110
+ return pickUp.readMark === session.readMark;
108
111
  }
109
112
  /**
110
113
  * „Oznacz jako nieprzeczytane" z listy — odwrotność {@link markSeen}, tylko lokalnie.
@@ -0,0 +1,30 @@
1
+ import { sessionCwdInArea } from './companion-scope.js';
2
+ import { BadRequestError } from './errors.js';
3
+ import { HERDR_CODEX_GIT_MESSAGE, HERDR_OUT_OF_SCOPE_DIFF_MESSAGE } from './state-sentences.js';
4
+ /**
5
+ * Bramka wspólna WSZYSTKICH tras diffa — starej i obu per plik. Oddaje sesję, z której
6
+ * katalogu wolno czytać, albo `null` w demo: tam diff to stały mock, bez odczytu z dysku.
7
+ */
8
+ export function diffSession(id, port) {
9
+ const session = port.require(id);
10
+ // Bramka zasięgu: diff roboczy to TREŚĆ katalogu, a wpis Codexa obiecuje sam stan. Klient
11
+ // przycisku dla Codexa nie rysuje — to jest druga linia, dla starego klienta i dla `curl`.
12
+ if (session.engine === 'codex')
13
+ throw new BadRequestError(HERDR_CODEX_GIT_MESSAGE);
14
+ // Panel poza zasięgiem: ta sama granica co transkrypt i wycinek ekranu — treść katalogu zostaje na Macu.
15
+ if (session.outOfScope === true)
16
+ throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
17
+ /*
18
+ * Niżej, za gałęzią demo: `outOfScope` mówi o katalogu, w którym panel stoi TERAZ (nadzorca
19
+ * liczy go od nowa po `cd`), a diff czyta `session.cwd` — katalog z chwili pojawienia się
20
+ * panelu, którego reattach nie rusza. Panel, który wystartował poza korzeniami i zrobił `cd` pod korzeń, miał więc zasięg,
21
+ * a diff dalej czytał stary, prywatny katalog. Bramka pyta o TEN
22
+ * katalog, z którego pójdzie odczyt, tą samą funkcją co nadzorca (`scopeOf`).
23
+ */
24
+ // Demo nie ma korzeni ani prawdziwych katalogów: jego diff to stały mock, bez odczytu z dysku.
25
+ if (port.config.demo)
26
+ return null;
27
+ if (!sessionCwdInArea(session, port.config))
28
+ throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
29
+ return session;
30
+ }
@@ -1,3 +1,4 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
1
2
  import { MAX_TRANSCRIPT_MESSAGES } from '@rarog/shared';
2
3
  import { isServerSentence, say } from '@rarog/shared/sentences';
3
4
  import { MAX_MESSAGE_BYTES, RING_MAX_BYTES, RingBuffer, jsonBytes } from './ring-buffer.js';
@@ -493,6 +494,11 @@ export class Session {
493
494
  #messages = [];
494
495
  /** Suma wag wiadomości w `#messages` — drugi sufit transkryptu (bajty, nie sztuki). */
495
496
  #messageBytes = 0;
497
+ /**
498
+ * Random name of this memory of the session for {@link readMark}: a card made again under the same id (a pane that
499
+ * resumes the same conversation) numbers its messages from 1 again.
500
+ */
501
+ #memoryId = randomBytes(6).toString('base64url');
496
502
  /**
497
503
  * Ring `seq` of the newest event when the pane last moved to another engine conversation (`/clear`, `/resume`); `0`
498
504
  * before any move. A message in memory with a higher `seq` belongs to the conversation the session writes now
@@ -554,7 +560,7 @@ export class Session {
554
560
  this.lastGitSignature = undefined;
555
561
  this.lastGitEvent = undefined;
556
562
  // Ring ma sufit BAJTÓW obok sufitu sztuk — patrz `ring-buffer.ts`.
557
- this.ring = new RingBuffer(init.ringCapacity, { maxBytes: RING_MAX_BYTES });
563
+ this.ring = new RingBuffer(init.ringCapacity, { maxBytes: RING_MAX_BYTES, startSeq: init.ringStartSeq });
558
564
  }
559
565
  /** Kształt wysyłany do klienta (pola serwerowe zostają na serwerze). */
560
566
  summary() {
@@ -718,6 +724,19 @@ export class Session {
718
724
  const last = this.#messages.at(-1);
719
725
  return last !== undefined && (last.seq ?? 0) > this.conversationStartSeq ? last : undefined;
720
726
  }
727
+ /**
728
+ * Opaque name of what this memory of the session holds, the voice agent's read mark: the random name of this memory
729
+ * (`#memoryId`), the ring `seq` of the newest message (`0` before the first one) and a digest of {@link stateSince}.
730
+ * Every message added to the transcript ({@link appendMessage}: a prompt, an agent message, a notice, imported
731
+ * history) gives another one, and so does every new `stateSince` (a state change, a history import that moves it
732
+ * back). Frames sent while the state stands and seen marks leave it as it is. The state stamp is there because
733
+ * the messages reach the memory from the conversation file while herdr reports a turn's states on its own: a turn
734
+ * can end before its messages arrive. 37 characters at most (8 + 1 + 16 digits of a safe integer + 1 + 11).
735
+ */
736
+ get readMark() {
737
+ const stamp = createHash('sha256').update(this.stateSince).digest('base64url').slice(0, 11);
738
+ return `${this.#memoryId}.${String(this.#messages.at(-1)?.seq ?? 0)}.${stamp}`;
739
+ }
721
740
  get messageCount() {
722
741
  return this.#messages.length;
723
742
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The one line of a pending decision on the list card (`SessionSummary.waitingFor.text`): the text of a permission
3
+ * request or a question, cut to its first line and to `WAITING_TEXT_MAX` code points. Pure functions; the manager
4
+ * calls them when it builds `waitingFor`.
5
+ */
6
+ import { EXIT_PLAN_MODE_TOOL, WAITING_TEXT_MAX } from '@rarog/shared';
7
+ // Ta sama etykieta, którą dostaje wiersz tool-calla w transkrypcie — patrz `decisionText`.
8
+ import { summarizeToolInput } from '../drivers/tool-summary.js';
9
+ /**
10
+ * Treść decyzji do JEDNEJ linii karty listy: pierwsza linia, przycięta do `WAITING_TEXT_MAX`.
11
+ *
12
+ * Pierwsza linia, a nie „pierwsze 120 znaków całości": heredoc, wypisana treść `.env` i plan
13
+ * z trzema akapitami mają się tu nie zmieścić Z DEFINICJI. Cięcie po znakach jest wtedy tylko
14
+ * sufitem na długi jednolinijkowiec, a nie jedyną obroną przed wklejeniem pół pliku w sidebar.
15
+ * Wielokropek dokładamy WYŁĄCZNIE tam, gdzie faktycznie uciął — inaczej linia obiecuje ciąg
16
+ * dalszy, którego nie ma.
17
+ */
18
+ export function waitingText(raw) {
19
+ const first = raw.split('\n', 1)[0]?.trim() ?? '';
20
+ /*
21
+ * Cięcie po PUNKTACH KODOWYCH, nie po jednostkach UTF-16: `slice(0, 120)` na linii
22
+ * z emoji na 120. znaku rozcina parę surogatów, `trimEnd()` samotnego surogata nie usuwa
23
+ * (to nie biały znak) i na karcie staje „�…". Grafem z modyfikatorem (flaga, odcień skóry)
24
+ * może się tu jeszcze rozpaść na dwa znaki, ale każdy z nich jest wtedy PEŁNY — żaden
25
+ * nie jest połówką kodu, więc przeglądarka rysuje litery, a nie znak zastępczy.
26
+ */
27
+ const points = [...first];
28
+ if (points.length <= WAITING_TEXT_MAX)
29
+ return first;
30
+ return `${points.slice(0, WAITING_TEXT_MAX).join('').trimEnd()}…`;
31
+ }
32
+ /**
33
+ * Treść ZGODY do jednej linii karty listy — z `displayText`, ale nie zawsze dosłownie.
34
+ *
35
+ * `displayText` jest jednolinijkowy tylko dla narzędzi z polem `command`. Dla całej reszty
36
+ * (`Edit`, `Write`, `Read`, `Task`, `WebFetch`…) `toolInputText` oddaje pretty-printowany JSON,
37
+ * więc PIERWSZĄ linią jest sama klamra — i karta mówiła „zgoda: Edit · {". Z takiego opisu
38
+ * bierzemy dokładnie to, co bierze etykieta tool-calla w transkrypcie (`summarizeToolInput`:
39
+ * `file_path`, `path`, `pattern`, `url`, `query`), a gdy nie ma czego wziąć — nic: „zgoda: Edit"
40
+ * jest uczciwe, klamra nie. Rozpoznanie idzie po PIERWSZEJ LINII, a nie po `startsWith('{')`,
41
+ * bo komenda Basha też umie zacząć się klamrą (`{ echo a; }` — grupa powłoki).
42
+ *
43
+ * Dwa `displayText` nie są treścią decyzji i tu nie wchodzą wcale:
44
+ *
45
+ * - PLAN (`ExitPlanMode`): treścią jest CAŁY plan, a jego nagłówek („# Plan") nie mówi nic
46
+ * ponad samo słowo „plan", które karta i tak stawia. Kanał globalny nie ma powodu wozić
47
+ * danych, których nikt nie rysuje (kontrakt `WaitingFor.text`),
48
+ * - karta ZDEGRADOWANA (`canAllow === false`, `DEGRADED_DISPLAY_TEXT`): tam stoi zdanie
49
+ * O RAROGU („nie potwierdziłem, czego dotyczy ten dialog"), a nie o decyzji. Powód
50
+ * degradacji niesie karta sesji (`herdrDialogReason`), nie wiersz listy.
51
+ */
52
+ export function decisionText(permission) {
53
+ if (permission.toolName === EXIT_PLAN_MODE_TOOL)
54
+ return '';
55
+ if (permission.canAllow === false)
56
+ return '';
57
+ const display = permission.displayText;
58
+ const first = display.split('\n', 1)[0]?.trim() ?? '';
59
+ if (first !== '{' && first !== '{}' && first !== '[')
60
+ return display;
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(display);
64
+ }
65
+ catch {
66
+ // Opis przycięty do 20 kB ma na końcu stopkę, więc nie jest już poprawnym JSON-em.
67
+ return '';
68
+ }
69
+ const summary = summarizeToolInput(permission.toolName, parsed);
70
+ // Bez trafionego klucza `summarizeToolInput` oddaje NAZWĘ narzędzia — a ta stoi już obok.
71
+ return summary === permission.toolName ? '' : summary;
72
+ }