@rarog/server 1.1.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 (161) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +46 -1
  3. package/node_modules/@rarog/shared/src/notify-copy.js +2 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/protocol/context.js +57 -0
  6. package/node_modules/@rarog/shared/src/protocol/coordination.js +42 -0
  7. package/node_modules/@rarog/shared/src/protocol/dialog-live.js +117 -0
  8. package/node_modules/@rarog/shared/src/protocol/files.js +1 -1
  9. package/node_modules/@rarog/shared/src/protocol/inbox.js +6 -0
  10. package/node_modules/@rarog/shared/src/protocol/presence.js +47 -0
  11. package/node_modules/@rarog/shared/src/protocol.js +14 -146
  12. package/node_modules/@rarog/shared/src/rest.js +16 -1
  13. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  14. package/node_modules/@rarog/shared/src/sentences/push.js +9 -0
  15. package/node_modules/@rarog/shared/src/sentences/rest.js +9 -0
  16. package/node_modules/@rarog/shared/src/sentences/restart.js +1 -0
  17. package/node_modules/@rarog/shared/src/sentences/session.js +24 -0
  18. package/package.json +2 -2
  19. package/plugin/rarog/.claude-plugin/plugin.json +4 -0
  20. package/plugin/rarog/bin/rarog-coordinator +7 -0
  21. package/plugin/rarog/hooks/hooks.json +18 -0
  22. package/plugin/rarog/hooks/recipient.mjs +95 -0
  23. package/plugin/rarog/lib/coordinator.mjs +1340 -0
  24. package/plugin/rarog/lib/threads.mjs +350 -0
  25. package/plugin/rarog/skills/coordinator/SKILL.md +111 -0
  26. package/plugin/rarog/skills/coordinator/check-and-merge.md +46 -0
  27. package/plugin/rarog/skills/coordinator/close-thread.md +15 -0
  28. package/plugin/rarog/skills/coordinator/role.md +61 -0
  29. package/plugin/rarog/skills/coordinator/send-back.md +39 -0
  30. package/plugin/rarog/skills/coordinator/start-thread.md +43 -0
  31. package/server/src/bootstrap/coordination.js +49 -0
  32. package/server/src/bootstrap/coordinator-start.js +27 -0
  33. package/server/src/bootstrap/inbox.js +4 -0
  34. package/server/src/bootstrap/pr-status.js +15 -7
  35. package/server/src/bootstrap/push.js +59 -5
  36. package/server/src/cli/doctor-pr-status.js +10 -6
  37. package/server/src/companion/catalog.js +1 -1
  38. package/server/src/companion/index.js +2 -4
  39. package/server/src/config/flags.js +4 -0
  40. package/server/src/config-env.js +15 -0
  41. package/server/src/config.js +17 -3
  42. package/server/src/coordination/merge-events.js +86 -0
  43. package/server/src/coordination/merge-prompt.js +244 -0
  44. package/server/src/coordination/registry.js +289 -0
  45. package/server/src/coordination/state.js +94 -0
  46. package/server/src/coordination/summary.js +422 -0
  47. package/server/src/coordination/thread-file.js +245 -0
  48. package/server/src/coordination/thread-git.js +110 -0
  49. package/server/src/coordination/watch.js +237 -0
  50. package/server/src/demo/content/coordinator.js +89 -0
  51. package/server/src/demo/content/en.js +57 -1
  52. package/server/src/demo/content/pl.js +57 -1
  53. package/server/src/demo/control.js +4 -2
  54. package/server/src/demo/inbox.js +12 -0
  55. package/server/src/demo/mock-herdr.js +5 -4
  56. package/server/src/demo/review-routes.js +2 -2
  57. package/server/src/demo/scenarios.js +31 -17
  58. package/server/src/demo/seeds.js +82 -40
  59. package/server/src/drivers/herdr/live-dialog.js +412 -0
  60. package/server/src/drivers/herdr/live-step.js +261 -0
  61. package/server/src/drivers/herdr/pause-gate.js +60 -0
  62. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  63. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  64. package/server/src/drivers/herdr/returned-prompt.js +4 -1
  65. package/server/src/drivers/herdr/screen-fallback.js +50 -0
  66. package/server/src/drivers/herdr/start-dialog-gate.js +136 -0
  67. package/server/src/drivers/herdr-driver.js +159 -77
  68. package/server/src/files/refusals.js +9 -2
  69. package/server/src/files/session-gate.js +5 -4
  70. package/server/src/git-branch-diff.js +194 -0
  71. package/server/src/herdr/argv.js +34 -3
  72. package/server/src/herdr/audit.js +32 -1
  73. package/server/src/herdr/background/cli-shapes.js +35 -15
  74. package/server/src/herdr/background/index.js +7 -7
  75. package/server/src/herdr/background/merge.js +17 -5
  76. package/server/src/herdr/background/notification.js +0 -4
  77. package/server/src/herdr/background/pull-request-files.js +53 -161
  78. package/server/src/herdr/background/pull-requests.js +54 -632
  79. package/server/src/herdr/background/queued-prompt.js +46 -0
  80. package/server/src/herdr/background/work.js +96 -0
  81. package/server/src/herdr/client.js +22 -46
  82. package/server/src/herdr/commands/catalog.js +11 -7
  83. package/server/src/herdr/commands/discover.js +33 -1
  84. package/server/src/herdr/commands/index.js +3 -2
  85. package/server/src/herdr/dialogs/copy.js +7 -0
  86. package/server/src/herdr/dialogs/index.js +13 -1
  87. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +4 -56
  88. package/server/src/herdr/dialogs/live/model.js +220 -0
  89. package/server/src/herdr/dialogs/live/policy.js +108 -0
  90. package/server/src/herdr/dialogs/live/view.js +261 -0
  91. package/server/src/herdr/dialogs/screen/form.js +6 -4
  92. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  93. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  94. package/server/src/herdr/dialogs/screen/signatures.js +78 -0
  95. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  96. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  97. package/server/src/herdr/engines.js +96 -0
  98. package/server/src/herdr/history-steps.js +9 -4
  99. package/server/src/herdr/identity.js +20 -5
  100. package/server/src/herdr/jsonl-follow.js +26 -3
  101. package/server/src/herdr/label-code.js +104 -0
  102. package/server/src/herdr/label-migration.js +142 -0
  103. package/server/src/herdr/launcher.js +30 -5
  104. package/server/src/herdr/plugin-copy.js +281 -0
  105. package/server/src/herdr/provenance.js +80 -40
  106. package/server/src/herdr/session-index.js +19 -0
  107. package/server/src/herdr/start-dialog-wait.js +96 -0
  108. package/server/src/herdr/supervisor.js +49 -23
  109. package/server/src/herdr/types.js +1 -0
  110. package/server/src/herdr/workspace-resolver.js +5 -4
  111. package/server/src/inbox/card.js +31 -8
  112. package/server/src/inbox/heads.js +1 -0
  113. package/server/src/inbox/inbox.js +21 -4
  114. package/server/src/inbox/removals.js +10 -1
  115. package/server/src/index.js +45 -8
  116. package/server/src/notify/apns-payload.js +5 -3
  117. package/server/src/notify/content.js +64 -0
  118. package/server/src/notify/index.js +11 -3
  119. package/server/src/notify/live-activity-state.js +19 -6
  120. package/server/src/notify/live-activity.js +5 -2
  121. package/server/src/notify/policy.js +53 -13
  122. package/server/src/notify/ready-to-merge.js +148 -0
  123. package/server/src/notify/stalled-wait.js +213 -0
  124. package/server/src/pr-status/facts.js +87 -0
  125. package/server/src/pr-status/gh.js +76 -9
  126. package/server/src/pr-status/index.js +1 -10
  127. package/server/src/pr-status/source.js +20 -6
  128. package/server/src/pr-status/tracker.js +32 -9
  129. package/server/src/project-root.js +233 -0
  130. package/server/src/routes/sessions.js +68 -2
  131. package/server/src/sessions/branch-diff.js +57 -0
  132. package/server/src/sessions/cli-registry.js +17 -3
  133. package/server/src/sessions/companion-scope.js +2 -1
  134. package/server/src/sessions/consent-cards.js +49 -2
  135. package/server/src/sessions/conversation-lists.js +11 -2
  136. package/server/src/sessions/coordinator-start.js +172 -0
  137. package/server/src/sessions/demo-modules.js +1 -0
  138. package/server/src/sessions/demo-seeds.js +100 -0
  139. package/server/src/sessions/driver-events.js +68 -14
  140. package/server/src/sessions/herdr-lifecycle.js +11 -4
  141. package/server/src/sessions/interrupt-windows.js +28 -4
  142. package/server/src/sessions/launch-gate.js +36 -11
  143. package/server/src/sessions/live-dialog.js +69 -0
  144. package/server/src/sessions/manager.js +138 -287
  145. package/server/src/sessions/owner-turn.js +36 -0
  146. package/server/src/sessions/pr-status-link.js +64 -16
  147. package/server/src/sessions/seen-marks.js +31 -12
  148. package/server/src/sessions/session-dialog.js +82 -0
  149. package/server/src/sessions/session-git.js +1 -0
  150. package/server/src/sessions/session-scope.js +6 -5
  151. package/server/src/sessions/session-take-back.js +5 -0
  152. package/server/src/sessions/session.js +82 -10
  153. package/server/src/sessions/state-machine.js +13 -0
  154. package/server/src/sessions/state-sentences.js +87 -30
  155. package/server/src/sessions/test-session.js +50 -0
  156. package/server/src/sessions/waiting-line.js +49 -0
  157. package/server/src/term/herdr-backend.js +15 -12
  158. package/server/src/term/lifecycle.js +4 -6
  159. package/server/src/transcript-import.js +20 -2
  160. package/server/src/version.js +4 -0
  161. /package/server/src/{companion/asks-owner.js → asks-owner.js} +0 -0
