@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,194 @@
1
+ /**
2
+ * Branch diff of a coordinator's thread: the files and commits its branch adds past the merge base with the branch of
3
+ * the project's main checkout, and one file's patch, read between two commits pinned once per request (boundary:
4
+ * `docs/security-model.md`, "Git reads"). Collectors only: the session gate, the routes and the log line live
5
+ * elsewhere, and nothing here reads the working tree.
6
+ */
7
+ import { DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, DIFF_GIT_FAILED_ERROR } from '@rarog/shared';
8
+ import { DiffError, MAX_DIFF_FILE_PATCH_BYTES, MAX_DIFF_LIST_FILES, parseNameStatusZ, validateDiffPath, } from './git-diff.js';
9
+ import { GIT_LOG_FORMAT, NO_EXT_DIFF, RELATIVE, clampPatch, parseGitLog, parseNumstatZ } from './git-status.js';
10
+ /** Most commits a list carries, the newest ones; the list of files has its own cap (`MAX_DIFF_LIST_FILES`). */
11
+ export const MAX_BRANCH_DIFF_COMMITS = 500;
12
+ const BRANCH_REF = 'refs/heads/';
13
+ const FULL_SHA = /^[0-9a-f]{40}$/u;
14
+ const NO_PROJECT_ROOT = { ok: false, refusal: 'no-project-root' };
15
+ const NO_BASE = { ok: false, refusal: 'no-base' };
16
+ /** Run in the main checkout: the full name of the branch `HEAD` is on, or `HEAD` when it is detached. */
17
+ function baseBranchArgs() {
18
+ return { sub: 'rev-parse', rest: ['--symbolic-full-name', 'HEAD'] };
19
+ }
20
+ /**
21
+ * Run in the session directory: its head, then for `<base>...HEAD` the two tips and every merge base with a leading
22
+ * `^`. No such line means the two share no commit.
23
+ */
24
+ function rangeArgs(baseRef) {
25
+ return { sub: 'rev-parse', rest: ['HEAD^{commit}', `${baseRef}...HEAD`] };
26
+ }
27
+ function nameStatusArgs(range) {
28
+ return { sub: 'diff', rest: [NO_EXT_DIFF, RELATIVE, '--name-status', '-z', range.base, range.head] };
29
+ }
30
+ function numstatArgs(range) {
31
+ return { sub: 'diff', rest: [NO_EXT_DIFF, RELATIVE, '--numstat', '-z', range.base, range.head] };
32
+ }
33
+ function logArgs(range, max) {
34
+ return {
35
+ sub: 'log', rest: [`--format=${GIT_LOG_FORMAT}`, `--max-count=${String(max)}`, `${range.base}..${range.head}`],
36
+ };
37
+ }
38
+ /**
39
+ * One path exactly, in both trees: `:(literal)` makes `docs/*.md` a path, not a pattern, and the excluded `<path>/`
40
+ * keeps out the files under the same name when a file became a directory or a directory a file, which a pathspec
41
+ * matches as well. The magic stands per pathspec, so the command has no global `--literal-pathspecs`, which would
42
+ * turn it off.
43
+ */
44
+ function exactPathspec(path) {
45
+ return [`:(literal)${path}`, `:(exclude,literal)${path}/`];
46
+ }
47
+ /** `origin` is the source of a rename. */
48
+ function patchArgs(range, path, origin) {
49
+ return {
50
+ sub: 'diff',
51
+ rest: [
52
+ NO_EXT_DIFF, RELATIVE, range.base, range.head, '--',
53
+ ...exactPathspec(path), ...(origin === undefined ? [] : exactPathspec(origin)),
54
+ ],
55
+ };
56
+ }
57
+ /** A runner that does not throw: an exception, also a synchronous one, is a process that did not start. */
58
+ async function runGit(run, command, cwd) {
59
+ try {
60
+ return await run(command, cwd);
61
+ }
62
+ catch {
63
+ return { ok: false, stdout: '', spawnFailed: 'UNKNOWN' };
64
+ }
65
+ }
66
+ /**
67
+ * The output of a command that must succeed. Every command here reads commits that exist (the range is pinned), so a
68
+ * refusal is as much a failure as a timeout: an empty list would pass for a branch without changes.
69
+ */
70
+ function answered(result) {
71
+ if (!result.ok)
72
+ throw new DiffError(DIFF_GIT_FAILED_ERROR);
73
+ return result;
74
+ }
75
+ /**
76
+ * The range of this request, or why there is none. The branch comes from the main checkout, the head and the merge base
77
+ * from the session directory. Several merge bases (criss-cross merges): the first one git prints, the one
78
+ * `git diff <a>...<b>` takes.
79
+ */
80
+ async function resolveRange(cwd, projectRoot, run) {
81
+ const ref = answered(await runGit(run, baseBranchArgs(), projectRoot)).stdout.trim();
82
+ const branch = ref.startsWith(BRANCH_REF) ? ref.slice(BRANCH_REF.length) : '';
83
+ if (branch === '' || /\s/u.test(branch))
84
+ return 'no-base';
85
+ const lines = answered(await runGit(run, rangeArgs(ref), cwd)).stdout.split('\n').filter((line) => line !== '');
86
+ const [head, ...rest] = lines;
87
+ const tips = rest.filter((line) => !line.startsWith('^'));
88
+ const bases = rest.filter((line) => line.startsWith('^')).map((line) => line.slice(1));
89
+ // Output of another shape (a SHA-256 repository, an unreadable line) cannot be pinned: no list rather than a guess.
90
+ if (head === undefined || tips.length !== 2 || ![head, ...tips, ...bases].every((sha) => FULL_SHA.test(sha))) {
91
+ throw new DiffError(DIFF_GIT_FAILED_ERROR);
92
+ }
93
+ const base = bases[0];
94
+ return base === undefined ? 'no-base' : { branch, base, head };
95
+ }
96
+ /** Line counts, or none: past their budget or on a failure the list goes without them, as the session list does. */
97
+ async function readCounts(cwd, range, run) {
98
+ if (run === null)
99
+ return new Map();
100
+ const result = await runGit(run, numstatArgs(range), cwd);
101
+ return result.ok ? parseNumstatZ(result.stdout) : new Map();
102
+ }
103
+ /** `git log` lines in `GIT_LOG_FORMAT`, newest first; a line cut by the read cap is dropped. */
104
+ function parseCommits(result) {
105
+ const lines = result.stdout.split('\n');
106
+ if (result.capped === true)
107
+ lines.pop();
108
+ return lines.map((line) => (line === '' ? null : parseGitLog(line))).filter((commit) => commit !== null);
109
+ }
110
+ /**
111
+ * The files and commits of the session's branch past its merge base with the branch of the main checkout, in git's
112
+ * order, with the head they show. Only committed content: work the thread has not committed is in the session diff.
113
+ *
114
+ * @throws DiffError `git-failed` when git did not answer or refused a read.
115
+ */
116
+ export async function collectBranchDiffList(target, opts) {
117
+ const projectRoot = target.projectRoot;
118
+ if (projectRoot === undefined || projectRoot === '')
119
+ return NO_PROJECT_ROOT;
120
+ const range = await resolveRange(target.cwd, projectRoot, opts.run);
121
+ if (range === 'no-base')
122
+ return NO_BASE;
123
+ const [names, counts, log] = await Promise.all([
124
+ runGit(opts.run, nameStatusArgs(range), target.cwd),
125
+ readCounts(target.cwd, range, opts.runNumstat ?? null),
126
+ runGit(opts.run, logArgs(range, opts.maxCommits ?? MAX_BRANCH_DIFF_COMMITS), target.cwd),
127
+ ]);
128
+ const listed = answered(names);
129
+ const commits = parseCommits(answered(log));
130
+ const max = opts.maxFiles ?? MAX_DIFF_LIST_FILES;
131
+ const files = [];
132
+ let truncated = listed.capped === true;
133
+ for (const [path, entry] of parseNameStatusZ(listed.stdout)) {
134
+ if (files.length >= max) {
135
+ truncated = true;
136
+ break;
137
+ }
138
+ files.push({ path, status: entry.status, ...counts.get(path) });
139
+ }
140
+ return { ok: true, value: { files, truncated, commits, base: { branch: range.branch }, head: range.head } };
141
+ }
142
+ /**
143
+ * The source of a rename for the pathspec, or `undefined` when another entry of the list is that path, whose block the
144
+ * patch would then carry, or lies under it, where the name became a directory on the branch. Without the source the
145
+ * file shows as new in full.
146
+ */
147
+ function originToInclude(path, entry, listed, partial) {
148
+ const origin = entry.origin;
149
+ if (origin === undefined || partial)
150
+ return undefined;
151
+ const under = `${origin}/`;
152
+ for (const other of listed.keys()) {
153
+ if (other !== path && (other === origin || other.startsWith(under)))
154
+ return undefined;
155
+ }
156
+ return origin;
157
+ }
158
+ /**
159
+ * The patch of one file of the branch diff.
160
+ *
161
+ * Order: the shape check (`bad-path`), then the range and the list of this request, then the patch between the same two
162
+ * commits.
163
+ *
164
+ * @throws DiffError `bad-path`: the path failed the shape check;
165
+ * `diff-file-not-found`: the path is not on the list of the current range (the branch moved, the file is not
166
+ * changed on the branch, only main or the working tree changed it);
167
+ * `git-failed`: git did not answer or refused, or a list cut by the read cap cannot tell the path is not on it.
168
+ */
169
+ export async function collectBranchDiffFile(target, rawPath, opts) {
170
+ const projectRoot = target.projectRoot;
171
+ if (projectRoot === undefined || projectRoot === '')
172
+ return NO_PROJECT_ROOT;
173
+ const path = validateDiffPath(rawPath);
174
+ if (path === null)
175
+ throw new DiffError(DIFF_BAD_PATH_ERROR);
176
+ const range = await resolveRange(target.cwd, projectRoot, opts.run);
177
+ if (range === 'no-base')
178
+ return NO_BASE;
179
+ const names = answered(await runGit(opts.run, nameStatusArgs(range), target.cwd));
180
+ const partial = names.capped === true;
181
+ const listed = parseNameStatusZ(names.stdout);
182
+ const entry = listed.get(path);
183
+ if (entry === undefined)
184
+ throw new DiffError(partial ? DIFF_GIT_FAILED_ERROR : DIFF_FILE_NOT_FOUND_ERROR);
185
+ const result = answered(await runGit(opts.run, patchArgs(range, path, originToInclude(path, entry, listed, partial)), target.cwd));
186
+ const capped = result.capped === true;
187
+ // A prefix cut by the read cap ends in half a line, which goes, as in `clampPatch`.
188
+ const cut = capped ? result.stdout.lastIndexOf('\n') : -1;
189
+ const patch = cut === -1 ? result.stdout : result.stdout.slice(0, cut + 1);
190
+ if (patch === '' && !capped)
191
+ throw new DiffError(DIFF_FILE_NOT_FOUND_ERROR);
192
+ const clamped = clampPatch(patch, opts.maxPatchBytes ?? MAX_DIFF_FILE_PATCH_BYTES);
193
+ return { ok: true, value: { path, patch: clamped.patch, truncated: clamped.truncated || capped } };
194
+ }
@@ -15,6 +15,7 @@
15
15
  * Allow-lista jest sprawdzana PO ZBUDOWANIU tablicy, a nie tylko przy budowie: budowniczy może
