@rarog/server 1.1.2-beta.1 → 1.1.2-beta.2

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 (124) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +43 -1
  3. package/node_modules/@rarog/shared/src/notify-copy.js +1 -0
  4. package/node_modules/@rarog/shared/src/protocol/context.js +57 -0
  5. package/node_modules/@rarog/shared/src/protocol/coordination.js +42 -0
  6. package/node_modules/@rarog/shared/src/protocol/dialog-live.js +117 -0
  7. package/node_modules/@rarog/shared/src/protocol/files.js +1 -1
  8. package/node_modules/@rarog/shared/src/protocol/inbox.js +6 -0
  9. package/node_modules/@rarog/shared/src/protocol/presence.js +47 -0
  10. package/node_modules/@rarog/shared/src/protocol.js +14 -146
  11. package/node_modules/@rarog/shared/src/rest.js +16 -1
  12. package/node_modules/@rarog/shared/src/sentences/push.js +6 -0
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +9 -0
  14. package/node_modules/@rarog/shared/src/sentences/restart.js +1 -0
  15. package/node_modules/@rarog/shared/src/sentences/session.js +24 -0
  16. package/package.json +2 -2
  17. package/plugin/rarog/.claude-plugin/plugin.json +4 -0
  18. package/plugin/rarog/bin/rarog-coordinator +7 -0
  19. package/plugin/rarog/hooks/hooks.json +18 -0
  20. package/plugin/rarog/hooks/recipient.mjs +95 -0
  21. package/plugin/rarog/lib/coordinator.mjs +1340 -0
  22. package/plugin/rarog/lib/threads.mjs +350 -0
  23. package/plugin/rarog/skills/coordinator/SKILL.md +111 -0
  24. package/plugin/rarog/skills/coordinator/check-and-merge.md +46 -0
  25. package/plugin/rarog/skills/coordinator/close-thread.md +15 -0
  26. package/plugin/rarog/skills/coordinator/role.md +61 -0
  27. package/plugin/rarog/skills/coordinator/send-back.md +39 -0
  28. package/plugin/rarog/skills/coordinator/start-thread.md +43 -0
  29. package/server/src/bootstrap/coordination.js +49 -0
  30. package/server/src/bootstrap/coordinator-start.js +27 -0
  31. package/server/src/bootstrap/inbox.js +4 -0
  32. package/server/src/bootstrap/push.js +24 -1
  33. package/server/src/companion/catalog.js +1 -1
  34. package/server/src/companion/index.js +2 -4
  35. package/server/src/config/flags.js +4 -0
  36. package/server/src/config-env.js +15 -0
  37. package/server/src/config.js +17 -3
  38. package/server/src/coordination/merge-events.js +86 -0
  39. package/server/src/coordination/merge-prompt.js +244 -0
  40. package/server/src/coordination/registry.js +289 -0
  41. package/server/src/coordination/state.js +94 -0
  42. package/server/src/coordination/summary.js +422 -0
  43. package/server/src/coordination/thread-file.js +245 -0
  44. package/server/src/coordination/thread-git.js +110 -0
  45. package/server/src/coordination/watch.js +237 -0
  46. package/server/src/demo/content/coordinator.js +89 -0
  47. package/server/src/demo/content/en.js +57 -1
  48. package/server/src/demo/content/pl.js +57 -1
  49. package/server/src/demo/inbox.js +12 -0
  50. package/server/src/demo/mock-herdr.js +3 -2
  51. package/server/src/demo/review-routes.js +2 -2
  52. package/server/src/demo/seeds.js +20 -2
  53. package/server/src/drivers/herdr/live-dialog.js +412 -0
  54. package/server/src/drivers/herdr/live-step.js +261 -0
  55. package/server/src/drivers/herdr/pause-gate.js +60 -0
  56. package/server/src/drivers/herdr/returned-prompt.js +4 -1
  57. package/server/src/drivers/herdr/screen-fallback.js +50 -0
  58. package/server/src/drivers/herdr/start-dialog-gate.js +4 -0
  59. package/server/src/drivers/herdr-driver.js +88 -66
  60. package/server/src/files/refusals.js +9 -2
  61. package/server/src/files/session-gate.js +5 -4
  62. package/server/src/git-branch-diff.js +194 -0
  63. package/server/src/herdr/argv.js +34 -3
  64. package/server/src/herdr/audit.js +32 -1
  65. package/server/src/herdr/background/cli-shapes.js +19 -0
  66. package/server/src/herdr/background/queued-prompt.js +46 -0
  67. package/server/src/herdr/background/work.js +12 -0
  68. package/server/src/herdr/client.js +22 -46
  69. package/server/src/herdr/commands/catalog.js +11 -7
  70. package/server/src/herdr/commands/discover.js +33 -1
  71. package/server/src/herdr/commands/index.js +3 -2
  72. package/server/src/herdr/dialogs/index.js +9 -0
  73. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +4 -56
  74. package/server/src/herdr/dialogs/live/model.js +220 -0
  75. package/server/src/herdr/dialogs/live/policy.js +108 -0
  76. package/server/src/herdr/dialogs/live/view.js +261 -0
  77. package/server/src/herdr/dialogs/screen/form.js +4 -3
  78. package/server/src/herdr/dialogs/screen/signatures.js +23 -0
  79. package/server/src/herdr/engines.js +96 -0
  80. package/server/src/herdr/history-steps.js +9 -4
  81. package/server/src/herdr/identity.js +20 -5
  82. package/server/src/herdr/jsonl-follow.js +20 -1
  83. package/server/src/herdr/plugin-copy.js +281 -0
  84. package/server/src/herdr/session-index.js +19 -0
  85. package/server/src/herdr/supervisor.js +16 -13
  86. package/server/src/herdr/types.js +1 -0
  87. package/server/src/inbox/card.js +31 -8
  88. package/server/src/inbox/heads.js +1 -0
  89. package/server/src/inbox/inbox.js +21 -4
  90. package/server/src/inbox/removals.js +10 -1
  91. package/server/src/index.js +37 -5
  92. package/server/src/notify/content.js +27 -0
  93. package/server/src/notify/index.js +7 -3
  94. package/server/src/notify/live-activity-state.js +14 -5
  95. package/server/src/notify/policy.js +49 -11
  96. package/server/src/notify/ready-to-merge.js +148 -0
  97. package/server/src/project-root.js +233 -0
  98. package/server/src/routes/sessions.js +68 -2
  99. package/server/src/sessions/branch-diff.js +57 -0
  100. package/server/src/sessions/cli-registry.js +17 -3
  101. package/server/src/sessions/companion-scope.js +2 -1
  102. package/server/src/sessions/consent-cards.js +49 -2
  103. package/server/src/sessions/conversation-lists.js +4 -1
  104. package/server/src/sessions/coordinator-start.js +172 -0
  105. package/server/src/sessions/demo-modules.js +1 -0
  106. package/server/src/sessions/demo-seeds.js +100 -0
  107. package/server/src/sessions/driver-events.js +61 -11
  108. package/server/src/sessions/herdr-lifecycle.js +11 -4
  109. package/server/src/sessions/launch-gate.js +36 -11
  110. package/server/src/sessions/live-dialog.js +69 -0
  111. package/server/src/sessions/manager.js +124 -282
  112. package/server/src/sessions/owner-turn.js +36 -0
  113. package/server/src/sessions/seen-marks.js +31 -12
  114. package/server/src/sessions/session-dialog.js +82 -0
  115. package/server/src/sessions/session-git.js +1 -0
  116. package/server/src/sessions/session-scope.js +6 -5
  117. package/server/src/sessions/session-take-back.js +5 -0
  118. package/server/src/sessions/session.js +72 -7
  119. package/server/src/sessions/state-machine.js +2 -0
  120. package/server/src/sessions/state-sentences.js +87 -30
  121. package/server/src/sessions/waiting-line.js +49 -0
  122. package/server/src/transcript-import.js +20 -2
  123. package/server/src/version.js +4 -0
  124. /package/server/src/{companion/asks-owner.js → asks-owner.js} +0 -0
