@rarog/server 1.0.1 → 1.1.0-beta.1

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 (78) hide show
  1. package/README.md +4 -3
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +49 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  6. package/node_modules/@rarog/shared/src/protocol.js +16 -17
  7. package/node_modules/@rarog/shared/src/rest.js +106 -12
  8. package/node_modules/@rarog/shared/src/sentences/rest.js +13 -0
  9. package/package.json +3 -3
  10. package/server/src/bootstrap/consent.js +88 -2
  11. package/server/src/bootstrap/http.js +3 -2
  12. package/server/src/bootstrap/inbox.js +29 -4
  13. package/server/src/bootstrap/sse.js +2 -1
  14. package/server/src/cli/doctor-no-hook.js +162 -0
  15. package/server/src/cli/doctor.js +2 -0
  16. package/server/src/cli/update-channel.js +100 -0
  17. package/server/src/cli/update-registry.js +160 -62
  18. package/server/src/cli/update.js +13 -3
  19. package/server/src/companion/turns-settle.js +4 -1
  20. package/server/src/companion/turns.js +36 -5
  21. package/server/src/config/files.js +32 -0
  22. package/server/src/config/flags.js +10 -1
  23. package/server/src/config-env.js +24 -0
  24. package/server/src/config.js +6 -2
  25. package/server/src/demo/files.js +49 -0
  26. package/server/src/demo/inbox.js +73 -0
  27. package/server/src/demo/review-routes.js +6 -1
  28. package/server/src/device-effects.js +3 -1
  29. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  30. package/server/src/drivers/herdr/consent-no-hook.js +316 -0
  31. package/server/src/drivers/herdr/refusals.js +226 -0
  32. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  33. package/server/src/drivers/herdr-driver.js +116 -287
  34. package/server/src/files/file-index.js +246 -0
  35. package/server/src/files/ignored.js +119 -0
  36. package/server/src/files/listing.js +76 -0
  37. package/server/src/files/path-rule.js +145 -0
  38. package/server/src/files/refusals.js +36 -0
  39. package/server/src/files/send-file.js +115 -0
  40. package/server/src/files/session-download.js +51 -0
  41. package/server/src/files/session-files.js +38 -0
  42. package/server/src/files/session-gate.js +48 -0
  43. package/server/src/git-status.js +3 -2
  44. package/server/src/herdr/audit.js +1 -1
  45. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  46. package/server/src/herdr/dialogs/index.js +6 -1
  47. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +132 -59
  48. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  49. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  50. package/server/src/herdr/dialogs/no-hook.js +63 -0
  51. package/server/src/herdr/dialogs/screen/block.js +10 -0
  52. package/server/src/herdr/dialogs/screen/parse.js +10 -1
  53. package/server/src/herdr/jsonl-pending.js +25 -1
  54. package/server/src/inbox/card.js +18 -9
  55. package/server/src/inbox/dialogs.js +40 -12
  56. package/server/src/inbox/heads.js +55 -0
  57. package/server/src/inbox/inbox.js +24 -2
  58. package/server/src/inbox/index.js +3 -1
  59. package/server/src/index.js +22 -18
  60. package/server/src/install/repair.js +8 -0
  61. package/server/src/log-timestamps.js +9 -4
  62. package/server/src/router.js +7 -1
  63. package/server/src/routes/devices.js +2 -2
  64. package/server/src/routes/inbox.js +91 -0
  65. package/server/src/routes/sessions.js +135 -14
  66. package/server/src/routes/system.js +5 -4
  67. package/server/src/safe-read.js +86 -1
  68. package/server/src/sessions/companion-scope.js +6 -2
  69. package/server/src/sessions/demo-modules.js +16 -0
  70. package/server/src/sessions/diff-measure.js +30 -0
  71. package/server/src/sessions/manager.js +64 -152
  72. package/server/src/sessions/ring-buffer.js +18 -3
  73. package/server/src/sessions/seen-marks.js +9 -6
  74. package/server/src/sessions/session-scope.js +30 -0
  75. package/server/src/sessions/session.js +20 -1
  76. package/server/src/sessions/waiting-line.js +72 -0
  77. package/server/src/sse.js +40 -6
  78. package/server/src/version.js +30 -0
@@ -1,5 +1,5 @@
1
1
  import { say } from '@rarog/shared/sentences';
2
- import { HERDR_BLOCKED_POLL_MS, HERDR_CONSENT_CARD_WAIT_MS, HERDR_PANE_ROWS_WAIT_MS, HERDR_PENDING_DEBOUNCE_MS, HERDR_PENDING_RETRY_MS, HERDR_SCREEN_CACHE_MS, HERDR_STALL_SETTLE_MS, HERDR_TURN_WATCHDOG_MS, } from '../config.js';
2
+ import { HERDR_BLOCKED_POLL_MS, HERDR_CONSENT_CARD_WAIT_MS, HERDR_PENDING_DEBOUNCE_MS, HERDR_PENDING_RETRY_MS, HERDR_SCREEN_CACHE_MS, HERDR_STALL_SETTLE_MS, HERDR_TURN_WATCHDOG_MS, } from '../config.js';
3
3
  import { APPLIED, STALE, refused } from './types.js';
4
4
  import { AsyncEventQueue, systemScheduler } from './runtime.js';
5
5
  import { HerdrOutOfScopeError, reasonOfError } from '../herdr/types.js';
@@ -14,17 +14,20 @@ import * as crons from './herdr/scheduled-task-poll.js';
14
14
  import { cliWaitsForPermission, noteConsentRegistryRead } from './herdr/consent-registry-read.js';
15
15
  import { PromptQueue, promptEntry } from './herdr/prompt-queue.js';
16
16
  import { QueueTakeBack } from './herdr/queue-take-back.js';
17
+ import { ReturnedPrompt } from './herdr/returned-prompt.js';
17
18
  import { TurnGuard } from './herdr/turn-guard.js';
18
19
  import { FormReserve } from './herdr/form-reserve.js';
19
20
  import { CliReserve } from './herdr/cli-reserve.js';
20
21
  import { CommandDialogSettle } from './herdr/command-dialog-settle.js';
21
22
  import { ConsentChannel } from './herdr/consent-channel.js';
23
+ import { ConsentNoHook } from './herdr/consent-no-hook.js';
22
24
  import { Layer2Cards, isLayer2Id, layer2HoldsKeys } from './herdr/layer2-card.js';
23
25
  import { Layer2Step } from './herdr/layer2-step.js';
24
- import { ANSWERED_HOOK_SHIELD_MS, CLI_WAITING_PROBES, DECIDED_SHIELD_MS, FORM_SUBMIT_CONFIRM_DELAY_MS, FORM_SUBMIT_GONE_MESSAGE, FORM_SUBMIT_KEY, HOOK_ANSWER_POLL_MS, HOOK_ANSWER_WAIT_MS, HOOK_PERMISSION_REQUEST_EVENT, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAGE, NOTE_NO_CHANNEL_MESSAGE, NOTE_WRITE_FAILED_MESSAGE, NO_ANSWER_ON_SCREEN_MESSAGE, NO_DIGIT_MESSAGE, PAUSE_ESCAPE_MESSAGE, SCREEN_ANSWER_REARM_DELAYS_MS, SCREEN_CHANGED_MESSAGE, SCREEN_DIALOG_TOOL, STALE_DECISION_MESSAGE, TERMINAL_DIALOG_MESSAGE, TERMINAL_ONLY_MESSAGE, affirmativeOption, alwaysOption, admittedHook, applyMultiSelectOverride, blockCardRecord, confirmFormSubmit, decideCard, dialogShapeOf, measuredConsentHolds, evaluationReqId, fallbackSnippet, formSubmitAbortMessage, hookAnnotations, hookAnswerPartialMessage, besideAtDecision, hookPendingFor, hookPendingFrom, noteNotDeliveredMessage, optionPolicy, otherDialogDump, screenAnswerIndex, screenDialogCard, screenFormReqId, staleDumpProvesOther, } from '../herdr/dialogs/index.js';
26
+ import { approveContext, auditRefusal, layer2KeyRefusal, refuseDecision, refuseNote, refuseSend, reportStaleDecision, } from './herdr/refusals.js';
27
+ import { ANSWERED_HOOK_SHIELD_MS, CLI_WAITING_PROBES, DECIDED_SHIELD_MS, FORM_SUBMIT_CONFIRM_DELAY_MS, FORM_SUBMIT_GONE_MESSAGE, FORM_SUBMIT_KEY, HOOK_ANSWER_POLL_MS, HOOK_ANSWER_WAIT_MS, HOOK_PERMISSION_REQUEST_EVENT, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAGE, NOTE_NO_CHANNEL_MESSAGE, NOTE_WRITE_FAILED_MESSAGE, NO_ANSWER_ON_SCREEN_MESSAGE, NO_DIGIT_MESSAGE, PAUSE_ESCAPE_MESSAGE, SCREEN_ANSWER_REARM_DELAYS_MS, SCREEN_CHANGED_MESSAGE, SCREEN_DIALOG_TOOL, TERMINAL_DIALOG_MESSAGE, TERMINAL_ONLY_MESSAGE, affirmativeOption, alwaysOption, admittedHook, applyMultiSelectOverride, blockCardRecord, confirmFormSubmit, decideCard, dialogShapeOf, measuredConsentHolds, evaluationReqId, fallbackSnippet, formSubmitAbortMessage, hookAnnotations, hookAnswerPartialMessage, besideAtDecision, hookPendingFor, hookPendingFrom, noteNotDeliveredMessage, optionPolicy, otherDialogDump, screenAnswerIndex, screenDialogCard, screenFormReqId, staleDumpProvesOther, } from '../herdr/dialogs/index.js';
25
28
  import { shadowAuditFields } from '../herdr/audit.js';