16
16
  * się pomylić, a `agent.start` uruchamia PROCES na Macu użytkownika.
17
17
  */
18
+ import { posix } from 'node:path';
18
19
  import { EFFORT_LEVELS, MODEL_ID_PATTERN, PERMISSION_MODES } from '@rarog/shared';
19
20
  import { say } from '@rarog/shared/sentences';
20
21
  import { ENGINE_SESSION_ID_PATTERN } from '../transcript-import.js';
@@ -34,6 +35,28 @@ export const ALLOWED_CLAUDE_FLAGS = new Set([
34
35
  ]);
35
36
  /** Jedyna flaga bez wartości. */
36
37
  export const VALUELESS_CLAUDE_FLAGS = new Set(['--fork-session']);
38
+ /**
39
+ * The only flag whose value is a path: the coordinator plugin copy. Its value passes {@link isPluginDirValue}, not
40
+ * {@link ARG_VALUE_PATTERN}, which has no `/`. Kept out of {@link ALLOWED_CLAUDE_FLAGS}, so a path never passes as
41
+ * the value of another flag and no other value passes here.
42
+ */
43
+ export const PATH_CLAUDE_FLAGS = new Set(['--plugin-dir']);
44
+ /** Ceiling of a `--plugin-dir` value in characters. */
45
+ export const PLUGIN_DIR_MAX = 512;
46
+ /**
47
+ * Shape of the plugin copy path: absolute, segments of letters, digits, `.`, `_`, `@`, `+` and `-`, ending in
48
+ * `/plugins/coordinator/<version>` (the layout of `plugin-copy.ts`). No space, quote, `$`, backtick, `;`, `|`, `&`,
49
+ * `<`, `>`, `(`, `)`, `\`, `*`, `?`, `[`, `]`, `~`, `#`, `!` or line end: the value is shell text like every other.
50
+ */
51
+ const PLUGIN_DIR_PATTERN = /^(?:\/[A-Za-z0-9._@+-]+)+\/plugins\/coordinator\/[A-Za-z0-9.+-]+$/;
52
+ /**
53
+ * Whether `value` may follow `--plugin-dir`: the shape above, at most {@link PLUGIN_DIR_MAX} characters, and
54
+ * normalized (no `.` or `..` segment, no `//`), so the path names the copy itself and nothing next to it. Decided from
55
+ * the value alone, because the gate after the build ({@link assertAllowedArgs}) sees only the array.
56
+ */
57
+ export function isPluginDirValue(value) {
58
+ return value.length <= PLUGIN_DIR_MAX && PLUGIN_DIR_PATTERN.test(value) && posix.normalize(value) === value;
59
+ }
37
60
  /**
38
61
  * Flagi wymienione w planie jako zablokowane NA STAŁE.
39
62
  *
@@ -119,7 +142,8 @@ export function assertAllowedArgs(args) {
119
142
  i += 1;
120
143
  continue;
121
144
  }
122
- if (!ALLOWED_CLAUDE_FLAGS.has(flag)) {
145
+ const path = PATH_CLAUDE_FLAGS.has(flag);
146
+ if (!path && !ALLOWED_CLAUDE_FLAGS.has(flag)) {
123
147
  throw notAllowed(i, flag);
124
148
  }
125
149
  const value = args[i + 1];
@@ -129,7 +153,7 @@ export function assertAllowedArgs(args) {
129
153
  if (value.startsWith('-')) {
130
154
  throw new HerdrArgvError(say('herdr.argv-value-like-flag.quoted', { flag }));
131
155
  }
132
- if (!ARG_VALUE_PATTERN.test(value)) {
156
+ if (path ? !isPluginDirValue(value) : !ARG_VALUE_PATTERN.test(value)) {
133
157
  throw new HerdrArgvError(say('herdr.argv-value-charset.quoted', { flag }));
134
158
  }
135
159
  i += 2;
@@ -148,7 +172,7 @@ function assertValue(flag, value) {
148
172
  * **ZERO argumentów pozycyjnych** — funkcja nie ma nawet parametru na prompt i mieć go nie
149
173
  * będzie (`docs/security-model.md`, „Starting sessions from the phone: three powers”).
150
174
  * Kolejność flag jest kontraktem: `--session-id`, `--resume` (+ `--fork-session`),
151
- * `--model`, `--effort`, `--permission-mode`.
175
+ * `--model`, `--effort`, `--permission-mode`, `--plugin-dir` (coordinator start and resume only, never a fork).
152
176
  *
153
177
  * Brak `req.model` → BRAK flagi `--model` (model domyślny konta) — to jest ścieżka DOMYŚLNA,
154
178
  * a nie przypadek brzegowy. Tak samo `effort` i `permissionMode`.
@@ -229,6 +253,13 @@ export function buildClaudeArgs(req, sessionId) {
229
253
  }
230
254
  args.push('--permission-mode', assertValue('--permission-mode', req.permissionMode));
231
255
  }
256
+ // A fork of the coordinator is an ordinary session, so it never gets the coordinator plugin.
257
+ if (req.pluginDir !== undefined && !forking) {
258
+ if (!isPluginDirValue(req.pluginDir)) {
259
+ throw new HerdrArgvError(say('herdr.argv-value-charset.quoted', { flag: '--plugin-dir' }));
260
+ }
261
+ args.push('--plugin-dir', req.pluginDir);
262
+ }
232
263
  assertAllowedArgs(args);
233
264
  return args;
234
265
  }
@@ -20,10 +20,12 @@
20
20
  import { appendFile, chmod, mkdir, rename, stat } from 'node:fs/promises';
21
21
  import { createHash } from 'node:crypto';
22
22
  import path from 'node:path';
23
- import { CLI_DIALOG_CLASSES, REFUSE_REASONS } from '@rarog/shared';
23
+ import { CLI_DIALOG_CLASSES, DIALOG_LIVE_KEYS, REFUSE_REASONS } from '@rarog/shared';
24
24
  import { REDACTED, redact } from '../auth/index.js';
25
25
  import { HOOK_BUDGET_SOURCES } from './hook-config.js';
26
26
  import { BLOCK_CARD_VERDICTS, DIALOG_ROUTES, DIALOG_ROUTE_REASONS, LAYER2_EPISODE_VERDICTS, LAYER2_WHYS, SHADOW_RESULTS, TERMINAL_DIALOG_IDS, } from './dialogs/index.js';
27
+ import { LIVE_CARD_SHAPES, LIVE_VERIFY_OUTCOMES } from './dialogs/live/model.js';
28
+ import { LIVE_ENTER_WHYS } from './dialogs/live/policy.js';
27
29
  import { NO_PROOF_REASONS } from './dialogs/shadow/evidence.js';
28
30
  export const HERDR_AUDIT_FILENAME = 'herdr-audit.log';
29
31
  /** Powyżej tego rozmiaru plik jedzie do `.log.1` (jedna generacja wstecz, jak `client.log`). */
