@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
@@ -0,0 +1,412 @@
1
+ /**
2
+ * Live dialog card on the driver (`docs/dialogs.md`, "Live dialog card"): while the pane waits on a dialog and no card
3
+ * with key buttons, consent channel card or layer 2 card stands for the dialog on screen, the dialog region goes to the
4
+ * phone as `SessionSummary.herdrDialogLive`, next to today's card, under an occurrence `lv:<12 hex>` whose revision grows
5
+ * when the view changes. The module issues, refreshes and ends occurrences, writes the `live-card` audit line and
6
+ * orders the evaluation of a pane under a CLI consent dialog herdr does not block on. For the key step
7
+ * (`live-step.ts`) it computes the view of a fresh screen, consumes an occurrence on Enter and Esc and applies the read
8
+ * after a key. It sends no key and builds no card; the view and the key rule are the pure module
9
+ * `herdr/dialogs/live/`.
10
+ */
11
+ import { randomBytes } from 'node:crypto';
12
+ import { parseOptions } from '../../herdr/dialogs/index.js';
13
+ import { ANSWERED_HOOK_SHIELD_MS } from '../../herdr/dialogs/timing.js';
14
+ import { liveClass, liveDialogView, liveDialogWire } from '../../herdr/dialogs/live/model.js';
15
+ import { liveRegion } from '../../herdr/dialogs/live/view.js';
16
+ import { isStateOnlyEngine } from '../../herdr/types.js';
17
+ import { cardShowsAll } from '../tool-text.js';
18
+ /** Prefix of a live card occurrence id. */
19
+ export const LIVE_ID_PREFIX = 'lv:';
20
+ /**
21
+ * How long a card the driver holds back (it waits for the consent channel card or for the judgement of its no-hook
22
+ * episode) keeps the live card away. Both waits are a few seconds; a held mark the driver never resolved expires here.
23
+ */
24
+ export const LIVE_HELD_MAX_MS = 10_000;
25
+ /**
26
+ * How long after Enter or Esc of the live card the same fingerprint gets no new occurrence: a screen the CLI has not
27
+ * repainted yet still shows the answered dialog, and a second Enter on it would answer the next one.
28
+ */
29
+ export const LIVE_REISSUE_BLOCK_MS = ANSWERED_HOOK_SHIELD_MS;
30
+ /** Issued ids the module remembers, so a key for an id it issued earlier is stale rather than unknown. */
31
+ const ISSUED_KEPT = 64;
32
+ /** No card stands for the dialog on screen, and no fact of another dialog's card counts for it. */
33
+ const ANOTHER_DIALOG = { kind: 'card', shape: 'no-card', toolUse: false, episode: false };
34
+ /**
35
+ * A permission card without buttons over the fresh screen. Its transcript entry and its no-hook episode count only for
36
+ * the dialog whose fingerprint the screen shows: another fingerprint means no card stands for the dialog on screen, and
37
+ * a card or a screen without a fingerprint proves no dialog, so the card stands without them.
38
+ */
39
+ function provenOn(screen, standing) {
40
+ const print = standing.print === undefined ? null : parseOptions(screen)?.bodyPrint ?? null;
41
+ if (print === null)
42
+ return { ...standing, toolUse: false, episode: false };
43
+ return print === standing.print ? standing : ANOTHER_DIALOG;
44
+ }
45
+ /** The kind of a published card: a card with key buttons, or one of the three shapes without them. */
46
+ function kindOf(active, event) {
47
+ if (event.type === 'permission-request') {
48
+ const withoutApprove = event.input === null || event.canAllow === false
49
+ || !cardShowsAll(event.displayText, event.truncation);
50
+ return withoutApprove ? 'degraded' : 'own';
51
+ }
52
+ if (event.type === 'screen-dialog')
53
+ return event.knownDialog === undefined ? 'screen-dialog' : 'own';
54
+ if (event.type === 'question-request') {
55
+ if (active.layer2Card !== undefined)
56
+ return 'own';
57
+ const answered = event.questions.every((question) => question.options.every((option) => option.terminalOnly));
58
+ return answered ? 'terminal' : 'own';
59
+ }
60
+ return 'own';
61
+ }
62
+ export class LiveDialogCards {
63
+ #config;
64
+ #port;
65
+ #occurrence = null;
66
+ #shown = null;
67
+ /** The last state the driver told the manager was not `blocked`: the manager holds no field now. */
68
+ #unblocked = false;
69
+ /** The evaluation the module ordered for a pane under a CLI consent dialog without a block; `null` = none. */
70
+ #followTimer = null;
71
+ /** The pane stood under such a dialog at the last check: a dialog that just came up is looked at once. */
72
+ #following = false;
73
+ /** The ids issued last, oldest first, at most {@link ISSUED_KEPT}. */
74
+ #issued = [];
75
+ /** The last Enter or Esc: the fingerprint it went to and when (the re-issue block). */
76
+ #lastUse = null;
77
+ constructor(config, port) {
78
+ this.#config = config;
79
+ this.#port = port;
80
+ }
81
+ /** The standing occurrence with this id that takes keys; `null` = unknown, replaced, ended or used. */
82
+ occurrence(id) {
83
+ const standing = this.#occurrence;
84
+ return standing?.id === id && !standing.used ? standing : null;
85
+ }
86
+ /**
87
+ * The standing occurrence with this id that takes keys and still stands for the pane as it is now: its binding is
88
+ * the one the facts give now (engine session and registry episode, or pane and start dialog). `null` = unknown,
89
+ * replaced, ended, used, or bound elsewhere now. No read.
90
+ */
91
+ boundNow(id) {
92
+ const standing = this.occurrence(id);
93
+ return standing !== null && standing.bind === this.#bindOf(this.#config.startDialog()) ? standing : null;
94
+ }
95
+ /** The standing occurrence that takes keys; `null` = none. */
96
+ current() {
97
+ const standing = this.#occurrence;
98
+ return standing === null || standing.used ? null : standing;
99
+ }
100
+ /** Whether the module issued this id (among the last ones it remembers). */
101
+ issued(id) {
102
+ return this.#issued.includes(id);
103
+ }
104
+ /**
105
+ * The id of the occurrence Enter or Esc went to within {@link LIVE_REISSUE_BLOCK_MS}; `null` = none. A key that comes
106
+ * then for the same dialog was decided over the card that answered it.
107
+ */
108
+ recentlyUsed() {
109
+ const last = this.#lastUse;
110
+ return last !== null && this.#config.scheduler.now() - last.at < LIVE_REISSUE_BLOCK_MS ? last.id : null;
111
+ }
112
+ /** The fingerprint Enter or Esc went to within {@link LIVE_REISSUE_BLOCK_MS}; `null` = none. */
113
+ recentPrint() {
114
+ return this.recentlyUsed() === null ? null : this.#lastUse?.print ?? null;
115
+ }
116
+ /**
117
+ * A key now would go past a dialog a live Enter or Esc decided: `bound` (the fingerprint {@link recentPrint} gave
118
+ * when the caller took the request) or the fingerprint used within the block now, and `screen` shows that dialog (the
119
+ * same fingerprint), no dialog, or was not read (`null`). Another dialog on screen is not decided by those keys, and
120
+ * the block running out while the request waits does not free a key for the dialog it decided. No read.
121
+ */
122
+ usedOn(screen, bound) {
123
+ const decided = [bound, this.recentPrint()].filter((print) => print !== null);
124
+ if (decided.length === 0)
125
+ return false;
126
+ if (screen === null)
127
+ return true;
128
+ const region = liveRegion(screen);
129
+ return region === null || decided.includes(region.print);
130
+ }
131
+ /**
132
+ * The live card a fresh `screen` gives under what stands for the dialog now: the view the key step compares with the
133
+ * occurrence. `noClass`: the registry class is in doubt, so a dialog in the session is judged with no class (a
134
+ * consent dialog); a start dialog keeps the class of its signature. `channel` = a consent channel card stands or a
135
+ * card is held back for it; `null` = no live card (the level, the pane does not wait, a card with key buttons, no
136
+ * dialog). No read, no state change.
137
+ */
138
+ viewOf(screen, noClass = false) {
139
+ if (!this.#works() || !this.#waiting() || this.#unblocked)
140
+ return null;
141
+ if (this.#config.channelCard(true))
142
+ return 'channel';
143
+ const sight = this.#sight(screen, noClass);
144
+ return sight === 'held' ? 'channel' : sight;
145
+ }
146
+ /**
147
+ * Enter or Esc is about to go to occurrence `id`: it takes no further key. The field stays with the manager until the
148
+ * next read ({@link refresh} or an evaluation) replaces or ends it; the same fingerprint gets no new occurrence for
149
+ * {@link LIVE_REISSUE_BLOCK_MS}.
150
+ */
151
+ use(id) {
152
+ const standing = this.occurrence(id);
153
+ if (standing === null)
154
+ return;
155
+ this.#occurrence = { ...standing, used: true };
156
+ this.#lastUse = { id, print: standing.view.print, at: this.#config.scheduler.now() };
157
+ }
158
+ /**
159
+ * A read after a key of the step (`null` = the read failed): the next revision, a new occurrence or the end, with the
160
+ * field to the manager as an evaluation sends it, but without the grace and the shield of an own answer, which stand
161
+ * right after the key. A used occurrence always ends here unless a new one replaces it, so the manager never keeps a
162
+ * field the step consumed. Returns the field that stands now; `null` = none.
163
+ */
164
+ refresh(screen) {
165
+ if (!this.#works())
166
+ return null;
167
+ if (this.#port.disposed() || !this.#waiting() || this.#unblocked)
168
+ this.#end();
169
+ else if (screen !== null)
170
+ this.#apply(screen);
171
+ if (this.#occurrence?.used === true)
172
+ this.#end();
173
+ const standing = this.current();
174
+ return standing === null ? null : liveDialogWire(standing.view, standing.id, standing.rev);
175
+ }
176
+ /** The driver published a card for the pane (`#showCard`): what it is decides whether the live card stands next to it. */
177
+ cardShown(active, event) {
178
+ const kind = kindOf(active, event);
179
+ const toolUse = event.type === 'permission-request' && event.input !== null && active.callId !== undefined;
180
+ this.#shown = {
181
+ active, kind, toolUse, at: this.#config.scheduler.now(),
182
+ ...(event.type === 'permission-request' && active.bodyPrint !== undefined ? { print: active.bodyPrint } : {}),
183
+ ...(event.type === 'permission-request' && event.input !== null && active.callId !== undefined
184
+ ? { call: { toolName: event.toolName, toolUseId: active.callId, input: event.input } }
185
+ : {}),
186
+ };
187
+ }
188
+ /** The driver held a card back instead of publishing it: the live card waits as long as that card does. */
189
+ cardHeld(active) {
190
+ this.#shown = { active, kind: 'held', toolUse: false, at: this.#config.scheduler.now() };
191
+ }
192
+ /**
193
+ * The driver told the manager a state (`agent-state`). Any state but `blocked` clears the manager's field, so the
194
+ * occurrence ends with it; until the manager hears `blocked` again a new field would be dropped, so none is issued.
195
+ * The driver tells one at each change of a CLI consent dialog, so here the module starts or stops following it.
196
+ */
197
+ stateSent(state) {
198
+ this.#unblocked = state !== 'blocked';
199
+ if (this.#unblocked)
200
+ this.#end();
201
+ this.#follow();
202
+ }
203
+ /** The driver is detached: no evaluation is ordered any more. */
204
+ dispose() {
205
+ this.#following = false;
206
+ this.#stopFollowing();
207
+ }
208
+ /**
209
+ * One look at the pane after an evaluation of the driver. The pane does not wait, or the manager was last told it does
210
+ * not: the occurrence ends. Within the grace of the block, of a held card or of an own answer nothing new is issued.
211
+ * A card with key buttons, a consent channel card or a layer 2 card ends the occurrence, unless the screen proves
212
+ * another dialog than the one of an own permission card (a desk decision in a queue leaves that card standing). The
213
+ * transcript entry and the no-hook episode of a permission card without buttons count only while the screen shows
214
+ * its fingerprint. Otherwise the view of a fresh screen issues an occurrence, the next revision of the standing one,
215
+ * or ends it when the screen has no dialog. A failed read changes nothing. Never throws.
216
+ */
217
+ async observe() {
218
+ if (!this.#works())
219
+ return;
220
+ try {
221
+ await this.#observe();
222
+ }
223
+ catch {
224
+ // A doubt leaves the card as it was; the next evaluation looks again.
225
+ }
226
+ finally {
227
+ this.#follow();
228
+ }
229
+ }
230
+ async #observe() {
231
+ if (!this.#waiting() || this.#unblocked) {
232
+ this.#end();
233
+ return;
234
+ }
235
+ if (this.#config.scheduler.now() - this.#port.blockedAt() < this.#config.graceMs)
236
+ return;
237
+ if (this.#occurrence === null && this.#port.shielded())
238
+ return;
239
+ const before = this.#standing();
240
+ if (before.kind === 'held')
241
+ return;
242
+ if (before.kind === 'own' && before.print === undefined) {
243
+ this.#end();
244
+ return;
245
+ }
246
+ const scope = this.#scope();
247
+ const screen = await this.#port.readDialog();
248
+ if (this.#port.disposed() || !this.#waiting() || this.#unblocked || this.#scope() !== scope || screen === null) {
249
+ return;
250
+ }
251
+ this.#apply(screen);
252
+ }
253
+ /** One screen applied: the view issues an occurrence or its next revision, or ends it; a held card keeps it. */
254
+ #apply(screen) {
255
+ const sight = this.#sight(screen);
256
+ if (sight === 'held')
257
+ return;
258
+ if (sight === null) {
259
+ this.#end();
260
+ return;
261
+ }
262
+ this.#show(sight);
263
+ }
264
+ /**
265
+ * The live card of `screen` under what stands for the dialog now; the one place the view is computed. `noClass`: a
266
+ * dialog in the session is judged with no registry class.
267
+ */
268
+ #sight(screen, noClass = false) {
269
+ let standing = this.#standing();
270
+ if (standing.kind === 'held')
271
+ return 'held';
272
+ if (standing.kind === 'own') {
273
+ const print = standing.print === undefined ? null : parseOptions(screen)?.bodyPrint ?? null;
274
+ if (print === null || print === standing.print)
275
+ return null;
276
+ // The own permission card describes another dialog than the one on screen: no card stands for this one.
277
+ standing = ANOTHER_DIALOG;
278
+ }
279
+ else if (standing.shape === 'degraded') {
280
+ standing = provenOn(screen, standing);
281
+ }
282
+ const start = this.#config.startDialog();
283
+ const place = start === null
284
+ ? { kind: 'session', cliDialog: noClass ? null : this.#config.cliReserve.cliWaiting }
285
+ : { kind: 'start', startDialog: start.id };
286
+ const view = liveDialogView(screen, {
287
+ level: this.#config.level, place, ownCard: false,
288
+ consent: this.#config.consentFacts(standing.toolUse, standing.episode),
289
+ });
290
+ if (view === null)
291
+ return null;
292
+ const bind = this.#bindOf(start);
293
+ const call = standing.toolUse ? standing.call : undefined;
294
+ return { view, bind, shape: standing.shape, cliDialog: liveClass(place), ...(call === undefined ? {} : { call }) };
295
+ }
296
+ /** The card that stands for the dialog now, from the driver's state; no read. */
297
+ #standing() {
298
+ if (this.#config.channelCard(true))
299
+ return { kind: 'own' };
300
+ const active = this.#port.activeReq();
301
+ const shown = this.#shown;
302
+ if (active === null) {
303
+ if (shown?.kind === 'held' && this.#config.scheduler.now() - shown.at < LIVE_HELD_MAX_MS)
304
+ return { kind: 'held' };
305
+ return { kind: 'card', shape: 'no-card', toolUse: false, episode: true };
306
+ }
307
+ // A card the module did not see published counts as one with buttons.
308
+ if (shown === null || shown.active !== active || shown.kind === 'held')
309
+ return { kind: 'own' };
310
+ const print = shown.print === undefined ? {} : { print: shown.print };
311
+ if (shown.kind === 'own')
312
+ return { kind: 'own', ...print };
313
+ const call = shown.call === undefined ? {} : { call: shown.call };
314
+ return { kind: 'card', shape: shown.kind, toolUse: shown.toolUse, episode: true, ...print, ...call };
315
+ }
316
+ /**
317
+ * What an occurrence is bound to under the facts now: the pane and its start dialog before the session starts, else
318
+ * the engine session and the registry episode.
319
+ */
320
+ #bindOf(start) {
321
+ return start === null ? this.#scope() : `pane|${start.id ?? start.title ?? ''}`;
322
+ }
323
+ /** What a session occurrence is bound to: the engine session and the registry episode. */
324
+ #scope() {
325
+ return `session|${this.#port.engineSession()}|${String(this.#config.cliReserve.cliEpisode)}`;
326
+ }
327
+ /** The module works for the pane: a level above `0` and a Claude Code pane inside the work area. */
328
+ #works() {
329
+ return this.#config.level !== 0 && this.#config.inScope && !isStateOnlyEngine(this.#config.engine);
330
+ }
331
+ /** The pane waits on a dialog now: the effective block of the driver or a CLI consent dialog. */
332
+ #waiting() {
333
+ return this.#port.blocked() || this.#port.consentDialog() !== null;
334
+ }
335
+ /**
336
+ * The driver's own poll evaluates the pane only through a block, so a consent dialog under herdr `idle` would get its
337
+ * field only at the next status event. While such a dialog stands without a block, the module orders the
338
+ * evaluation: at once for a dialog that just came up, then every `pollMs`, until the dialog closes, a block begins
339
+ * (the driver's poll takes over) or the driver is detached.
340
+ */
341
+ #follow() {
342
+ if (!this.#works())
343
+ return;
344
+ if (this.#port.disposed() || this.#port.consentDialog() === null || this.#port.blocked()) {
345
+ this.#following = false;
346
+ this.#stopFollowing();
347
+ return;
348
+ }
349
+ const first = !this.#following;
350
+ this.#following = true;
351
+ if (this.#followTimer !== null)
352
+ return;
353
+ this.#followTimer = this.#config.scheduler.setTimeout(() => {
354
+ this.#followTimer = null;
355
+ void this.#port.evaluate().catch(() => undefined);
356
+ }, first ? 0 : this.#config.pollMs);
357
+ }
358
+ #stopFollowing() {
359
+ if (this.#followTimer === null)
360
+ return;
361
+ this.#config.scheduler.clearTimeout(this.#followTimer);
362
+ this.#followTimer = null;
363
+ }
364
+ /**
365
+ * A view for the phone: a new occurrence when none stands, it is bound elsewhere or it is used, else the next
366
+ * revision when the fingerprint or the field changed. Within {@link LIVE_REISSUE_BLOCK_MS} after Enter or Esc the
367
+ * fingerprint they went to gets no new occurrence, and a used one ends. The field goes out only with a new occurrence
368
+ * or revision; the audit line at the issue and when the keys change.
369
+ */
370
+ #show({ view, bind, shape, cliDialog }) {
371
+ const body = JSON.stringify(liveDialogWire(view, '', 0));
372
+ const standing = this.#occurrence;
373
+ if (standing !== null && !standing.used && standing.bind === bind) {
374
+ if (standing.view.print === view.print && standing.body === body)
375
+ return;
376
+ this.#occurrence = { ...standing, rev: standing.rev + 1, view, body, shape };
377
+ this.#port.emit(liveDialogWire(view, standing.id, standing.rev + 1));
378
+ if (!sameKeys(standing.view.keys, view.keys))
379
+ this.#note(this.#occurrence, cliDialog);
380
+ return;
381
+ }
382
+ if (this.recentlyUsed() !== null && this.#lastUse?.print === view.print) {
383
+ this.#end();
384
+ return;
385
+ }
386
+ const id = this.#config.newId?.() ?? `${LIVE_ID_PREFIX}${randomBytes(6).toString('hex')}`;
387
+ this.#occurrence = { id, bind, rev: 0, view, body, shape, used: false };
388
+ this.#issued.push(id);
389
+ if (this.#issued.length > ISSUED_KEPT)
390
+ this.#issued.shift();
391
+ this.#port.emit(liveDialogWire(view, id, 0));
392
+ this.#note(this.#occurrence, cliDialog);
393
+ }
394
+ #note(occurrence, cliDialog) {
395
+ const { view } = occurrence;
396
+ this.#port.audit({
397
+ reqId: occurrence.id, liveShape: occurrence.shape, liveKeys: [...view.keys],
398
+ ...(view.why === undefined ? {} : { liveWhy: view.why }),
399
+ ...(cliDialog === null ? {} : { cliDialog }),
400
+ });
401
+ }
402
+ /** The occurrence ends and the field goes out. */
403
+ #end() {
404
+ if (this.#occurrence === null)
405
+ return;
406
+ this.#occurrence = null;
407
+ this.#port.emit(null);
408
+ }
409
+ }
410
+ function sameKeys(a, b) {
411
+ return a.length === b.length && a.every((key, i) => key === b[i]);
412
+ }
@@ -0,0 +1,261 @@
1
+ import { LIVE_ENTER_KEY, LIVE_ESCAPE_KEY } from '../../herdr/dialogs/live/policy.js';
2
+ import { LIVE_TAB_GLYPHS } from '../../herdr/dialogs/live/model.js';
3
+ import { LIVE_CURSOR } from '../../herdr/dialogs/live/view.js';
4
+ import { isStateOnlyEngine } from '../../herdr/types.js';
5
+ import { STALE } from '../types.js';
6
+ import { ESC_SETTLE_MS } from './commands.js';
7
+ const NOT_SHOWN = { kind: 'not-shown' };
8
+ const STALE_KEY = { kind: 'stale' };
9
+ const SEND_OFF = { kind: 'send-off' };
10
+ const refusedKey = (reason) => ({ kind: 'refused', reason });
11
+ /** The region text with the cursor glyph blanked: two views that differ only there differ by the cursor. */
12
+ const withoutCursor = (text) => text.replaceAll(LIVE_CURSOR, ' ');
13
+ /**
14
+ * The first line of a region with a letter, without the checkbox glyphs of a form tab bar: the dialog title. A toggled
15
+ * box (☐ to ☒ in the tab) keeps the title; two forms whose tabs read alike then share it.
16
+ */
17
+ const titleOf = (text) => (text.split('\n').find((line) => /\p{L}/u.test(line))?.trim() ?? '')
18
+ .replace(LIVE_TAB_GLYPHS, '');
19
+ /**
20
+ * What the read after a key saw against the view the key went to: a failed read (`unknown`), no live card (`gone`),
21
+ * a consent channel card (`other-dialog`), the same view (`same`), the cursor alone moved (`cursor`), the same dialog
22
+ * changed (`changed`, a toggled checkbox) or another dialog (`other-dialog`).
23
+ */
24
+ export function liveVerifyOutcome(before, after, sight) {
25
+ if (after === null)
26
+ return 'unknown';
27
+ if (sight === null)
28
+ return 'gone';
29
+ if (sight === 'channel')
30
+ return 'other-dialog';
31
+ if (sight.view.print === before.print)
32
+ return 'same';
33
+ if (withoutCursor(sight.view.text) === withoutCursor(before.text))
34
+ return 'cursor';
35
+ return titleOf(sight.view.text) === titleOf(before.text) ? 'changed' : 'other-dialog';
36
+ }
37
+ export class LiveStep {
38
+ #config;
39
+ #port;
40
+ /** A key of the live card or a bound `deny` is in flight. */
41
+ #busy = false;
42
+ /** Bound denies that used an occurrence right before their Esc; its field ends when they settle. */
43
+ #denyUsed = new WeakSet();
44
+ constructor(config, port) {
45
+ this.#config = config;
46
+ this.#port = port;
47
+ }
48
+ /** One key of the live card. Never rejects. */
49
+ key(body) {
50
+ const { cards } = this.#config;
51
+ if (isStateOnlyEngine(this.#config.engine)) {
52
+ this.#note(body, {}, 'refused', null);
53
+ return Promise.resolve(NOT_SHOWN);
54
+ }
55
+ const occurrence = cards.occurrence(body.id);
56
+ if (occurrence === null) {
57
+ const issued = cards.issued(body.id);
58
+ const stale = issued || cards.current() !== null;
59
+ this.#note(body, issued ? { reqId: body.id } : {}, 'refused', stale ? 'stale-card' : null);
60
+ return Promise.resolve(stale ? STALE_KEY : NOT_SHOWN);
61
+ }
62
+ const known = { reqId: body.id };
63
+ if (this.#busy)
64
+ return Promise.resolve(this.#refuse(body, known, 'in-flight'));
65
+ if (!occurrence.view.keys.includes(body.key))
66
+ return Promise.resolve(this.#refuse(body, known, 'terminal-only'));
67
+ this.#busy = true;
68
+ return this.#port.enqueue(() => this.#run(body))
69
+ .then((outcome) => outcome ?? STALE_KEY, () => STALE_KEY)
70
+ .finally(() => { this.#busy = false; });
71
+ }
72
+ /**
73
+ * Binds a `deny` of today's card when the driver accepts it, synchronously and before the driver queue. `null` = a
74
+ * key of the live card is in flight: the deny is refused (`in-flight`). A binding to a live occurrence holds the
75
+ * in-flight lock until {@link release}. With none standing it binds to none and keeps the fingerprint a live Enter or
76
+ * Esc went to within the re-issue block; whether that key decided the dialog is known only from the screen right
77
+ * before the Esc ({@link denyKey}).
78
+ */
79
+ bindDeny() {
80
+ if (this.#busy)
81
+ return null;
82
+ const { cards } = this.#config;
83
+ const standing = cards.current();
84
+ if (standing !== null) {
85
+ this.#busy = true;
86
+ return { id: standing.id, holds: true, decided: null };
87
+ }
88
+ return { id: null, holds: false, decided: cards.recentPrint() };
89
+ }
90
+ /**
91
+ * A bound `deny` right before its Esc, with no `await` up to the key: the occurrence it was bound to takes keys,
92
+ * still stands for the pane as it is now (the same engine session and registry episode, or the same start dialog)
93
+ * and is used now, so a key of the live card for it gets `stale`; a used, replaced or rebound one ends the deny
94
+ * without a key (`stale`). A deny bound to none uses the occurrence that takes keys now, unless Enter or Esc of the
95
+ * live card went a moment ago, or when the deny came, to the dialog on `screen` (the fresh read right before the Esc;
96
+ * `null` = no read).
97
+ * `null` = today's Esc goes.
98
+ */
99
+ denyKey(binding, screen) {
100
+ const { cards } = this.#config;
101
+ if (binding.id !== null) {
102
+ if (cards.boundNow(binding.id) === null)
103
+ return Promise.resolve(STALE);
104
+ cards.use(binding.id);
105
+ this.#denyUsed.add(binding);
106
+ return null;
107
+ }
108
+ if (cards.usedOn(screen, binding.decided))
109
+ return Promise.resolve(STALE);
110
+ const standing = cards.current();
111
+ if (standing !== null) {
112
+ cards.use(standing.id);
113
+ this.#denyUsed.add(binding);
114
+ }
115
+ return null;
116
+ }
117
+ /**
118
+ * The bound `deny` settled: the lock it holds goes, and an occurrence it used ends with its field, as after Enter or
119
+ * Esc of the live card (the Esc went, or may have reached the pane), so the phone holds no card whose keys are stale.
120
+ * Returns `outcome`.
121
+ */
122
+ release(binding, outcome) {
123
+ if (binding.holds)
124
+ this.#busy = false;
125
+ if (this.#denyUsed.delete(binding))
126
+ this.#config.cards.refresh(null);
127
+ return outcome;
128
+ }
129
+ async #run(body) {
130
+ const { cards } = this.#config;
131
+ const port = this.#port;
132
+ const before = cards.occurrence(body.id);
133
+ if (port.disposed() || before === null)
134
+ return this.#stale(body);
135
+ if (before.rev !== body.rev)
136
+ return this.#refuse(body, { reqId: body.id }, 'screen-changed');
137
+ const noted = await this.#noteFreshRegistry();
138
+ const screen = await port.readFresh();
139
+ // No `await` from here to the key.
140
+ const occurrence = cards.occurrence(body.id);
141
+ if (port.disposed() || occurrence === null)
142
+ return this.#stale(body);
143
+ if (occurrence.rev !== body.rev || screen === null)
144
+ return this.#changed(body, screen);
145
+ const sight = cards.viewOf(screen, !noted);
146
+ if (sight === 'channel')
147
+ return this.#refuse(body, { reqId: body.id }, 'consent-dialog');
148
+ if (sight === null || sight.view.print !== occurrence.view.print)
149
+ return this.#changed(body, screen);
150
+ if (sight.bind !== occurrence.bind) {
151
+ cards.refresh(screen);
152
+ return this.#stale(body);
153
+ }
154
+ const fields = {
155
+ reqId: body.id,
156
+ ...(sight.cliDialog === null ? {} : { cliDialog: sight.cliDialog }),
157
+ ...(sight.call === undefined ? {} : { toolUseId: sight.call.toolUseId }),
158
+ };
159
+ if (!sight.view.keys.includes(body.key)) {
160
+ cards.refresh(screen);
161
+ return this.#refuse(body, fields, 'terminal-only');
162
+ }
163
+ const enter = body.key === LIVE_ENTER_KEY;
164
+ const ends = enter || body.key === LIVE_ESCAPE_KEY;
165
+ if (enter && sight.call !== undefined) {
166
+ this.#config.screenFallback.liveKeyNoted(sight.call.toolName, sight.call.input);
167
+ }
168
+ if (ends)
169
+ cards.use(body.id);
170
+ // The engine session the key goes to: its line keeps it when another session comes during the call.
171
+ const engine = port.engineSession();
172
+ const sent = await port.sendLiveKey(body.key, enter
173
+ ? {
174
+ method: 'approve', keys: [body.key], ...fields,
175
+ ...(sight.call === undefined ? {} : { toolName: sight.call.toolName }),
176
+ ...(sight.view.cursorLabel === null ? {} : { optionLabel: sight.view.cursorLabel }),
177
+ }
178
+ : { method: 'send_keys', keys: [body.key], ...fields });
179
+ if (sent !== 'sent') {
180
+ // The key may have reached the pane: the used occurrence ends with its field, and the key never goes again.
181
+ if (ends)
182
+ cards.refresh(null);
183
+ if (sent === 'off') {
184
+ this.#note(body, fields, 'refused', null, engine);
185
+ return SEND_OFF;
186
+ }
187
+ this.#note(body, fields, 'failed', 'send-failed', engine);
188
+ return refusedKey('send-failed');
189
+ }
190
+ this.#note(body, fields, 'sent', null, engine);
191
+ return this.#after(body, occurrence.view, ends);
192
+ }
193
+ /**
194
+ * A fresh registry read of the engine session goes to the driver as a registry signal: the class and the episode the
195
+ * key is judged by are the ones it gives, not those of the last manager signal. `false` = no read reached the
196
+ * driver (no reader, no engine session, a failed read, a signal that knows no class of the session, or another
197
+ * engine session by the time it came back), so the key is judged with no registry class.
198
+ */
199
+ async #noteFreshRegistry() {
200
+ const read = this.#config.registryRead;
201
+ const port = this.#port;
202
+ const engine = port.engineSession();
203
+ if (read === undefined || engine === '')
204
+ return false;
205
+ let signal;
206
+ try {
207
+ signal = await read(engine);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ if (signal.kind === 'unknown' || port.disposed() || port.engineSession() !== engine)
213
+ return false;
214
+ port.noteRegistry(signal);
215
+ return true;
216
+ }
217
+ /** The read after a key that went: the card the phone gets back and the verify line. */
218
+ async #after(body, before, ends) {
219
+ const port = this.#port;
220
+ await port.sleep(this.#config.settleMs ?? ESC_SETTLE_MS);
221
+ const after = await port.readFresh();
222
+ const { cards } = this.#config;
223
+ const outcome = liveVerifyOutcome(before, after, after === null ? null : cards.viewOf(after));
224
+ const live = cards.refresh(after);
225
+ // A driver disposed during the wait writes nothing: its data directory may already be gone.
226
+ if (!port.disposed()) {
227
+ port.audit({ method: 'live-verify', reqId: body.id, liveKey: body.key, liveOutcome: outcome });
228
+ }
229
+ if (ends)
230
+ port.reevaluate();
231
+ return { kind: 'sent', live };
232
+ }
233
+ /** The occurrence no longer takes keys, or no longer stands for the session on screen. */
234
+ #stale(body) {
235
+ this.#note(body, { reqId: body.id }, 'refused', 'stale-card');
236
+ return STALE_KEY;
237
+ }
238
+ /** The view under the card changed: the phone gets the view the step read, the key none. */
239
+ #changed(body, screen) {
240
+ if (screen !== null)
241
+ this.#config.cards.refresh(screen);
242
+ return this.#refuse(body, { reqId: body.id }, 'screen-changed');
243
+ }
244
+ #refuse(body, fields, reason) {
245
+ this.#note(body, fields, 'refused', reason);
246
+ return refusedKey(reason);
247
+ }
248
+ /**
249
+ * The `live-key` line of one key request. `engine`: the engine session the line names; after a client call, the one
250
+ * of the moment before the call, else the one now.
251
+ */
252
+ #note(body, fields, result, reason, engine = this.#port.engineSession()) {
253
+ if (this.#port.disposed())
254
+ return;
255
+ this.#port.audit({
256
+ method: 'live-key', liveKey: body.key, liveRev: body.rev, liveResult: result, ...fields,
257
+ ...(engine === '' ? {} : { engineSessionId: engine }),
258
+ ...(reason === null ? {} : { reason }),
259
+ });
260
+ }
261
+ }