@@ -1,5 +1,19 @@
1
1
  import { backdateState } from './activity-clocks.js';
2
2
  import * as seenMarks from './seen-marks.js';
3
+ import { ownerTurn } from './owner-turn.js';
4
+ import { dropTurnTally, tallyAfterHistory } from './state-sentences.js';
5
+ import { isStateOnlyEngine } from '../herdr/engines.js';
6
+ /**
7
+ * What a transcript message from the file ends of a send from Rarog: `turn` — the mark of the turn the send opened
8
+ * (an assistant entry or a `user` entry: the turn started, or someone else sent a prompt); `prompt` — the blocked
9
+ * prompt and its resend button (a `user` entry: the field no longer holds the blocked prompt). A message from another
10
+ * session was typed into no field and opened no send of this session, so it ends neither; a `system` note neither.
11
+ */
12
+ export function sendEndedBy(event) {
13
+ if (event.notFromOwner === true)
14
+ return { turn: false, prompt: false };
15
+ return { turn: event.role !== 'system', prompt: event.role === 'user' };
16
+ }
3
17
  /** `init` from the driver: engine session, model, effort, ultracode and pull requests of the conversation. */
4
18
  export function applyInitEvent(session, event, port) {
5
19
  /*
@@ -9,8 +23,9 @@ export function applyInitEvent(session, event, port) {
9
23
  * pliku jsonl", a Codex takiego pliku nie ma. Karta zostaje ta sama — jest jedna
10
24
  * na panel.
11
25
  */
12
- if (session.engine === 'codex') {
13
- session.observedSessionId = event.engineSessionId;
26
+ if (isStateOnlyEngine(session.engine)) {
27
+ // `''`: herdr stopped reporting a session for the pane; the seen mark goes back to the pane address.
28
+ session.observedSessionId = event.engineSessionId === '' ? undefined : event.engineSessionId;
14
29
  return;
15
30
  }
16
31
  const previousEngineSession = session.engineSessionId;
@@ -27,6 +42,8 @@ export function applyInitEvent(session, event, port) {
27
42
  */
28
43
  if (previousEngineSession !== undefined && previousEngineSession !== event.engineSessionId) {
29
44
  port.config.notifier?.forget(session.id);
45
+ // The stalled wait alarm of the previous conversation stops its tries too.
46
+ port.config.stalledWait?.forget(session.id);
30
47
  // A claim window of the previous conversation does not hold a dialog of the new one (`claim-window.ts`).
31
48
  port.claimWindows.conversationChanged(session);
32
49
  }
@@ -62,10 +79,13 @@ export function applyInitEvent(session, event, port) {
62
79
  */
63
80
  const imported = session.importedHistory;
64
81
  session.importedHistory = undefined;
82
+ // The owner's turn belongs to the conversation, so only a move changes it here (`owner-turn.ts`).
83
+ const ownerTurnBefore = conversationChanged && ownerTurn(session);
65
84
  if (conversationChanged) {
66
85
  session.conversationStartSeq = imported?.engineSessionId === event.engineSessionId
67
86
  ? imported.fromSeq : session.ring.lastSeq;
68
87
  }
88
+ const ownerTurnChanged = conversationChanged && ownerTurn(session) !== ownerTurnBefore;
69
89
  if (conversationChanged)
70
90
  port.conversationChanged(session.id, event.engineSessionId); // voice agent
71
91
  const nextUltracode = event.ultracode === null ? undefined
@@ -77,11 +97,13 @@ export function applyInitEvent(session, event, port) {
77
97
  * PR-y należą do rozmowy jak artefakty. Driver po wymianie startuje z pustym podpisem listy, więc
78
98
  * pusta lista nowej rozmowy nie wyszłaby z niego nigdy: lista poprzedniej schodzi tu, przy zmianie rozmowy.
79
99
  */
80
- const pullRequestsDropped = conversationChanged
81
- && (session.pullRequests !== undefined || session.scheduledTasks !== undefined);
100
+ const pullRequestsDropped = conversationChanged && (session.pullRequests !== undefined
101
+ || session.pullRequestLinks !== undefined || session.scheduledTasks !== undefined);
82
102
  if (pullRequestsDropped) {
83
- // Scheduled tasks too; the driver sends the new conversation's list after this `init`, also when empty.
103
+ // The links and the window too, and scheduled tasks; the driver sends the new conversation's after this `init`.
84
104
  session.pullRequests = undefined;
105
+ session.pullRequestLinks = undefined;
106
+ session.pullRequestWindowStart = undefined;
85
107
  session.scheduledTasks = undefined;
86
108
  }
87
109
  const moved = port.applyTransition(session, { type: 'driver-init' });
@@ -93,9 +115,9 @@ export function applyInitEvent(session, event, port) {
93
115
  session.emptyStart = false;
94
116
  port.applyTransition(session, { type: 'result', subtype: 'success' });
95
117
  // Jak w `#settleEmptyStart`: tura zerowa nie domyka rachunku wiadomości.
96
- session.turnInput = undefined;
118
+ dropTurnTally(session);
97
119
  }
98
- else if ((modelChanged || effortChanged || ultracodeChanged || pullRequestsDropped) && !moved) {
120
+ else if ((modelChanged || effortChanged || ultracodeChanged || pullRequestsDropped || ownerTurnChanged) && !moved) {
99
121
  /*
100
122
  * Sam model ani sam effort nie są przejściem stanu, więc karta musi dostać osobne
101
123
  * odświeżenie. Dotyczy to też effortu: `init` poza `starting` nie rusza stanu
@@ -116,9 +138,12 @@ export function applyInitEvent(session, event, port) {
116
138
  export function applyHistoryEvent(session, event, port) {
117
139
  if (session.state === 'done')
118
140
  return;
119
- // Historii nie liczymy, a bywa w niej prompt tury, która jeszcze trwa: po każdej porcji
120
- // rachunek wiadomości tury jest niepełny do następnego końca tury.
121
- session.turnInput = undefined;
141
+ /*
142
+ * History is not counted, and it may hold the prompt of a turn still running: after every portion the turn tally
143
+ * is incomplete until the next turn end. The exception is the attach history of a pane just adopted while it is out
144
+ * of a turn: the tally starts from zero there (`tallyAfterHistory`).
145
+ */
146
+ tallyAfterHistory(session, event.messages);
122
147
  // Where this conversation's history starts in memory, for an `init` that names it next (`applyInitEvent`).
123
148
  if (event.engineSessionId !== undefined && session.importedHistory?.engineSessionId !== event.engineSessionId) {
124
149
  session.importedHistory = { engineSessionId: event.engineSessionId, fromSeq: session.ring.lastSeq };
@@ -135,6 +160,7 @@ export function applyHistoryEvent(session, event, port) {
135
160
  port.appendMessage(session, item.role, item.blocks, item.at, item.attachments, {
136
161
  ...(item.notice !== undefined ? { notice: item.notice } : {}),
137
162
  ...(item.promptBlocked !== undefined ? { promptBlocked: item.promptBlocked } : {}),
163
+ ...(item.notFromOwner === true ? { notFromOwner: true } : {}),
138
164
  });
139
165
  }
140
166
  /*
@@ -179,6 +205,8 @@ function cardSignature(session) {
179
205
  // własne zdarzenia (`dialog-screen` porównuje pełny tekst) — dwa kilobajty ekranu w podpisie byłyby pracą
180
206
  // przy każdym obrocie resyncu.
181
207
  + `|${String(session.herdrDialogScreen?.length ?? 0)}|${session.cliDialog ?? ''}`
208
+ // The live card by occurrence and revision: its view changes only with a new revision (`dialog-live`).
209
+ + `|${session.herdrDialogLive?.id ?? ''}:${String(session.herdrDialogLive?.rev ?? '')}`
182
210
  + `|${String(session.stale)}`;
183
211
  }
184
212
  /**
@@ -191,6 +219,17 @@ function emitIfChanged(session, before, port) {
191
219
  if (cardSignature(session) !== before)
192
220
  port.emitSessionChanged(session);
193
221
  }
222
+ /**
223
+ * A state-only engine (Codex, agy) going from a standing dialog straight to herdr `idle`, with no `working` in
224
+ * between, ended no work: a trust or update dialog was closed, or an approval was dismissed with Esc. Rarog reads no
225
+ * transcript of such a pane, so this pair of states is all it has, and it carries no result. A herdr `done` after
226
+ * a dialog stays a result: in the recorded Codex CLI 0.171.0 and Antigravity CLI 1.5.18 runs (herdr 0.9.5) every
227
+ * `done` came after `working`. A Claude card keeps its own rule.
228
+ */
229
+ function dialogClosedWithoutWork(session, event) {
230
+ return isStateOnlyEngine(session.engine) && session.state === 'waiting-permission'
231
+ && event.state === 'idle' && event.seen === true;
232
+ }
194
233
  /*
195
234
  * Stan raportowany przez ZEWNĘTRZNEGO nadzorcę. Zdarzenie niesie trzy niezależne
196
235
  * rzeczy: stan (przez maszynę stanów), `seen` (SUROWY status badge'a herdr: `false`
@@ -227,6 +266,7 @@ export function applyAgentStateEvent(session, event, port) {
227
266
  session.herdrDialogReason = undefined;
228
267
  session.herdrDialogScreen = undefined;
229
268
  session.cliDialog = undefined;
269
+ session.herdrDialogLive = undefined;
230
270
  port.herdrBlocked.delete(session.id);
231
271
  port.timingLeft(session);
232
272
  port.claimWindows.herdrMoved(session);
@@ -251,14 +291,28 @@ export function applyAgentStateEvent(session, event, port) {
251
291
  emitIfChanged(session, before, port);
252
292
  return;
253
293
  }
254
- const smEvent = event.state === 'working'
255
- ? { type: 'agent-working' }
256
- : (event.state === 'idle' ? { type: 'agent-idle' } : { type: 'agent-blocked' });
294
+ /*
295
+ * A subagent's request has no dialog on the pane while its hook waits, so herdr reports `working` or `idle` while its
296
+ * channel card stands in `pending`: the state stays in `waiting-permission` or goes back there
297
+ * (`ConsentCards.subagentCardHold`), except inside the grace after an interrupt or a blocked prompt.
298
+ */
299
+ const subagent = event.state === 'blocked' ? null : port.subagentCardHold(session, event.state);
300
+ const reconcile = subagent === 'reconcile' && !port.inWorkingGrace(session);
301
+ const smEvent = reconcile ? { type: 'subagent-consent-pending' }
302
+ : event.state === 'working' ? { type: 'agent-working' }
303
+ : (event.state === 'idle' ? { type: 'agent-idle' } : { type: 'agent-blocked' });
257
304
  // `#applyTransition` sam rozgłasza `session-changed`, gdy stan się ruszył — drugi
258
305
  // broadcast byłby przy 17 panelach czystym szumem w strumieniu globalnym.
259
306
  // Right after the hook claimed a phone answer the answered dialog is still on the pane, so herdr repeats `blocked`:
260
307
  // inside the claim window it leaves the state alone (`claim-window.ts`), and a dialog that stays moves it after.
261
- if (event.state === 'blocked' && port.claimWindows.holdBlocked(session, event.detail)) {
308
+ const hold = event.state === 'blocked' ? port.claimWindows.holdBlocked(session, event.detail) : subagent === 'hold';
309
+ if (!hold && smEvent.type === 'agent-idle' && dialogClosedWithoutWork(session, event)) {
310
+ // No turn ended: the card goes back received, and the manager notes the exit like a card standing up
311
+ // (`awaitingFirstTurn` gives `afterStart`), which pushes nothing and leaves no owed result.
312
+ session.seen = true;
313
+ session.awaitingFirstTurn = true;
314
+ }
315
+ if (hold) {
262
316
  emitIfChanged(session, before, port);
263
317
  }
264
318
  else if (port.applyTransition(session, smEvent, event.detail)) {
@@ -13,6 +13,7 @@ import { sentenceOfError } from '../herdr/types.js';
13
13
  import * as seenMarks from './seen-marks.js';
14
14
  import { Session } from './session.js';
15
15
  import { HERDR_RECOVERY_GONE_MS, HERDR_RESTORE_MATCH_MS, HERDR_RESTORE_QUIET_MAX_MS, HERDR_UNKNOWN_DETAIL, } from './state-sentences.js';
16
+ import { isStateOnlyEngine } from '../herdr/engines.js';
16
17
  /** Lifecycle events of herdr panes and their state; one instance per manager. */
17
18
  export class HerdrLifecycle {
18
19
  #config;
@@ -149,7 +150,8 @@ export class HerdrLifecycle {
149
150
  const markedUnseen = initial.seen !== undefined && seenMarks.wasMarkedUnseen(agent, this.#config.herdrDeps?.seen);
150
151
  if (markedUnseen && initial.seen === true)
151
152
  seen = undefined;
152
- const codex = agent.engine === 'codex';
153
+ const engine = agent.engine;
154
+ const codex = isStateOnlyEngine(engine);
153
155
  const session = new Session({
154
156
  /*
155
157
  * Tożsamość karty: najpierw ALIAS po uuidzie silnika (ta sama sesja wznowiona w nowym
@@ -178,7 +180,11 @@ export class HerdrLifecycle {
178
180
  * ma, więc jego uuid dostaje własne pole i jedno zastosowanie — znacznik „obejrzane".
179
181
  */
180
182
  ...(codex
181
- ? { engine: 'codex', observedSessionId: agent.agentSessionId }
183
+ // Without a session ID from herdr (`''`) the card has no observed session: its seen mark goes by pane.
184
+ ? {
185
+ engine,
186
+ ...(agent.agentSessionId === '' ? {} : { observedSessionId: agent.agentSessionId }),
187
+ }
182
188
  : { engineSessionId: agent.agentSessionId }),
183
189
  /*
184
190
  * Adres wpisu w kliencie, gdy agent stoi w terminalu Raroga — ale tylko wtedy, gdy terminal
@@ -255,7 +261,8 @@ export class HerdrLifecycle {
255
261
  */
256
262
  this.#port.git.requestGitStatus(session);
257
263
  this.#port.git.watch(session);
258
- void this.#port.attachHerdrDriver(supervisor, session, agent.key);
264
+ // Adopted: the card's state is the snapshot just read, so its attach history may start the turn tally.
265
+ void this.#port.attachHerdrDriver(supervisor, session, agent.key, true);
259
266
  }
260
267
  /** Pole `termId` karty z migawki agenta: tylko przy włączonym terminalu (`RAROG_TERM`). */
261
268
  termIdField(agent) {
@@ -319,7 +326,7 @@ export class HerdrLifecycle {
319
326
  // Defensywnie: nowa karta nie dziedziczy znacznika poprzedniej o tym samym id.
320
327
  this.herdrRestoreQuiet.delete(session.id);
321
328
  this.#pruneGoneIdle();
322
- if (!this.#herdrGoneIdle.delete(agentSessionId))
329
+ if (agentSessionId === '' || !this.#herdrGoneIdle.delete(agentSessionId))
323
330
  return;
324
331
  if (session.state !== 'running' && session.state !== 'starting')
325
332
  return;
@@ -56,9 +56,17 @@ export class InterruptWindows {
56
56
  * Porównanie tożsamości przy rozstrzygnięciu nie jest asekuracją: nowa tura użytkownika
57
57
  * unieważnia oba okna (`resetInterruptWindows`), a spóźniony `escape` sprzed tej tury nie
58
58
  * ma prawa ani skasować cudzego wpisu, ani otworzyć debounce'u NAD nową turą.
59
+ *
60
+ * @param fromCard for an interrupt taken from `waiting-permission`: the session's `stateSince` right after the
61
+ * interrupt moved it to `waiting-input`; `null` otherwise. The transition runs before the driver's answer, and an
62
+ * `escape` the driver refused or could not send (the pause, a start dialog, a failed send) leaves the dialog
63
+ * standing: the card goes back on its decision while herdr still reports the pane `blocked` and the session has
64
+ * not moved since, instead of standing sendable until the driver shows its card again. A dialog answered at the
65
+ * desk in the meantime does not bring it back: herdr `idle` on `waiting-input` changes neither the state nor
66
+ * `stateSince`, and nothing else would clear the card.
59
67
  */
60
- trackInterrupt(id, delivered) {
61
- const tracked = delivered.then((sent) => this.#settleInterrupt(id, tracked, sent), (err) => {
68
+ trackInterrupt(id, delivered, fromCard = null) {
69
+ const tracked = delivered.then((sent) => this.#settleInterrupt(id, tracked, sent, fromCard), (err) => {
62
70
  /*
63
71
  * Kontrakt mówi, że odmowy lecą SYNCHRONICZNIE, więc odrzucona obietnica to
64
72
  * awaria kanału, nie decyzja. „Nie dostarczono" jest tu jedyną uczciwą odpowiedzią:
@@ -66,20 +74,36 @@ export class InterruptWindows {
66
74
  * gorszym kłamstwem niż `delivered: 'no'`.
67
75
  */
68
76
  this.#port.logger?.(`interrupt ${id}: ${describeError(err)}`);
69
- return this.#settleInterrupt(id, tracked, false);
77
+ return this.#settleInterrupt(id, tracked, false, fromCard);
70
78
  });
71
79
  this.#interruptsInFlight.set(id, tracked);
72
80
  return tracked;
73
81
  }
74
82
  /** Rozstrzygnięcie: zamyka okno „w locie", a dostarczony klawisz otwiera debounce. */
75
- #settleInterrupt(id, tracked, sent) {
83
+ #settleInterrupt(id, tracked, sent, fromCard) {
76
84
  if (this.#interruptsInFlight.get(id) !== tracked)
77
85
  return sent;
78
86
  this.#interruptsInFlight.delete(id);
79
87
  if (sent)
80
88
  this.#lastInterruptAtMs.set(id, this.#port.now());
89
+ else if (fromCard !== null)
90
+ this.#cardBack(id, fromCard);
81
91
  return sent;
82
92
  }
93
+ /**
94
+ * The card of an interrupt not delivered goes back on its decision: same session, driver and state since then, and
95
+ * herdr still reports the pane `blocked`.
96
+ */
97
+ #cardBack(id, since) {
98
+ const session = this.#port.sessions.get(id);
99
+ if (session === undefined || session.driver === null || !this.#port.herdrBlocked.has(id))
100
+ return;
101
+ if (session.state !== 'waiting-input' || session.stateSince !== since)
102
+ return;
103
+ if (this.#port.applyTransition(session, { type: 'agent-blocked' })) {
104
+ this.#port.logger?.(`interrupt ${id}: not delivered, the card is back on its decision`);
105
+ }
106
+ }
83
107
  /** Zeruje OBA okna przerwania tej sesji — nowa tura i zniknięcie karty. */
84
108
  resetInterruptWindows(id) {
85
109
  this.#interruptsInFlight.delete(id);
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * Launch gate of the session manager: every check that can refuse a new herdr session before anything exists on the
3
- * other side (directory, permission mode, model, pane cap, launch switch, resume checks, ultracode, start prompt), in
4
- * that order, the launch slots (one per 5 s and an hourly cap, "Starting sessions from the phone: three powers" in
3
+ * other side (directory, permission mode, model, pane cap, launch switch, resume checks, ultracode, coordinator
4
+ * reservation, start prompt), in that order, the launch slots (one per 5 s and an hourly cap, "Starting sessions from the phone: three powers" in
5
5
  * `docs/security-model.md`) and the start options of a resume.
6
6
  * The manager owns one {@link LaunchGate} and gives it a narrow {@link LaunchGatePort}. The pane, the card and the
7
7
  * second half of the start (`#finishLaunch`: readiness, the start prompt waiting for a start dialog, session restarts)
8
8
  * stay in the manager. This module does not import `manager.ts`.
9
9
  */
10
10
  import { resolve } from 'node:path';
11
+ import { coordinatorLabel, coordinatorPrompt } from './coordinator-start.js';
11
12
  import { BadRequestError, BadStateError, TooManyRequestsError, UltracodeRefusedError } from './errors.js';
12
13
  import { HERDR_DOUBLE_WRITER_MESSAGE, HERDR_LAUNCH_OFF_MESSAGE, RESUME_FOREIGN_CWD_MESSAGE, RESUME_NOT_FOUND_MESSAGE, RESUME_UNVERIFIABLE_MESSAGE, ULTRACODE_CLI_UNKNOWN_MESSAGE, ULTRACODE_EFFORT_MESSAGE, launchThrottledMessage, transcriptCwdBelongs, ultracodeCliTooOldMessage, } from './state-sentences.js';
13
14
  import { HERDR_LAUNCH_HOURLY_CAP, HERDR_LAUNCH_MIN_INTERVAL_MS } from '../config.js';
@@ -103,27 +104,51 @@ export class LaunchGate {
103
104
  }
104
105
  }
105
106
  this.#assertUltracodeLaunch(opts);
106
- if (!slotTaken && !this.#takeLaunchSlot()) {
107
- throw new TooManyRequestsError(launchThrottledMessage(this.#port.system()));
107
+ // The last check that can refuse; from here on a refusal releases the reservation it took.
108
+ const coordinator = this.#port.coordinator(opts);
109
+ try {
110
+ if (!slotTaken && !this.#takeLaunchSlot()) {
111
+ throw new TooManyRequestsError(launchThrottledMessage(this.#port.system()));
112
+ }
113
+ const prompt = this.startPrompt(opts.cwd, opts.prompt, coordinator?.pluginDir ?? null, null);
114
+ return {
115
+ opts, resumeModelSeed, ultracodeDropped, prompt, coordinator,
116
+ labelText: coordinator === null ? prompt?.text ?? null : coordinatorLabel(prompt?.text ?? ''),
117
+ };
118
+ }
119
+ catch (error) {
120
+ coordinator?.release();
121
+ throw error;
108
122
  }
123
+ }
124
+ /**
125
+ * The start prompt of a new process through the send guard; a coordinator's (`pluginDir` set) is the skill command
126
+ * before the user's prompt, checked whole (the byte ceiling counts the joined text) against the catalog with the
127
+ * plugin copy. A restart that resends a blocked prompt calls it before `/exit`, so its dry check is this very check;
128
+ * `key` names the pane in a command refusal log line (`null` before a pane exists).
129
+ */
130
+ startPrompt(cwd, prompt, pluginDir, key) {
109
131
  /*
110
132
  * Prompt przechodzi przez guard PRZED `launch()`, żeby 400 wróciło na POST-a, a nie
111
133
  * zostawiło po sobie panelu z odrzuconym zdaniem. Tryb `'unknown'` jest tu celowy
112
134
  * i NIE jest tym samym co przy wysyłce do istniejącego panelu: panelu jeszcze nie ma,
113
135
  * więc nie ma czego czytać ze stopki — a tryb, w którym wstanie, wybiera właśnie
114
- * `#assertPermissionMode` dwie linie wyżej.
136
+ * `#assertPermissionMode` w `admitLaunch`.
115
137
  */
116
- const rawPrompt = opts.prompt !== undefined && opts.prompt !== '' ? opts.prompt : null;
138
+ const rawPrompt = pluginDir !== null
139
+ ? coordinatorPrompt(prompt)
140
+ : prompt !== undefined && prompt !== '' ? prompt : null;
141
+ if (rawPrompt === null)
142
+ return null;
117
143
  // Nowy panel wstaje na wydaniu zainstalowanym, więc katalog komend liczymy dla niego.
118
- const catalog = rawPrompt === null ? null : this.#port.commandCatalog(opts.cwd, this.#port.cli.cliVersion.installed);
119
- const prompt = rawPrompt === null || catalog === null ? null : {
120
- ...this.#port.checkSendable(rawPrompt, null, opts.cwd, {
121
- mode: 'unknown', cwd: opts.cwd, yoloRoots: this.#config.yoloRoots ?? [], catalog,
144
+ const catalog = this.#port.commandCatalog(cwd, this.#port.cli.cliVersion.installed, pluginDir === null ? undefined : [pluginDir]);
145
+ return {
146
+ ...this.#port.checkSendable(rawPrompt, key, cwd, {
147
+ mode: 'unknown', cwd, yoloRoots: this.#config.yoloRoots ?? [], catalog,
122
148
  ...(this.#config.realPath !== undefined ? { realPath: this.#config.realPath } : {}),
123
149
  }),
124
150
  catalog,
125
151
  };
126
- return { opts, resumeModelSeed, ultracodeDropped, prompt };
127
152
  }
128
153
  /**
129
154
  * Throttle zakładania paneli: jeden na 5 s i 40 na godzinę
@@ -0,0 +1,69 @@
1
+ import { DECISION_STATES } from './state-sentences.js';
2
+ /**
3
+ * The driver's `dialog-live` event: the field of the new occurrence or revision, or its end. Only the session card
4
+ * field, like `cli-dialog`: no pending, state transition or push. A late field after the session left the decision does
5
+ * not bring the card back, because `agent-state` has just cleared it; the same occurrence and revision twice is a no-op.
6
+ */
7
+ export function applyDialogLive(session, event, port) {
8
+ const { live } = event;
9
+ if (live !== undefined && !DECISION_STATES.includes(session.state))
10
+ return;
11
+ if (sameRevision(session.herdrDialogLive, live))
12
+ return;
13
+ session.herdrDialogLive = live;
14
+ port.emitSessionChanged(session);
15
+ }
16
+ /** The driver sends a view only with a new occurrence or revision, so `id` and `rev` name the view. */
17
+ function sameRevision(a, b) {
18
+ if (a === undefined || b === undefined)
19
+ return a === b;
20
+ return a.id === b.id && a.rev === b.rev;
21
+ }
22
+ /**
23
+ * Sessions with a live card key or a `deny` in flight. Keyed by the session object, so a session that a restart
24
+ * replaced starts unlocked and two managers in one process never share a lock.
25
+ */
26
+ const inFlight = new WeakSet();
27
+ const IN_FLIGHT_KEY = { kind: 'refused', reason: 'in-flight' };
28
+ const IN_FLIGHT_DECISION = { outcome: 'refused', reason: 'in-flight' };
29
+ const NOT_SHOWN = { kind: 'not-shown' };
30
+ const SEND_OFF = { kind: 'send-off' };
31
+ /**
32
+ * Runs `step` holding the session's lock; `busy` when another key or deny of the session is in flight. The lock is
33
+ * taken before `step` starts and goes when its promise settles, also when `step` throws on the call.
34
+ */
35
+ function holding(session, busy, step) {
36
+ if (inFlight.has(session))
37
+ return Promise.resolve(busy);
38
+ inFlight.add(session);
39
+ const release = () => { inFlight.delete(session); };
40
+ let pending;
41
+ try {
42
+ pending = step();
43
+ }
44
+ catch (error) {
45
+ release();
46
+ throw error;
47
+ }
48
+ return pending.finally(release);
49
+ }
50
+ /**
51
+ * One key of the live card to the session's driver. A closed write channel (`RAROG_HERDR_SEND=0` or a read-only
52
+ * supervisor) answers `send-off` before the lock and the driver; a driver without live cards answers `not-shown`.
53
+ * The manager checks the session, the restart and the work area before this call.
54
+ */
55
+ export function pressDialogKey(session, body, writable) {
56
+ if (!writable)
57
+ return Promise.resolve(SEND_OFF);
58
+ const key = session.driver?.dialogKey?.bind(session.driver);
59
+ if (key === undefined)
60
+ return Promise.resolve(NOT_SHOWN);
61
+ return holding(session, IN_FLIGHT_KEY, () => key(body));
62
+ }
63
+ /**
64
+ * Today's `deny` of the session that goes to its driver (`POST /api/sessions/:id/permission` and
65
+ * `/permissions/:permId`), under the same lock as a live key: `in-flight` while a key or another deny is in flight.
66
+ */
67
+ export function denyUnderLock(session, deny) {
68
+ return holding(session, IN_FLIGHT_DECISION, deny);
69
+ }