@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,233 @@
1
+ /**
2
+ * The main checkout of a directory inside a linked git worktree, read from the `.git` file and `commondir` without
3
+ * running `git`. Reads go through a port that resolves links and reads text, so the caller decides what a read may
4
+ * see and when a changed file stops the read. A layout the function cannot read unambiguously comes back as "no
5
+ * proof" with the `.git` path; the caller turns it into its own refusal.
6
+ *
7
+ * `ProjectRoots` is that read for session summaries: on the work-area disk port, only for a main checkout inside the
8
+ * work area, with conclusive answers remembered per directory until the session's git watcher reports a change. It
9
+ * never runs `git` and never writes.
10
+ */
11
+ import path from 'node:path';
12
+ import { areaDiskOf, inExcludedOnDisk, inWorkAreaOnDisk } from './config/work-area.js';
13
+ import { DIRECT_DISK } from './folder-gate/disk.js';
14
+ import { DISK_LAYOUT } from './herdr/commands/registry.js';
15
+ /** Linked worktree gita: plik `.git` z jedną linią `gitdir: <katalog>`, a w tym katalogu `commondir`. */
16
+ const GIT_FILE_PREFIX = 'gitdir: ';
17
+ const GIT_COMMONDIR = 'commondir';
18
+ /** Katalog i wszystkie wyżej, od niego do korzenia. */
19
+ export function upwards(dir) {
20
+ const out = [];
21
+ let current = path.resolve(dir);
22
+ for (;;) {
23
+ out.push(current);
24
+ const parent = path.dirname(current);
25
+ if (parent === current)
26
+ return out;
27
+ current = parent;
28
+ }
29
+ }
30
+ /**
31
+ * Główny checkout dla `cwd` w linked worktree gita albo `null` (opis modułu; dokumentacja Claude Code: settings,
32
+ * „Where Claude Code keeps the local file in a git repository”; worktrees, „What worktrees share with the main
33
+ * checkout”). Najbliższy `.git` od `cwd` w górę: katalog = zwykły checkout (`null`); plik = jedna linia
34
+ * `gitdir: <katalog>` (ścieżka bezwzględna albo względna wobec katalogu pliku), a w tym katalogu `commondir` ze
35
+ * wspólnym katalogiem repozytorium; bez `commondir` to nie worktree (submoduł, `--separate-git-dir`), korzeniem jest
36
+ * katalog z plikiem `.git`. Wspólny katalog musi się nazywać `.git`, główny checkout to katalog nad nim; repozytorium
37
+ * bare, `gitdir` bez katalogu i każdy inny układ = brak dowodu. Odczyt bez uruchamiania `git`; pliki `.git` i
38
+ * `commondir` przechodzą przez sprawdzenie startu, katalogi gita nie (zmieniają się przy każdej operacji gita),
39
+ * dowiązania tak.
40
+ */
41
+ export async function mainCheckoutOf(reader, cwd) {
42
+ for (const dir of upwards(cwd)) {
43
+ const dotGit = path.join(dir, DISK_LAYOUT.gitDir);
44
+ const found = await reader.linked(dotGit);
45
+ if (found.info === null)
46
+ continue;
47
+ if (found.info.kind === 'dir')
48
+ return { ok: true, root: null };
49
+ const lines = (await reader.text(dotGit) ?? '').split('\n').filter((line) => line.trim() !== '');
50
+ const line = lines.length === 1 ? lines[0] ?? '' : '';
51
+ const target = line.startsWith(GIT_FILE_PREFIX) ? line.slice(GIT_FILE_PREFIX.length).trim() : '';
52
+ if (target === '')
53
+ return { ok: false, dotGit };
54
+ const gitDir = await reader.linked(path.isAbsolute(target) ? target : `${path.dirname(found.real)}/${target}`);
55
+ if (gitDir.info?.kind !== 'dir')
56
+ return { ok: false, dotGit };
57
+ const common = (await reader.text(path.join(gitDir.real, GIT_COMMONDIR)))?.trim();
58
+ if (common === undefined)
59
+ return { ok: true, root: null };
60
+ if (common === '' || common.includes('\n'))
61
+ return { ok: false, dotGit };
62
+ const commonDir = await reader.linked(path.isAbsolute(common) ? common : `${gitDir.real}/${common}`);
63
+ if (commonDir.info?.kind !== 'dir' || path.basename(commonDir.real) !== DISK_LAYOUT.gitDir) {
64
+ return { ok: false, dotGit };
65
+ }
66
+ return { ok: true, root: path.dirname(commonDir.real) };
67
+ }
68
+ return { ok: true, root: null };
69
+ }
70
+ /** Ceiling of a `.git` file and of `commondir`: one path, not kilobytes. A longer file is not a git pointer. */
71
+ const POINTER_MAX_BYTES = 4 * 1024;
72
+ /** Codes of a lookup that finds nothing under the path. */
73
+ const NOTHING_UNDER_PATH = new Set(['ENOENT', 'ENOTDIR']);
74
+ const nothingUnder = (error) => NOTHING_UNDER_PATH.has(error.code ?? '');
75
+ /**
76
+ * The read port of {@link mainCheckoutOf} on a work-area disk. A symlink in the last segment of a pointer path
77
+ * (`.git`, the `gitdir` target, the shared directory) stops the read, because such a link could put a session under
78
+ * any repository's main checkout; links earlier on the path resolve. Pointer files are read only as regular files
79
+ * within {@link POINTER_MAX_BYTES} and never through a link, so a FIFO under the name cannot hold the read.
80
+ */
81
+ function checkoutReaderOf(disk) {
82
+ return {
83
+ async linked(file) {
84
+ let entry;
85
+ try {
86
+ entry = await disk.call('lstat', { path: file });
87
+ }
88
+ catch (error) {
89
+ if (nothingUnder(error))
90
+ return { real: file, info: null };
91
+ throw error;
92
+ }
93
+ if (entry.isSymbolicLink())
94
+ throw new Error(`a symlink stands at ${file}`);
95
+ const kind = entry.isDirectory() ? 'dir' : entry.isFile() ? 'file' : 'other';
96
+ return { real: await disk.call('realpath', { path: file }), info: { kind } };
97
+ },
98
+ async text(file) {
99
+ let head;
100
+ try {
101
+ head = await disk.call('readHead', { path: file, maxBytes: POINTER_MAX_BYTES, followSymlink: false });
102
+ }
103
+ catch (error) {
104
+ if (nothingUnder(error))
105
+ return null;
106
+ throw error;
107
+ }
108
+ if (head === null || head.truncated)
109
+ throw new Error(`not a git pointer file: ${file}`);
110
+ return head.bytes.toString('utf8');
111
+ },
112
+ };
113
+ }
114
+ const REFUSED = { kind: 'refused' };
115
+ /**
116
+ * The main checkout a session in `cwd` belongs to, for its summary (`projectRoot`); `undefined` for a directory that
117
+ * is a main checkout itself, lies in no repository, in a submodule, or belongs to a main checkout outside the work
118
+ * area, where actions of the project's group would reach a directory the server does not serve.
119
+ *
120
+ * Reads go through the work-area disk port, so a guarded folder that is closed refuses them without a macOS consent
121
+ * window; a directory in an excluded or closed folder is refused before any read. A conclusive answer (a main
122
+ * checkout, or none) is remembered by the real path of the directory, so other spellings of it share the answer. A
123
+ * git watcher event ({@link forget}) reads again at once and serves the old answer until the new one settles, so
124
+ * the session does not leave its group between the two. A refusal or a failed read is not remembered: the next
125
+ * summary reads again, which is how a folder that opens later gives the field.
126
+ */
127
+ export class ProjectRoots {
128
+ #roots;
129
+ #home;
130
+ #disk;
131
+ #changed;
132
+ #known = new Map();
133
+ #pending = new Map();
134
+ #reads = 0;
135
+ constructor(config) {
136
+ this.#roots = config.roots;
137
+ this.#home = config.home;
138
+ this.#disk = config.disk ?? DIRECT_DISK;
139
+ this.#changed = config.changed;
140
+ }
141
+ /**
142
+ * The answer for a summary, without waiting: the remembered main checkout of `cwd`, or `undefined`. A directory
143
+ * without a fresh answer starts a read unless one runs; when it settles with another answer, `changed` gets `cwd`.
144
+ */
145
+ peek(cwd) {
146
+ const key = this.#keyOf(cwd);
147
+ const known = this.#known.get(key);
148
+ if (known === undefined || known.stale)
149
+ void this.#start(cwd, key, false);
150
+ return known?.root ?? undefined;
151
+ }
152
+ /** The main checkout of `cwd` now: the remembered fresh answer, else the read in flight or a new one. */
153
+ read(cwd) {
154
+ const key = this.#keyOf(cwd);
155
+ const known = this.#known.get(key);
156
+ if (known !== undefined && !known.stale)
157
+ return Promise.resolve(known.root ?? undefined);
158
+ return this.#start(cwd, key, false);
159
+ }
160
+ /**
161
+ * The git watcher saw a change in the repositories of these session directories: each one with an answer or a read
162
+ * in flight reads again now; a read already in flight may have missed the change, so its answer is dropped.
163
+ */
164
+ forget(cwds) {
165
+ for (const cwd of cwds) {
166
+ const key = this.#keyOf(cwd);
167
+ const known = this.#known.get(key);
168
+ if (known === undefined && !this.#pending.has(key))
169
+ continue;
170
+ if (known !== undefined)
171
+ known.stale = true;
172
+ void this.#start(cwd, key, true);
173
+ }
174
+ }
175
+ /** The real path of `cwd` (metadata only, never waits for a consent window); as written when it does not resolve. */
176
+ #keyOf(cwd) {
177
+ try {
178
+ return this.#disk.sync('realpath', { path: cwd });
179
+ }
180
+ catch {
181
+ return path.resolve(cwd);
182
+ }
183
+ }
184
+ /** Joins the read in flight for `key`, or starts one; `restart` starts a new one that takes over its askers. */
185
+ #start(cwd, key, restart) {
186
+ const running = this.#pending.get(key);
187
+ if (running !== undefined && !restart) {
188
+ running.askers.add(cwd);
189
+ return running.answer;
190
+ }
191
+ this.#reads += 1;
192
+ const id = this.#reads;
193
+ const askers = new Set(running?.askers ?? []).add(cwd);
194
+ const answer = this.#lookUp(cwd).then((verdict) => this.#settle(key, id, verdict));
195
+ this.#pending.set(key, { id, askers, answer });
196
+ return answer;
197
+ }
198
+ /** Remembers a conclusive answer, drops a refused one, and tells the askers when the served answer changed. */
199
+ #settle(key, id, verdict) {
200
+ const found = verdict.kind === 'root' ? verdict.root : null;
201
+ const pending = this.#pending.get(key);
202
+ if (pending?.id !== id)
203
+ return found ?? undefined;
204
+ this.#pending.delete(key);
205
+ const served = this.#known.get(key)?.root ?? null;
206
+ if (verdict.kind === 'root')
207
+ this.#known.set(key, { root: verdict.root, stale: false });
208
+ else
209
+ this.#known.delete(key);
210
+ if (found !== served)
211
+ for (const cwd of pending.askers)
212
+ this.#changed(cwd);
213
+ return found ?? undefined;
214
+ }
215
+ async #lookUp(cwd) {
216
+ try {
217
+ if (!path.isAbsolute(cwd))
218
+ return REFUSED;
219
+ const area = areaDiskOf(this.#disk);
220
+ if (inExcludedOnDisk(cwd, this.#roots, this.#home, area))
221
+ return REFUSED;
222
+ const main = await mainCheckoutOf(checkoutReaderOf(this.#disk), cwd);
223
+ if (!main.ok)
224
+ return REFUSED;
225
+ if (main.root === null)
226
+ return { kind: 'root', root: null };
227
+ return inWorkAreaOnDisk(main.root, this.#roots, this.#home, area) ? { kind: 'root', root: main.root } : REFUSED;
228
+ }
229
+ catch {
230
+ return REFUSED;
231
+ }
232
+ }
233
+ }
@@ -1,4 +1,4 @@
1
- import { MAX_FILES_PER_MESSAGE, MAX_IMAGES_PER_MESSAGE, MAX_MESSAGE_BODY_BYTES, checkMessageImageLimits, closeBodySchema, createSessionBodySchema, permissionDecisionBodySchema, sessionModeBodySchema, sessionModelBodySchema, } from '@rarog/shared';
1
+ import { MAX_FILES_PER_MESSAGE, MAX_IMAGES_PER_MESSAGE, MAX_MESSAGE_BODY_BYTES, checkMessageImageLimits, closeBodySchema, createSessionBodySchema, dialogKeyBodySchema, permissionDecisionBodySchema, sessionModeBodySchema, sessionModelBodySchema, } from '@rarog/shared';
2
2
  import { COMPANION_BUSY_ERROR, COMPANION_CLI_ERROR, COMPANION_DISABLED_ERROR, COMPANION_LIMIT_ERROR, COMPANION_SESSIONS_DISABLED_ERROR, COMPANION_TIMEOUT_ERROR, companionTurnsCountSchema, answersBodySchema, companionAskBodySchema, messageBodySchema, queueTakeBackBodySchema, restartBodySchema, seenBodySchema, } from '@rarog/shared/rest';
3
3
  import { say } from '@rarog/shared/sentences';
4
4
  import { redact } from '../auth/index.js';
@@ -6,9 +6,11 @@ import { sendDownload } from '../files/send-file.js';
6
6
  import { conversationToken } from '../companion/conversation.js';
7
7
  import { readSettledTurns } from '../companion/turns-settle.js';
8
8
  import { clientLabel, diffErrorStatus, managerErrorStatus, methodNotAllowed, parseBody, readJsonBody, readValidatedBody, recheckDevice, sendError, sendFailure, sendJson, } from '../router.js';
9
+ import { branchDiffFile, branchDiffFiles } from '../sessions/branch-diff.js';
9
10
  import { parseLastEventId } from '../sse.js';
10
11
  import { decodeSegment } from './context.js';
11
12
  import { checkCwd } from './projects.js';
13
+ import { isStateOnlyEngine } from '../herdr/engines.js';
12
14
  /**
13
15
  * Sprawdza model podany przez klienta wobec allow-listy serwera.
14
16
  *
@@ -113,6 +115,29 @@ const sendDecision = (res, result) => {
113
115
  }
114
116
  sendError(res, 410, 'gone', say('rest.decision-expired'));
115
117
  };
118
+ /**
119
+ * The outcome of a live card key as the answer of `POST /api/sessions/:id/dialog-key`: 200 `{live}` (the key went),
120
+ * 409 (no live card), 410 `stale-card` (another or a used occurrence), 422 with the refusal body of a decision (no key
121
+ * went, or `send-failed`: the key may have reached the pane and never goes again), 503 (the write channel is closed).
122
+ */
123
+ const sendDialogKey = (res, outcome) => {
124
+ switch (outcome.kind) {
125
+ case 'sent':
126
+ sendJson(res, 200, { live: outcome.live });
127
+ return;
128
+ case 'not-shown':
129
+ sendError(res, 409, 'no-live-card', say('dialogs.refuse.stale-card'));
130
+ return;
131
+ case 'stale':
132
+ sendError(res, 410, 'stale-card', say('dialogs.refuse.stale-card'));
133
+ return;
134
+ case 'refused':
135
+ sendError(res, 422, 'refused', say(`dialogs.refuse.${outcome.reason}`), { reason: outcome.reason });
136
+ return;
137
+ case 'send-off':
138
+ sendError(res, 503, 'herdr-send-off', say('session.herdr-read-only'));
139
+ }
140
+ };
116
141
  /**
117
142
  * Uruchamia akcję managera i mapuje wyjątki na 404/409/500.
118
143
  *
@@ -243,6 +268,34 @@ export async function routeSessions(ctx, req, res, rq) {
243
268
  sendJson(res, 200, answer);
244
269
  return true;
245
270
  }
271
+ /*
272
+ * The branch diff of a coordinator's thread (`sessions/branch-diff.ts`): `GET …/branch-diff/files` (files and
273
+ * commits of the branch past its base) and `GET …/branch-diff/file?path=…` (one file's patch), refusing with the
274
+ * codes of the routes above; a session that is no thread of a project gets 400 `bad-request` with a sentence.
275
+ */
276
+ if (action === 'branch-diff' && segments.length === 5 && (segments[4] === 'files' || segments[4] === 'file')) {
277
+ if (method !== 'GET')
278
+ return methodNotAllowed(res, 'GET');
279
+ const port = manager.branchDiffPort();
280
+ let answer;
281
+ try {
282
+ answer = segments[4] === 'files'
283
+ ? await branchDiffFiles(sessionId, port)
284
+ : await branchDiffFile(sessionId, url.searchParams.get('path') ?? '', port);
285
+ }
286
+ catch (err) {
287
+ const status = diffErrorStatus(err);
288
+ if (status === 500)
289
+ log.error(`manager action failed: ${redact(err, secrets)}`);
290
+ if (!res.headersSent)
291
+ sendFailure(res, status, err, 'diff');
292
+ return true;
293
+ }
294
+ if (!recheckDevice(req, res, 'while reading the branch diff of'))
295
+ return true;
296
+ sendJson(res, 200, answer);
297
+ return true;
298
+ }
246
299
  /*
247
300
  * GET /api/sessions/:id/files?dir=<rel> → one directory of the session (`files/session-files.ts`): the gate of the
248
301
  * file routes, the listing, git's `ignored` labels. With `RAROG_FILES=0` the route does not exist: 404 as an
@@ -447,7 +500,7 @@ export async function routeSessions(ctx, req, res, rq) {
447
500
  const session = manager.get(sessionId);
448
501
  // Sesja poza zasięgiem i wpis Codexa nie oddają niczego z katalogu panelu: to ta
449
502
  // sama granica co transkrypt i diff, a czytnik nie jest o nic pytany.
450
- const closed = session === undefined || session.outOfScope === true || session.engine === 'codex';
503
+ const closed = session === undefined || session.outOfScope === true || isStateOnlyEngine(session.engine);
451
504
  const image = closed || deps.readUpload === undefined
452
505
  ? null
453
506
  : await deps.readUpload(session.cwd, decodeSegment(segments[4] ?? ''));
@@ -783,6 +836,19 @@ export async function routeSessions(ctx, req, res, rq) {
783
836
  }
784
837
  return true;
785
838
  }
839
+ /*
840
+ * POST /api/sessions/:id/dialog-key {id, rev, key}: one key of the live dialog card (`docs/dialogs.md`, "Live
841
+ * dialog card"). The manager answers 404, 409 during a restart and 400 outside the work area with its sentence;
842
+ * the outcome of the key maps in `sendDialogKey`. No retry on the server's side: a key goes at most once.
843
+ */
844
+ if (action === 'dialog-key' && segments.length === 4) {
845
+ const body = await readValidatedBody(req, res, config, dialogKeyBodySchema);
846
+ if (body === null)
847
+ return true;
848
+ return runManagerAction(res, log, secrets, async () => {
849
+ sendDialogKey(res, await manager.dialogKey(sessionId, body));
850
+ }, 'message');
851
+ }
786
852
  if (action === 'permissions' && segments.length === 5) {
787
853
  const permId = decodeSegment(segments[4] ?? '');
788
854
  const body = await readValidatedBody(req, res, config, permissionDecisionBodySchema);
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The branch diff routes of a coordinator's thread (`GET /api/sessions/:id/branch-diff/files` and
3
+ * `…/branch-diff/file?path=…`): the scope gate of the session diff, the main checkout of the session read fresh, then
4
+ * the collectors of `git-branch-diff.ts`. A session that is no thread of a project, or whose branch has no base, gets a
5
+ * refusal with a sentence (400 `bad-request`); git failures and bad paths throw `DiffError` with the codes of the
6
+ * session diff routes. The demo answers from its fixed data. It runs no git itself and does not import `manager.ts`.
7
+ */
8
+ import { DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR } from '@rarog/shared';
9
+ import { say } from '@rarog/shared/sentences';
10
+ import { collectBranchDiffFile, collectBranchDiffList } from '../git-branch-diff.js';
11
+ import { DiffError, validateDiffPath } from '../git-diff.js';
12
+ import { ProjectRoots } from '../project-root.js';
13
+ import { BadRequestError } from './errors.js';
14
+ import { diffSession } from './session-scope.js';
15
+ const REFUSALS = {
16
+ 'no-project-root': () => new BadRequestError(say('rest.branch-diff-no-project')),
17
+ 'no-base': () => new BadRequestError(say('rest.branch-diff-no-base')),
18
+ };
19
+ /**
20
+ * The main checkout of the session directory, read now: the rule of the summaries' `projectRoot` (a main checkout
21
+ * inside the work area, read through the work-area disk), without their memory, so a worktree removed or moved since
22
+ * the last summary is seen at once.
23
+ */
24
+ function projectRootOf(cwd, port) {
25
+ return new ProjectRoots({
26
+ roots: port.roots, home: port.home, ...(port.disk === undefined ? {} : { disk: port.disk }), changed: () => { },
27
+ }).read(cwd);
28
+ }
29
+ /** `GET …/branch-diff/files`: the files and commits of the thread's branch past its base. */
30
+ export async function branchDiffFiles(id, port) {
31
+ const session = diffSession(id, port);
32
+ if (session === null)
33
+ return port.demoList();
34
+ const projectRoot = await projectRootOf(session.cwd, port);
35
+ const answer = await collectBranchDiffList({ cwd: session.cwd, projectRoot }, { run: port.run, runNumstat: port.runNumstat });
36
+ if (!answer.ok)
37
+ throw REFUSALS[answer.refusal]();
38
+ return answer.value;
39
+ }
40
+ /** `GET …/branch-diff/file?path=…`: the patch of one file of that list. */
41
+ export async function branchDiffFile(id, path, port) {
42
+ const session = diffSession(id, port);
43
+ // The shape check stands before the demo branch: `?path=../x` is 400 there too, as in production.
44
+ if (validateDiffPath(path) === null)
45
+ throw new DiffError(DIFF_BAD_PATH_ERROR);
46
+ if (session === null) {
47
+ const patch = port.demoFile(path);
48
+ if (patch === null)
49
+ throw new DiffError(DIFF_FILE_NOT_FOUND_ERROR);
50
+ return patch;
51
+ }
52
+ const projectRoot = await projectRootOf(session.cwd, port);
53
+ const answer = await collectBranchDiffFile({ cwd: session.cwd, projectRoot }, path, { run: port.run });
54
+ if (!answer.ok)
55
+ throw REFUSALS[answer.refusal]();
56
+ return answer.value;
57
+ }
@@ -1,6 +1,7 @@
1
1
  import { cliProcessStartOf, cliUpdateFor, cliWaitingOf, runningCliVersion } from '../cli-version.js';
2
2
  import { cliAcceptsNotes } from './question-card.js';
3
3
  import { CLI_VERSION_POLL_MS, CLI_WAITING_POLL_MS, HERDR_MODE_UNKNOWN_MESSAGE, herdrDialogStandsMessage, } from './state-sentences.js';
4
+ import { isStateOnlyEngine } from '../herdr/engines.js';
4
5
  /** Readings of the CLI registry and the two ticks that refresh them; one instance per manager. */
5
6
  export class CliRegistryState {
6
7
  #config;
@@ -23,6 +24,8 @@ export class CliRegistryState {
23
24
  * prawa ruszać mimochodem.
24
25
  */
25
26
  #cliRegistry = null;
27
+ /** Whether the fast tick has given an accepted reading; from then on {@link cliPidsOf} trusts only it. */
28
+ #cliRegistryAccepted = false;
26
29
  /**
27
30
  * Czego ostatnio przyjęty odczyt rejestru NIE widział: żywe pidy z plikiem bez wpisu
28
31
  * i rozmowy żywych procesów bez pliku. Przy którymkolwiek rejestr nie dowodzi, że rozmowę pisze
@@ -54,7 +57,7 @@ export class CliRegistryState {
54
57
  * od Raroga żadnej władzy — pigułka nad nim byłaby obietnicą bez pokrycia.
55
58
  */
56
59
  cliUpdateOf(session) {
57
- if (session.engine === 'codex' || session.outOfScope === true)
60
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
58
61
  return undefined;
59
62
  if (session.driver === null || session.herdrKey === undefined)
60
63
  return undefined;
@@ -167,6 +170,7 @@ export class CliRegistryState {
167
170
  this.#cliRegistryGen = generation;
168
171
  }
169
172
  this.#cliRegistry = snapshot.registry;
173
+ this.#cliRegistryAccepted = true;
170
174
  this.#cliRegistryDoubt = {
171
175
  ...(snapshot.unreadablePids === undefined ? {} : { unreadablePids: snapshot.unreadablePids }),
172
176
  ...(snapshot.unlistedSessions === undefined ? {} : { unlistedSessions: snapshot.unlistedSessions }),
@@ -194,7 +198,7 @@ export class CliRegistryState {
194
198
  * już zrestartowanym CLI nie potrzebuje osobnej ścieżki).
195
199
  */
196
200
  #noteCliProcessStart(session) {
197
- if (session.engine === 'codex' || session.outOfScope === true || session.herdrKey === undefined)
201
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true || session.herdrKey === undefined)
198
202
  return;
199
203
  const sessionId = session.engineSessionId;
200
204
  const startedAt = cliProcessStartOf({ registry: this.#cliRegistry, ...this.#cliRegistryDoubt }, sessionId);
@@ -208,7 +212,7 @@ export class CliRegistryState {
208
212
  * ani odczytu ekranu — sygnał byłby tam obietnicą bez pokrycia.
209
213
  */
210
214
  cliWaitingOf(session) {
211
- if (this.#config.cliWaiting !== true || session.engine === 'codex'
215
+ if (this.#config.cliWaiting !== true || isStateOnlyEngine(session.engine)
212
216
  || session.outOfScope === true || session.driver === null || session.herdrKey === undefined) {
213
217
  return { kind: 'unknown' };
214
218
  }
@@ -223,6 +227,16 @@ export class CliRegistryState {
223
227
  const registry = this.#cliRegistry ?? this.#cliVersion.registry;
224
228
  return cliAcceptsNotes(runningCliVersion(registry, session.engineSessionId));
225
229
  }
230
+ /**
231
+ * The live process ids writing the conversation: the fast tick's last accepted reading once there is one (a failed
232
+ * reading is unknown, never the older slow snapshot), else the slow one. `null` = unknown: no reading, a failed
233
+ * one, or no live process of the conversation.
234
+ */
235
+ cliPidsOf(conversation) {
236
+ const registry = this.#cliRegistryAccepted ? this.#cliRegistry : this.#cliVersion.registry;
237
+ const entries = registry?.get(conversation);
238
+ return entries === undefined || entries.length === 0 ? null : entries.map((entry) => entry.pid);
239
+ }
226
240
  /** 400 bramki „nie znam trybu" — z nazwaną przyczyną, gdy rejestr mówi o dialogu. */
227
241
  modeUnknownMessage(session) {
228
242
  const signal = this.cliWaitingOf(session);
@@ -8,6 +8,7 @@ import { homedir } from 'node:os';
8
8
  import { say } from '@rarog/shared/sentences';
9
9
  import { inWorkAreaOnDisk } from '../config/work-area.js';
10
10
  import { BadStateError } from './errors.js';
11
+ import { isStateOnlyEngine } from '../herdr/engines.js';
11
12
  /**
12
13
  * Scope of the commands list (`GET /api/sessions/:id/commands`) and of the voice agent, the same as for sending and
13
14
  * for reading the session catalog. Out of scope: a pane outside `RAROG_HERDR_ROOTS` (every Codex pane among them)
@@ -16,7 +17,7 @@ import { BadStateError } from './errors.js';
16
17
  * directory. A card without a pane is in scope with its directory; demo mode reads the registry only.
17
18
  */
18
19
  export function inCommandScope(session, config, options = {}) {
19
- if (session.engine === 'codex' || session.outOfScope === true)
20
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
20
21
  return false;
21
22
  return config.demo || sessionCwdInArea(session, config, options);
22
23
  }
@@ -4,6 +4,7 @@ import { classifyRisk } from '../risk.js';
4
4
  import { consentStep } from '../herdr/consent-step.js';
5
5
  import { CONSENT_FINAL_STATES, CONSENT_HOLDING_STATES } from '../herdr/dialogs/layer1/contract.js';
6
6
  import { consentPermissionRequest, consentResolvedEvent, consentSettledEvent, } from '../herdr/dialogs/layer1/frames.js';
7
+ import { isStateOnlyEngine } from '../herdr/engines.js';
7
8
  /** Consent channel cards of the manager's sessions; one instance per manager. */
8
9
  export class ConsentCards {
9
10
  #config;
@@ -18,6 +19,11 @@ export class ConsentCards {
18
19
  * pole rekordu (`retired` w widoku portu). Błąd zapisu zostawia wpis do końca procesu.
19
20
  */
20
21
  #consentRetired = new Set();
22
+ /**
23
+ * The stay in `waiting-permission` (its `stateSince`) whose hold by a subagent card is already in the log
24
+ * ({@link subagentCardHold}): one line per stay, however many herdr statuses repeat during it.
25
+ */
26
+ #subagentHeldSince = new WeakMap();
21
27
  constructor(config, port) {
22
28
  this.#config = config;
23
29
  this.#port = port;
@@ -183,7 +189,12 @@ export class ConsentCards {
183
189
  this.#port.emitSession(session, { type: 'permission-pending', request: this.#consentRequest(session, view) });
184
190
  this.#port.timingCard(session, 'hook');
185
191
  if (view.state !== 'pending' || !this.#port.applyTransition(session, { type: 'permission-requested' })) {
186
- this.#port.emitSessionChanged(session);
192
+ // A subagent's card is the decision that stands, also after the turn ended (`waiting-input`): herdr never
193
+ // reports `blocked` for it. Its silent transition goes first; the banner comes from the note below.
194
+ const reconciled = view.state === 'pending' && view.agentId !== null
195
+ && this.#port.applyTransition(session, { type: 'subagent-consent-pending' });
196
+ if (!reconciled)
197
+ this.#port.emitSessionChanged(session);
187
198
  if (view.state === 'pending')
188
199
  this.#port.note(session, { type: 'permission-requested' });
189
200
  }
@@ -377,7 +388,7 @@ export class ConsentCards {
377
388
  const engines = new Set();
378
389
  if (session.engineSessionId !== undefined && session.engineSessionId !== '')
379
390
  engines.add(session.engineSessionId);
380
- if (agent.engine !== 'codex' && agent.agentSessionId !== '')
391
+ if (!isStateOnlyEngine(agent.engine) && agent.agentSessionId !== '')
381
392
  engines.add(agent.agentSessionId);
382
393
  if (engines.size === 0)
383
394
  return;
@@ -462,6 +473,42 @@ export class ConsentCards {
462
473
  return this.#port.hasPending(session.id)
463
474
  || this.consentRequests(session).some((request) => request.state === 'pending');
464
475
  }
476
+ /**
477
+ * What herdr `working` or `idle` does to the session state while a subagent's channel card of the conversation this
478
+ * session handles stands in `pending`. A background subagent's request has no dialog on screen while the hook waits
479
+ * ("When the hook gets a request" in `docs/dialogs.md`), so herdr never reports `blocked` for it, and the session
480
+ * belongs in `waiting-permission` until the card leaves `pending` ({@link applyConsentCard} moves it then):
481
+ * `hold` in `waiting-permission` (the first hold of each stay goes to the log), `reconcile` from `running` and
482
+ * `waiting-input` (a turn end or an early herdr status left the state), `null` without such a card and in every other
483
+ * state. A main-thread card does not count: its dialog stands on the pane and herdr reports it. A cycle error = `null`.
484
+ */
485
+ subagentCardHold(session, herdr) {
486
+ const state = session.state;
487
+ if (state !== 'waiting-permission' && state !== 'running' && state !== 'waiting-input')
488
+ return null;
489
+ if (!this.#subagentCardPending(session))
490
+ return null;
491
+ if (state !== 'waiting-permission')
492
+ return 'reconcile';
493
+ if (this.#subagentHeldSince.get(session) !== session.stateSince) {
494
+ this.#subagentHeldSince.set(session, session.stateSince);
495
+ this.#config.logger?.(`consent: session ${session.id} stays waiting-permission: subagent card pending (herdr: ${herdr})`);
496
+ }
497
+ return 'hold';
498
+ }
499
+ #subagentCardPending(session) {
500
+ const consent = this.#config.consent;
501
+ const engine = session.engineSessionId;
502
+ if (consent === undefined || engine === undefined || engine === '' || !this.#ownsConsent(session))
503
+ return false;
504
+ try {
505
+ return consent.cards(engine).some((card) => card.state === 'pending' && card.agentId !== null
506
+ && !this.#consentCardRetired(engine, card));
507
+ }
508
+ catch {
509
+ return false;
510
+ }
511
+ }
465
512
  }
466
513
  /** Kto zdjął kartę kanału zgód w `permission-resolved`: hook (skutek albo koniec cyklu), nie urządzenie. */
467
514
  const CONSENT_RESOLVED_BY = 'hook';
@@ -1,4 +1,5 @@
1
- import { holdsOwedDone, stuckWaits } from '../herdr/background/work.js';
1
+ import { agentsWoken, holdsOwedDone, stuckWaits } from '../herdr/background/work.js';
2
+ import { noteSubagentWakes } from './state-sentences.js';
2
3
  export function applyConversationList(session, event, port) {
3
4
  switch (event.type) {
4
5
  /*
@@ -16,6 +17,8 @@ export function applyConversationList(session, event, port) {
16
17
  return;
17
18
  const held = holdsOwedDone(session.backgroundTasks);
18
19
  const waits = stuckWaits(session.state, session.backgroundTasks, tasks);
20
+ // A subagent woken from standby works in the main pane: a turn herdr reports for it alone has no result.
21
+ noteSubagentWakes(session, agentsWoken(session.backgroundTasks, tasks));
19
22
  session.backgroundTasks = tasks;
20
23
  port.emitSessionChanged(session);
21
24
  /*