@@ -135,6 +137,20 @@ export const AUDIT_MISMATCH_REASONS = [
135
137
  * `jsonl` — wpis transkryptu, `hook` — zrzut hooka, `screen` — sam ekran.
136
138
  */
137
139
  export const AUDIT_CARD_SOURCES = ['jsonl', 'hook', 'screen'];
140
+ /**
141
+ * What came of a key of the live card (`liveResult`): it went (`sent`), the step refused it before any key
142
+ * (`refused`, with `reason`), or the client call failed after it started (`failed`, reason `send-failed`): the key
143
+ * may have reached the pane.
144
+ */
145
+ export const LIVE_KEY_RESULTS = ['sent', 'refused', 'failed'];
146
+ /** The fields of the live card lines, those set: the driver copies them into its entry in one step. */
147
+ export function pickLiveFields(shape) {
148
+ const { liveShape, liveKeys, liveWhy, liveKey, liveRev, liveResult, liveOutcome, engineSessionId } = shape;
149
+ const all = {
150
+ liveShape, liveKeys, liveWhy, liveKey, liveRev, liveResult, liveOutcome, engineSessionId,
151
+ };
152
+ return Object.fromEntries(Object.entries(all).filter(([, value]) => value !== undefined));
153
+ }
138
154
  /** Kind of key a layer 2 card sent (`layer2Key`): a digit, a key of the key row (`send/key-row.ts`) or Esc. */
139
155
  export const LAYER2_KEY_KINDS = ['digit', 'key', 'escape'];
140
156
  /**
@@ -230,6 +246,18 @@ export function auditShapeFields(shape) {
230
246
  ? shape.layer2Key : undefined);
231
247
  put('layer2Outcome', shape.layer2Outcome !== undefined
232
248
  && LAYER2_VERIFY_OUTCOMES.includes(shape.layer2Outcome) ? shape.layer2Outcome : undefined);
249
+ put('liveShape', shape.liveShape !== undefined && LIVE_CARD_SHAPES.includes(shape.liveShape)
250
+ ? shape.liveShape : undefined);
251
+ put('liveWhy', shape.liveWhy !== undefined && LIVE_ENTER_WHYS.includes(shape.liveWhy)
252
+ ? shape.liveWhy : undefined);
253
+ put('liveKey', shape.liveKey !== undefined && DIALOG_LIVE_KEYS.includes(shape.liveKey)
254
+ ? shape.liveKey : undefined);
255
+ put('liveRev', auditCount(shape.liveRev));
256
+ put('liveResult', shape.liveResult !== undefined && LIVE_KEY_RESULTS.includes(shape.liveResult)
257
+ ? shape.liveResult : undefined);
258
+ put('liveOutcome', shape.liveOutcome !== undefined
259
+ && LIVE_VERIFY_OUTCOMES.includes(shape.liveOutcome) ? shape.liveOutcome : undefined);
260
+ put('engineSessionId', auditId(shape.engineSessionId));
233
261
  return out;
234
262
  }
235
263
  /** Ścieżka dziennika dla katalogu danych Raroga. */
@@ -251,6 +279,9 @@ function toLine(event, at, secrets) {
251
279
  entry['sender'] = event.sender;
252
280
  if (event.keys !== undefined)
253
281
  entry['keys'] = [...event.keys];
282
+ if (event.liveKeys !== undefined) {
283
+ entry['liveKeys'] = event.liveKeys.filter((key) => DIALOG_LIVE_KEYS.includes(key));
284
+ }
254
285
  /*
255
286
  * Kontekst decyzji (`docs/security-model.md`, „Starting sessions from the phone: three powers”).
256
287
  * Wpis `keys: ['1']` nie odpowiada na pytanie „co zatwierdzono" —
@@ -77,6 +77,25 @@ export const CLI_SHAPES = {
77
77
  cli: '2.1.296',
78
78
  common: { prompt: ORDINARY_WORD, origin: ORDINARY_WORD, kind: ORDINARY_WORD, human: ORDINARY_WORD },
79
79
  },
80
+ /**
81
+ * A message another Claude session sent with `SendMessage` lands in the receiving session's main file on the same
82
+ * two carriers as a human prompt: a meta `user` entry when the receiver is idle, a queue attachment in prompt mode
83
+ * when the message is absorbed into a running turn. Both carry the origin kind `peer`, the sender's inbox socket in
84
+ * `from` and the bare message text in `body`. A subagent's message to its parent has the same origin kind and a
85
+ * `body`, but `from` holds the agent id, never a socket address. The sender's process id stands in
86
+ * `verifiedPeerPid` and, as `<pid>.sock`, in the socket's file name. Measured by hand on session files
87
+ * (CLI 2.1.302–2.1.332). Read by `queued-prompt.ts` and `coordination/merge-prompt.ts`.
88
+ */
89
+ crossSessionPeer: {
90
+ what: 'origin of a message from another Claude session: kind, sender socket, sender process and message text',
91
+ literals: { peer: 'peer', from: 'from', body: 'body', socket: 'uds:', verifiedPid: 'verifiedPeerPid' },
92
+ cli: '2.1.331',
93
+ common: {
94
+ peer: 'origin kind shared with subagent messages; modules that tell senders apart may read it too',
95
+ from: ORDINARY_WORD,
96
+ body: ORDINARY_WORD,
97
+ },
98
+ },
80
99
  notificationOrigin: {
81
100
  what: 'wartość `origin.kind` wpisu, którą CLI znakuje notkę o zadaniu w tle (bramka notki)',
82
101
  literals: { kind: 'task-notification' },
@@ -23,6 +23,10 @@
23
23
  * w regule dla wpisu `user`: wśród 112 zmierzonych promptów człowieka nie miał go żaden, a każda
24
24
  * z 40 wiadomości od subagentów go niesie. Kierunek awarii jest ten sam co przed tym modułem (wiadomości nie
25
25
  * widać), nigdy odwrotny (cudzy tekst jako wypowiedź użytkownika).
26
+ *
27
+ * The module also recognizes a message from another Claude session ({@link crossSessionPrompt}), on this carrier and
28
+ * on the meta `user` entry. It is a separate function with its own condition, so the human prompt rule above stays
29
+ * as it is; the parser shows such a message only when its caller asks for it.
26
30
  */
27
31
  import { CLI_SHAPES } from './cli-shapes.js';
28
32
  const CARRIERS = CLI_SHAPES.notificationCarriers.literals;
@@ -50,3 +54,45 @@ export function queuedHumanPrompt(value) {
50
54
  const at = entry['timestamp'];
51
55
  return { prompt: attachment[CARRIERS.queuedText], at: typeof at === 'string' ? at : '' };
52
56
  }
57
+ const PEER = CLI_SHAPES.crossSessionPeer.literals;
58
+ /**
59
+ * Whether an entry of the MAIN file is a message another Claude session sent with `SendMessage`; `null` = no.
60
+ *
61
+ * Both carriers count, so an idle receiver and a turn that absorbed the message give the same text: the meta `user`
62
+ * entry (idle) and the queue attachment in prompt mode (mid-turn). The origin must be exactly `peer` with a socket
63
+ * address in `from` and a non-empty `body`; a subagent's message (`from` = agent id), a delivery or idle notice
64
+ * (no `peer` origin) and an unmeasured origin stay out. Whether such a message is shown at all is the caller's call:
65
+ * the text is model-written, not typed by the user.
66
+ */
67
+ export function crossSessionPrompt(value) {
68
+ const entry = asRecord(value);
69
+ if (entry === null || entry['isSidechain'] === true)
70
+ return null;
71
+ let origin;
72
+ if (entry['type'] === 'user') {
73
+ if (entry['isMeta'] !== true)
74
+ return null;
75
+ origin = asRecord(entry[QUEUED.origin]);
76
+ }
77
+ else if (entry['type'] === CARRIERS.attachmentType) {
78
+ const attachment = asRecord(entry[CARRIERS.attachmentField]);
79
+ if (attachment === null || attachment['type'] !== CARRIERS.queuedCommand)
80
+ return null;
81
+ if (attachment[QUEUED.mode] !== QUEUED.prompt)
82
+ return null;
83
+ origin = asRecord(attachment[QUEUED.origin]);
84
+ }
85
+ else {
86
+ return null;
87
+ }
88
+ if (origin === null || origin[QUEUED.kind] !== PEER.peer)
89
+ return null;
90
+ const from = origin[PEER.from];
91
+ const body = origin[PEER.body];
92
+ if (typeof from !== 'string' || !from.startsWith(PEER.socket))
93
+ return null;
94
+ if (typeof body !== 'string' || body.trim() === '')
95
+ return null;
96
+ const at = entry['timestamp'];
97
+ return { body, at: typeof at === 'string' ? at : '' };
98
+ }
@@ -144,6 +144,18 @@ export function stuckWaits(state, before, after) {
144
144
  export function holdsOwedDone(tasks) {
145
145
  return tasksHoldingDonePush(tasks) > 0 || waitingOnOwnCommand(tasks);
146
146
  }
147
+ /**
148
+ * Subagents that woke between two lists of a session: in standby ({@link waitingAgent}) on the list `before`, on the
149
+ * list `after` under the same id without `waitingSince` (the wake overlay of `merge.ts`). A subagent works in the
150
+ * main pane, so herdr reports that pane as working although the main agent got no input; the manager counts these
151
+ * wakes into the turn tally, and a turn with no input but a wake has no result (`noResultTurn` in
152
+ * `notify/policy.ts`). Not a wake: an agent new on the list, one that came back from dormancy (it was off the list),
153
+ * and one that woke and stood again between two lists (a new `waitingSince`).
154
+ */
155
+ export function agentsWoken(before, after) {
156
+ const waiting = new Set((before ?? []).filter(waitingAgent).map((task) => task.id));
157
+ return (after ?? []).filter((task) => task.kind === 'agent' && !waitingAgent(task) && waiting.has(task.id)).length;
158
+ }
147
159
  /**
148
160
  * Restart sesji na nowym Claude Code: czy lista go blokuje.
149
161
  *
@@ -3,23 +3,27 @@
3
3
  * herdr → klasy błędów Raroga.
4
4
  *
5
5
  * Tu mieszka też TWARDY FILTR WEJŚCIOWY integracji: `agent === 'claude'` (a przy
6
- * `RAROG_CODEX_STATUS` także `agent === 'codex'`), `agent_session.kind === 'id'`
7
- * i `value` pasujące do `ENGINE_SESSION_ID_PATTERN`. Filtr musi być w tym miejscu, bo tylko tu
6
+ * `RAROG_CODEX_STATUS` także `agent === 'codex'`, a przy `RAROG_AGY_STATUS` `agent === 'agy'`; rodzaje zna
7
+ * `engineOfAgent` z `engines.ts`),
8
+ * `agent_session.kind === 'id'` i `value` pasujące do `ENGINE_SESSION_ID_PATTERN`. Filtr musi być
9
+ * w tym miejscu, bo tylko tu
8
10
  * widać jeszcze surowe pola `agent`/`kind` — kontrakt `HerdrAgentInfo` ich nie niesie.
9
11
  * Cokolwiek innego (inny agent, `kind: 'path'`, panel bez `cwd`) NIE ISTNIEJE dla Raroga:
10
12
  * nie ma pliku transkryptu, nie ma sprawdzalnego zakresu, nie ma czego pokazać.
13
+ * A state-only engine is the exception to the session rule: without a session ID it enters with
14
+ * `agentSessionId: ''`.
11
15
  *
12
16
  * Nieznane pola odpowiedzi IGNORUJEMY (`z.looseObject`, nie `z.strictObject`): herdr wydaje
13
17
  * minor co 2–3 tygodnie i dokłada pola addytywnie, a Rarog nie ma prawa paść od nowego pola.
14
18
  */
15
19
  import { z } from 'zod';
16
- import { basename } from 'node:path';
17
20
  import { TERM_ID_RE } from '@rarog/shared';
18
21
  import { foreign, say } from '@rarog/shared/sentences';
19
22
  import { HERDR_PROMPT_WAIT_MS, HERDR_START_REQUEST_TIMEOUT_MS, HERDR_START_WAIT_MS, termPaneTokenOf, } from '../config.js';
20
23
  import { ENGINE_SESSION_ID_PATTERN } from '../transcript-import.js';
21
24
  import { assertAllowedKeys } from './dialogs/send/keys.js';
22
25
  import { RAROG_AGENT_NAME_RE } from './provenance.js';
26
+ import { engineOfAgent, isStateOnlyEngine, normalizeEngineTitle } from './engines.js';
23
27
  import { FORM_SUBMIT_KEY, assertFormSubmitKeys } from './dialogs/send/form-submit.js';
24
28
  import { MODE_CYCLE_KEY, assertModeCycleKeys } from './mode-cycle.js';
25
29
  import { assertDialogKey } from './dialogs/send/key-row.js';
@@ -257,31 +261,6 @@ const startAgentResultSchema = z.looseObject({
257
261
  function toStatus(raw) {
258
262
  return KNOWN_STATUSES.has(raw) ? raw : 'unknown';
259
263
  }
260
- /** Klatka spinnera Codexa: znak brajlowski (U+2800–U+28FF) z odstępem za nim. */
261
- const CODEX_SPINNER_RE = /^[⠀-⣿]+\s*/u;
262
- /**
263
- * Tytuł Codexa → tytuł dla karty. JEDNO miejsce, w którym znika spinner i katalog.
264
- *
265
- * Zmierzone na żywym herdr 0.9.0: `terminal_title_stripped` Codexa ma kształt
266
- * `<pierwszy prompt> | <katalog>`, w trakcie pracy z wiodącą klatką spinnera braille (`⠴ …`),
267
- * a przed pierwszym promptem jest SAMĄ nazwą katalogu.
268
- *
269
- * Normalizacja musi być tutaj, a nie w warstwie widoku, z dwóch powodów: nadzorca porównuje
270
- * tytuły między migawkami, więc kolejne klatki spinnera zgłaszałyby `titleChanged` kilka razy
271
- * na sekundę, a manager ma dostać w zdarzeniu tekst, który da się pokazać bez dalszej obróbki.
272
- * Sufiks katalogu zdejmujemy, bo nazwę projektu wiersz w kliencie i tak bierze z `cwd` — zostawiony
273
- * dublowałby ją w każdym wierszu.
274
- */
275
- export function normalizeCodexTitle(raw, cwd) {
276
- const dir = basename(cwd);
277
- let title = raw.replace(CODEX_SPINNER_RE, '').trim();
278
- if (dir !== '' && title.endsWith(` | ${dir}`)) {
279
- title = title.slice(0, title.length - dir.length - 3).trim();
280
- }
281
- // Tytuł równy samej nazwie katalogu = panel PRZED pierwszym promptem. Pusty string znaczy
282
- // „nie ma tytułu", a manager zamienia go na nazwę katalogu tą samą regułą co dla Claude.
283
- return title === dir ? '' : title;
284
- }
285
264
  /**
286
265
  * Surowy wpis herdr → `HerdrAgentInfo`, albo `null`, gdy agent nie jest dla Raroga.
287
266
  *
@@ -293,22 +272,18 @@ export function normalizeAgentInfo(raw, opts = {}) {
293
272
  if (!parsed.success)
294
273
  return null;
295
274
  const info = parsed.data;
296
- /*
297
- * Bramka silnika. `codex` wchodzi WYŁĄCZNIE przy jawnej fladze; każdy inny agent
298
- * (`future-agent`, `aider`, …) odpada tak jak dotąd — Rarog nie zna ani jego stopki, ani
299
- * jego pliku treści, więc wiersz w sidebarze byłby obietnicą bez pokrycia.
300
- */
301
- const engine = info.agent === 'claude' ? 'claude'
302
- : (info.agent === 'codex' && opts.codexStatus === true ? 'codex' : null);
275
+ // Engine gate: the registry admits `claude` and, behind its flag, each state-only engine.
276
+ const engine = engineOfAgent(info.agent, {
277
+ codexStatus: opts.codexStatus === true, agyStatus: opts.agyStatus === true,
278
+ });
303
279
  if (engine === null)
304
280
  return null;
305
281
  const session = info.agent_session;
306
- if (session === null || session === undefined)
307
- return null;
308
- if (session.kind !== 'id')
309
- return null;
310
- const value = session.value;
311
- if (typeof value !== 'string' || !ENGINE_SESSION_ID_PATTERN.test(value))
282
+ const value = session?.kind === 'id' && typeof session.value === 'string'
283
+ && ENGINE_SESSION_ID_PATTERN.test(session.value) ? session.value : '';
284
+ // Claude needs its session (the transcript file). A state-only engine enters without one, as `''`: herdr 0.9.5
285
+ // reports no `agent_session` for Codex CLI 0.171.0, and the session only addresses the seen mark.
286
+ if (value === '' && !isStateOnlyEngine(engine))
312
287
  return null;
313
288
  const cwd = info.cwd;
314
289
  if (typeof cwd !== 'string' || cwd === '')
@@ -345,9 +320,10 @@ export function normalizeAgentInfo(raw, opts = {}) {
345
320
  // założonych ręcznie w terminalu — czyli do całej dotychczasowej wartości Raroga.
346
321
  // Wpis Codexa jest tu WYJĄTKIEM i to jego jedyne miejsce: nic do niego nie wysyłamy,
347
322
  // a odpowiedź herdr tego pola dla Codexa w ogóle nie niesie (zmierzone).
348
- interactiveReady: engine === 'codex' ? false : (info.interactive_ready ?? true),
349
- title: engine === 'codex'
350
- ? normalizeCodexTitle(info.terminal_title_stripped ?? '', cwd)
323
+ // An agy record does carry `interactive_ready: true`; a state-only entry still takes no sending.
324
+ interactiveReady: isStateOnlyEngine(engine) ? false : (info.interactive_ready ?? true),
325
+ title: isStateOnlyEngine(engine)
326
+ ? normalizeEngineTitle(engine, info.terminal_title_stripped ?? '', cwd)
351
327
  : (info.terminal_title_stripped ?? ''),
352
328
  stateChangeSeq: info.state_change_seq ?? 0,
353
329
  };
@@ -545,7 +521,7 @@ async function readPaneHistory(call, paneId, lines) {
545
521
  /**
546
522
  * Typowana fasada nad transportem.
547
523
  *
548
- * `opts` niesie dziś jedną rzecz — flagę `RAROG_CODEX_STATUS`. Jest polem FASADY,
524
+ * `opts` niesie flagi silników samego stanu (`RAROG_CODEX_STATUS`, `RAROG_AGY_STATUS`). Są polem FASADY,
549
525
  * a nie argumentem każdego wywołania, bo obie drogi wpisu (`agent.list` przy resyncu
550
526
  * i `agent.get` przy pushu) muszą filtrować IDENTYCZNIE: jedna bramka, jedno źródło prawdy.
551
527
  */
@@ -573,7 +549,7 @@ export function createHerdrClient(requester, opts = {}) {
573
549
  const info = parsed.success ? normalizeAgentInfo(parsed.data.agent, opts) : null;
574
550
  if (info === null) {
575
551
  // Panel istnieje, ale nie jest już agentem obsługiwanym przez Raroga (Claude, a przy
576
- // `RAROG_CODEX_STATUS` także Codex) z sesją po id — dla Raroga to dokładnie to samo,
552
+ // fladze silnika także Codex albo agy) — dla Raroga to dokładnie to samo,
577
553
  // co zniknięcie panelu.
578
554
  throw new HerdrGoneError(say('herdr.agent-gone', { key: paneId }));
579
555
  }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Katalog komend sesji — JEDNA migawka tego, co Rarog przepuszcza z telefonu, per `(cwd, wersja CLI)`.
2
+ * Katalog komend sesji — JEDNA migawka tego, co Rarog przepuszcza z telefonu, per `(cwd, wersja CLI)` and the
3
+ * session's plugin directories (`--plugin-dir` of a coordinator).
3
4
  *
4
5
  * Migawka = wpisy `allowed` rejestru wbudowanych (`registry.ts`, zmierzone per wersja CLI) ∪ wbudowane
5
6
  * skille `allowed` ∪ skille i komendy z dysku w opisanym podzbiorze (`discover.ts`). Ta sama migawka idzie
@@ -141,14 +142,15 @@ export function createCommandCatalogs(opts) {
141
142
  opts.log?.(line);
142
143
  };
143
144
  return {
144
- get(cwd, cliVersion) {
145
+ get(cwd, cliVersion, pluginDirs = []) {
145
146
  if (cliVersion !== COMMANDS_CLI) {
146
147
  logOnce(`command catalog: CLI ${cliVersion ?? 'of unknown version'} not measured — built-in set `
147
148
  + `from the ${COMMANDS_CLI} measurement`);
148
149
  }
149
- // Jedna wersja zmierzona = jeden zestaw wbudowanych, więc klucz pamięci to sam katalog.
150
+ // Jedna wersja zmierzona = jeden zestaw wbudowanych, więc klucz pamięci to katalog i pluginy sesji.
151
+ const key = pluginDirs.length === 0 ? cwd : JSON.stringify([cwd, ...pluginDirs]);
150
152
  const at = now();
151
- const entry = cache.get(cwd);
153
+ const entry = cache.get(key);
152
154
  if (entry !== undefined) {
153
155
  if (at - entry.checkedAt < checkMs)
154
156
  return entry.catalog;
@@ -158,21 +160,23 @@ export function createCommandCatalogs(opts) {
158
160
  }
159
161
  let discovered;
160
162
  try {
161
- discovered = discover({ home: opts.home, cwd, roots: opts.roots, reserved });
163
+ discovered = discover({
164
+ home: opts.home, cwd, roots: opts.roots, reserved, ...(pluginDirs.length === 0 ? {} : { pluginDirs }),
165
+ });
162
166
  }
163
167
  catch (error) {
164
168
  // Skan nie rzuca z założenia; gdyby jednak — wysyłka nie dostaje 500, tylko allow-listę z samego
165
169
  // rejestru (skille z dysku dostają odmowę), a następne pytanie skanuje od nowa.
166
170
  logOnce(`command catalog: disk scan for ${cwd} failed (${error instanceof Error ? error.name : 'error'}) `
167
171
  + '— snapshot from the registry alone');
168
- cache.delete(cwd);
172
+ cache.delete(key);
169
173
  return registryCatalog();
170
174
  }
171
175
  for (const note of discovered.notes)
172
176
  logOnce(note);
173
177
  const fresh = buildCatalog(cwd, discovered);
174
178
  const catalog = entry !== undefined && entry.catalog.revision === fresh.revision ? entry.catalog : fresh;
175
- cache.set(cwd, { catalog, stamps: discovered.stamps, checkedAt: at, scannedAt: at });
179
+ cache.set(key, { catalog, stamps: discovered.stamps, checkedAt: at, scannedAt: at });
176
180
  return catalog;
177
181
  },
178
182
  };