@@ -0,0 +1,36 @@
1
+ import { textAsksOwner } from '../asks-owner.js';
2
+ /**
3
+ * Whether a message the session is about to append asks the owner: an agent message with a text block that asks
4
+ * (`asks-owner.ts`). Read before the size cap, because the history merges the agent entries of a long turn into one
5
+ * message whose cut tail would otherwise lose the question.
6
+ */
7
+ export function blocksAskOwner(role, blocks) {
8
+ return role === 'assistant' && blocks.some((block) => block.type === 'text' && textAsksOwner(block.text.text));
9
+ }
10
+ /**
11
+ * The owner's message: a prompt (`user` without a harness notice and without the "not from the owner" mark) or the
12
+ * note of a prompt blocked by a hook, which after a restart is all that stands for the blocked prompt.
13
+ */
14
+ export function isOwnerMessage(message, notFromOwner) {
15
+ if (message.role === 'user')
16
+ return message.notice === undefined && !notFromOwner;
17
+ return message.role === 'system' && message.promptBlocked !== undefined;
18
+ }
19
+ /** Whether the session waits for the owner after a question; a prompt held as a deferred echo has answered it. */
20
+ export function ownerTurn(session) {
21
+ if (session.heldEchoes.length > 0)
22
+ return false;
23
+ for (const message of session.messagesNewestFirst()) {
24
+ if (message.seq <= session.conversationStartSeq)
25
+ return false;
26
+ if (isOwnerMessage(message, session.notFromOwner(message)))
27
+ return false;
28
+ if (session.asksOwner(message))
29
+ return true;
30
+ }
31
+ return false;
32
+ }
33
+ /** The mark for the app's echo of a sent text: a local command (`/rename`, `/model`) is no message of the owner. */
34
+ export function localCommandMark(slash) {
35
+ return slash?.kind === 'local' ? { notFromOwner: true } : {};
36
+ }
@@ -1,4 +1,5 @@
1
1
  import { say } from '@rarog/shared/sentences';
2
+ import { isStateOnlyEngine } from '../herdr/engines.js';
2
3
  import { noResultTurn } from '../notify/policy.js';
3
4
  import { inReadConversation } from './companion-scope.js';
4
5
  import { BadStateError } from './errors.js';