26
29
  import { diagnosisFields, originFields } from './herdr/audit-fields.js';
27
- import { ASK_USER_QUESTION_TOOL, SANDBOX_NETWORK_TOOL, SESSION_PAUSED_DIALOG, blockVisible, canonicalLabel, exitDialogTasks, matchKnownDialog, parseOptions, resolveOptions, routeDialog, routeHookOf, routeScreenOf, sameDialogIdentity, sessionPausedDialog, standingConsentDialog, } from '../herdr/dialogs/index.js';
30
+ import { ASK_USER_QUESTION_TOOL, SANDBOX_NETWORK_TOOL, SESSION_PAUSED_DIALOG, canonicalLabel, exitDialogTasks, matchKnownDialog, parseOptions, resolveOptions, sameDialogIdentity, sessionPausedDialog, standingConsentDialog, } from '../herdr/dialogs/index.js';
28
31
  import { SHADOW_DEADLINE_MS, registryEvidenceFromSignal, shadowCardEligible } from '../herdr/dialogs/index.js';
29
32
  import { consentDigitRefused, consentModeNow, consentOnlyEvent } from '../herdr/dialogs/index.js';
30
33
  import { collapseFooterMode, parseModeFooter } from '../herdr/dialogs/screen/mode-footer.js';
@@ -155,6 +158,7 @@ export class HerdrDriver {
155
158
  #promptQueue;
156
159
  /** Taking both prompt queues back for the app: `drivers/herdr/queue-take-back.ts`. */
157
160
  #takeBack;
161
+ #returnedPrompt;
158
162
  #paneId;
159
163
  #mode;
160
164
  #lastTitle = null;
@@ -282,6 +286,10 @@ export class HerdrDriver {
282
286
  #formReserve;
283
287
  /** The CLI registry fallback: `drivers/herdr/cli-reserve.ts`. */
284
288
  #cliReserve;
289
+ /** Consent without a hook and cards without the approve button, in the log: `drivers/herdr/consent-no-hook.ts`. */
290
+ #noHook;
291
+ /** The port of the refusals and their audit funnel: `drivers/herdr/refusals.ts`. */
292
+ #refusals;
285
293
  /** The wait behind a command dialog the driver confirmed: `drivers/herdr/command-dialog-settle.ts`. */
286
294
  #commandSettle;
287
295
  /** The layer 2 card with buttons (`docs/dialog-card.md`): `drivers/herdr/layer2-card.ts`. */
@@ -347,6 +355,7 @@ export class HerdrDriver {
347
355
  const reservePort = this.#reservePort();
348
356
  this.#formReserve = new FormReserve({ deps, scheduler: this.#scheduler }, reservePort);
349
357
  this.#cliReserve = new CliReserve({ inScope: this.#inScope, form: this.#formReserve }, reservePort);
358
+ this.#refusals = this.#refusalPort();
350
359
  this.#commandSettle = new CommandDialogSettle({ pollMs: deps.modelConfirmPollMs ?? MODEL_CONFIRM_POLL_MS }, {
351
360
  disposed: () => this.#disposed,
352
361
  readScreen: () => this.#deps.client.readScreen(this.#paneId, 'detection').then((s) => s.text, () => null),
@@ -379,6 +388,14 @@ export class HerdrDriver {
379
388
  deps, scheduler: this.#scheduler, key: this.#key, consentCardWaitMs: this.#consentCardWaitMs,
380
389
  follower: this.#follower, claude: this.#engine === 'claude' && this.#inScope, queue: this.#promptQueue,
381
390
  }, this.#takeBackPort());
391
+ this.#returnedPrompt = new ReturnedPrompt({ deps, scheduler: this.#scheduler, key: this.#key }, { paneId: () => this.#paneId });
392
+ this.#noHook = new ConsentNoHook({ deps, scheduler: this.#scheduler, inScope: this.#inScope, cwd: this.#cwd }, {
393
+ disposed: () => this.#disposed, agentSessionId: () => this.#agentSessionId, blockedNow: () => this.#blockedNow(),
394
+ blockedSeq: () => this.#blockedSeq, blockedAt: () => this.#blockedAt, answeredAt: () => this.#answeredAt,
395
+ cliWaiting: () => this.#cliReserve.cliWaiting, screenText: () => this.#screenText,
396
+ cliVersion: () => (this.#cliReserve.cliSignal?.kind === 'unknown' ? null : this.#cliReserve.cliSignal?.version ?? null),
397
+ permissionMode: () => (this.#mode === 'unknown' ? null : this.#mode),
398
+ });
382
399
  this.#promptQueue.restore(this.#engine === 'claude', () => ++this.#turnGuard.sendGeneration);
383
400
  if (this.#follower !== null)
384
401
  void this.#pumpFollower(this.#follower);
@@ -674,6 +691,8 @@ export class HerdrDriver {
674
691
  }
675
692
  // Prompt doszedł do panelu — także zablokowany przez hook: odmowę niesie notka, nie ostrzeżenie wysyłki.
676
693
  onDelivered();
694
+ if (outcome === 'sent' && slash === null && !midTurn)
695
+ this.#returnedPrompt.noteSent(finalText);
677
696
  this.#turnGuard.afterSubmit(outcome === 'blocked', slash, echo, generation, silent);
678
697
  }
679
698
  /**
@@ -810,7 +829,7 @@ export class HerdrDriver {
810
829
  const { client } = this.#deps;
811
830
  const sent = await this.#send(() => (key.via === 'keys'
812
831
  ? client.sendKeys(this.#paneId, key.keys) : client.sendDialogKey(this.#paneId, key.key)), {
813
- ...entry, ...this.#approveContext(),
832
+ ...entry, ...approveContext(this.#refusals),
814
833
  });
815
834
  if (!sent)
816
835
  return false;
@@ -846,6 +865,24 @@ export class HerdrDriver {
846
865
  evaluate: () => this.#evaluate(),
847
866
  };
848
867
  }
868
+ /** Port of the refusals: the card, screen and registry state they read and the steps that stay here. */
869
+ #refusalPort() {
870
+ return {
871
+ deps: this.#deps,
872
+ scheduler: this.#scheduler,
873
+ paneId: () => this.#paneId,
874
+ agentSessionId: () => this.#agentSessionId,
875
+ screenText: () => this.#screenText,
876
+ activeReq: () => this.#activeReq,
877
+ pending: () => this.#pending,
878
+ cliWaiting: () => this.#cliReserve.cliWaiting,
879
+ resolveOptions: (text, expected) => this.#resolveOptions(text, expected),
880
+ audit: (entry, at) => { this.#audit(entry, at); },
881
+ system: (text) => { this.#system(text); },
882
+ clearActive: (reason) => { this.#clearActive(reason); },
883
+ scheduleEvaluate: () => { this.#scheduleEvaluate(); },
884
+ };
885
+ }
849
886
  /**
850
887
  * Wysyłka z tokenem echa odroczonego nie doszła do panelu: wpis z okna echa wypada (inaczej
851
888
  * identyczny prompt wysłany potem trafiłby na sierotę), a manager dostaje `echo-refused` i spłukuje
@@ -1093,7 +1130,7 @@ export class HerdrDriver {
1093
1130
  this.#shadowKeySent(shadow, false);
1094
1131
  if (this.#disposed)
1095
1132
  return STALE;
1096
- return this.#refuseDecision(PAUSE_ESCAPE_MESSAGE, 'Esc na pauzie „Session paused”', 'terminal-only');
1133
+ return refuseDecision(this.#refusals, PAUSE_ESCAPE_MESSAGE, 'Esc na pauzie „Session paused”', 'terminal-only');
1097
1134
  }
1098
1135
  if (this.#disposed) {
1099
1136
  this.#shadowKeySent(shadow, false);
@@ -1129,7 +1166,7 @@ export class HerdrDriver {
1129
1166
  // doszło, dialog stoi dalej i zrzut wciąż jest jego prawdziwym opisem. Wyjątek ten sam co po cyfrze:
1130
1167
  // zrzut `Bash` INNEGO dialogu, który czeka w kolejce za zamkniętym (`#clearHookAfterDecision`).
1131
1168
  if (!ok)
1132
- return this.#refuseSend();
1169
+ return refuseSend(this.#refusals);
1133
1170
  const keptHookAt = this.#clearHookAfterDecision(this.#readHookFile(), resolvedText, denied);
1134
1171
  /*
1135
1172
  * Osłona po własnej decyzji także po `escape`. Karta BEZ przycisków jest
@@ -1180,9 +1217,9 @@ export class HerdrDriver {
1180
1217
  const sessionAddressed = active.screen === true
1181
1218
  && active.toolName.startsWith(`${SCREEN_DIALOG_TOOL}:`);
1182
1219
  if (!sessionAddressed)
1183
- return Promise.resolve(this.#reportStaleDecision());
1220
+ return Promise.resolve(reportStaleDecision(this.#refusals));
1184
1221
  }
1185
- const held = this.#layer2KeyRefusal();
1222
+ const held = layer2KeyRefusal(this.#refusals);
1186
1223
  if (held !== null)
1187
1224
  return Promise.resolve(held);
1188
1225
  /*
@@ -1191,7 +1228,7 @@ export class HerdrDriver {
1191
1228
  * etykiety, nie na flagę — przyszła opcja „Yes…” w takim dialogu nie ma prawa stać się celem tapnięcia.
1192
1229
  */
1193
1230
  if (active.terminalDialog !== undefined) {
1194
- return Promise.resolve(this.#refuseDecision(TERMINAL_DIALOG_MESSAGE, 'dialog z listy terminalowej', 'terminal-only'));
1231
+ return Promise.resolve(refuseDecision(this.#refusals, TERMINAL_DIALOG_MESSAGE, 'dialog z listy terminalowej', 'terminal-only'));
1195
1232
  }
1196
1233
  /*
1197
1234
  * Lista opcji jest tu jedyną bramką i jest pusta wszędzie tam, gdzie Rarog nie wie, co
@@ -1209,7 +1246,7 @@ export class HerdrDriver {
1209
1246
  // Karta nie niesie przycisku „zawsze", a ta bramka zamyka go też dla starego
1210
1247
  // albo obcego klienta — „don't ask again for <host>" zostaje do wybrania przy biurku.
1211
1248
  if (decision === 'allow-always' && active.toolName === SANDBOX_NETWORK_TOOL) {
1212
- return Promise.resolve(this.#refuseDecision(TERMINAL_ONLY_MESSAGE, 'sieć sandboksa: tylko zgoda jednorazowa', 'terminal-only'));
1249
+ return Promise.resolve(refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'sieć sandboksa: tylko zgoda jednorazowa', 'terminal-only'));
1213
1250
  }
1214
1251
  /*
1215
1252
  * Dialog zaufania BEZ cyfr: karta nie ma opcji, a zatwierdzenie idzie osobną ścieżką `down`/`enter`
@@ -1221,7 +1258,7 @@ export class HerdrDriver {
1221
1258
  ? alwaysOption(active.options)
1222
1259
  : affirmativeOption(active.options);
1223
1260
  if (option === null) {
1224
- return Promise.resolve(this.#refuseDecision(NO_DIGIT_MESSAGE, decision === 'allow-always'
1261
+ return Promise.resolve(refuseDecision(this.#refusals, NO_DIGIT_MESSAGE, decision === 'allow-always'
1225
1262
  ? 'brak jednoznacznej opcji „nie pytaj więcej"'
1226
1263
  : 'zgoda bez jednoznacznej opcji „tak"', 'no-digit'));
1227
1264
  }
@@ -1259,7 +1296,7 @@ export class HerdrDriver {
1259
1296
  if (active === null)
1260
1297
  return Promise.resolve(STALE);
1261
1298
  if (active.reqId !== reqId)
1262
- return Promise.resolve(this.#reportStaleDecision());
1299
+ return Promise.resolve(reportStaleDecision(this.#refusals));
1263
1300
  const target = active.hookAnswer;
1264
1301
  const complete = target !== undefined
1265
1302
  && answers.length === target.questions.length
@@ -1272,7 +1309,7 @@ export class HerdrDriver {
1272
1309
  */
1273
1310
  const noted = notes?.some((note) => note !== null && note.trim() !== '') === true;
1274
1311
  if (noted && (target === undefined || !complete || this.#deps.hookAnswers === undefined)) {
1275
- return Promise.resolve(this.#refuseNote(NOTE_NO_CHANNEL_MESSAGE));
1312
+ return Promise.resolve(refuseNote(this.#refusals, NOTE_NO_CHANNEL_MESSAGE));
1276
1313
  }
1277
1314
  if (target !== undefined && complete && this.#deps.hookAnswers !== undefined) {
1278
1315
  return this.#answerViaHook(active, target, answers, noted ? notes : undefined);
@@ -1301,7 +1338,7 @@ export class HerdrDriver {
1301
1338
  groups: answers.map((group) => group.length),
1302
1339
  };
1303
1340
  if (index === -1) {
1304
- return Promise.resolve(this.#refuseDecision(NO_DIGIT_MESSAGE, 'pytania z ekranu nie ma na karcie', 'no-digit', shape));
1341
+ return Promise.resolve(refuseDecision(this.#refusals, NO_DIGIT_MESSAGE, 'pytania z ekranu nie ma na karcie', 'no-digit', shape));
1305
1342
  }
1306
1343
  const first = answers[index] ?? [];
1307
1344
  /*
@@ -1311,7 +1348,7 @@ export class HerdrDriver {
1311
1348
  * tamta oddaje `screen-changed`, choć ekran się nie zmienił.
1312
1349
  */
1313
1350
  if (active.multiSelect === true) {
1314
- return Promise.resolve(this.#refuseDecision(MULTI_SELECT_MESSAGE, 'wielokrotny wybór', 'multi-select', shape));
1351
+ return Promise.resolve(refuseDecision(this.#refusals, MULTI_SELECT_MESSAGE, 'wielokrotny wybór', 'multi-select', shape));
1315
1352
  }
1316
1353
  /*
1317
1354
  * PUSTA grupa to brak odpowiedzi na pytanie, które stoi w terminalu — nie wielokrotny
@@ -1319,11 +1356,11 @@ export class HerdrDriver {
1319
1356
  * „Wielokrotny wybór zrób w terminalu" przy formularzu bez żadnego checkboxa.
1320
1357
  */
1321
1358
  if (first.length === 0) {
1322
- return Promise.resolve(this.#refuseDecision(NO_ANSWER_ON_SCREEN_MESSAGE, 'brak odpowiedzi na pytanie z ekranu', 'no-digit', shape));
1359
+ return Promise.resolve(refuseDecision(this.#refusals, NO_ANSWER_ON_SCREEN_MESSAGE, 'brak odpowiedzi na pytanie z ekranu', 'no-digit', shape));
1323
1360
  }
1324
1361
  // Wielokrotny wybór wymagałby `space` + `enter`, czyli wyboru po POZYCJI.
1325
1362
  if (first.length !== 1) {
1326
- return Promise.resolve(this.#refuseDecision(MULTI_SELECT_MESSAGE, 'wielokrotny wybór', 'multi-select', shape));
1363
+ return Promise.resolve(refuseDecision(this.#refusals, MULTI_SELECT_MESSAGE, 'wielokrotny wybór', 'multi-select', shape));
1327
1364
  }
1328
1365
  const label = canonicalLabel(first[0] ?? '');
1329
1366
  /*
@@ -1333,11 +1370,11 @@ export class HerdrDriver {
1333
1370
  * kluczu kanonicznym odpowiedzi, więc pełna etykieta i sam jej prefiks dostają tę samą odmowę.
1334
1371
  */
1335
1372
  if (active.terminalOnlyLabels?.includes(label) === true) {
1336
- return Promise.resolve(this.#refuseDecision(TERMINAL_ONLY_MESSAGE, 'opcja tylko z terminala na karcie', 'terminal-only'));
1373
+ return Promise.resolve(refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'opcja tylko z terminala na karcie', 'terminal-only'));
1337
1374
  }
1338
1375
  const option = active.options.find((candidate) => candidate.label === label);
1339
1376
  if (option === undefined) {
1340
- return Promise.resolve(this.#refuseDecision(NO_DIGIT_MESSAGE, 'etykiety nie ma na żywej liście opcji', 'no-digit', shape));
1377
+ return Promise.resolve(refuseDecision(this.#refusals, NO_DIGIT_MESSAGE, 'etykiety nie ma na żywej liście opcji', 'no-digit', shape));
1341
1378
  }
1342
1379
  /*
1343
1380
  * Bramka SERWEROWA, nie tylko UI: opcja eskalująca uprawnienia („always allow…") jest na
@@ -1360,8 +1397,8 @@ export class HerdrDriver {
1360
1397
  if (policy.digitBlocked || option.terminalOnly === true) {
1361
1398
  // Karta dialogu z listy terminalowej: flagę ma KAŻDA opcja, a zdanie o uprawnieniach byłoby fałszem.
1362
1399
  return Promise.resolve(policy.why === 'terminal-dialog'
1363
- ? this.#refuseDecision(TERMINAL_DIALOG_MESSAGE, 'dialog z listy terminalowej', 'terminal-only')
1364
- : this.#refuseDecision(TERMINAL_ONLY_MESSAGE, 'opcja eskalująca uprawnienia', 'terminal-only'));
1400
+ ? refuseDecision(this.#refusals, TERMINAL_DIALOG_MESSAGE, 'dialog z listy terminalowej', 'terminal-only')
1401
+ : refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'opcja eskalująca uprawnienia', 'terminal-only'));
1365
1402
  }
1366
1403
  return this.#sendDigit(option, active);
1367
1404
  }
@@ -1387,7 +1424,7 @@ export class HerdrDriver {
1387
1424
  if (channel === undefined) {
1388
1425
  return notes === undefined
1389
1426
  ? this.#answerWithDigit(active, answers)
1390
- : this.#refuseNote(NOTE_NO_CHANNEL_MESSAGE);
1427
+ : refuseNote(this.#refusals, NOTE_NO_CHANNEL_MESSAGE);
1391
1428
  }
1392
1429
  /*
1393
1430
  * Reguła „jedno tapnięcie nie zmienia trwale uprawnień” obowiązuje w KAŻDYM kanale: opcja eskalująca uprawnienia
@@ -1397,7 +1434,7 @@ export class HerdrDriver {
1397
1434
  */
1398
1435
  const escalating = answers.flat().some((raw) => target.blocked.includes(canonicalLabel(raw)));
1399
1436
  if (escalating) {
1400
- return this.#refuseDecision(TERMINAL_ONLY_MESSAGE, 'opcja eskalująca uprawnienia', 'terminal-only');
1437
+ return refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'opcja eskalująca uprawnienia', 'terminal-only');
1401
1438
  }
1402
1439
  // Klucz mapy to DOSŁOWNA treść pytania z payloadu (po niej dopasowuje CLI), a wiele
1403
1440
  // wartości jedzie JEDNYM stringiem po przecinku — tak CLI czyta `multiSelect`.
@@ -1415,7 +1452,7 @@ export class HerdrDriver {
1415
1452
  */
1416
1453
  const annotations = notes === undefined ? null : hookAnnotations(target, answers, notes);
1417
1454
  if (notes !== undefined && annotations === null)
1418
- return this.#refuseNote(NOTE_NOT_ALLOWED_MESSAGE);
1455
+ return refuseNote(this.#refusals, NOTE_NOT_ALLOWED_MESSAGE);
1419
1456
  const noteCount = annotations === null ? 0 : Object.keys(annotations).length;
1420
1457
  /*
1421
1458
  * Zakaz fallbacku cyfrą wynika z ŻĄDANIA (niepuste notatki od człowieka), a nie z liczby
@@ -1424,7 +1461,7 @@ export class HerdrDriver {
1424
1461
  */
1425
1462
  const noted = notes !== undefined;
1426
1463
  if (noted && noteCount === 0)
1427
- return this.#refuseNote(NOTE_NOT_ALLOWED_MESSAGE);
1464
+ return refuseNote(this.#refusals, NOTE_NOT_ALLOWED_MESSAGE);
1428
1465
  let path;
1429
1466
  try {
1430
1467
  path = channel.write(this.#agentSessionId, target.key, map, noteCount > 0 ? annotations : null);
@@ -1439,7 +1476,7 @@ export class HerdrDriver {
1439
1476
  */
1440
1477
  if (path === null) {
1441
1478
  return noted
1442
- ? this.#refuseNote(NOTE_WRITE_FAILED_MESSAGE)
1479
+ ? refuseNote(this.#refusals, NOTE_WRITE_FAILED_MESSAGE)
1443
1480
  : this.#answerWithDigit(active, answers);
1444
1481
  }
1445
1482
  // Numer blokady sprzed osłony — do przywrócenia, gdy odpowiedź z notatką nie dojdzie.
@@ -1535,9 +1572,10 @@ export class HerdrDriver {
1535
1572
  * notatki jej nie gasi i oceny nie ponawia. Notatka nie doszła tak samo, więc zdanie z jej treścią idzie
1536
1573
  * do transkryptu, a dziennik dostaje nazwę narzędzia karty, na którą przyszła odpowiedź.
1537
1574
  */
1538
- if (this.#activeReq !== null && this.#activeReq !== active)
1539
- return this.#refuseNote(message, active.toolName);
1540
- return this.#refuseDecision(message, 'notatka: hook nie odebrał pliku odpowiedzi', 'send-failed');
1575
+ if (this.#activeReq !== null && this.#activeReq !== active) {
1576
+ return refuseNote(this.#refusals, message, active.toolName);
1577
+ }
1578
+ return refuseDecision(this.#refusals, message, 'notatka: hook nie odebrał pliku odpowiedzi', 'send-failed');
1541
1579
  }
1542
1580
  /*
1543
1581
  * Karta podmieniona w oknie czekania: nowy zrzut i nowy ekran wystawiły inną kartę, a odpowiedź
@@ -1551,7 +1589,7 @@ export class HerdrDriver {
1551
1589
  if (this.#activeReq === null)
1552
1590
  return STALE;
1553
1591
  if (this.#activeReq !== active)
1554
- return this.#reportStaleDecision();
1592
+ return reportStaleDecision(this.#refusals);
1555
1593
  /*
1556
1594
  * Cyfra dowozi TYLKO pytanie stojące na ekranie — i wcale nie musi to być pierwsze
1557
1595
  * pytanie karty (zakładkę przełącza się przy biurku bez mignięcia `agent_status`).
@@ -1578,227 +1616,6 @@ export class HerdrDriver {
1578
1616
  await this.#sleep(pollMs);
1579
1617
  }
1580
1618
  }
1581
- /**
1582
- * Odmowa wysyłki cyfry: powiedz DLACZEGO i ODBUDUJ kartę.
1583
- *
1584
- * Karta gaśnie i ocena buduje ją od nowa z tego, co stoi TERAZ — decyzja nie wyszła, ale
1585
- * człowiek ma na czym pracować. To JEDYNA ścieżka odbudowy po odmowie
1586
- * decyzji: pending w managerze przeżywa `refused` (kontrakt `DecisionOutcome`), więc
1587
- * odbudowa nie musi już nadrabiać wpisu zjedzonego przez first-wins.
1588
- */
1589
- #refuseDecision(message, reason, audit, shape) {
1590
- this.#auditRefusal(audit, this.#activeReq?.toolName, 'refuse', shape);
1591
- this.#system(message);
1592
- this.#clearActive(reason);
1593
- this.#scheduleEvaluate();
1594
- return refused(audit);
1595
- }
1596
- /**
1597
- * Herdr odrzucił samo wywołanie — nic nie poszło do panelu.
1598
- *
1599
- * Karty NIE gasimy i oceny nie ponawiamy: dialog stoi dalej, a `#send` zdążył już
1600
- * powiedzieć człowiekowi, co się stało (blokada / panel zniknął / tryb tylko do odczytu).
1601
- * Wpis w dzienniku dokłada tę odmowę do licznika (`summarizeRefusals` w `herdr/audit.ts`) — bez niego
1602
- * najczęstsza awaria kanału nie miałaby w statystyce ani jednej linii.
1603
- */
1604
- #refuseSend() {
1605
- this.#auditRefusal('send-failed', this.#activeReq?.toolName);
1606
- return refused('send-failed');
1607
- }
1608
- /**
1609
- * `allow` over a layer 2 card (`layer2HoldsKeys`, `docs/dialog-card.md`): `terminal-only` with the sentence of the
1610
- * terminal dialogs, the card stays; a choice goes only through the layer 2 step. `null` = another card or none.
1611
- */
1612
- #layer2KeyRefusal() {
1613
- if (!layer2HoldsKeys(this.#activeReq))
1614
- return null;
1615
- this.#auditRefusal('terminal-only', this.#activeReq?.toolName);
1616
- this.#system(TERMINAL_DIALOG_MESSAGE);
1617
- return refused('terminal-only');
1618
- }
1619
- /**
1620
- * Odpowiedź z NOTATKĄ nie wyszła — nic nie poszło ani do panelu, ani do pliku.
1621
- *
1622
- * Karty NIE gasimy, jak przy `#refuseSend`: dialog stoi dalej, a człowiek ma na niej szkic
1623
- * z notatką (odmowa 422 zostawia kartę w stanie wyboru). Powód `send-failed` z zamkniętej
1624
- * listy znaczy dokładnie to: „nic nie doszło" — dokładniejsze zdanie idzie do transkryptu.
1625
- * `toolName` podaje wołający, gdy odpowiedź przyszła na inną kartę niż ta, która stoi.
1626
- */
1627
- #refuseNote(message, toolName = this.#activeReq?.toolName) {
1628
- this.#auditRefusal('send-failed', toolName);
1629
- this.#system(message);
1630
- return refused('send-failed');
1631
- }
1632
- /**
1633
- * Wpis „decyzja NIE wyszła" — jedyna metoda dziennika bez ani jednego bajtu do panelu.
1634
- *
1635
- * Powód jest z zamkniętej listy, bo te wpisy mają się SUMOWAĆ (`summarizeRefusals` w `herdr/audit.ts`),
1636
- * a nie opisywać: zdanie dla człowieka i tak idzie do transkryptu osobno. Nazwa narzędzia
1637
- * jedzie z kartą — bez niej „18 odmów" nie mówi, czego dotyczyły.
1638
- */
1639
- #auditRefusal(reason, toolName, method = 'refuse', shape, degrade) {
1640
- const at = this.#deps.now();
1641
- // The class from the CLI registry when it says `waiting`: the counter must tell WHICH dialogs
1642
- // Rarog cannot read, and the router verdict (`#routeFields`) uses it as input.
1643
- const cliDialog = this.#cliReserve.cliWaiting;
1644
- const hook = this.#readHookQuietly();
1645
- /*
1646
- * KSZTAŁT przypadku. Karta bez decyzji niesie go z oceny (`decideCard` liczy go z tego
1647
- * samego odczytu ekranu, z którego powstała karta, razem z podpowodem sprzed spadku na ścieżkę
1648
- * ekranową). Odmowa wysyłki — ze stojącej karty i z ostatniego odczytu ekranu, tego samego, który
1649
- * trafia do zrzutu odmowy.
1650
- */
1651
- const caseShape = {
1652
- ...(degrade === undefined
1653
- ? {
1654
- ...originFields(this.#activeReq?.reqId ?? null, this.#activeReq?.origin),
1655
- ...diagnosisFields({ mismatchReason: null, ...dialogShapeOf(this.#screenText) }),
1656
- }
1657
- : { ...originFields(degrade.reqId, degrade.origin), ...diagnosisFields(degrade.diagnosis) }),
1658
- ...this.#routeFields(hook),
1659
- };
1660
- const entry = {
1661
- method,
1662
- reason,
1663
- ...(toolName === undefined ? {} : { toolName }),
1664
- ...(shape === undefined ? {} : { shape }),
1665
- ...(cliDialog === null ? {} : { cliDialog }),
1666
- ...caseShape,
1667
- };
1668
- const dump = this.#refusalDump(reason, toolName, caseShape, cliDialog, hook, at);
1669
- const write = (rows) => {
1670
- const withRows = rows === null ? {} : { paneRows: rows };
1671
- this.#audit({ ...entry, ...withRows }, at);
1672
- if (dump !== null)
1673
- this.#writeDump({ ...dump, shape: { ...caseShape, ...withRows } });
1674
- };
1675
- /*
1676
- * Wiersze panelu z herdr WYŁĄCZNIE przy karcie bez decyzji: jeden `pane.list`, po nim
1677
- * wpis i zrzut. Karta nie czeka — wpis dochodzi do pliku z czasem oceny. Budżet czekania liczy
1678
- * DRIVER (`HERDR_PANE_ROWS_WAIT_MS`, łącznie z kolejką slotów gniazda): po nim wpis i zrzut idą
1679
- * bez wierszy, dokładnie raz, a spóźniony wynik przepada. Sufit gniazda zostaje zwykły — krótszy
1680
- * oznaczałby herdr jako niedostępny z powodu diagnostyki. Błąd odczytu
1681
- * albo brak metody = wpis bez wierszy, nigdy liczba zgadnięta z ekranu.
1682
- */
1683
- const client = this.#deps.client;
1684
- if (method !== 'degrade' || client.readPaneRows === undefined) {
1685
- write(null);
1686
- return;
1687
- }
1688
- let timer = null;
1689
- let written = false;
1690
- const once = (rows) => {
1691
- if (written)
1692
- return;
1693
- written = true;
1694
- if (timer !== null)
1695
- this.#scheduler.clearTimeout(timer);
1696
- write(rows);
1697
- };
1698
- timer = this.#scheduler.setTimeout(() => { once(null); }, this.#deps.paneRowsWaitMs ?? HERDR_PANE_ROWS_WAIT_MS);
1699
- void client.readPaneRows(this.#paneId).then((rows) => { once(rows); }, () => { once(null); });
1700
- }
1701
- /**
1702
- * Zrzut diagnostyczny do `<dataDir>/refusals/`
1703
- * („Refusal diagnostics” w `docs/dialogs.md`) — jedno wywołanie na jedną odmowę.
1704
- *
1705
- * Stoi w `#auditRefusal`, bo to JEDYNY lejek odmów w driverze: każdy powód, który wchodzi
1706
- * do statystyki, zostawia też ekran, z którego powstał. Ekran bierzemy z cache'u ostatniego
1707
- * odczytu (`#screenText`) — świeżego, bo ocena dialogu czyta go tuż przed decyzją.
1708
- *
1709
- * Treść zrzutu składamy OD RAZU (ekran, zrzut hooka i wpis jsonl z chwili odmowy), a zapisujemy
1710
- * po odczycie wierszy panelu (`#writeDump`) — w tym czasie kolejna ocena mogłaby podmienić cache.
1711
- *
1712
- * Ze zrzutu hooka jadą wyłącznie METADANE (zdarzenie, czas, narzędzie, a w kształcie przypadku
1713
- * identyfikatory tury i subagenta). `toolInput` NIE —
1714
- * on siedzi w `pending/` i nie ma powodu leżeć na dysku drugi raz.
1715
- */
1716
- #refusalDump(reason, toolName, shape, cliDialog, hook, at) {
1717
- if (this.#deps.dumpRefusal === undefined)
1718
- return null;
1719
- const pending = this.#pending;
1720
- return {
1721
- reason,
1722
- toolName,
1723
- ...(this.#deps.sessionId === undefined ? {} : { sessionId: this.#deps.sessionId }),
1724
- screen: this.#screenText,
1725
- hook: hook === null
1726
- ? null
1727
- : {
1728
- toolName: hook.toolName,
1729
- at: hook.at,
1730
- ...(hook.hookEventName === undefined ? {} : { hookEventName: hook.hookEventName }),
1731
- },
1732
- jsonl: pending === null ? null : { id: pending.id, toolName: pending.toolName },
1733
- shape,
1734
- ...(cliDialog === null ? {} : { cliDialog }),
1735
- at,
1736
- };
1737
- }
1738
- #writeDump(dump) {
1739
- try {
1740
- this.#deps.dumpRefusal?.(dump);
1741
- }
1742
- catch {
1743
- // Diagnostyka nie ma prawa wywrócić obsługi odmowy — cisza, jak przy dzienniku.
1744
- }
1745
- }
1746
- /**
1747
- * Zrzut hooka tej sesji do dziennika; błąd czytnika znaczy „brak zrzutu”, nigdy wyjątek w obsłudze. Zrzut `Bash`
1748
- * starszy niż 10 minut liczy się tylko z dowodem z ostatniego odczytu ekranu (`admittedHook`),
1749
- * jak w ocenie: inaczej rozdzielacz widziałby zrzut, którego karta nie wzięła.
1750
- */
1751
- #readHookQuietly() {
1752
- try {
1753
- const raw = this.#deps.readPendingHook?.(this.#agentSessionId) ?? null;
1754
- return admittedHook(raw, this.#screenText, (text, expected) => this.#resolveOptions(text, expected));
1755
- }
1756
- catch {
1757
- return null;
1758
- }
1759
- }
1760
- /**
1761
- * Pola dziennika z rozdzielacza warstw i pełnego bloku (`approve`, `degrade`, `refuse`): werdykt
1762
- * `routeDialog` z klasy rejestru CLI, zrzutu hooka i ostatniego odczytu ekranu (`#screenText`, ten sam,
1763
- * który trafia do zrzutu odmowy) oraz `blockVisible` z tego odczytu. Wyłącznie dziennik — karta, przyciski
1764
- * i klawisze od tych pól nie zależą. Wyjątek parsera daje wpis bez tych pól, nigdy wstrzymaną wysyłkę.
1765
- */
1766
- #routeFields(hook) {
1767
- try {
1768
- const text = this.#screenText;
1769
- const { route, reason } = routeDialog({
1770
- cliDialog: this.#cliReserve.cliWaiting, hook: routeHookOf(hook), screen: routeScreenOf(text),
1771
- });
1772
- return { ...(text === null ? {} : { blockVisible: blockVisible(text) }), route, routeReason: reason };
1773
- }
1774
- catch {
1775
- return {};
1776
- }
1777
- }
1778
- /** Kontekst rejestru i rozdzielacza do wpisu `approve`: klasa CLI (gdy `waiting`) i {@link #routeFields}. */
1779
- #approveContext() {
1780
- const cliDialog = this.#cliReserve.cliWaiting;
1781
- return { ...(cliDialog === null ? {} : { cliDialog }), ...this.#routeFields(this.#readHookQuietly()) };
1782
- }
1783
- /**
1784
- * Odpowiedź w inny dialog niż ten, który AKTUALNIE stoi — mówimy o tym GŁOŚNO.
1785
- *
1786
- * `active === null` to normalny wyścig (dialog właśnie rozstrzygnięto — decyzja spóźniona
1787
- * o ułamek sekundy, cisza jest poprawna). Ale odpowiedź adresująca INNY dialog znaczy, że
1788
- * telefon patrzył na nieświeżą kartę — a jej zjedzenie po cichu wyglądałoby jak „tapnąłem
1789
- * i nic".
1790
- */
1791
- #reportStaleDecision() {
1792
- this.#auditRefusal('stale-card', this.#activeReq?.toolName);
1793
- this.#system(STALE_DECISION_MESSAGE);
1794
- /*
1795
- * `refused`, nie `stale`: Rarog POKAZUJE dziś inną kartę niż ta, w którą tapnięto, więc
1796
- * karta, o której mówi żądanie, ma zniknąć razem ze swoim pendingiem — ale ta ŻYWA ma
1797
- * zostać. `stale` wygasiłoby cały pending sesji (410 + `expired`), czyli zdjęłoby także
1798
- * kartę, która mówi prawdę o ekranie.
1799
- */
1800
- return refused('stale-card');
1801
- }
1802
1619
  /**
1803
1620
  * Jedna cyfra do panelu + wpis dziennika, który mówi CO zatwierdzono, a nie co wysłano.
1804
1621
  *
@@ -1817,7 +1634,7 @@ export class HerdrDriver {
1817
1634
  return STALE;
1818
1635
  // Tryb kanału (`main`): zgoda na narzędzie nie idzie cyfrą, także odpowiedź na potwierdzenie z ekranu.
1819
1636
  if (consentDigitRefused(this.#deps, this.#cliReserve.cliWaiting, answered, consent)) {
1820
- return this.#refuseDecision(TERMINAL_ONLY_MESSAGE, 'consent channel main: no digit for a consent', 'terminal-only');
1637
+ return refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'consent channel main: no digit for a consent', 'terminal-only');
1821
1638
  }
1822
1639
  const shadow = consent && this.#shadowChannel() !== undefined ? await this.#shadowStep('allow', answered) : null;
1823
1640
  // Digit that only the measured mark lets through: the send shield before the fresh read and the key.
@@ -1825,8 +1642,9 @@ export class HerdrDriver {
1825
1642
  && consentDigitRefused(this.#deps, this.#cliReserve.cliWaiting, { ...answered, measuredConsent: undefined }, true)
1826
1643
  ? answered.measuredConsent : undefined;
1827
1644
  const shield = mark === undefined ? null : await this.#promptQueue.keyShield(mark.cliDialog);
1828
- if (shield !== null)
1829
- return this.#refuseDecision(SCREEN_CHANGED_MESSAGE, `measured: ${shield}`, 'screen-changed');
1645
+ if (shield !== null) {
1646
+ return refuseDecision(this.#refusals, SCREEN_CHANGED_MESSAGE, `measured: ${shield}`, 'screen-changed');
1647
+ }
1830
1648
  const held = await this.#digitStillHolds(option, answered);
1831
1649
  if (!held.ok) {
1832
1650
  this.#shadowKeySent(shadow, false);
@@ -1840,7 +1658,7 @@ export class HerdrDriver {
1840
1658
  }
1841
1659
  // Measured digit: a hook registration without a card can come during the fresh read, after the shield.
1842
1660
  if (mark !== undefined && this.#promptQueue.keyHookWaits()) {
1843
- return this.#refuseDecision(SCREEN_CHANGED_MESSAGE, 'measured: hook', 'screen-changed');
1661
+ return refuseDecision(this.#refusals, SCREEN_CHANGED_MESSAGE, 'measured: hook', 'screen-changed');
1844
1662
  }
1845
1663
  const live = held.dialog;
1846
1664
  // Odświeżamy meldunek o dialogu zaufania w chwili DECYZJI: to od niej liczy się karencja
@@ -1867,13 +1685,13 @@ export class HerdrDriver {
1867
1685
  // Tożsamość i pochodzenie zatwierdzonej karty — spina wpis z `degrade`/`refuse`.
1868
1686
  ...originFields(answered.reqId, answered.origin),
1869
1687
  // Klasa CLI i werdykt rozdzielacza ze świeżego ekranu `#digitStillHolds` — tylko dziennik.
1870
- ...this.#approveContext(),
1688
+ ...approveContext(this.#refusals),
1871
1689
  // Wynik kroku trybu cienia i klucz pliku — tylko dziennik.
1872
1690
  ...shadowAuditFields(shadow),
1873
1691
  });
1874
1692
  this.#shadowKeySent(shadow, sent);
1875
1693
  if (!sent)
1876
- return this.#refuseSend();
1694
+ return refuseSend(this.#refusals);
1877
1695
  /*
1878
1696
  * Tryb zatwierdzania z ŻYWEGO odczytu, nie z karty: `preview` jest
1879
1697
  * własnością POJEDYNCZEGO pytania, a formularz przełącza zakładki bez mignięcia
@@ -1977,7 +1795,7 @@ export class HerdrDriver {
1977
1795
  const abort = (message, reason) => {
1978
1796
  // Licznik odmów obejmuje TAKŻE ten krok: `abort` jest wspólną drogą obu ścieżek
1979
1797
  // odmowy (`gone()` też przez nią przechodzi), a wpis znaczy „cyfra poszła, `enter` NIE".
1980
- this.#auditRefusal('form-submit', toolName);
1798
+ auditRefusal(this.#refusals, 'form-submit', toolName);
1981
1799
  this.#system(message);
1982
1800
  // Gasimy WYŁĄCZNIE własną kartę: przy podmianie w oknie pauzy `#clearActive` trafiłby
1983
1801
  // w świeżą kartę postawioną przez ocenę panelu — a ona mówi prawdę o ekranie.
@@ -2026,9 +1844,9 @@ export class HerdrDriver {
2026
1844
  {
2027
1845
  method: 'approve', keys: [FORM_SUBMIT_KEY], toolName, optionLabel: option.label,
2028
1846
  ...originFields(answered.reqId, answered.origin),
2029
- ...this.#approveContext(),
1847
+ ...approveContext(this.#refusals),
2030
1848
  });
2031
- return sent ? APPLIED : this.#refuseSend();
1849
+ return sent ? APPLIED : refuseSend(this.#refusals);
2032
1850
  }
2033
1851
  /**
2034
1852
  * Zatwierdzenie dialogu zaufania BEZ cyfr (wyjątek od drogi cyfrowej, wzorem drogi formularza).
@@ -2055,7 +1873,7 @@ export class HerdrDriver {
2055
1873
  return STALE;
2056
1874
  const seq = this.#blockedSeq;
2057
1875
  const refuse = (why) => {
2058
- this.#auditRefusal('screen-changed', toolName);
1876
+ auditRefusal(this.#refusals, 'screen-changed', toolName);
2059
1877
  this.#system(SCREEN_CHANGED_MESSAGE);
2060
1878
  // Gasimy WYŁĄCZNIE własną kartę: podmieniona w trakcie mówi prawdę o ekranie.
2061
1879
  if (this.#activeReq === answered) {
@@ -2096,7 +1914,7 @@ export class HerdrDriver {
2096
1914
  // `send_keys`, nie `approve`: `down` tylko przesuwa `❯`, niczego nie zatwierdza.
2097
1915
  const moved = await this.#send(() => this.#deps.client.sendTrustStep(this.#paneId, TRUST_DOWN_KEY), { method: 'send_keys', keys: [TRUST_DOWN_KEY], ...audit });
2098
1916
  if (!moved)
2099
- return this.#refuseSend();
1917
+ return refuseSend(this.#refusals);
2100
1918
  await this.#sleep(this.#deps.formSubmitConfirmDelayMs ?? FORM_SUBMIT_CONFIRM_DELAY_MS);
2101
1919
  verdict = await read(false);
2102
1920
  if (verdict === null)
@@ -2115,9 +1933,9 @@ export class HerdrDriver {
2115
1933
  // Meldunek o dialogu zaufania w chwili decyzji, po dowodzie z ekranu i po kontroli stanu: od niej liczy się
2116
1934
  // karencja zniknięcia. Meldunek jest synchroniczny (zapis czasu u nadzorcy), więc kontroli nie unieważnia.
2117
1935
  this.#deps.markTrustDialog?.();
2118
- const sent = await this.#send(() => this.#deps.client.sendTrustStep(this.#paneId, enterKey), { method: 'approve', keys: [enterKey], ...audit, ...this.#approveContext() });
1936
+ const sent = await this.#send(() => this.#deps.client.sendTrustStep(this.#paneId, enterKey), { method: 'approve', keys: [enterKey], ...audit, ...approveContext(this.#refusals) });
2119
1937
  if (!sent)
2120
- return this.#refuseSend();
1938
+ return refuseSend(this.#refusals);
2121
1939
  this.#noteDecided(answered, seq, this.#hookGeneration(), this.#pending, {
2122
1940
  bodyPrint: expectedPrint ?? null, screenReqId: answered.reqId,
2123
1941
  });
@@ -2325,7 +2143,7 @@ export class HerdrDriver {
2325
2143
  && this.#sameScreenPermission(text, answered)) {
2326
2144
  return { ok: true, dialog };
2327
2145
  }
2328
- this.#auditRefusal('screen-changed', this.#activeReq?.toolName);
2146
+ auditRefusal(this.#refusals, 'screen-changed', this.#activeReq?.toolName);
2329
2147
  this.#system(SCREEN_CHANGED_MESSAGE);
2330
2148
  // Karta jest już nieprawdą — gasimy ją i każemy ocenie zbudować nową z tego, co stoi
2331
2149
  // TERAZ (świeży ekran siedzi po `#readDialog(true)` w cache'u tej blokady).
@@ -2825,16 +2643,10 @@ export class HerdrDriver {
2825
2643
  return 'no-dialog';
2826
2644
  }
2827
2645
  /**
2828
- * Przerwanie tury JEDNYM `escape`, nie `ctrl+c`.
2829
- * Esc jest kanonicznym przerwaniem Claude Code: zatrzymuje turę i ODDAJE prompt
2830
- * do composera panelu — dokładnie ta semantyka, którą Rarog obiecuje po swojej stronie
2831
- * (`escInterrupt` w widoku sesji). `ctrl+c` tego nie robi, a w trakcie tury bywał przez
2832
- * TUI ignorowany. Jeden Esc, nie dwa: podwójny na pustym polu otwiera w CC rewind.
2833
- *
2834
- * Obietnica rozstrzyga się PO wysłaniu klawisza (`true` = poszedł), bo przerwanie czeka
2835
- * w tej samej kolejce co wysyłki — router składa z tego `delivered`. Metoda celowo
2836
- * NIE jest `async`: `#assertInScope()` ma rzucać synchronicznie, inaczej odmowa dla panelu
2837
- * poza zasięgiem zamienia się w odrzuconą obietnicę i przestaje być 400.
2646
+ * Interrupts the turn with ONE `escape`, not `ctrl+c`: Esc is Claude Code's own interrupt, and a second one on an
2647
+ * empty field opens the rewind. Whether Esc handed the prompt back to the field: {@link returnedPrompt}. The promise
2648
+ * settles AFTER the key went (`true` = sent), as the interrupt waits in the send queue; the router builds `delivered`
2649
+ * from it. Not `async`: `#assertInScope()` must throw synchronously, or an out-of-scope refusal stops being a 400.
2838
2650
  */
2839
2651
  interrupt() {
2840
2652
  this.#assertInScope();
@@ -2843,18 +2655,21 @@ export class HerdrDriver {
2843
2655
  // Flaga PRZED wysyłką: nawet gdy `escape` nie dojdzie, następna wysyłka ma wyczyścić pole.
2844
2656
  this.#needsEscape = true;
2845
2657
  const session = this.#agentSessionId;
2846
- // Po Esc pole nie trzyma już na pewno zablokowanego promptu (CLI oddaje do niego przerwany prompt).
2658
+ // After Esc the field no longer surely holds the blocked prompt: it may hold the interrupted one.
2847
2659
  this.#turnGuard.blockedLeftover = null;
2848
2660
  const token = ++this.#interruptProbeToken;
2849
2661
  return this.#enqueue(async () => {
2662
+ const expected = await this.#returnedPrompt.beforeEscape(this.#engine === 'claude' && !this.#blockedNow()
2663
+ && this.#activeReq === null && this.#promptQueue.prompts.length === 0 && !this.#promptQueue.submitUnsettled()
2664
+ && !this.#takeBack.holdsField());
2850
2665
  /*
2851
- * Pauza „Session paused”: Esc z klawiatury apki przy fokusie poza kartą idzie tędy,
2852
- * nie przez „Odrzuć”, a Esc na pauzie zostaje odmową (`#pauseBlocksEscape`). Odmowa ZANIM ruszy cokolwiek innego;
2853
- * karta wraca oceną (`#refuseDecision`), bo manager zdjął ją już przy przejściu `interrupt-requested`.
2666
+ * "Session paused": Esc from the app keyboard with focus outside the card comes here, not through "Deny", and Esc
2667
+ * on the pause stays a refusal (`#pauseBlocksEscape`): before any state change and after the field read above, so
2668
+ * no read follows the gate before the key. `refuseDecision` restores the card the manager took at the interrupt.
2854
2669
  */
2855
2670
  if ((await this.#pauseBlocksEscape()).blocks) {
2856
2671
  if (!this.#disposed) {
2857
- this.#refuseDecision(PAUSE_ESCAPE_MESSAGE, 'przerwanie: Esc na pauzie „Session paused”', 'terminal-only');
2672
+ refuseDecision(this.#refusals, PAUSE_ESCAPE_MESSAGE, 'przerwanie: Esc na pauzie „Session paused”', 'terminal-only');
2858
2673
  }
2859
2674
  return false;
2860
2675
  }
@@ -2866,9 +2681,9 @@ export class HerdrDriver {
2866
2681
  */
2867
2682
  this.#turnGuard.clearWatchdog();
2868
2683
  this.#turnGuard.localCommand = null;
2869
- // Set again here: a send that was in flight when Esc came cleared the flag in `afterSubmit`, yet the CLI
2870
- // hands that prompt back to its field, and the next send would type behind it. Not after a move to another
2871
- // conversation: its field holds that conversation's text, not the prompt this interrupt was accepted for.
2684
+ // Set again here: a send that was in flight when Esc came cleared the flag in `afterSubmit`, yet Esc may hand
2685
+ // that prompt back to its field (CLI 2.1.329), and the next send would type behind it. Not after a move to
2686
+ // another conversation: its field holds that conversation's text, not the prompt this interrupt was accepted for.
2872
2687
  if (this.#agentSessionId === session)
2873
2688
  this.#needsEscape = true;
2874
2689
  /*
@@ -2899,6 +2714,7 @@ export class HerdrDriver {
2899
2714
  throw err;
2900
2715
  }
2901
2716
  }, { method: 'send_keys', keys: ['escape'] }, 'interrupt');
2717
+ this.#returnedPrompt.start(sent ? expected : null, () => this.#disposed || token !== this.#interruptProbeToken || this.#agentSessionId !== session);
2902
2718
  if (sent && !this.#disposed) {
2903
2719
  /*
2904
2720
  * Ślad po geście pisze SERWER, a nie telefon: tylko on zna
@@ -2919,6 +2735,10 @@ export class HerdrDriver {
2919
2735
  // Krok, który poległ, oddaje `undefined` — dla przerwania to znaczy „klawisz nie poszedł".
2920
2736
  }).then((sent) => sent ?? false);
2921
2737
  }
2738
+ /** {@link SessionDriver.returnedPrompt}: the field read after the last delivered `escape` (`returned-prompt.ts`). */
2739
+ returnedPrompt() {
2740
+ return this.#returnedPrompt.answer();
2741
+ }
2922
2742
  /**
2923
2743
  * Sonda stanu po przerwaniu — poza kolejką wysyłek (nie blokuje kolejnych promptów).
2924
2744
  *
@@ -3073,6 +2893,7 @@ export class HerdrDriver {
3073
2893
  const waiting = signal.kind === 'waiting' ? signal.dialog : null;
3074
2894
  const was = this.#cliReserve.cliWaiting;
3075
2895
  this.#cliReserve.cliWaiting = waiting;
2896
+ this.#noHook.registrySignal(signal.kind === 'active');
3076
2897
  if (signal.kind === 'active')
3077
2898
  this.#cliReserve.cliActiveAt = this.#scheduler.now();
3078
2899
  if (waiting === null) {
@@ -3148,6 +2969,7 @@ export class HerdrDriver {
3148
2969
  }
3149
2970
  this.#turnGuard.clearWatchdog();
3150
2971
  this.#consentChannel.dispose();
2972
+ this.#noHook.dispose();
3151
2973
  stopTasks(this.#tasks, this.#scheduler);
3152
2974
  if (this.#blockedTimer !== null) {
3153
2975
  this.#scheduler.clearTimeout(this.#blockedTimer);
@@ -3204,6 +3026,7 @@ export class HerdrDriver {
3204
3026
  this.#lastFollowAt = this.#scheduler.now();
3205
3027
  // Pole nowej rozmowy nie trzyma promptu zablokowanego w poprzedniej ani tekstu oddanego po jej Enterze.
3206
3028
  this.#turnGuard.blockedLeftover = null;
3029
+ this.#returnedPrompt.conversationChanged();
3207
3030
  // The new conversation ran no send: a block entry of the old file still on its way decides none (notice only).
3208
3031
  this.#turnGuard.executedGeneration = 0;
3209
3032
  this.#promptQueue.heldLeftover = null;
@@ -3272,8 +3095,9 @@ export class HerdrDriver {
3272
3095
  this.#formReserve.formMisses = 0;
3273
3096
  }
3274
3097
  // herdr sam widzi blokadę — rezerwa z rejestru oddaje mu ją PO CICHU (ta sama blokada).
3098
+ // The block only changes hands, so the consent-without-hook episode goes on.
3275
3099
  if (status === 'blocked')
3276
- this.#cliReserve.dropCliHold();
3100
+ this.#noHook.handover(() => { this.#cliReserve.dropCliHold(); });
3277
3101
  /*
3278
3102
  * Spóźniony herdr `working` (albo `idle`/`done`), a rejestr CLI dalej mówi `waiting`:
3279
3103
  * dialog sprzed chwili wciąż stoi, więc blokada przechodzi na rezerwę z rejestru — bez nowego
@@ -3437,6 +3261,7 @@ export class HerdrDriver {
3437
3261
  // Blokada EFEKTYWNA: formularz trzymany przez rezerwę też stoi i też może się podmienić.
3438
3262
  const wanted = !this.#disposed && this.#inScope && this.#blockedNow();
3439
3263
  if (!wanted) {
3264
+ this.#noHook.blockEnded();
3440
3265
  if (this.#blockedTimer !== null) {
3441
3266
  this.#scheduler.clearTimeout(this.#blockedTimer);
3442
3267
  this.#blockedTimer = null;
@@ -3626,6 +3451,7 @@ export class HerdrDriver {
3626
3451
  resetPulseEcho(this.#pulseEcho);
3627
3452
  switch (event.type) {
3628
3453
  case 'history': {
3454
+ this.#returnedPrompt.noteHistory(event.messages);
3629
3455
  const { messages, output } = withoutCommandOutput(event.messages);
3630
3456
  // Wiadomość z kolejki wklejeń stoi w pliku bez Entera Raroga: wpis kolejki się kończy.
3631
3457
  for (const m of messages)
@@ -3642,6 +3468,7 @@ export class HerdrDriver {
3642
3468
  // zablokowanego promptu pewnie.
3643
3469
  if (event.role === 'user')
3644
3470
  this.#turnGuard.blockedLeftover = null;
3471
+ this.#returnedPrompt.noteFile([event]);
3645
3472
  if (event.role === 'user' && (this.#promptQueue.heldLeftover !== null || this.#promptQueue.submitted !== null)) {
3646
3473
  const sent = squashWhitespace(event.blocks.map((block) => (block.type === 'text' ? block.text.text : '')).join(''));
3647
3474
  // Pozostałość wstrzymanego promptu albo wiadomości z kolejki wysłana: pole już jej nie trzyma.
@@ -3994,7 +3821,7 @@ export class HerdrDriver {
3994
3821
  // Karta bez decyzji postawiona przy OCENIE ekranu — degradacja, nie odmowa wysyłki.
3995
3822
  // Kształt przypadku i pochodzenie karty jadą z oceny.
3996
3823
  if (action.audit !== null) {
3997
- this.#auditRefusal(action.audit, source?.toolName, 'degrade', undefined, {
3824
+ auditRefusal(this.#refusals, action.audit, source?.toolName, 'degrade', undefined, {
3998
3825
  reqId: action.kind === 'card' ? action.card.active.reqId : action.reqId,
3999
3826
  origin: action.kind === 'card' ? action.card.active.origin : action.origin,
4000
3827
  // `decideCard` daje kształt przy każdym `audit`; zapas z cache'u ekranu, żeby wpis nie zniknął.
@@ -4048,6 +3875,7 @@ export class HerdrDriver {
4048
3875
  const event = consentOnlyEvent(card.event, card.active, this.#deps, this.#cliReserve.cliWaiting, {
4049
3876
  engineSessionId: this.#agentSessionId, cwd: this.#cwd,
4050
3877
  });
3878
+ this.#noHook.noteCard(card);
4051
3879
  if (event.type === 'permission-request' && event.canAllow === false) {
4052
3880
  // Jedna karta na dialog: przy żywej karcie kanału zgód karta zgody bez przycisku zgody nie idzie do managera.
4053
3881
  if (this.#consentChannel.consentCardStands()) {
@@ -4071,6 +3899,7 @@ export class HerdrDriver {
4071
3899
  this.#undecided = undecided
4072
3900
  ? { active: card.active, cliDialog: 'cliDialog' in event ? event.cliDialog ?? null : null }
4073
3901
  : null;
3902
+ this.#noHook.cardShown(card, event);
4074
3903
  this.#emit(event);
4075
3904
  this.#auditBlockCard(card.active);
4076
3905
  }
@@ -4179,7 +4008,7 @@ export class HerdrDriver {
4179
4008
  }
4180
4009
  else {
4181
4010
  // Ekran z bramki wysyłki wchodzi do cache'u jak każdy odczyt dialogu — zrzut odmowy
4182
- // (`#refusalDump`) bierze go stamtąd.
4011
+ // (`refusalDump`) bierze go stamtąd.
4183
4012
  this.#screenText = screen;
4184
4013
  this.#screenAt = this.#scheduler.now();
4185
4014
  this.#notePause(screen);
@@ -4192,7 +4021,7 @@ export class HerdrDriver {
4192
4021
  const origin = { source: 'screen' };
4193
4022
  // Karta bez zatwierdzania = odmowa w dzienniku: suma odmów ma ją policzyć
4194
4023
  // razem z resztą „odpowiedz w terminalu", a zrzut ekranu wyjaśnia, co stało.
4195
- this.#auditRefusal('consent-dialog', `${SCREEN_DIALOG_TOOL}:${dialog}`, 'degrade', undefined, {
4024
+ auditRefusal(this.#refusals, 'consent-dialog', `${SCREEN_DIALOG_TOOL}:${dialog}`, 'degrade', undefined, {
4196
4025
  reqId, origin, diagnosis: { mismatchReason: null, ...dialogShapeOf(text) },
4197
4026
  });
4198
4027
  this.#clearActive('dialog zgody CLI');