@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,281 @@
1
+ /**
2
+ * Copy of the coordinator plugin in the data directory, one per package version:
3
+ * `<dataDir>/plugins/coordinator/<version>/`, the directory a coordinator gets in `--plugin-dir` (`argv.ts`).
4
+ *
5
+ * The package carries the plugin as `plugin/rarog/` next to its `package.json`; an update of the package replaces
6
+ * those files, so a live coordinator never runs from the package itself. {@link ensurePluginCopy} reads the plugin and
7
+ * the version from the package on disk at that moment, so the copy and its directory name come from the same package.
8
+ * A copy whose content hash (relative path, execute bit and bytes of every file) differs from the package is written
9
+ * again; copies of other versions go once no live session uses them ({@link prunePluginCopies}).
10
+ *
11
+ * The module does not decide who is a coordinator, does not start anything and does not know live sessions: the
12
+ * caller passes the `--plugin-dir` values of live sessions, or `null` when it does not know them.
13
+ */
14
+ import { randomBytes, createHash } from 'node:crypto';
15
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
16
+ import path from 'node:path';
17
+ import { INSTALL_ROOT } from '../install/mode.js';
18
+ import { readRegularFileSync } from '../safe-read.js';
19
+ import { readPackageVersion } from '../version.js';
20
+ import { isPluginDirValue } from './argv.js';
21
+ /** The plugin directory under the install root (the package and the clone have the same layout). */
22
+ export const PLUGIN_SOURCE_SUBDIR = ['plugin', 'rarog'];
23
+ /** The copies' directory under the data directory. */
24
+ export const PLUGIN_COPY_SUBDIR = ['plugins', 'coordinator'];
25
+ /** Mode of every directory of the copy: like the data directory, nobody else writes code that runs from it. */
26
+ export const PLUGIN_COPY_DIR_MODE = 0o700;
27
+ /** Ceilings of the plugin tree: the plugin is a dozen small files, so more means a wrong directory. */
28
+ export const PLUGIN_COPY_MAX_FILES = 64;
29
+ export const PLUGIN_COPY_MAX_BYTES = 2 * 1024 * 1024;
30
+ export const PLUGIN_COPY_MAX_DEPTH = 8;
31
+ /** Work directory of a copy being written; a leftover one is removed by {@link prunePluginCopies}. */
32
+ const TMP_PREFIX = '.tmp-';
33
+ /** A replaced copy on its way out. */
34
+ const OLD_PREFIX = '.old-';
35
+ /** A version directory name: the `version` alphabet of `package.json` (`version.ts`), never `.` or `..`. */
36
+ const VERSION_NAME = /^[0-9A-Za-z.+-]{1,64}$/;
37
+ const isVersionName = (name) => VERSION_NAME.test(name) && name !== '.' && name !== '..';
38
+ function codeOf(failure) {
39
+ const code = failure?.code;
40
+ return typeof code === 'string' ? code : failure instanceof Error ? failure.message : String(failure);
41
+ }
42
+ /** Hash of the tree: for every file its path, execute bit, length and bytes, in path order. */
43
+ function treeHash(files) {
44
+ const hash = createHash('sha256');
45
+ for (const file of files) {
46
+ hash.update(`${file.rel}\0${file.exec ? 'x' : '-'}\0${String(file.bytes.length)}\0`).update(file.bytes);
47
+ }
48
+ return hash.digest('hex');
49
+ }
50
+ /**
51
+ * Every regular file under `root`, with its bytes. A symlink, FIFO, device or socket anywhere in the tree, a root
52
+ * that is not a real directory, or a tree over the ceilings gives a reason instead: the copy runs outside the
53
+ * sandbox, so it carries exactly what the package has, and a FIFO must not hang the server (`safe-read.ts`).
54
+ */
55
+ export function readPluginTree(root) {
56
+ const files = [];
57
+ let bytes = 0;
58
+ const walk = (rel, depth) => {
59
+ const dir = path.join(root, rel);
60
+ let names;
61
+ try {
62
+ names = readdirSync(dir).sort();
63
+ }
64
+ catch (failure) {
65
+ return `${dir}: ${codeOf(failure)}`;
66
+ }
67
+ for (const name of names) {
68
+ const childRel = rel === '' ? name : `${rel}/${name}`;
69
+ const child = path.join(root, childRel);
70
+ let info;
71
+ try {
72
+ info = lstatSync(child);
73
+ }
74
+ catch (failure) {
75
+ return `${child}: ${codeOf(failure)}`;
76
+ }
77
+ if (info.isDirectory()) {
78
+ if (depth >= PLUGIN_COPY_MAX_DEPTH)
79
+ return `${child}: deeper than ${String(PLUGIN_COPY_MAX_DEPTH)} levels`;
80
+ const issue = walk(childRel, depth + 1);
81
+ if (issue !== null)
82
+ return issue;
83
+ continue;
84
+ }
85
+ if (!info.isFile())
86
+ return `${child}: not a regular file or directory`;
87
+ if (files.length >= PLUGIN_COPY_MAX_FILES)
88
+ return `${root}: more than ${String(PLUGIN_COPY_MAX_FILES)} files`;
89
+ let read;
90
+ try {
91
+ read = readRegularFileSync(child, { maxBytes: PLUGIN_COPY_MAX_BYTES - bytes, followSymlink: false });
92
+ }
93
+ catch (failure) {
94
+ return `${child}: ${codeOf(failure)}`;
95
+ }
96
+ if (read === null)
97
+ return `${child}: not a regular file`;
98
+ if (read.truncated)
99
+ return `${root}: more than ${String(PLUGIN_COPY_MAX_BYTES)} bytes`;
100
+ bytes += read.bytes.length;
101
+ files.push({ rel: childRel, bytes: read.bytes, exec: (info.mode & 0o100) !== 0 });
102
+ }
103
+ return null;
104
+ };
105
+ let info;
106
+ try {
107
+ info = lstatSync(root);
108
+ }
109
+ catch (failure) {
110
+ return { ok: false, reason: `${root}: ${codeOf(failure)}` };
111
+ }
112
+ if (!info.isDirectory())
113
+ return { ok: false, reason: `${root}: not a directory (a symlink is not accepted)` };
114
+ const issue = walk('', 1);
115
+ if (issue !== null)
116
+ return { ok: false, reason: issue };
117
+ files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
118
+ return { ok: true, files, hash: treeHash(files) };
119
+ }
120
+ /** `<dataDir>/plugins/coordinator`. */
121
+ export function pluginCopyRoot(dataDir) {
122
+ return path.join(dataDir, ...PLUGIN_COPY_SUBDIR);
123
+ }
124
+ /**
125
+ * Why a directory on the way to the copies cannot hold them, or `null`: it must be a real directory (not a symlink)
126
+ * of this user that nobody else can write.
127
+ */
128
+ function dirIssue(dir) {
129
+ let info;
130
+ try {
131
+ info = lstatSync(dir);
132
+ }
133
+ catch (failure) {
134
+ return `${dir}: ${codeOf(failure)}`;
135
+ }
136
+ if (!info.isDirectory())
137
+ return `${dir}: expected a directory (symlinks and other types are rejected)`;
138
+ const uid = process.getuid?.();
139
+ if (uid !== undefined && info.uid !== uid)
140
+ return `${dir}: owned by uid ${String(info.uid)}, not by this process`;
141
+ if ((info.mode & 0o022) !== 0)
142
+ return `${dir}: writable by group or others (mode ${(info.mode & 0o777).toString(8)})`;
143
+ return null;
144
+ }
145
+ /** `dir` created with {@link PLUGIN_COPY_DIR_MODE} when missing, then checked by {@link dirIssue}. */
146
+ function ensureDir(dir) {
147
+ try {
148
+ mkdirSync(dir, { mode: PLUGIN_COPY_DIR_MODE });
149
+ }
150
+ catch (failure) {
151
+ if (codeOf(failure) !== 'EEXIST')
152
+ return `${dir}: ${codeOf(failure)}`;
153
+ }
154
+ return dirIssue(dir);
155
+ }
156
+ /** Writes the tree into the new directory `dir`: directories 0700, files read-only, `bin/` entries executable. */
157
+ function writeTree(dir, files) {
158
+ for (const file of files) {
159
+ const target = path.join(dir, ...file.rel.split('/'));
160
+ mkdirSync(path.dirname(target), { recursive: true, mode: PLUGIN_COPY_DIR_MODE });
161
+ writeFileSync(target, file.bytes, { flag: 'wx', mode: file.exec ? 0o500 : 0o400 });
162
+ // The mode of `writeFileSync` passes through the umask; the execute bit must not depend on it.
163
+ chmodSync(target, file.exec ? 0o500 : 0o400);
164
+ }
165
+ }
166
+ /**
167
+ * The copy for the package on disk, ready for `--plugin-dir`: an existing copy with the package's hash is used as it
168
+ * is; a missing one, or one with another hash, is written to a work directory next to it, checked against the hash and
169
+ * renamed into place. A copy that differs is replaced even when a live session runs from it: it no longer is what the
170
+ * package ships. Then other versions not in `inUse` are removed. Synchronous, so two starts in one process never
171
+ * interleave. Never throws.
172
+ */
173
+ export function ensurePluginCopy(opts) {
174
+ const installRoot = opts.installRoot ?? INSTALL_ROOT;
175
+ let version;
176
+ try {
177
+ version = readPackageVersion(path.join(installRoot, 'package.json'));
178
+ }
179
+ catch (failure) {
180
+ return { ok: false, code: 'source', reason: `package version: ${codeOf(failure)}` };
181
+ }
182
+ if (!isVersionName(version)) {
183
+ return { ok: false, code: 'source', reason: `package version ${JSON.stringify(version)} cannot name a directory` };
184
+ }
185
+ const root = pluginCopyRoot(opts.dataDir);
186
+ const dir = path.join(root, version);
187
+ if (!isPluginDirValue(dir)) {
188
+ return { ok: false, code: 'path', reason: `${dir}: the path fails the --plugin-dir rule (isPluginDirValue)` };
189
+ }
190
+ const source = readPluginTree(path.join(installRoot, ...PLUGIN_SOURCE_SUBDIR));
191
+ if (!source.ok)
192
+ return { ok: false, code: 'source', reason: source.reason };
193
+ const issue = ensureDir(path.dirname(root)) ?? ensureDir(root);
194
+ if (issue !== null)
195
+ return { ok: false, code: 'data-dir', reason: issue };
196
+ let present = true;
197
+ try {
198
+ lstatSync(dir);
199
+ }
200
+ catch {
201
+ present = false;
202
+ }
203
+ if (present) {
204
+ const copy = readPluginTree(dir);
205
+ if (copy.ok && copy.hash === source.hash) {
206
+ prunePluginCopies(opts.dataDir, { current: version, inUse: opts.inUse });
207
+ return { ok: true, dir, version, written: false };
208
+ }
209
+ }
210
+ const work = path.join(root, `${TMP_PREFIX}${randomBytes(6).toString('hex')}`);
211
+ let old = null;
212
+ try {
213
+ mkdirSync(work, { mode: PLUGIN_COPY_DIR_MODE });
214
+ writeTree(work, source.files);
215
+ const written = readPluginTree(work);
216
+ if (!written.ok || written.hash !== source.hash) {
217
+ return { ok: false, code: 'write', reason: `${work}: the written copy differs from the package` };
218
+ }
219
+ if (present) {
220
+ old = path.join(root, `${OLD_PREFIX}${randomBytes(6).toString('hex')}`);
221
+ renameSync(dir, old);
222
+ }
223
+ renameSync(work, dir);
224
+ }
225
+ catch (failure) {
226
+ // The old copy goes back when the new one did not take its place.
227
+ if (old !== null) {
228
+ try {
229
+ renameSync(old, dir);
230
+ old = null;
231
+ }
232
+ catch {
233
+ // Left as `.old-*`: the next prune removes it, the next start writes the copy again.
234
+ }
235
+ }
236
+ return { ok: false, code: 'write', reason: `${dir}: ${codeOf(failure)}` };
237
+ }
238
+ finally {
239
+ rmSync(work, { recursive: true, force: true });
240
+ if (old !== null)
241
+ rmSync(old, { recursive: true, force: true });
242
+ }
243
+ prunePluginCopies(opts.dataDir, { current: version, inUse: opts.inUse });
244
+ return { ok: true, dir, version, written: true };
245
+ }
246
+ /**
247
+ * Removes copies no live session uses and leftovers of an interrupted copy; returns the removed paths. Only direct
248
+ * children of the copies' directory that are real directories: a version-shaped name other than `current` and not in
249
+ * `inUse`, or a `.tmp-*` and `.old-*` leftover. Anything else (a file, a symlink, another name) stays. Never throws.
250
+ */
251
+ export function prunePluginCopies(dataDir, opts) {
252
+ const root = pluginCopyRoot(dataDir);
253
+ if (dirIssue(root) !== null)
254
+ return [];
255
+ let names;
256
+ try {
257
+ names = readdirSync(root).sort();
258
+ }
259
+ catch {
260
+ return [];
261
+ }
262
+ const removed = [];
263
+ for (const name of names) {
264
+ const dir = path.join(root, name);
265
+ const leftover = name.startsWith(TMP_PREFIX) || name.startsWith(OLD_PREFIX);
266
+ if (!leftover) {
267
+ if (opts.inUse === null || !isVersionName(name) || name === opts.current || opts.inUse.has(dir))
268
+ continue;
269
+ }
270
+ try {
271
+ if (!lstatSync(dir).isDirectory())
272
+ continue;
273
+ rmSync(dir, { recursive: true, force: true });
274
+ removed.push(dir);
275
+ }
276
+ catch {
277
+ // A copy that cannot be removed now stays for the next prune.
278
+ }
279
+ }
280
+ return removed;
281
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The supervisor's index of entries by engine session ID. An entry without a session ID (a state-only engine whose
3
+ * session herdr does not report, `agentSessionId: ''`) never enters it and is never found by it: such entries are
4
+ * known by their pane alone, so two panes without a session ID stay two entries. No herdr calls, no other state.
5
+ */
6
+ export class SessionIndex {
7
+ #keys = new Map();
8
+ /** The entry key of this engine session; `undefined` for `''`. */
9
+ get(agentSessionId) {
10
+ return agentSessionId === '' ? undefined : this.#keys.get(agentSessionId);
11
+ }
12
+ set(agentSessionId, key) {
13
+ if (agentSessionId !== '')
14
+ this.#keys.set(agentSessionId, key);
15
+ }
16
+ delete(agentSessionId) {
17
+ this.#keys.delete(agentSessionId);
18
+ }
19
+ }
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * Model subskrypcji (zweryfikowany na żywym serwerze):
10
10
  * - `events.subscribe` przyjmuje listę wpisów: globalne (`pane.created`, `pane.closed`,
11
- * `pane.exited`, `pane.moved`, `pane.agent_detected`) i per panel
11
+ * `pane.exited`, `pane.moved`, `pane.agent_detected`, `tab.closed`, `workspace.closed`) i per panel
12
12
  * (`pane.agent_status_changed` z `pane_id` — GLOBALNEJ wersji nie ma),