@@ -230,7 +231,8 @@ export function clearReceipt(session) {
230
231
  /**
231
232
  * A turn without a result keeps the received result of the previous turn. Such a turn (`noResultTurn`:
232
233
  * started by a subagent standby notice alone, or by an artifact notification or a context compaction alone with no
233
- * tool call) leaves nothing new to read, so its end must not light the card as a new result once the previous one
234
+ * tool call, or a pane working with no input while a subagent woken from standby works in it) leaves nothing new to
235
+ * read, so its end must not light the card as a new result once the previous one
234
236
  * was received.
235
237
  *
236
238
  * `#applyTransition` calls this after the turn start has cleared the seen fields and before it sends the session
@@ -303,10 +305,11 @@ export function noteHumanReceipt(session) {
303
305
  * indeksu pisarzy jsonl nie dotyczy. Bez uuidu albo bez numeru stanu znacznik byłby
304
306
  * zgadywaniem (po restarcie serwera herdr numery startują od nowa), więc wtedy nie
305
307
  * zapisujemy nic: karta i tak schodzi z sekcji uwagi, tyle że tylko w tym procesie.
308
+ * A state-only card without a session ID is the exception: its address is the pane ({@link markSessionOf}).
306
309
  */
307
310
  export function rememberSeenMark(session, store) {
308
311
  const key = session.herdrKey;
309
- const engineSessionId = session.engineSessionId ?? session.observedSessionId;
312
+ const engineSessionId = markSessionOf(session);
310
313
  const seq = session.herdrSeq;
311
314
  if (key === undefined || engineSessionId === undefined || seq === undefined)
312
315
  return;
@@ -315,7 +318,7 @@ export function rememberSeenMark(session, store) {
315
318
  /** Ręczne „nieprzeczytane" pod tym samym adresem i numerem co {@link rememberSeenMark}. */
316
319
  export function rememberUnseenMark(session, store) {
317
320
  const key = session.herdrKey;
318
- const engineSessionId = session.engineSessionId ?? session.observedSessionId;
321
+ const engineSessionId = markSessionOf(session);
319
322
  const seq = session.herdrSeq;
320
323
  if (key === undefined || engineSessionId === undefined || seq === undefined)
321
324
  return;
@@ -369,7 +372,7 @@ export function clearHerdrDone(session, key, deps) {
369
372
  */
370
373
  export function seenSeqWentBack(session, store) {
371
374
  const key = session.herdrKey;
372
- const engineSessionId = session.engineSessionId ?? session.observedSessionId;
375
+ const engineSessionId = markSessionOf(session);
373
376
  const current = session.herdrSeq;
374
377
  if (store === undefined || key === undefined || engineSessionId === undefined)
375
378
  return false;
@@ -391,7 +394,7 @@ export function seenMarkCovers(session, store) {
391
394
  const key = session.herdrKey;
392
395
  // Ta sama para adresów co w `markSeen()` — inaczej znacznik Codexa dałoby się zapisać,
393
396
  // ale nigdy odczytać.
394
- const engineSessionId = session.engineSessionId ?? session.observedSessionId;
397
+ const engineSessionId = markSessionOf(session);
395
398
  const current = session.herdrSeq;
396
399
  if (store === undefined || key === undefined || engineSessionId === undefined)
397
400
  return false;
@@ -404,14 +407,15 @@ export function seenMarkCovers(session, store) {
404
407
  /**
405
408
  * To samo pytanie dla panelu, który dopiero staje się kartą (`appeared`).
406
409
  *
407
- * Bez rozgałęzienia na silnik i to jest poprawne: `agentSessionId` wpisu z herdr niesie uuid
408
- * TEGO silnika, który w panelu siedzi (dla Codexa — rollout), a znacznik jest zapisany
409
- * dokładnie pod tym uuidem. Rozejście się pól zaczyna się dopiero w `Session`.
410
+ * `agentSessionId` wpisu z herdr niesie uuid TEGO silnika, który w panelu siedzi (dla Codexa — rollout,
411
+ * `''` when herdr reports none), a znacznik jest zapisany dokładnie pod tym adresem ({@link markSessionOfAgent}).
412
+ * Rozejście się pól zaczyna się dopiero w `Session`.
410
413
  */
411
414
  export function wasSeen(agent, store) {
412
415
  if (store === undefined)
413
416
  return false;
414
- return store.seq(agent.key, agent.agentSessionId) === agent.stateChangeSeq;
417
+ const address = markSessionOfAgent(agent);
418
+ return address !== undefined && store.seq(agent.key, address) === agent.stateChangeSeq;
415
419
  }
416
420
  /**
417
421
  * Who received the result of a pane that becomes a card, when it was not a human: the `by` of the durable receipt
@@ -419,15 +423,30 @@ export function wasSeen(agent, store) {
419
423
  * may be another result, which nobody picked up.
420
424
  */
421
425
  export function seenByOf(agent, store) {
422
- if (store === undefined || store.seq(agent.key, agent.agentSessionId) !== agent.stateChangeSeq)
426
+ const address = markSessionOfAgent(agent);
427
+ if (store === undefined || address === undefined || store.seq(agent.key, address) !== agent.stateChangeSeq) {
423
428
  return undefined;
424
- return store.seenBy(agent.key, agent.agentSessionId);
429
+ }
430
+ return store.seenBy(agent.key, address);
425
431
  }
426
432
  /** Ręczne „nieprzeczytane" przy tym samym numerze stanu — ten sam adres co {@link wasSeen}. */
427
433
  export function wasMarkedUnseen(agent, store) {
428
434
  if (store === undefined)
429
435
  return false;
430
- return store.unseenSeq(agent.key, agent.agentSessionId) === agent.stateChangeSeq;
436
+ const address = markSessionOfAgent(agent);
437
+ return address !== undefined && store.unseenSeq(agent.key, address) === agent.stateChangeSeq;
438
+ }
439
+ /**
440
+ * The engine session part of a durable mark's address; the other part is the card's herdr key. A state-only card
441
+ * without a session ID (herdr reports none for Codex) is addressed by its pane alone, as `''`: its mark still
442
+ * survives a resync and a Rarog restart. Claude without a session has no address, so no mark.
443
+ */
444
+ function markSessionOf(session) {
445
+ return session.engineSessionId ?? session.observedSessionId ?? (isStateOnlyEngine(session.engine) ? '' : undefined);
446
+ }
447
+ /** The same address for a pane that becomes a card: its entry carries the session ID, `''` when herdr reports none. */
448
+ function markSessionOfAgent(agent) {
449
+ return agent.agentSessionId !== '' || isStateOnlyEngine(agent.engine) ? agent.agentSessionId : undefined;
431
450
  }
432
451
  function describeError(error) {
433
452
  return error instanceof Error ? error.message : String(error);
@@ -0,0 +1,82 @@
1
+ import { STALE } from '../drivers/types.js';
2
+ import { BadRequestError, BadStateError } from './errors.js';
3
+ import { HERDR_ALLOW_MESSAGE, HERDR_OUT_OF_SCOPE_MESSAGE } from './state-sentences.js';
4
+ /**
5
+ * Dialog, którego Rarog nie zna z jsonl — decyzja adresowana SAMĄ SESJĄ.
6
+ *
7
+ * Taka karta nie ma wpisu w `PendingInteractions` (stan `waiting-permission` bez pending),
8
+ * bo nie ma z czego jej złożyć: `permId` pochodzi z `tool_use.id` w transkrypcie, a tego
9
+ * dialogu w transkrypcie nie ma. Zwykła ścieżka first-wins oddałaby tu `gone`.
10
+ *
11
+ * `deny` (`escape`) wolno ZAWSZE — anuluje, nigdy nie zatwierdza (wyjątki w driverze: pauza „Session
12
+ * paused” i karta warstwy 2 — odmowa `refused` jak każda inna). `allow` wolno WYŁĄCZNIE
13
+ * dla dialogu rozpoznanego z zamkniętej listy sygnatur: dopiero wtedy Rarog
14
+ * wie, co zatwierdza, a cyfrę składa driver z TEKSTU opcji twierdzącej. Dla wszystkiego
15
+ * innego zostaje 409 z radą „zatwierdź w terminalu" — i to jest granica, za którą Rarog
16
+ * przestałby być narzędziem, a stałby się klikaczem w cudze menu.
17
+ */
18
+ export async function decideHerdrDialog(session, decision, port) {
19
+ /*
20
+ * Dialog z zamkniętej listy sygnatur (trust/model) nie niesie `alwaysLabel`, więc UI nie
21
+ * ma skąd wysłać `allow-always` — a gdyby wysłał (stary bundle, ręczny POST), odmowa jest
22
+ * jedyną uczciwą odpowiedzią: nie ma opcji, którą to zatwierdza.
23
+ */
24
+ if (decision === 'allow-always')
25
+ throw new BadStateError(HERDR_ALLOW_MESSAGE);
26
+ if (decision === 'allow' && session.herdrDialog === undefined) {
27
+ throw new BadStateError(HERDR_ALLOW_MESSAGE);
28
+ }
29
+ // Panel spoza zasięgu odmawia TUTAJ, a nie dopiero w driverze: `HerdrOutOfScopeError`
30
+ // nie ma odpowiednika w `managerErrorStatus`, więc wracałby do telefonu jako 500
31
+ // („Błąd serwera.") zamiast zdania, które mówi, co się stało.
32
+ if (session.outOfScope === true)
33
+ throw new BadRequestError(HERDR_OUT_OF_SCOPE_MESSAGE);
34
+ port.assertHerdrWritable();
35
+ /*
36
+ * Rozpoznanie gaśnie PRZED wysłaniem cyfry, a nie po przemalowaniu ekranu — i musi zgasnąć
37
+ * przed `await`, bo ta karta nie ma wpisu w `#pending`, więc nie chroni jej blokada
38
+ * równoległych prób stamtąd. Drugie tapnięcie w „Zatwierdź" (dwa urządzenia, powtórzony
39
+ * tap) w oknie, w którym driver czyta ekran, wysłałoby DRUGĄ cyfrę do panelu, który
40
+ * zdążył już ruszyć dalej — czyli w środek następnego dialogu.
41
+ *
42
+ * Po `refused` rozpoznanie wraca WYŁĄCZNIE dla `send-failed` — warunki przy samym
43
+ * przywróceniu niżej.
44
+ */
45
+ const dialog = session.herdrDialog;
46
+ if (decision === 'allow') {
47
+ session.herdrDialog = undefined;
48
+ port.emitSessionChanged(session);
49
+ }
50
+ // `reqId` jest dla drivera herdr nieznaczący (nie ma prośby o zgodę, jest dialog na
51
+ // ekranie), ale kontrakt `SessionDriver` go wymaga — przekazujemy id sesji. Driver
52
+ // rozpoznaje po tym kartę ekranową i szuka cyfry u siebie, nie po `reqId`.
53
+ const outcome = await (session.driver?.respondPermission(session.id, decision)
54
+ ?? Promise.resolve(STALE));
55
+ if (outcome.kind === 'refused') {
56
+ /*
57
+ * Rozpoznanie WRACA tylko po `send-failed`: to jedyna odmowa, przy której z Raroga nie
58
+ * wyszedł ani jeden bajt, driver karty nie wycofał (`refuseSend` świadomie nie woła ani
59
+ * `#clearActive`, ani `#scheduleEvaluate`) i dialog na pewno stoi dalej na ekranie.
60
+ *
61
+ * Pozostałe powody (`screen-changed`, `no-digit`, `multi-select`, `terminal-only`,
62
+ * `form-submit`) idą przez `#clearActive`, czyli przez zdarzenie `permission-cleared`,
63
+ * po którym handler managera zeruje `herdrDialog` — i to zerowanie jest PRAWDĄ NOWSZĄ niż
64
+ * migawka sprzed `await`. Bezwarunkowe przywracanie cofało je i zostawiało „Zatwierdź"
65
+ * dla dialogu, którego driver się przed chwilą wyparł. Odbudowę karty robi
66
+ * `#scheduleEvaluate()` w driverze — jedna ścieżka, nie druga mechanika tutaj;
67
+ * kosztem jest przycisk znikający na jeden debounce oceny.
68
+ *
69
+ * Warunek `herdrDialog === undefined` domyka drugą stronę: gdyby w oknie `await`
70
+ * wszedł ŚWIEŻY `screen-dialog`, migawka sprzed decyzji nadpisałaby nowe rozpoznanie.
71
+ */
72
+ if (decision === 'allow' && outcome.reason === 'send-failed'
73
+ && session.herdrDialog === undefined) {
74
+ session.herdrDialog = dialog;
75
+ port.emitSessionChanged(session);
76
+ }
77
+ return { outcome: 'refused', reason: outcome.reason };
78
+ }
79
+ if (outcome.kind === 'stale')
80
+ return { outcome: 'gone' };
81
+ return { outcome: 'ok' };
82
+ }
@@ -246,6 +246,7 @@ export class SessionGit {
246
246
  * resztę rodzeństwa. Sesja mogła zniknąć w oknie debounce'u — wtedy nie ma o co pytać.
247
247
  */
248
248
  #gitChanged(cwds) {
249
+ this.#port.gitChanged?.(cwds);
249
250
  for (const cwd of cwds) {
250
251
  for (const session of this.#port.sessions.values()) {
251
252
  if (session.cwd !== cwd)
@@ -1,16 +1,17 @@
1
1
  import { sessionCwdInArea } from './companion-scope.js';
2
2
  import { BadRequestError } from './errors.js';
3
- import { HERDR_CODEX_GIT_MESSAGE, HERDR_OUT_OF_SCOPE_DIFF_MESSAGE } from './state-sentences.js';
3
+ import { HERDR_OUT_OF_SCOPE_DIFF_MESSAGE } from './state-sentences.js';
4
+ import { STATE_ONLY_REFUSALS, isStateOnlyEngine } from '../herdr/engines.js';
4
5
  /**
5
6
  * Bramka wspólna WSZYSTKICH tras diffa — starej i obu per plik. Oddaje sesję, z której
6
7
  * katalogu wolno czytać, albo `null` w demo: tam diff to stały mock, bez odczytu z dysku.
7
8
  */
8
9
  export function diffSession(id, port) {
9
10
  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);
11
+ // Scope gate: the working diff is the CONTENT of the directory, and a state-only entry promises state alone.
12
+ // The client draws no button for it; this is the second line, for an old client and for `curl`.
13
+ if (isStateOnlyEngine(session.engine))
14
+ throw new BadRequestError(STATE_ONLY_REFUSALS[session.engine].git);
14
15
  // Panel poza zasięgiem: ta sama granica co transkrypt i wycinek ekranu — treść katalogu zostaje na Macu.
15
16
  if (session.outOfScope === true)
16
17
  throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
@@ -2,6 +2,7 @@ import { say } from '@rarog/shared/sentences';
2
2
  import { echoKey } from '../herdr/jsonl-follow.js';
3
3
  import { BadRequestError, BadStateError, GoneError } from './errors.js';
4
4
  import { pauseHeldFlush, takeHeld } from './held-echo.js';
5
+ import { ownerTurn } from './owner-turn.js';
5
6
  import { SEND_REGISTRY_WINDOW_MS } from './send-registry.js';
6
7
  import { HERDR_OUT_OF_SCOPE_MESSAGE, RESTART_IN_PROGRESS_MESSAGE } from './state-sentences.js';
7
8
  /** How long a result answers a retry: the window of the send registry, so a retry after a long outage still matches. */
@@ -67,7 +68,11 @@ export class SessionTakeBack {
67
68
  #answer(session, result, entry, results, timing) {
68
69
  if ('refused' in result)
69
70
  throw takeBackRefusal(result.refused);
71
+ const turnBefore = ownerTurn(session);
70
72
  const items = [...result.cli, ...result.rarog].map((taken) => itemOf(session, taken));
73
+ // A held prompt counted as the owner's answer: without it the question waits again, and the list has to know.
74
+ if (ownerTurn(session) !== turnBefore)
75
+ this.#port.emitSessionChanged(session);
71
76
  entry.doneAt = this.#port.now();
72
77
  // Take-backs that ran together finish over the cap: the oldest finished results go now, not at the next start.
73
78
  this.#trim(results);
@@ -2,6 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { MAX_TRANSCRIPT_MESSAGES } from '@rarog/shared';
3
3
  import { isServerSentence, say } from '@rarog/shared/sentences';
4
4
  import { MAX_MESSAGE_BYTES, RING_MAX_BYTES, RingBuffer, jsonBytes } from './ring-buffer.js';
5
+ import { blocksAskOwner, ownerTurn } from './owner-turn.js';
5
6
  /**
6
7
  * Ile wiadomości trzymamy w RAM na sesję. Stała mieszka w shared (ten sam sufit
7
8
  * tnie tablicę `messages` w store klienta); tu zostaje re-eksport dla dotychczasowych importów.
@@ -236,6 +237,12 @@ export class Session {
236
237
  * kasowana razem z kartą.
237
238
  */
238
239
  cliDialog;
240
+ /**
241
+ * The live dialog card (`docs/dialogs.md`, "Live dialog card"): the dialog region of the pane and the keys the server
242
+ * takes now. The driver owns its lifetime and sends it with the `dialog-live` event (`sessions/live-dialog.ts`); a card
243
+ * swap leaves it, leaving the blocked state clears it.
244
+ */
245
+ herdrDialogLive;
239
246
  /** Panel spoza `RAROG_HERDR_ROOTS`: karta bez transkryptu i bez wysyłki. */
240
247
  outOfScope;
241
248
  /** Adres panelu w herdr; zmienia się przy `pane move`, więc NIGDY nie jest kluczem. */
@@ -363,7 +370,7 @@ export class Session {
363
370
  */
364
371
  observedSessionId;
365
372
  /**
366
- * Silnik panelu — `'codex'` albo `undefined` (Claude).
373
+ * Engine of a state-only pane (the herdr engine registry) or `undefined` (Claude).
367
374
  *
368
375
  * Niezmienny przez całe życie karty: zmiana silnika w tym samym panelu to `gone` +
369
376
  * `appeared` w nadzorcy, czyli NOWA karta. Gdyby to pole dało się przestawić w miejscu,
@@ -385,11 +392,20 @@ export class Session {
385
392
  * bieżącego procesu CLI. `undefined` = nie wiemy (ustawienia Claude Code mogą je włączyć bez wiedzy Raroga).
386
393
  */
387
394
  ultracode;
395
+ /** {@link SessionInit.projectRoot} and {@link SessionInit.coordination} of a demo seed. */
396
+ projectRoot;
397
+ coordination;
388
398
  /**
389
399
  * Wersja CLI zainstalowana w chwili startu panelu przez Raroga: zapas dla bramki wersji, gdy rejestr
390
400
  * procesów CLI nie ma jeszcze wpisu świeżego panelu. Pole SERWEROWE: nie ma go w `summary()` ani w rejestrze.
391
401
  */
392
402
  cliVersionAtLaunch;
403
+ /**
404
+ * `--plugin-dir` of the session's process: the coordinator plugin copy (`sessions/coordinator-start.ts`), `null` for
405
+ * a process this server started without it, `undefined` for a pane it found (its arguments are not known). A server
406
+ * field: not in `summary()` nor in the registry, so a server restart forgets it.
407
+ */
408
+ pluginDir;
393
409
  /** Żywy driver albo `null` (sesja zamknięta, wznawialna, albo odtworzona z rejestru). */
394
410
  driver = null;
395
411
  /**
@@ -397,16 +413,26 @@ export class Session {
397
413
  * notek o końcu obserwacji artefaktu, ile czegokolwiek innego roli `user` i ile wywołań narzędzi
398
414
  * głównego agenta. Pole SERWEROWE, nie ma go w `summary()` ani w rejestrze.
399
415
  *
400
- * `undefined` = rachunek NIEPEŁNY i nie wolno z niego wnioskować: po podpięciu drivera i po
401
- * każdej porcji historii (wiadomości trwającej tury stoją w historii, której nie liczymy), po
402
- * utracie ciągłości pliku rozmowy (nowa rozmowa w panelu, skrócenie, przeskok przyrostu) i po
403
- * końcu tury z pustym rachunkiem (wiadomość tej tury mogła jeszcze nie dojść z pliku i doliczy
404
- * się do następnej). Pełny robi się przy następnym końcu PRAWDZIWEJ tury, który manager zobaczy.
416
+ * `undefined` means an INCOMPLETE tally that nothing may be inferred from: after a driver attaches and after
417
+ * every history portion (the messages of a running turn stand in the history, which is not counted), after a lost
418
+ * continuity of the conversation file (a new conversation in the pane, a truncation, a skipped growth) and after
419
+ * a turn end with an empty tally (that turn's message may not have arrived from the file yet and would count
420
+ * towards the next one), unless a subagent woke from standby in that window (`subagentWakes`): the turn was its
421
+ * work alone, and the tally after it starts from zero. It becomes complete at the next end of a REAL turn the
422
+ * manager sees, or earlier, from zero, when the attach history of a pane just adopted shows it out of a turn
423
+ * ({@link turnTallyAttach}).
405
424
  *
406
425
  * Liczy manager (`#noteTurnInput`, `#noteToolCalls`), zamyka koniec tury (`#applyTransition`),
407
426
  * czyta harmonogram powiadomień: tura bez wyniku (`noResultTurn`) nie daje „gotowe".
408
427
  */
409
428
  turnInput = undefined;
429
+ /**
430
+ * The attach of the driver of a pane just adopted, while its history may still start the turn tally from zero
431
+ * (`tallyAfterHistory` in `state-sentences.ts`): the attach time and whether history was read while the card was
432
+ * still standing up. `undefined` once a turn starts or ends, the file continuity is lost, or a zero turn settles.
433
+ * Server field, RAM.
434
+ */
435
+ turnTallyAttach = undefined;
410
436
  /**
411
437
  * Koniec tury po samym meldunku o artefakcie, w której manager nie zobaczył wywołania narzędzia:
412
438
  * zdarzenie końca, rachunek z tej chwili i czas. Also a turn after a compaction alone.
@@ -501,6 +527,10 @@ export class Session {
501
527
  #messages = [];
502
528
  /** Suma wag wiadomości w `#messages` — drugi sufit transkryptu (bajty, nie sztuki). */
503
529
  #messageBytes = 0;
530
+ /** Ring `seq` of the messages in memory with the "not from the owner" mark ({@link MessageExtra.notFromOwner}). */
531
+ #notFromOwner = new Set();
532
+ /** Ring `seq` of the messages in memory that asked the owner when appended, before the size cap (`owner-turn.ts`). */
533
+ #asksOwner = new Set();
504
534
  /**
505
535
  * Random name of this memory of the session for {@link readMark}: a card made again under the same id (a pane that
506
536
  * resumes the same conversation) numbers its messages from 1 again.
@@ -547,7 +577,10 @@ export class Session {
547
577
  this.model = init.model;
548
578
  this.effort = init.effort;
549
579
  this.ultracode = init.ultracode;
580
+ this.projectRoot = init.projectRoot;
581
+ this.coordination = init.coordination;
550
582
  this.cliVersionAtLaunch = init.cliVersionAtLaunch;
583
+ this.pluginDir = init.pluginDir;
551
584
  this.seen = init.seen;
552
585
  this.stale = undefined;
553
586
  this.herdrMode = init.herdrMode;
@@ -557,6 +590,7 @@ export class Session {
557
590
  this.herdrDialogReason = undefined;
558
591
  this.herdrDialogScreen = undefined;
559
592
  this.cliDialog = undefined;
593
+ this.herdrDialogLive = undefined;
560
594
  this.outOfScope = init.outOfScope;
561
595
  this.paneId = init.paneId;
562
596
  this.launchedByRarog = init.launchedByRarog;
@@ -605,6 +639,8 @@ export class Session {
605
639
  summary.herdrDialogScreen = this.herdrDialogScreen;
606
640
  if (this.cliDialog !== undefined)
607
641
  summary.cliDialog = this.cliDialog;
642
+ if (this.herdrDialogLive !== undefined)
643
+ summary.herdrDialogLive = this.herdrDialogLive;
608
644
  if (this.outOfScope !== undefined)
609
645
  summary.outOfScope = this.outOfScope;
610
646
  // `engine` i `termId` jadą na drut, `observedSessionId` NIE — uuid rollouta Codexa
@@ -651,6 +687,12 @@ export class Session {
651
687
  summary.effort = this.effort;
652
688
  if (this.ultracode !== undefined)
653
689
  summary.ultracode = this.ultracode;
690
+ if (this.projectRoot !== undefined)
691
+ summary.projectRoot = this.projectRoot;
692
+ if (this.coordination !== undefined)
693
+ summary.coordination = structuredClone(this.coordination);
694
+ if (ownerTurn(this))
695
+ summary.ownerTurn = true;
654
696
  return summary;
655
697
  }
656
698
  /**
@@ -676,6 +718,10 @@ export class Session {
676
718
  const seq = this.ring.push(event);
677
719
  message.seq = seq;
678
720
  this.#messages.push(message);
721
+ if (extra.notFromOwner === true)
722
+ this.#notFromOwner.add(seq);
723
+ if (blocksAskOwner(role, blocks))
724
+ this.#asksOwner.add(seq);
679
725
  this.#messageBytes += jsonBytes(message);
680
726
  if (this.#messages.length > MAX_TRANSCRIPT_MESSAGES) {
681
727
  this.#dropOldestMessages(this.#messages.length - MAX_TRANSCRIPT_MESSAGES);
@@ -708,8 +754,11 @@ export class Session {
708
754
  /** Zdejmuje `count` najstarszych wiadomości razem z ich wagą. */
709
755
  #dropOldestMessages(count) {
710
756
  const gone = this.#messages.splice(0, count);
711
- for (const message of gone)
757
+ for (const message of gone) {
712
758
  this.#messageBytes -= jsonBytes(message);
759
+ this.#notFromOwner.delete(message.seq);
760
+ this.#asksOwner.delete(message.seq);
761
+ }
713
762
  if (this.#messages.length === 0)
714
763
  this.#messageBytes = 0;
715
764
  }
@@ -744,6 +793,22 @@ export class Session {
744
793
  const stamp = createHash('sha256').update(this.stateSince).digest('base64url').slice(0, 11);
745
794
  return `${this.#memoryId}.${String(this.#messages.at(-1)?.seq ?? 0)}.${stamp}`;
746
795
  }
796
+ /** Messages in memory from the newest back, for a scan that stops early (`owner-turn.ts`). */
797
+ *messagesNewestFirst() {
798
+ for (let at = this.#messages.length - 1; at >= 0; at -= 1) {
799
+ const message = this.#messages[at];
800
+ if (message !== undefined)
801
+ yield message;
802
+ }
803
+ }
804
+ /** Whether a message in memory carries the server-only "not from the owner" mark. */
805
+ notFromOwner(message) {
806
+ return this.#notFromOwner.has(message.seq);
807
+ }
808
+ /** Whether a message in memory asked the owner when it was appended, read before the size cap. */
809
+ asksOwner(message) {
810
+ return this.#asksOwner.has(message.seq);
811
+ }
747
812
  get messageCount() {
748
813
  return this.#messages.length;
749
814
  }
@@ -150,6 +150,8 @@ export function transition(state, ev) {
150
150
  // i „Odrzuć dialog (Esc)" zamiast kart zgody (pusta tablica `pendingPermissions`).
151
151
  case 'agent-blocked':
152
152
  return AGENT_BLOCKED_FROM.includes(state) ? 'waiting-permission' : state;
153
+ case 'subagent-consent-pending':
154
+ return state === 'running' || state === 'waiting-input' ? 'waiting-permission' : state;
153
155
  }
154
156
  // Nieznany wariant zdarzenia (np. nowszy serwer w przyszłości) — identyczność, nigdy wyjątek.
155
157
  return state;
@@ -161,7 +161,6 @@ export const HERDR_RESUME_MESSAGE = say('rest.bad-state');
161
161
  * przychodzi PRZED `/exit` — sesja jest nietknięta i człowiek ma wiedzieć, co zrobić, żeby
162
162
  * restart przeszedł.
163
163
  */
164
- export const RESTART_CODEX_MESSAGE = say('restart.codex');
165
164
  export const RESTART_IN_PROGRESS_MESSAGE = say('restart.in-progress');
166
165
  export const RESTART_NO_PANEL_MESSAGE = say('restart.no-panel');
167
166
  export const RESTART_UNSUPPORTED_MESSAGE = say('restart.unsupported');
@@ -332,26 +331,6 @@ export const RESUME_UNVERIFIABLE_MESSAGE = say('session.resume-unverifiable');
332
331
  * warunek techniczny „jest czym adresować taba".
333
332
  */
334
333
  export const HERDR_NOT_OWNED_MESSAGE = say('session.close-not-owned');
335
- /**
336
- * 409 na `closePanel: true` dla panelu CODEXA.
337
- *
338
- * Granica władzy stoi TU, a nie w copy klienta: nowy klient „×" dla Codexa nie rysuje, ale stary
339
- * (w dawnej PWA: otwarta od wczoraj zakładka) rysuje go dalej — i jego żądanie doszłoby do `tab.close`
340
- * dokładnie tak samo jak dla panelu Claude. Wpis Codexa daje wyłącznie STAN; zamknięcie
341
- * cudzego panelu byłoby jedyną władzą, jaką by dawał, a tej nie obiecywaliśmy.
342
- */
343
- export const HERDR_CODEX_CLOSE_MESSAGE = say('session.codex-close');
344
- /**
345
- * 400 na diff sesji z karty Codexa.
346
- *
347
- * `diff` pyta o `engine` i `outOfScope` jak każda metoda karty (bramka zasięgu). Bez tego
348
- * dla wpisu Codexa byłaby to władza: treść katalogu panelu (bywa spoza `RAROG_HERDR_ROOTS`) wydana z karty, która
349
- * obiecuje SAM STAN. Zdanie „wpis
350
- * nie dokłada Rarogowi ani grama władzy" ma być prawdą po stronie SERWERA, a nie tylko
351
- * w kliencie. Wiersz gita w nagłówku (gałąź, liczniki) zostaje: to ten sam odczyt, który karta
352
- * i tak pokazuje na liście.
353
- */
354
- export const HERDR_CODEX_GIT_MESSAGE = say('session.codex-git');
355
334
  /**
356
335
  * 409 na przerwanie sesji bez podpiętego drivera.
357
336
  *
@@ -410,7 +389,8 @@ export const HERDR_OUT_OF_SCOPE_MESSAGE = say('session.out-of-scope');
410
389
  *
411
390
  * Diff roboczy to TREŚĆ katalogu. Panel poza zasięgiem nie oddaje transkryptu ani wycinka ekranu
412
391
  * i nie ma nawet linii gita, a `diff` do tego dnia jego katalog oddawał — jedyna metoda karty bez
413
- * bramki zasięgu (patrz {@link HERDR_CODEX_GIT_MESSAGE}).
392
+ * bramki zasięgu. A state-only card is refused by the same gate with its engine's sentence
393
+ * (`STATE_ONLY_REFUSALS` in `herdr/engines.ts`).
414
394
  */
415
395
  export const HERDR_OUT_OF_SCOPE_DIFF_MESSAGE = say('session.out-of-scope-diff');
416
396
  /** 400 for a send while the write channel is closed (`RAROG_HERDR_SEND=0`). */
@@ -542,8 +522,10 @@ export function inTurn(state) {
542
522
  */
543
523
  export function startsTurn(event) {
544
524
  return event.type === 'turn-start' || event.type === 'agent-working'
545
- || event.type === 'resumed' || event.type === 'agent-blocked';
525
+ || event.type === 'resumed' || event.type === 'agent-blocked' || event.type === 'subagent-consent-pending';
546
526
  }
527
+ /** A complete tally with no input yet. */
528
+ const ZERO_TALLY = { standbyNotices: 0, artifactWatch: 0, other: 0, toolCalls: 0, compactions: 0 };
547
529
  /**
548
530
  * Rachunek wiadomości tury PO jej końcu (`Session.turnInput`).
549
531
  *
@@ -553,19 +535,94 @@ export function startsTurn(event) {
553
535
  * 2 s), a koniec tury melduje herdr, niezależnie. Spóźniona notka o postoju doliczyłaby się do
554
536
  * NASTĘPNEJ tury i wyciszyła jej „gotowe". Rachunek po takim końcu jest więc niepełny
555
537
  * (`undefined`) do kolejnego końca tury: jedna tura bez wnioskowania, czyli zwykłe „gotowe".
538
+ * Not so when a subagent woke from standby in that window (`subagentWakes`): the turn was the woken subagent's work
539
+ * in the pane, its standby notice usually arrives a second after the turn end, and it must count towards the next
540
+ * turn, so the tally starts from zero.
556
541
  *
557
- * Drugi wyjątek: sesja, która wstaje (`started` w `#applyTransition`: pierwsze wyjście z tury karty
558
- * powstałej w `starting`, w tym tura zerowa). To nie koniec tury, tylko panel, który wstał (pierwsze
559
- * `idle` nowego panelu, podpięcie panelu bez tury, pusta sesja z Raroga) — rachunek niepełny po
560
- * podpięciu drivera ma taki zostać, aż manager zobaczy koniec PRAWDZIWEJ tury
561
- * (inaczej prompt startowy sesji założonej z Raroga nie liczyłby się nigdzie).
542
+ * Second exception: a session that is standing up (`started` in `#applyTransition`: the first exit from a turn of
543
+ * a card created in `starting`, the zero turn included). That is no turn end but a pane that came up, so the tally
544
+ * stays as the attach left it; {@link closeTurnTally} starts it from zero only when the attach history was read
545
+ * (otherwise the start prompt of a session created from Rarog would count nowhere).
562
546
  */
563
547
  export function nextTurnInput(ended, started) {
564
548
  if (started)
565
549
  return undefined;
566
550
  // Pusty = bez wejścia. Wywołania narzędzi wejściem nie są: tura musiała mieć przyczynę.
567
- const empty = ended !== undefined && noInputYet(ended);
568
- return empty ? undefined : { standbyNotices: 0, artifactWatch: 0, other: 0, toolCalls: 0, compactions: 0 };
551
+ const empty = ended !== undefined && noInputYet(ended) && (ended.subagentWakes ?? 0) === 0;
552
+ return empty ? undefined : { ...ZERO_TALLY };
553
+ }
554
+ /**
555
+ * Subagents that woke from standby on a task list swap (`agentsWoken` in `herdr/background/work.ts`) go into the
556
+ * tally of the current window. Like input, they count from turn end to turn end: the wake shows on the list before
557
+ * herdr reports the pane working. An incomplete tally stays incomplete. A wake that herdr never turned into a turn
558
+ * stays in the tally until the next turn end; a turn with any input is judged by that input alone.
559
+ */
560
+ export function noteSubagentWakes(session, wakes) {
561
+ const turn = session.turnInput;
562
+ if (wakes === 0 || turn === undefined)
563
+ return;
564
+ session.turnInput = { ...turn, subagentWakes: (turn.subagentWakes ?? 0) + wakes };
565
+ }
566
+ /**
567
+ * A new driver: the tally is incomplete. With the attach time (a pane just adopted, whose card state is the snapshot
568
+ * read for it) its history may start the tally from zero ({@link tallyAfterHistory}). Without it (a pane started from
569
+ * Rarog, a driver attached again after a herdr outage, whose card state may be older than the outage) the tally
570
+ * stays incomplete until the next turn end.
571
+ */
572
+ export function tallyOnAttach(session, atMs) {
573
+ session.turnInput = undefined;
574
+ session.turnTallyAttach = atMs === undefined ? undefined : { atMs, historyRead: false };
575
+ }
576
+ /**
577
+ * The tally stays incomplete until the next turn end and the attach no longer starts it: the file continuity was
578
+ * lost (the new conversation's history may hold the prompt of a running turn) or a zero turn settled.
579
+ */
580
+ export function dropTurnTally(session) {
581
+ session.turnInput = undefined;
582
+ session.turnTallyAttach = undefined;
583
+ }
584
+ /**
585
+ * The tally after a history portion. History is not counted, so the tally is incomplete, except for the attach
586
+ * history of a pane just adopted ({@link tallyOnAttach}) when it is out of a turn: everything before the attach then stands in that history, and
587
+ * the tally starts from zero. A card still standing up (`awaitingFirstTurn`) does not know yet where the pane
588
+ * stands, so its first exit decides ({@link closeTurnTally}). A pane in a turn keeps the tally incomplete, and so
589
+ * does history written after the attach: a pane with no conversation file at attach gets the first prompt of the
590
+ * fresh conversation as history. Known gap: "out of a turn" is the state the card shows, which herdr reports
591
+ * `working` late (the working grace) and which right after the attach is the adoption snapshot, so a turn started
592
+ * in those seconds before the attach looks idle and its prompt, in the history, is not counted.
593
+ */
594
+ export function tallyAfterHistory(session, messages) {
595
+ session.turnInput = undefined;
596
+ const attach = session.turnTallyAttach;
597
+ if (attach === undefined)
598
+ return;
599
+ // An unreadable time counts as written after the attach: nothing is inferred from it.
600
+ const beforeAttach = messages.every((message) => Date.parse(message.at) <= attach.atMs);
601
+ if (!beforeAttach || (inTurn(session.state) && !session.awaitingFirstTurn)) {
602
+ session.turnTallyAttach = undefined;
603
+ }
604
+ else if (session.awaitingFirstTurn) {
605
+ session.turnTallyAttach = { ...attach, historyRead: true };
606
+ }
607
+ else {
608
+ session.turnInput = { ...ZERO_TALLY };
609
+ }
610
+ }
611
+ /**
612
+ * The tally at a turn exit (`leavesTurn` in `#applyTransition`), after the scheduler got the ended one. A real turn
613
+ * end follows {@link nextTurnInput} and ends the attach. The first exit of a card standing up (`started`) starts
614
+ * from zero when the attach history was read while it stood up; before that history the attach waits for it.
615
+ */
616
+ export function closeTurnTally(session, started) {
617
+ const attach = session.turnTallyAttach;
618
+ if (started && attach !== undefined) {
619
+ session.turnInput = attach.historyRead ? { ...ZERO_TALLY } : undefined;
620
+ if (attach.historyRead)
621
+ session.turnTallyAttach = undefined;
622
+ return;
623
+ }
624
+ session.turnTallyAttach = undefined;
625
+ session.turnInput = nextTurnInput(session.turnInput, started);
569
626
  }
570
627
  /**
571
628
  * Jak długo po końcu tury po samym meldunku o artefakcie spóźnione wywołanie narzędzia z pliku