@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,172 @@
1
+ /**
2
+ * Start of a project coordinator, decided before anything exists in herdr. A Launch with the coordinator switch
3
+ * reserves its project's role in the coordinator registry; a resume of the conversation the registry keeps for the
4
+ * project reserves it again; a fork and any other resume stay ordinary. A reserved start gets the plugin copy for
5
+ * `--plugin-dir` and `/rarog:coordinator` as its first prompt, and its ticket settles the reservation exactly once.
6
+ * The module starts no process and writes no session state; the plugin path comes from the copy it made, never from
7
+ * the client.
8
+ */
9
+ import path from 'node:path';
10
+ import { say } from '@rarog/shared/sentences';
11
+ import { projectOfSession } from '../coordination/summary.js';
12
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
13
+ import { DISK_LAYOUT } from '../herdr/commands/registry.js';
14
+ import { BadRequestError, BadStateError } from './errors.js';
15
+ /** The coordinator skill of the plugin; every coordinator start and resume sends it first, so its rules are fresh. */
16
+ export const COORDINATOR_SKILL_COMMAND = '/rarog:coordinator';
17
+ /** A process whose state is one of these is gone, so it runs from no plugin copy. */
18
+ const GONE = new Set(['done', 'resumable']);
19
+ /**
20
+ * First prompt of a coordinator start: the skill command with the user's prompt as its arguments. A prompt that
21
+ * already starts with the command (the start prompt sent again after a hook blocked it) stays as it is.
22
+ */
23
+ export function coordinatorPrompt(prompt) {
24
+ const own = prompt ?? '';
25
+ if (own.trim() === '')
26
+ return COORDINATOR_SKILL_COMMAND;
27
+ const first = /^\S+/.exec(own.trimStart())?.[0] ?? '';
28
+ return first.toLowerCase() === COORDINATOR_SKILL_COMMAND ? own : `${COORDINATOR_SKILL_COMMAND} ${own}`;
29
+ }
30
+ /** The user's words of a coordinator's start prompt (the text after the skill command) for the card label. */
31
+ export function coordinatorLabel(text) {
32
+ const trimmed = text.trim();
33
+ const own = trimmed.toLowerCase().startsWith(COORDINATOR_SKILL_COMMAND)
34
+ ? trimmed.slice(COORDINATOR_SKILL_COMMAND.length).trim()
35
+ : trimmed;
36
+ return own === '' ? null : own;
37
+ }
38
+ /** The plugin directories of a session's command catalog: its coordinator plugin copy, if any. */
39
+ export function pluginDirsOf(session) {
40
+ return typeof session.pluginDir === 'string' ? [session.pluginDir] : undefined;
41
+ }
42
+ /**
43
+ * The `--plugin-dir` values of the live sessions, which the copy keeps; `null` while a live session's arguments are
44
+ * not known (a pane found after a server restart may run a coordinator from an older copy), and then nothing goes.
45
+ */
46
+ export function pluginCopiesInUse(sessions) {
47
+ const dirs = new Set();
48
+ for (const session of sessions) {
49
+ if (GONE.has(session.state))
50
+ continue;
51
+ if (session.pluginDir === undefined)
52
+ return null;
53
+ if (session.pluginDir !== null)
54
+ dirs.add(session.pluginDir);
55
+ }
56
+ return dirs;
57
+ }
58
+ class Ticket {
59
+ pluginDir;
60
+ #registry;
61
+ #reservation;
62
+ #roleChanged;
63
+ #settled = false;
64
+ constructor(registry, reservation, pluginDir, roleChanged) {
65
+ this.#registry = registry;
66
+ this.#reservation = reservation;
67
+ this.pluginDir = pluginDir;
68
+ this.#roleChanged = roleChanged;
69
+ }
70
+ release() {
71
+ if (this.#settled)
72
+ return;
73
+ this.#settled = true;
74
+ this.#registry.release(this.#reservation);
75
+ }
76
+ started(card) {
77
+ if (this.#settled)
78
+ return;
79
+ card.ready.then(() => {
80
+ if (this.#settled)
81
+ return;
82
+ if (!card.current()) {
83
+ this.release();
84
+ return;
85
+ }
86
+ this.#settled = true;
87
+ this.#registry.confirm(this.#reservation, card.id, card.conversation);
88
+ this.#roleChanged(card.id);
89
+ }, () => { this.release(); });
90
+ }
91
+ }
92
+ /** The coordinator decision of every start; one instance per server, shared by every manager start. */
93
+ export class CoordinatorStart {
94
+ #registry;
95
+ #pluginCopy;
96
+ #roleChanged;
97
+ #log;
98
+ #disk;
99
+ constructor(opts) {
100
+ this.#registry = opts.registry;
101
+ this.#pluginCopy = opts.pluginCopy;
102
+ this.#roleChanged = opts.roleChanged;
103
+ this.#log = opts.log;
104
+ this.#disk = opts.disk ?? DIRECT_DISK;
105
+ }
106
+ /**
107
+ * The ticket of a coordinator start, or `null` for an ordinary one. Synchronous from the reservation to the copy,
108
+ * so two starts cannot both pass. `coordinator` counts only for a new conversation: with `resumeFrom` the registry
109
+ * alone decides, so the switch never makes a resumed conversation the coordinator.
110
+ *
111
+ * @throws {BadRequestError} the Launch is not in the top folder of a project's main git checkout
112
+ * @throws {BadStateError} the project's coordinator lives or starts, or the plugin copy failed
113
+ */
114
+ admit(opts, port) {
115
+ if (opts.fork === true)
116
+ return null;
117
+ let reservation;
118
+ if (opts.resumeFrom !== undefined) {
119
+ const project = projectOfSession({ peek: () => undefined }, opts.cwd, this.#disk);
120
+ const id = opts.sessionId ?? port.aliasFor(opts.resumeFrom);
121
+ const reserved = this.#registry.reserveResume(project, opts.resumeFrom, id);
122
+ if (reserved === null)
123
+ return null;
124
+ reservation = reserved;
125
+ }
126
+ else if (opts.coordinator === true) {
127
+ reservation = this.#reserveLaunch(opts.cwd, port);
128
+ }
129
+ else {
130
+ return null;
131
+ }
132
+ const copy = this.#pluginCopy(pluginCopiesInUse(port.sessions()));
133
+ if (!copy.ok) {
134
+ this.#registry.release(reservation);
135
+ this.#log(`coordinator: plugin copy failed (${copy.code}): ${copy.reason}`);
136
+ throw new BadStateError(copy.code === 'path'
137
+ ? say('session.coordinator-plugin-path')
138
+ : say('session.coordinator-plugin-missing', { reason: copy.code }));
139
+ }
140
+ return new Ticket(this.#registry, reservation, copy.dir, this.#roleChanged);
141
+ }
142
+ /**
143
+ * A Launch reserves the project of its directory, which must be the top folder of a main checkout: `.git` right
144
+ * under it is a directory. The registry keys a project by the main checkout the summary overlay reads
145
+ * (`projectOfSession`), and in a subdirectory or a linked worktree the Launch directory is another string.
146
+ * A live process of the project's stored conversation refuses the Launch like a live coordinator: after a server
147
+ * restart nothing in memory knows it ran with the plugin, and the plugin of a second coordinator would refuse its
148
+ * claim while the first lives. An unknown process reading admits.
149
+ */
150
+ #reserveLaunch(cwd, port) {
151
+ const refused = new BadRequestError(say('session.coordinator-not-project', { cwd }));
152
+ let project;
153
+ try {
154
+ const real = this.#disk.sync('realpath', { path: cwd });
155
+ if (!this.#disk.sync('lstat', { path: path.join(real, DISK_LAYOUT.gitDir) }).isDirectory())
156
+ throw refused;
157
+ project = projectOfSession({ peek: () => undefined }, cwd, this.#disk);
158
+ }
159
+ catch {
160
+ // A missing `.git`, a closed guarded folder or any other read error: no proof of a main checkout.
161
+ throw refused;
162
+ }
163
+ const reserved = this.#registry.reserveLaunch(project, (conversation) => port.cliPids(conversation) !== null);
164
+ if (reserved.ok)
165
+ return reserved.reservation;
166
+ if (reserved.reason === 'live')
167
+ throw new BadStateError(say('session.coordinator-live'));
168
+ if (reserved.reason === 'starting')
169
+ throw new BadStateError(say('session.coordinator-starting'));
170
+ throw refused;
171
+ }
172
+ }
@@ -10,6 +10,7 @@ export async function loadDemoModules(content) {
10
10
  demoDiff: () => seeds.demoDiff(content),
11
11
  demoDiffFiles: seeds.demoDiffFiles,
12
12
  demoDiffFile: (path) => seeds.demoDiffFile(content, path),
13
+ demoBranchDiffFiles: seeds.demoBranchDiffFiles,
13
14
  demoFileEntries: files.demoFileEntries,
14
15
  demoFileBytes: files.demoFileBytes,
15
16
  };
@@ -0,0 +1,100 @@
1
+ import { classifyRisk } from '../risk.js';
2
+ import { STALE } from '../drivers/types.js';
3
+ import { permissionSemantics } from '../drivers/tool-text.js';
4
+ import { Session } from './session.js';
5
+ import { seedDetailField } from './state-sentences.js';
6
+ /**
7
+ * Sesje demo — jedyne miejsce, w którym karta powstaje bez udziału herdr.
8
+ *
9
+ * Ziarna niosą historię, wiersz gita i czekającą zgodę, czyli rzeczy, których `HerdrAgent`
10
+ * nie ma i mieć nie może. Driver dla nich daje MOCK NADZORCY (`demo/mock-herdr.ts`) przez
11
+ * `attach(key)` — dzięki temu demo chodzi tą samą ścieżką co produkcja i żaden scenariusz
12
+ * (zgoda, pytanie, limit, błąd, git) nie ginie.
13
+ */
14
+ export function applyDemoSeeds(port) {
15
+ const supervisor = port.supervisor;
16
+ const now = port.now;
17
+ const demo = port.demo;
18
+ for (const seed of demo.demoSeeds(now)) {
19
+ const session = new Session({
20
+ id: seed.id,
21
+ cwd: seed.cwd,
22
+ title: seed.title,
23
+ // Panel „Raroga" także w demo: dzięki temu da się przeklikać ścieżkę „Zamknij panel"
24
+ // (i jej potwierdzenie), a nie tylko „Ukryj".
25
+ herdrKey: seed.id,
26
+ paneId: `w0:${seed.id}`,
27
+ launchedByRarog: true,
28
+ // Seed niesie gotową etykietę; gdyby jej nie miał, liczymy ją z pierwszego promptu
29
+ // dokładnie tak, jak przy prawdziwym `create()`.
30
+ label: seed.label ?? port.labelFor(seed.cwd, seedPrompt(seed)),
31
+ state: seed.state,
32
+ ...seedDetailField(seed),
33
+ stateSince: port.iso(now - seed.stateSinceAgoMs),
34
+ createdAt: port.iso(now - seed.createdAtAgoMs),
35
+ lastActivityAt: port.iso(now - seed.lastActivityAgoMs),
36
+ branch: seed.branch,
37
+ dirtyCount: seed.dirtyCount,
38
+ ahead: seed.ahead,
39
+ behind: seed.behind,
40
+ lastSummary: seed.lastSummary,
41
+ model: seed.model,
42
+ effort: seed.effort,
43
+ ultracode: seed.ultracode,
44
+ engineSessionId: seed.engineSessionId,
45
+ ...(seed.projectRoot === undefined ? {} : { projectRoot: seed.projectRoot }),
46
+ ...(seed.coordination === undefined ? {} : { coordination: seed.coordination }),
47
+ });
48
+ for (const message of seed.messages) {
49
+ session.appendMessage(message.role, demo.demoBlocks(message.blocks), port.iso(now - message.agoMs), message.attachments, message.notice === undefined ? {} : { notice: message.notice });
50
+ }
51
+ // `appendMessage` przesuwa `lastActivityAt` — seed decyduje o nim sam.
52
+ session.lastActivityAt = port.iso(now - seed.lastActivityAgoMs);
53
+ port.sessions.set(session.id, session);
54
+ port.herdrByKey.set(seed.id, session.id);
55
+ port.indexEngineSession(session);
56
+ if (seed.live !== undefined && supervisor !== undefined) {
57
+ // Mock nadzorcy zna scenariusz każdego ziarna po jego kluczu — model i effort też
58
+ // stamtąd, żeby pigułka w composerze pokazywała w demo realne warianty.
59
+ port.attachDriver(session, supervisor.attach(seed.id));
60
+ }
61
+ const permission = seed.permission;
62
+ if (permission !== undefined) {
63
+ const request = {
64
+ permId: permission.permId,
65
+ sessionId: session.id,
66
+ toolName: permission.toolName,
67
+ displayText: permission.displayText,
68
+ risk: classifyRisk(permission.displayText, permission.toolName),
69
+ cwd: session.cwd,
70
+ createdAt: port.iso(now - permission.agoMs),
71
+ subject: port.permissionSubject(permission.toolName),
72
+ // Ta sama reguła co na żywo — seed z komendą powłoki niesie jej input.
73
+ ...permissionSemantics(permission.input, permission.displayText),
74
+ };
75
+ port.pending.addPermission(request, async (decision, message) => {
76
+ // Sesja seeda bez drivera nie ma czym wysłać decyzji — `stale` jest tu prawdą
77
+ // (karta nie reprezentuje niczego żywego), a nie odmową do pokazania na ekranie.
78
+ const driver = session.driver;
79
+ if (driver === null)
80
+ return STALE;
81
+ return driver.respondPermission(permission.permId, decision, message);
82
+ });
83
+ // Do bufora (żeby replay transkryptu był spójny), bez broadcastu — nikt jeszcze nie słucha.
84
+ session.pushEvent({ type: 'permission-pending', request });
85
+ }
86
+ }
87
+ }
88
+ /** Pierwszy prompt użytkownika z seeda demo (do etykiety) albo `null`, gdy seed go nie ma. */
89
+ function seedPrompt(seed) {
90
+ for (const message of seed.messages) {
91
+ // Notka harnessu nie jest promptem człowieka — rola efektywna, nie `role`.
92
+ if (message.role !== 'user' || message.notice !== undefined)
93
+ continue;
94
+ for (const block of message.blocks) {
95
+ if (block.type === 'text' && block.text.trim() !== '')
96
+ return block.text;
97
+ }
98
+ }
99
+ return null;
100
+ }
@@ -1,5 +1,19 @@
1
1
  import { backdateState } from './activity-clocks.js';
2
2
  import * as seenMarks from './seen-marks.js';
3
+ import { ownerTurn } from './owner-turn.js';
4
+ import { dropTurnTally, tallyAfterHistory } from './state-sentences.js';
5
+ import { isStateOnlyEngine } from '../herdr/engines.js';
6
+ /**
7
+ * What a transcript message from the file ends of a send from Rarog: `turn` — the mark of the turn the send opened
8
+ * (an assistant entry or a `user` entry: the turn started, or someone else sent a prompt); `prompt` — the blocked
9
+ * prompt and its resend button (a `user` entry: the field no longer holds the blocked prompt). A message from another
10
+ * session was typed into no field and opened no send of this session, so it ends neither; a `system` note neither.
11
+ */
12
+ export function sendEndedBy(event) {
13
+ if (event.notFromOwner === true)
14
+ return { turn: false, prompt: false };
15
+ return { turn: event.role !== 'system', prompt: event.role === 'user' };
16
+ }
3
17
  /** `init` from the driver: engine session, model, effort, ultracode and pull requests of the conversation. */
4
18
  export function applyInitEvent(session, event, port) {
5
19
  /*
@@ -9,8 +23,9 @@ export function applyInitEvent(session, event, port) {
9
23
  * pliku jsonl", a Codex takiego pliku nie ma. Karta zostaje ta sama — jest jedna
10
24
  * na panel.
11
25
  */
12
- if (session.engine === 'codex') {
13
- session.observedSessionId = event.engineSessionId;
26
+ if (isStateOnlyEngine(session.engine)) {
27
+ // `''`: herdr stopped reporting a session for the pane; the seen mark goes back to the pane address.
28
+ session.observedSessionId = event.engineSessionId === '' ? undefined : event.engineSessionId;
14
29
  return;
15
30
  }
16
31
  const previousEngineSession = session.engineSessionId;
@@ -64,10 +79,13 @@ export function applyInitEvent(session, event, port) {
64
79
  */
65
80
  const imported = session.importedHistory;
66
81
  session.importedHistory = undefined;
82
+ // The owner's turn belongs to the conversation, so only a move changes it here (`owner-turn.ts`).
83
+ const ownerTurnBefore = conversationChanged && ownerTurn(session);
67
84
  if (conversationChanged) {
68
85
  session.conversationStartSeq = imported?.engineSessionId === event.engineSessionId
69
86
  ? imported.fromSeq : session.ring.lastSeq;
70
87
  }
88
+ const ownerTurnChanged = conversationChanged && ownerTurn(session) !== ownerTurnBefore;
71
89
  if (conversationChanged)
72
90
  port.conversationChanged(session.id, event.engineSessionId); // voice agent
73
91
  const nextUltracode = event.ultracode === null ? undefined
@@ -97,9 +115,9 @@ export function applyInitEvent(session, event, port) {
97
115
  session.emptyStart = false;
98
116
  port.applyTransition(session, { type: 'result', subtype: 'success' });
99
117
  // Jak w `#settleEmptyStart`: tura zerowa nie domyka rachunku wiadomości.
100
- session.turnInput = undefined;
118
+ dropTurnTally(session);
101
119
  }
102
- else if ((modelChanged || effortChanged || ultracodeChanged || pullRequestsDropped) && !moved) {
120
+ else if ((modelChanged || effortChanged || ultracodeChanged || pullRequestsDropped || ownerTurnChanged) && !moved) {
103
121
  /*
104
122
  * Sam model ani sam effort nie są przejściem stanu, więc karta musi dostać osobne
105
123
  * odświeżenie. Dotyczy to też effortu: `init` poza `starting` nie rusza stanu
@@ -120,9 +138,12 @@ export function applyInitEvent(session, event, port) {
120
138
  export function applyHistoryEvent(session, event, port) {
121
139
  if (session.state === 'done')
122
140
  return;
123
- // Historii nie liczymy, a bywa w niej prompt tury, która jeszcze trwa: po każdej porcji
124
- // rachunek wiadomości tury jest niepełny do następnego końca tury.
125
- session.turnInput = undefined;
141
+ /*
142
+ * History is not counted, and it may hold the prompt of a turn still running: after every portion the turn tally
143
+ * is incomplete until the next turn end. The exception is the attach history of a pane just adopted while it is out
144
+ * of a turn: the tally starts from zero there (`tallyAfterHistory`).
145
+ */
146
+ tallyAfterHistory(session, event.messages);
126
147
  // Where this conversation's history starts in memory, for an `init` that names it next (`applyInitEvent`).
127
148
  if (event.engineSessionId !== undefined && session.importedHistory?.engineSessionId !== event.engineSessionId) {
128
149
  session.importedHistory = { engineSessionId: event.engineSessionId, fromSeq: session.ring.lastSeq };
@@ -139,6 +160,7 @@ export function applyHistoryEvent(session, event, port) {
139
160
  port.appendMessage(session, item.role, item.blocks, item.at, item.attachments, {
140
161
  ...(item.notice !== undefined ? { notice: item.notice } : {}),
141
162
  ...(item.promptBlocked !== undefined ? { promptBlocked: item.promptBlocked } : {}),
163
+ ...(item.notFromOwner === true ? { notFromOwner: true } : {}),
142
164
  });
143
165
  }
144
166
  /*
@@ -183,6 +205,8 @@ function cardSignature(session) {
183
205
  // własne zdarzenia (`dialog-screen` porównuje pełny tekst) — dwa kilobajty ekranu w podpisie byłyby pracą
184
206
  // przy każdym obrocie resyncu.
185
207
  + `|${String(session.herdrDialogScreen?.length ?? 0)}|${session.cliDialog ?? ''}`
208
+ // The live card by occurrence and revision: its view changes only with a new revision (`dialog-live`).
209
+ + `|${session.herdrDialogLive?.id ?? ''}:${String(session.herdrDialogLive?.rev ?? '')}`
186
210
  + `|${String(session.stale)}`;
187
211
  }
188
212
  /**
@@ -195,6 +219,17 @@ function emitIfChanged(session, before, port) {
195
219
  if (cardSignature(session) !== before)
196
220
  port.emitSessionChanged(session);
197
221
  }
222
+ /**
223
+ * A state-only engine (Codex, agy) going from a standing dialog straight to herdr `idle`, with no `working` in
224
+ * between, ended no work: a trust or update dialog was closed, or an approval was dismissed with Esc. Rarog reads no
225
+ * transcript of such a pane, so this pair of states is all it has, and it carries no result. A herdr `done` after
226
+ * a dialog stays a result: in the recorded Codex CLI 0.171.0 and Antigravity CLI 1.5.18 runs (herdr 0.9.5) every
227
+ * `done` came after `working`. A Claude card keeps its own rule.
228
+ */
229
+ function dialogClosedWithoutWork(session, event) {
230
+ return isStateOnlyEngine(session.engine) && session.state === 'waiting-permission'
231
+ && event.state === 'idle' && event.seen === true;
232
+ }
198
233
  /*
199
234
  * Stan raportowany przez ZEWNĘTRZNEGO nadzorcę. Zdarzenie niesie trzy niezależne
200
235
  * rzeczy: stan (przez maszynę stanów), `seen` (SUROWY status badge'a herdr: `false`
@@ -231,6 +266,7 @@ export function applyAgentStateEvent(session, event, port) {
231
266
  session.herdrDialogReason = undefined;
232
267
  session.herdrDialogScreen = undefined;
233
268
  session.cliDialog = undefined;
269
+ session.herdrDialogLive = undefined;
234
270
  port.herdrBlocked.delete(session.id);
235
271
  port.timingLeft(session);
236
272
  port.claimWindows.herdrMoved(session);
@@ -255,14 +291,28 @@ export function applyAgentStateEvent(session, event, port) {
255
291
  emitIfChanged(session, before, port);
256
292
  return;
257
293
  }
258
- const smEvent = event.state === 'working'
259
- ? { type: 'agent-working' }
260
- : (event.state === 'idle' ? { type: 'agent-idle' } : { type: 'agent-blocked' });
294
+ /*
295
+ * A subagent's request has no dialog on the pane while its hook waits, so herdr reports `working` or `idle` while its
296
+ * channel card stands in `pending`: the state stays in `waiting-permission` or goes back there
297
+ * (`ConsentCards.subagentCardHold`), except inside the grace after an interrupt or a blocked prompt.
298
+ */
299
+ const subagent = event.state === 'blocked' ? null : port.subagentCardHold(session, event.state);
300
+ const reconcile = subagent === 'reconcile' && !port.inWorkingGrace(session);
301
+ const smEvent = reconcile ? { type: 'subagent-consent-pending' }
302
+ : event.state === 'working' ? { type: 'agent-working' }
303
+ : (event.state === 'idle' ? { type: 'agent-idle' } : { type: 'agent-blocked' });
261
304
  // `#applyTransition` sam rozgłasza `session-changed`, gdy stan się ruszył — drugi
262
305
  // broadcast byłby przy 17 panelach czystym szumem w strumieniu globalnym.
263
306
  // Right after the hook claimed a phone answer the answered dialog is still on the pane, so herdr repeats `blocked`:
264
307
  // inside the claim window it leaves the state alone (`claim-window.ts`), and a dialog that stays moves it after.
265
- if (event.state === 'blocked' && port.claimWindows.holdBlocked(session, event.detail)) {
308
+ const hold = event.state === 'blocked' ? port.claimWindows.holdBlocked(session, event.detail) : subagent === 'hold';
309
+ if (!hold && smEvent.type === 'agent-idle' && dialogClosedWithoutWork(session, event)) {
310
+ // No turn ended: the card goes back received, and the manager notes the exit like a card standing up
311
+ // (`awaitingFirstTurn` gives `afterStart`), which pushes nothing and leaves no owed result.
312
+ session.seen = true;
313
+ session.awaitingFirstTurn = true;
314
+ }
315
+ if (hold) {
266
316
  emitIfChanged(session, before, port);
267
317
  }
268
318
  else if (port.applyTransition(session, smEvent, event.detail)) {
@@ -13,6 +13,7 @@ import { sentenceOfError } from '../herdr/types.js';
13
13
  import * as seenMarks from './seen-marks.js';
14
14
  import { Session } from './session.js';
15
15
  import { HERDR_RECOVERY_GONE_MS, HERDR_RESTORE_MATCH_MS, HERDR_RESTORE_QUIET_MAX_MS, HERDR_UNKNOWN_DETAIL, } from './state-sentences.js';
16
+ import { isStateOnlyEngine } from '../herdr/engines.js';
16
17
  /** Lifecycle events of herdr panes and their state; one instance per manager. */
17
18
  export class HerdrLifecycle {
18
19
  #config;
@@ -149,7 +150,8 @@ export class HerdrLifecycle {
149
150
  const markedUnseen = initial.seen !== undefined && seenMarks.wasMarkedUnseen(agent, this.#config.herdrDeps?.seen);
150
151
  if (markedUnseen && initial.seen === true)
151
152
  seen = undefined;
152
- const codex = agent.engine === 'codex';
153
+ const engine = agent.engine;
154
+ const codex = isStateOnlyEngine(engine);
153
155
  const session = new Session({
154
156
  /*
155
157
  * Tożsamość karty: najpierw ALIAS po uuidzie silnika (ta sama sesja wznowiona w nowym
@@ -178,7 +180,11 @@ export class HerdrLifecycle {
178
180
  * ma, więc jego uuid dostaje własne pole i jedno zastosowanie — znacznik „obejrzane".
179
181
  */
180
182
  ...(codex
181
- ? { engine: 'codex', observedSessionId: agent.agentSessionId }
183
+ // Without a session ID from herdr (`''`) the card has no observed session: its seen mark goes by pane.
184
+ ? {
185
+ engine,
186
+ ...(agent.agentSessionId === '' ? {} : { observedSessionId: agent.agentSessionId }),
187
+ }
182
188
  : { engineSessionId: agent.agentSessionId }),
183
189
  /*
184
190
  * Adres wpisu w kliencie, gdy agent stoi w terminalu Raroga — ale tylko wtedy, gdy terminal
@@ -255,7 +261,8 @@ export class HerdrLifecycle {
255
261
  */
256
262
  this.#port.git.requestGitStatus(session);
257
263
  this.#port.git.watch(session);
258
- void this.#port.attachHerdrDriver(supervisor, session, agent.key);
264
+ // Adopted: the card's state is the snapshot just read, so its attach history may start the turn tally.
265
+ void this.#port.attachHerdrDriver(supervisor, session, agent.key, true);
259
266
  }
260
267
  /** Pole `termId` karty z migawki agenta: tylko przy włączonym terminalu (`RAROG_TERM`). */
261
268
  termIdField(agent) {
@@ -319,7 +326,7 @@ export class HerdrLifecycle {
319
326
  // Defensywnie: nowa karta nie dziedziczy znacznika poprzedniej o tym samym id.
320
327
  this.herdrRestoreQuiet.delete(session.id);
321
328
  this.#pruneGoneIdle();
322
- if (!this.#herdrGoneIdle.delete(agentSessionId))
329
+ if (agentSessionId === '' || !this.#herdrGoneIdle.delete(agentSessionId))
323
330
  return;
324
331
  if (session.state !== 'running' && session.state !== 'starting')
325
332
  return;
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * Launch gate of the session manager: every check that can refuse a new herdr session before anything exists on the
3
- * other side (directory, permission mode, model, pane cap, launch switch, resume checks, ultracode, start prompt), in
4
- * that order, the launch slots (one per 5 s and an hourly cap, "Starting sessions from the phone: three powers" in
3
+ * other side (directory, permission mode, model, pane cap, launch switch, resume checks, ultracode, coordinator
4
+ * reservation, start prompt), in that order, the launch slots (one per 5 s and an hourly cap, "Starting sessions from the phone: three powers" in
5
5
  * `docs/security-model.md`) and the start options of a resume.
6
6
  * The manager owns one {@link LaunchGate} and gives it a narrow {@link LaunchGatePort}. The pane, the card and the
7
7
  * second half of the start (`#finishLaunch`: readiness, the start prompt waiting for a start dialog, session restarts)
8
8
  * stay in the manager. This module does not import `manager.ts`.
9
9
  */
10
10
  import { resolve } from 'node:path';
11
+ import { coordinatorLabel, coordinatorPrompt } from './coordinator-start.js';
11
12
  import { BadRequestError, BadStateError, TooManyRequestsError, UltracodeRefusedError } from './errors.js';
12
13
  import { HERDR_DOUBLE_WRITER_MESSAGE, HERDR_LAUNCH_OFF_MESSAGE, RESUME_FOREIGN_CWD_MESSAGE, RESUME_NOT_FOUND_MESSAGE, RESUME_UNVERIFIABLE_MESSAGE, ULTRACODE_CLI_UNKNOWN_MESSAGE, ULTRACODE_EFFORT_MESSAGE, launchThrottledMessage, transcriptCwdBelongs, ultracodeCliTooOldMessage, } from './state-sentences.js';
13
14
  import { HERDR_LAUNCH_HOURLY_CAP, HERDR_LAUNCH_MIN_INTERVAL_MS } from '../config.js';
@@ -103,27 +104,51 @@ export class LaunchGate {
103
104
  }
104
105
  }
105
106
  this.#assertUltracodeLaunch(opts);
106
- if (!slotTaken && !this.#takeLaunchSlot()) {
107
- throw new TooManyRequestsError(launchThrottledMessage(this.#port.system()));
107
+ // The last check that can refuse; from here on a refusal releases the reservation it took.
108
+ const coordinator = this.#port.coordinator(opts);
109
+ try {
110
+ if (!slotTaken && !this.#takeLaunchSlot()) {
111
+ throw new TooManyRequestsError(launchThrottledMessage(this.#port.system()));
112
+ }
113
+ const prompt = this.startPrompt(opts.cwd, opts.prompt, coordinator?.pluginDir ?? null, null);
114
+ return {
115
+ opts, resumeModelSeed, ultracodeDropped, prompt, coordinator,
116
+ labelText: coordinator === null ? prompt?.text ?? null : coordinatorLabel(prompt?.text ?? ''),
117
+ };
118
+ }
119
+ catch (error) {
120
+ coordinator?.release();
121
+ throw error;
108
122
  }
123
+ }
124
+ /**
125
+ * The start prompt of a new process through the send guard; a coordinator's (`pluginDir` set) is the skill command
126
+ * before the user's prompt, checked whole (the byte ceiling counts the joined text) against the catalog with the
127
+ * plugin copy. A restart that resends a blocked prompt calls it before `/exit`, so its dry check is this very check;
128
+ * `key` names the pane in a command refusal log line (`null` before a pane exists).
129
+ */
130
+ startPrompt(cwd, prompt, pluginDir, key) {
109
131
  /*
110
132
  * Prompt przechodzi przez guard PRZED `launch()`, żeby 400 wróciło na POST-a, a nie
111
133
  * zostawiło po sobie panelu z odrzuconym zdaniem. Tryb `'unknown'` jest tu celowy
112
134
  * i NIE jest tym samym co przy wysyłce do istniejącego panelu: panelu jeszcze nie ma,
113
135
  * więc nie ma czego czytać ze stopki — a tryb, w którym wstanie, wybiera właśnie
114
- * `#assertPermissionMode` dwie linie wyżej.
136
+ * `#assertPermissionMode` w `admitLaunch`.
115
137
  */
116
- const rawPrompt = opts.prompt !== undefined && opts.prompt !== '' ? opts.prompt : null;
138
+ const rawPrompt = pluginDir !== null
139
+ ? coordinatorPrompt(prompt)
140
+ : prompt !== undefined && prompt !== '' ? prompt : null;
141
+ if (rawPrompt === null)
142
+ return null;
117
143
  // Nowy panel wstaje na wydaniu zainstalowanym, więc katalog komend liczymy dla niego.
118
- const catalog = rawPrompt === null ? null : this.#port.commandCatalog(opts.cwd, this.#port.cli.cliVersion.installed);
119
- const prompt = rawPrompt === null || catalog === null ? null : {
120
- ...this.#port.checkSendable(rawPrompt, null, opts.cwd, {
121
- mode: 'unknown', cwd: opts.cwd, yoloRoots: this.#config.yoloRoots ?? [], catalog,
144
+ const catalog = this.#port.commandCatalog(cwd, this.#port.cli.cliVersion.installed, pluginDir === null ? undefined : [pluginDir]);
145
+ return {
146
+ ...this.#port.checkSendable(rawPrompt, key, cwd, {
147
+ mode: 'unknown', cwd, yoloRoots: this.#config.yoloRoots ?? [], catalog,
122
148
  ...(this.#config.realPath !== undefined ? { realPath: this.#config.realPath } : {}),
123
149
  }),
124
150
  catalog,
125
151
  };
126
- return { opts, resumeModelSeed, ultracodeDropped, prompt };
127
152
  }
128
153
  /**
129
154
  * Throttle zakładania paneli: jeden na 5 s i 40 na godzinę
@@ -0,0 +1,69 @@
1
+ import { DECISION_STATES } from './state-sentences.js';
2
+ /**
3
+ * The driver's `dialog-live` event: the field of the new occurrence or revision, or its end. Only the session card
4
+ * field, like `cli-dialog`: no pending, state transition or push. A late field after the session left the decision does
5
+ * not bring the card back, because `agent-state` has just cleared it; the same occurrence and revision twice is a no-op.
6
+ */
7
+ export function applyDialogLive(session, event, port) {
8
+ const { live } = event;
9
+ if (live !== undefined && !DECISION_STATES.includes(session.state))
10
+ return;
11
+ if (sameRevision(session.herdrDialogLive, live))
12
+ return;
13
+ session.herdrDialogLive = live;
14
+ port.emitSessionChanged(session);
15
+ }
16
+ /** The driver sends a view only with a new occurrence or revision, so `id` and `rev` name the view. */
17
+ function sameRevision(a, b) {
18
+ if (a === undefined || b === undefined)
19
+ return a === b;
20
+ return a.id === b.id && a.rev === b.rev;
21
+ }
22
+ /**
23
+ * Sessions with a live card key or a `deny` in flight. Keyed by the session object, so a session that a restart
24
+ * replaced starts unlocked and two managers in one process never share a lock.
25
+ */
26
+ const inFlight = new WeakSet();
27
+ const IN_FLIGHT_KEY = { kind: 'refused', reason: 'in-flight' };
28
+ const IN_FLIGHT_DECISION = { outcome: 'refused', reason: 'in-flight' };
29
+ const NOT_SHOWN = { kind: 'not-shown' };
30
+ const SEND_OFF = { kind: 'send-off' };
31
+ /**
32
+ * Runs `step` holding the session's lock; `busy` when another key or deny of the session is in flight. The lock is
33
+ * taken before `step` starts and goes when its promise settles, also when `step` throws on the call.
34
+ */
35
+ function holding(session, busy, step) {
36
+ if (inFlight.has(session))
37
+ return Promise.resolve(busy);
38
+ inFlight.add(session);
39
+ const release = () => { inFlight.delete(session); };
40
+ let pending;
41
+ try {
42
+ pending = step();
43
+ }
44
+ catch (error) {
45
+ release();
46
+ throw error;
47
+ }
48
+ return pending.finally(release);
49
+ }
50
+ /**
51
+ * One key of the live card to the session's driver. A closed write channel (`RAROG_HERDR_SEND=0` or a read-only
52
+ * supervisor) answers `send-off` before the lock and the driver; a driver without live cards answers `not-shown`.
53
+ * The manager checks the session, the restart and the work area before this call.
54
+ */
55
+ export function pressDialogKey(session, body, writable) {
56
+ if (!writable)
57
+ return Promise.resolve(SEND_OFF);
58
+ const key = session.driver?.dialogKey?.bind(session.driver);
59
+ if (key === undefined)
60
+ return Promise.resolve(NOT_SHOWN);
61
+ return holding(session, IN_FLIGHT_KEY, () => key(body));
62
+ }
63
+ /**
64
+ * Today's `deny` of the session that goes to its driver (`POST /api/sessions/:id/permission` and
65
+ * `/permissions/:permId`), under the same lock as a live key: `in-flight` while a key or another deny is in flight.
66
+ */
67
+ export function denyUnderLock(session, deny) {
68
+ return holding(session, IN_FLIGHT_DECISION, deny);
69
+ }