13
13
  * - nie ma `events.unsubscribe` ani `events.update`, więc każda zmiana składu paneli to
14
14
  * ZAMKNIĘCIE połączenia i ponowna subskrypcja pełną listą (debounce 500 ms — przy
@@ -29,6 +29,8 @@ import { AsyncEventQueue, systemScheduler } from '../drivers/runtime.js';
29
29
  import { createAnswerRecheck } from './answer-recheck.js';
30
30
  import { createHerdrAuditLog } from './audit.js';
31
31
  import { createHerdrClient, createHerdrLaunchClient } from './client.js';
32
+ import { STATE_ONLY_REFUSALS, isStateOnlyEngine } from './engines.js';
33
+ import { SessionIndex } from './session-index.js';
32
34
  import { createHiddenStore, sessionIdFor } from './identity.js';
33
35
  import { createLabelMigration, isLegacyPaneLabel } from './label-migration.js';
34
36
  import { createSendThrottle } from './commands/index.js';
@@ -43,12 +45,6 @@ import { HERDR_PANE_CAP_MESSAGE, sentenceOfError, HerdrGoneError, HerdrLaunchTim
43
45
  * z `canLaunch` i tak nie powinien dopuścić tu żądania.
44
46
  */
45
47
  const LAUNCH_NOT_WIRED = say('herdr.launch-off-panels');
46
- /**
47
- * Odmowa `closeTab` na panelu Codexa — bliźniaczka `HERDR_CODEX_CLOSE_MESSAGE`
48
- * z managera: ten sam kod zdania z rejestru, bez importu z warstwy sesji (nadzorca importuje
49
- * z niej wyłącznie typy i ta zależność miałaby iść w drugą stronę).
50
- */
51
- const CODEX_CLOSE_MESSAGE = say('session.codex-close');
52
48
  /** Odmowa operacji na kluczu, którego nadzorca nie zna (panel zniknął z herdr). */
53
49
  const agentGone = (key) => new HerdrGoneError(say('herdr.agent-gone', { key }));
54
50
  /**
@@ -91,10 +87,13 @@ const GLOBAL_SUBSCRIPTIONS = [
91
87
  { type: 'pane.exited' },
92
88
  { type: 'pane.moved' },
93
89
  { type: 'pane.agent_detected' },
90
+ // Closing a workspace sends no `pane.closed` for its panes (herdr 0.9.5); a closed tab refreshes the list too.
91
+ { type: 'tab.closed' },
92
+ { type: 'workspace.closed' },
94
93
  ];
95
94
  /** Zdarzenia, po których pytamy o pełną listę (skład paneli mógł się zmienić). */
96
95
  const COMPOSITION_EVENTS = new Set([
97
- 'pane_created', 'pane_closed', 'pane_exited', 'pane_moved', 'pane_agent_detected',
96
+ 'pane_created', 'pane_closed', 'pane_exited', 'pane_moved', 'pane_agent_detected', 'tab_closed', 'workspace_closed',
98
97
  ]);
99
98
  /** `pane.updated` (firehose ~10 ramek/s) świadomie NIE jest subskrybowane. */
100
99
  const STATUS_EVENT = 'pane_agent_status_changed';
@@ -141,6 +140,7 @@ export function createHerdrSupervisor(config, deps) {
141
140
  const client = deps.client
142
141
  ?? createHerdrClient(requireSocket(socket), {
143
142
  codexStatus: config.codexStatusEnabled === true,
143
+ agyStatus: config.agyStatusEnabled === true,
144
144
  });
145
145
  /*
146
146
  * Kanał TWORZENIA powstaje tylko wtedy, gdy jest z czego: bez własnego gniazda i bez jawnie
@@ -196,7 +196,7 @@ export function createHerdrSupervisor(config, deps) {
196
196
  const lifecycle = new AsyncEventQueue();
197
197
  const agents = new Map();
198
198
  const byPane = new Map();
199
- const bySession = new Map();
199
+ const bySession = new SessionIndex();
200
200
  /**
201
201
  * Klucze agentów `claude` uruchomionych przez TEN proces Raroga.
202
202
  *
@@ -786,7 +786,7 @@ export function createHerdrSupervisor(config, deps) {
786
786
  * A przede wszystkim: to jest ODCZYT TREŚCI cudzego panelu, którego wpis Codexa nie
787
787
  * obiecuje. Tryb zostaje `unknown`, więc bramka wysyłki jest fail-closed z definicji.
788
788
  */
789
- if (entry.agent.engine === 'codex')
789
+ if (isStateOnlyEngine(entry.agent.engine))
790
790
  return 'unknown';
791
791
  entry.lastModeReadAt = now();
792
792
  let exact;
@@ -852,7 +852,9 @@ export function createHerdrSupervisor(config, deps) {
852
852
  * and on disk, so a link into such a folder or a root that is a symlink to home does not open it. Scope ignores
853
853
  * the folder gate: a pane in a guarded folder a root opens stays in scope while the folder is closed.
854
854
  */
855
- const scopeOf = (info) => (info.engine === 'codex' ? false : inWorkAreaOnDisk(info.cwd, config.roots, home, undefined, { gate: 'ignore' }));
855
+ const scopeOf = (info) => (isStateOnlyEngine(info.engine)
856
+ ? false
857
+ : inWorkAreaOnDisk(info.cwd, config.roots, home, undefined, { gate: 'ignore' }));
856
858
  /**
857
859
  * Nowy wpis agenta w mapach supervisora.
858
860
  *
@@ -1709,8 +1711,9 @@ export function createHerdrSupervisor(config, deps) {
1709
1711
  * bramkę na ten scenariusz; ta jest drugą warstwą i stoi na prawdzie nadzorcy — bo to
1710
1712
  * on, a nie karta, wie, jaki silnik naprawdę siedzi w panelu.
1711
1713
  */
1712
- if (entry.agent.engine === 'codex')
1713
- throw new HerdrNotOwnedError(CODEX_CLOSE_MESSAGE);
1714
+ if (isStateOnlyEngine(entry.agent.engine)) {
1715
+ throw new HerdrNotOwnedError(STATE_ONLY_REFUSALS[entry.agent.engine].close);
1716
+ }
1714
1717
  if (entry.agent.tabId === '') {
1715
1718
  throw new HerdrNotOwnedError(say('herdr.tab-unknown'));
1716
1719
  }
@@ -1,4 +1,5 @@
1
1
  import { arglessCodeOf, foreign, isServerSentence, say, textOf, } from '@rarog/shared/sentences';
2
+ export { STATE_ONLY_REFUSALS, isStateOnlyEngine } from './engines.js';
2
3
  /**
3
4
  * Powłoki, po których panel uchodzi za „gołą powłokę". Nazwa procesu wg jądra — bez `-`
4
5
  * loginowego. Czytają ją dwa miejsca i oba ZAMYKAJĄ panel tylko po tym rozpoznaniu: sprzątanie
@@ -5,7 +5,9 @@
5
5
  * reads no file and keeps no state; the tracker in `inbox.ts` keeps the shown turn between reads.
6
6
  */
7
7
  import { createHash } from 'node:crypto';
8
+ import { inboxCardMergeSchema } from '@rarog/shared';
8
9
  import { DECISION_STATES, WORKING_STATES } from '../sessions/state-sentences.js';
10
+ import { isStateOnlyEngine } from '../herdr/engines.js';
9
11
  const FAILED_STATES = ['error', 'limit-reached', 'interrupted'];
10
12
  /** Card kind of a session state; `null` for a closed session (`done`, `resumable`). */
11
13
  export function cardKindOf(state) {
@@ -43,7 +45,7 @@ export function shownTurnFor(kind, segments) {
43
45
  }
44
46
  /** Whether a session can have a card at all: an open Claude session in scope. */
45
47
  function carded(session) {
46
- if (session.engine === 'codex' || session.outOfScope === true)
48
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
47
49
  return null;
48
50
  return cardKindOf(session.state);
49
51
  }
@@ -51,36 +53,57 @@ function carded(session) {
51
53
  * The card of a session over the turn it shows, or `null` when it has none.
52
54
  *
53
55
  * @param requestOf the card id behind the summary's `waitingFor`; none = the dialog is known by its summary only
56
+ * @param checked the commit the coordinator's checks passed on, from the session's thread file; none = not a thread
57
+ * or not checked
54
58
  */
55
- export function composeCard(session, shown, requestOf = () => undefined) {
59
+ export function composeCard(session, shown, requestOf = () => undefined, checked) {
56
60
  const kind = carded(session);
57
61
  if (kind === null || shown === undefined)
58
62
  return null;
59
63
  const at = kind === 'result' ? shown.at : session.stateSince;
60
64
  const decided = kind === 'decision' ? dialogOf(session, requestOf) : undefined;
61
65
  const dialog = decided?.dialog;
62
- const key = keyOf(shown.turnId, kind, dialog, at);
66
+ const merge = kind === 'result' ? mergeOf(session, checked) : undefined;
67
+ const key = keyOf(shown.turnId, kind, dialog, at, merge);
63
68
  // The revision changes the version only: a removal of the card holds while its buttons change.
64
69
  const revision = decided?.revision === undefined ? [] : [decided.revision];
70
+ // Only a card with a Merge adds its commit, so every other card keeps the version it had.
71
+ const commit = key.checked === undefined ? [] : [key.checked];
65
72
  return {
66
73
  sessionId: session.id,
67
74
  turnId: shown.turnId,
68
- version: digest([shown.version, kind, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', ...revision]),
75
+ version: digest([
76
+ shown.version, kind, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', ...revision, ...commit,
77
+ ]),
69
78
  kind,
70
79
  state: session.state,
71
80
  at,
72
81
  text: shown.text,
73
82
  truncated: shown.truncated,
74
83
  ...(dialog === undefined ? {} : { dialog }),
84
+ ...(merge === undefined ? {} : { merge }),
75
85
  };
76
86
  }
87
+ /**
88
+ * The Merge of a result card: the session is a thread that is `ready` (the state rule of the coordination modules,
89
+ * which this function does not repeat), its coordinator is live and `checked` is a full SHA. Anything less gives a
90
+ * card without Merge, never one the stream would reject.
91
+ */
92
+ function mergeOf(session, checked) {
93
+ const role = session.coordination;
94
+ if (role?.role !== 'thread' || role.merge?.state !== 'ready' || role.coordinatorId === undefined)
95
+ return undefined;
96
+ const merge = inboxCardMergeSchema.safeParse({ name: role.name, coordinatorId: role.coordinatorId, checked });
97
+ return merge.success ? merge.data : undefined;
98
+ }
77
99
  /** The removal key of a card. */
78
100
  export function removalKeyOf(card) {
79
- return keyOf(card.turnId, card.kind, card.dialog, card.at);
101
+ return keyOf(card.turnId, card.kind, card.dialog, card.at, card.merge);
80
102
  }
81
- function keyOf(turnId, kind, dialog, at) {
82
- if (kind === 'result')
83
- return { turnId, card: kind };
103
+ function keyOf(turnId, kind, dialog, at, merge) {
104
+ if (kind === 'result') {
105
+ return merge === undefined ? { turnId, card: kind } : { turnId, card: kind, checked: merge.checked };
106
+ }
84
107
  if (kind === 'failed')
85
108
  return { turnId, card: kind, since: at };
86
109
  if (dialog === undefined)
@@ -3,6 +3,7 @@ export function headOf(card) {
3
3
  return {
4
4
  sessionId: card.sessionId, turnId: card.turnId, version: card.version, kind: card.kind, state: card.state,
5
5
  at: card.at, ...(card.dialog === undefined ? {} : { dialog: card.dialog.kind }),
6
+ ...(card.merge === undefined ? {} : { merge: card.merge }),
6
7
  };
7
8
  }
8
9
  /** Newest first, as the Inbox shows the cards; the session id keeps the order stable for equal times. */
@@ -13,12 +13,16 @@ const CLOSED_STATES = ['done', 'resumable'];
13
13
  function sameMark(a, b) {
14
14
  return a.state === b.state && a.stateSince === b.stateSince && a.transitions === b.transitions;
15
15
  }
16
- /** What a session summary says that its card depends on, besides the conversation file. */
17
- function lookOf(session) {
16
+ /**
17
+ * What a session summary says that its card depends on, besides the conversation file: also the role in its
18
+ * project's coordination and the checked commit of a thread, which change while the session state stays.
19
+ */
20
+ function lookOf(session, checked) {
18
21
  return JSON.stringify([
19
22
  session.state, session.stateSince, session.herdrDialog ?? null, session.herdrDialogReason ?? null,
20
23
  session.waitingFor ?? null,
21
24
  session.engine ?? null, session.outOfScope ?? false,
25
+ session.coordination ?? null, checked ?? null,
22
26
  ]);
23
27
  }
24
28
  export class Inbox {
@@ -27,6 +31,7 @@ export class Inbox {
27
31
  #log;
28
32
  #debounceMs;
29
33
  #timing;
34
+ #checkedOf;
30
35
  #store;
31
36
  #cards = new Map();
32
37
  #turns = new Map();
@@ -52,6 +57,7 @@ export class Inbox {
52
57
  this.#log = config.log;
53
58
  this.#debounceMs = config.debounceMs ?? INBOX_DEBOUNCE_MS;
54
59
  this.#timing = config.timing;
60
+ this.#checkedOf = config.checkedOf ?? (() => undefined);
55
61
  this.#store = new RemovalStore({
56
62
  dataDir: config.dataDir,
57
63
  isOpen: (sessionId) => {
@@ -258,7 +264,7 @@ export class Inbox {
258
264
  }
259
265
  #observe(session) {
260
266
  this.#states.set(session.id, session.state);
261
- const look = lookOf(session);
267
+ const look = lookOf(session, this.#checked(session.id));
262
268
  if (this.#looks.get(session.id) === look)
263
269
  return;
264
270
  this.#looks.set(session.id, look);
@@ -397,7 +403,7 @@ export class Inbox {
397
403
  }
398
404
  this.#turns.set(sessionId, turns);
399
405
  const requestOf = (dialog, waitingFor) => this.#dialogs.request(sessionId, dialog, waitingFor);
400
- const card = composeCard(session, working ? turns.ended : turns.shown, requestOf);
406
+ const card = composeCard(session, working ? turns.ended : turns.shown, requestOf, this.#checked(sessionId));
401
407
  if (card === null) {
402
408
  this.#cards.delete(sessionId);
403
409
  return false;
@@ -417,6 +423,17 @@ export class Inbox {
417
423
  return undefined;
418
424
  }
419
425
  }
426
+ /** {@link InboxConfig.checkedOf}; a failure of it gives a card without Merge, not a lost event or card read. */
427
+ #checked(sessionId) {
428
+ try {
429
+ return this.#checkedOf(sessionId);
430
+ }
431
+ catch (err) {
432
+ const reason = err instanceof Error ? err.message : String(err);
433
+ this.#log(`inbox: checked commit read failed for session ${sessionId} (${reason})`);
434
+ return undefined;
435
+ }
436
+ }
420
437
  /** The session has no card and no shown turn; its removals stay. */
421
438
  #forget(sessionId) {
422
439
  this.#cards.delete(sessionId);
@@ -22,9 +22,13 @@ const FILE_MAX_BYTES = 1024 * 1024;
22
22
  const FILE_MODE = 0o600;
23
23
  const CARD_KINDS = ['result', 'decision', 'failed'];
24
24
  const DIALOG_KINDS = ['permission', 'question', 'panel'];
25
+ /** The checked commit of a removed Merge card: a full lowercase SHA, as the card carries it. */
26
+ const CHECKED_PATTERN = /^[0-9a-f]{40}$/u;
25
27
  /** Map key of a removal key. */
26
28
  function slot(key) {
27
- return JSON.stringify([key.turnId, key.card, key.dialog ?? '', key.dialogId ?? '', key.since ?? '']);
29
+ return JSON.stringify([
30
+ key.turnId, key.card, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', key.checked ?? '',
31
+ ]);
28
32
  }
29
33
  function entryOf(raw) {
30
34
  if (typeof raw !== 'object' || raw === null)
@@ -38,11 +42,16 @@ function entryOf(raw) {
38
42
  if (card === undefined)
39
43
  return null;
40
44
  const dialog = DIALOG_KINDS.find((kind) => kind === e['dialog']);
45
+ const checked = e['checked'];
46
+ // A checked commit that is not a full SHA matches no card; read without it, it would hide the plain result card.
47
+ if (checked !== undefined && (typeof checked !== 'string' || !CHECKED_PATTERN.test(checked)))
48
+ return null;
41
49
  return {
42
50
  sessionId: e['sessionId'], turnId: e['turnId'], card,
43
51
  ...(dialog === undefined ? {} : { dialog }),
44
52
  ...(typeof e['dialogId'] === 'string' && e['dialogId'] !== '' ? { dialogId: e['dialogId'] } : {}),
45
53
  ...(typeof e['since'] === 'string' ? { since: e['since'] } : {}),
54
+ ...(typeof checked === 'string' ? { checked } : {}),
46
55
  ...(e['seen'] === true ? { seen: true } : {}),
47
56
  };
48
57
  }