@songsid/agend 2.3.5 → 2.3.6-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 (214) hide show
  1. package/README.md +11 -1
  2. package/README.zh-TW.md +11 -1
  3. package/dist/agent-cli-instructions.md +15 -9
  4. package/dist/agent-cli.js +47 -20
  5. package/dist/agent-cli.js.map +1 -1
  6. package/dist/agent-endpoint.js +23 -8
  7. package/dist/agent-endpoint.js.map +1 -1
  8. package/dist/agent-list-output.d.ts +23 -0
  9. package/dist/agent-list-output.js +53 -0
  10. package/dist/agent-list-output.js.map +1 -0
  11. package/dist/agent-whats-new.js +10 -7
  12. package/dist/agent-whats-new.js.map +1 -1
  13. package/dist/auth-api.js +3 -1
  14. package/dist/auth-api.js.map +1 -1
  15. package/dist/backend/agy-onboarding.d.ts +14 -0
  16. package/dist/backend/agy-onboarding.js +114 -0
  17. package/dist/backend/agy-onboarding.js.map +1 -0
  18. package/dist/backend/antigravity.js +3 -0
  19. package/dist/backend/antigravity.js.map +1 -1
  20. package/dist/backend/claude-code.d.ts +8 -0
  21. package/dist/backend/claude-code.js +11 -4
  22. package/dist/backend/claude-code.js.map +1 -1
  23. package/dist/backend/codex.d.ts +7 -14
  24. package/dist/backend/codex.js +32 -32
  25. package/dist/backend/codex.js.map +1 -1
  26. package/dist/backend/grok-mcp.d.ts +5 -0
  27. package/dist/backend/grok-mcp.js +221 -0
  28. package/dist/backend/grok-mcp.js.map +1 -0
  29. package/dist/backend/grok.d.ts +19 -10
  30. package/dist/backend/grok.js +117 -83
  31. package/dist/backend/grok.js.map +1 -1
  32. package/dist/backend/types.d.ts +16 -1
  33. package/dist/backend/types.js.map +1 -1
  34. package/dist/channel/mcp-tools.js +10 -10
  35. package/dist/channel/mcp-tools.js.map +1 -1
  36. package/dist/claude-model-observation.d.ts +71 -0
  37. package/dist/claude-model-observation.js +169 -0
  38. package/dist/claude-model-observation.js.map +1 -0
  39. package/dist/cli.js +62 -12
  40. package/dist/cli.js.map +1 -1
  41. package/dist/codex-pane-ownership.d.ts +13 -0
  42. package/dist/codex-pane-ownership.js +192 -0
  43. package/dist/codex-pane-ownership.js.map +1 -0
  44. package/dist/config-validator.js +19 -0
  45. package/dist/config-validator.js.map +1 -1
  46. package/dist/cross-instance-envelope.d.ts +4 -1
  47. package/dist/cross-instance-envelope.js +12 -7
  48. package/dist/cross-instance-envelope.js.map +1 -1
  49. package/dist/daemon.d.ts +26 -2
  50. package/dist/daemon.js +344 -49
  51. package/dist/daemon.js.map +1 -1
  52. package/dist/decision-list.d.ts +5 -4
  53. package/dist/decision-list.js +22 -8
  54. package/dist/decision-list.js.map +1 -1
  55. package/dist/delivery-consumed-watch.d.ts +24 -0
  56. package/dist/delivery-consumed-watch.js +21 -10
  57. package/dist/delivery-consumed-watch.js.map +1 -1
  58. package/dist/delivery-outbox.d.ts +9 -1
  59. package/dist/delivery-outbox.js +16 -0
  60. package/dist/delivery-outbox.js.map +1 -1
  61. package/dist/delivery-reconciliation.d.ts +1 -1
  62. package/dist/delivery-reconciliation.js +1 -1
  63. package/dist/dispatcher-liveness.d.ts +172 -0
  64. package/dist/dispatcher-liveness.js +238 -0
  65. package/dist/dispatcher-liveness.js.map +1 -0
  66. package/dist/fleet-manager.d.ts +30 -2
  67. package/dist/fleet-manager.js +195 -22
  68. package/dist/fleet-manager.js.map +1 -1
  69. package/dist/general-knowledge/skills/concepts/SKILL.md +43 -4
  70. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +17 -2
  71. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +18 -8
  72. package/dist/general-knowledge/skills/fleet-health/SKILL.md +15 -0
  73. package/dist/general-knowledge/skills/multi-channel/SKILL.md +1 -1
  74. package/dist/general-knowledge/skills/scheduling/SKILL.md +1 -1
  75. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +63 -17
  76. package/dist/general-knowledge/skills/worker-collaboration/SKILL.md +5 -1
  77. package/dist/grok-delivery-proof.d.ts +24 -0
  78. package/dist/grok-delivery-proof.js +124 -0
  79. package/dist/grok-delivery-proof.js.map +1 -0
  80. package/dist/human-delivery-receipts.d.ts +4 -2
  81. package/dist/human-delivery-receipts.js +20 -13
  82. package/dist/human-delivery-receipts.js.map +1 -1
  83. package/dist/inbound-presentation.d.ts +28 -0
  84. package/dist/inbound-presentation.js +48 -0
  85. package/dist/inbound-presentation.js.map +1 -0
  86. package/dist/install-user-systemd.d.ts +20 -0
  87. package/dist/install-user-systemd.js +55 -0
  88. package/dist/install-user-systemd.js.map +1 -0
  89. package/dist/instance-config-impact.js +2 -0
  90. package/dist/instance-config-impact.js.map +1 -1
  91. package/dist/instance-lifecycle.d.ts +2 -0
  92. package/dist/instance-lifecycle.js +3 -0
  93. package/dist/instance-lifecycle.js.map +1 -1
  94. package/dist/instructions.d.ts +10 -2
  95. package/dist/instructions.js +32 -7
  96. package/dist/instructions.js.map +1 -1
  97. package/dist/linux-launchers.d.ts +88 -0
  98. package/dist/linux-launchers.js +296 -0
  99. package/dist/linux-launchers.js.map +1 -0
  100. package/dist/locale.js +174 -8
  101. package/dist/locale.js.map +1 -1
  102. package/dist/log-steps.d.ts +13 -0
  103. package/dist/log-steps.js +85 -40
  104. package/dist/log-steps.js.map +1 -1
  105. package/dist/needs-you-hub.js +8 -4
  106. package/dist/needs-you-hub.js.map +1 -1
  107. package/dist/needs-you.d.ts +7 -2
  108. package/dist/needs-you.js +5 -9
  109. package/dist/needs-you.js.map +1 -1
  110. package/dist/office-share-page.js +1 -1
  111. package/dist/office-share-page.js.map +1 -1
  112. package/dist/outbound-handlers.d.ts +1 -0
  113. package/dist/outbound-handlers.js +25 -19
  114. package/dist/outbound-handlers.js.map +1 -1
  115. package/dist/outbound-schemas.d.ts +20 -0
  116. package/dist/outbound-schemas.js +24 -4
  117. package/dist/outbound-schemas.js.map +1 -1
  118. package/dist/queued-handoffs.d.ts +3 -1
  119. package/dist/queued-handoffs.js +1 -1
  120. package/dist/queued-handoffs.js.map +1 -1
  121. package/dist/scheduler/db.d.ts +3 -0
  122. package/dist/scheduler/db.js +4 -0
  123. package/dist/scheduler/db.js.map +1 -1
  124. package/dist/scheduler/task-board.d.ts +1 -0
  125. package/dist/scheduler/task-board.js +10 -1
  126. package/dist/scheduler/task-board.js.map +1 -1
  127. package/dist/scheduler/task-liveness.d.ts +34 -0
  128. package/dist/scheduler/task-liveness.js +49 -0
  129. package/dist/scheduler/task-liveness.js.map +1 -0
  130. package/dist/selection-card.d.ts +4 -3
  131. package/dist/selection-card.js +2 -1
  132. package/dist/selection-card.js.map +1 -1
  133. package/dist/service-installer.js +11 -2
  134. package/dist/service-installer.js.map +1 -1
  135. package/dist/settings-change.d.ts +2 -0
  136. package/dist/settings-change.js +43 -29
  137. package/dist/settings-change.js.map +1 -1
  138. package/dist/settings-confirmation.d.ts +4 -0
  139. package/dist/settings-confirmation.js +5 -1
  140. package/dist/settings-confirmation.js.map +1 -1
  141. package/dist/settings-http-confirmation.js +2 -1
  142. package/dist/settings-http-confirmation.js.map +1 -1
  143. package/dist/settings-summary.d.ts +24 -0
  144. package/dist/settings-summary.js +42 -0
  145. package/dist/settings-summary.js.map +1 -0
  146. package/dist/task-board-tool.d.ts +0 -12
  147. package/dist/task-board-tool.js +52 -4
  148. package/dist/task-board-tool.js.map +1 -1
  149. package/dist/tool-receipt-output.d.ts +151 -0
  150. package/dist/tool-receipt-output.js +50 -0
  151. package/dist/tool-receipt-output.js.map +1 -0
  152. package/dist/topic-commands.js +2 -1
  153. package/dist/topic-commands.js.map +1 -1
  154. package/dist/transcript-delta-reader.d.ts +9 -1
  155. package/dist/transcript-delta-reader.js +37 -8
  156. package/dist/transcript-delta-reader.js.map +1 -1
  157. package/dist/transcript-monitor.d.ts +5 -1
  158. package/dist/transcript-monitor.js +66 -4
  159. package/dist/transcript-monitor.js.map +1 -1
  160. package/dist/transcript-sources.d.ts +2 -0
  161. package/dist/transcript-sources.js +2 -0
  162. package/dist/transcript-sources.js.map +1 -1
  163. package/dist/types.d.ts +10 -0
  164. package/dist/ui/chat-quote.js +12 -17
  165. package/dist/ui/chat-render.js +11 -2
  166. package/dist/ui/chat-strings.js +4 -4
  167. package/dist/ui/fleet-canvas.js +5 -2
  168. package/dist/ui/fleet-office-card.js +4 -2
  169. package/dist/ui/fleet-org.js +2 -0
  170. package/dist/ui/panel-chat.js +28 -6
  171. package/dist/ui/panel-details.js +6 -1
  172. package/dist/ui/panel-log.js +4 -2
  173. package/dist/ui/panel-needs.js +2 -0
  174. package/dist/ui/panel-settings.js +29 -1
  175. package/dist/ui/settings-registry.js +4 -0
  176. package/dist/ui/settings-strings.js +14 -0
  177. package/dist/ui/shared/app-i18n.js +2 -2
  178. package/dist/ui/shared/app-needs.js +3 -0
  179. package/dist/ui/shared/app-shell.js +48 -3
  180. package/dist/ui/shared/app.css +2 -0
  181. package/dist/ui/shared/chat-work-bar.css +12 -0
  182. package/dist/ui/shared/model-observation.js +16 -0
  183. package/dist/ui/shared/usage-dialog.js +2 -1
  184. package/dist/ui/shared/view-strings.js +2 -0
  185. package/dist/update-dispatch.d.ts +62 -0
  186. package/dist/update-dispatch.js +69 -2
  187. package/dist/update-dispatch.js.map +1 -1
  188. package/dist/usage/agent-output.d.ts +144 -0
  189. package/dist/usage/agent-output.js +76 -0
  190. package/dist/usage/agent-output.js.map +1 -0
  191. package/dist/usage/i18n-keys.d.ts +1 -1
  192. package/dist/usage/i18n-keys.js +1 -1
  193. package/dist/usage/i18n-keys.js.map +1 -1
  194. package/dist/usage/i18n.d.ts +1 -1
  195. package/dist/usage/i18n.js +2 -1
  196. package/dist/usage/i18n.js.map +1 -1
  197. package/dist/usage/providers.d.ts +4 -1
  198. package/dist/usage/providers.js +22 -11
  199. package/dist/usage/providers.js.map +1 -1
  200. package/dist/usage/usage-api.d.ts +1 -1
  201. package/dist/usage/usage-api.js +4 -4
  202. package/dist/usage/usage-api.js.map +1 -1
  203. package/dist/web-api.d.ts +1 -0
  204. package/dist/web-api.js +2 -1
  205. package/dist/web-api.js.map +1 -1
  206. package/dist/windows-shortcuts.d.ts +29 -5
  207. package/dist/windows-shortcuts.js +52 -9
  208. package/dist/windows-shortcuts.js.map +1 -1
  209. package/dist/workflow-templates/default.md +2 -2
  210. package/launcher/agend-install.cjs +7 -1
  211. package/package.json +1 -1
  212. package/templates/icons/agend-restart.ico +0 -0
  213. package/templates/icons/agend.ico +0 -0
  214. package/templates/windows-shortcuts.ps1 +45 -12
package/dist/daemon.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { ClaudeModelObserver, normalizeClaudeModel } from "./claude-model-observation.js";
2
+ import { checkpointGrokDelivery } from "./grok-delivery-proof.js";
1
3
  import { codexMetadataHomes } from "./backend/codex-metadata.js";
2
4
  import { claudeMinimumError, cliVersionBelow } from "./claude-model-minimum.js";
3
5
  import { quotaNoticeProblem } from "./quota-notice-config.js";
@@ -16,6 +18,7 @@ import { clearKiroSessionProof, proveKiroSessionId, recordKiroSessionProof } fro
16
18
  import { fileURLToPath } from "node:url";
17
19
  import { ensureInstanceDir } from "./private-dir.js";
18
20
  import { createHash, randomBytes, randomUUID } from "node:crypto";
21
+ import { HumanReminderState, humanReceiptMarker, escapeInboundField } from "./inbound-presentation.js";
19
22
  import { EventEmitter } from "node:events";
20
23
  import { rotateLogIfNeededAsync } from "./logger.js";
21
24
  import { coredumpFilterLaunchPrefix } from "./coredump-filter.js";
@@ -52,7 +55,7 @@ import { HangDetector } from "./hang-detector.js";
52
55
  import { writeSecretFile } from "./secret-file.js";
53
56
  import { PaneWriteLock } from "./pane-write-lock.js";
54
57
  import { answerRemoteCard } from "./remote-card-answer.js";
55
- import { buildFleetInstructions } from "./instructions.js";
58
+ import { buildFleetInstructions, INBOUND_HEADER_RULE } from "./instructions.js";
56
59
  import { formatHumanInboundMessage, prepareDeliveryWire, steerInboundEnvelope, BTW_INBOUND_PREFIX, humanBodyHash, humanOwnerObjectId } from "./human-delivery-receipts.js";
57
60
  import { formatCrossInstanceInboundMessage, renderCrossInstanceHandoffMetadata, } from "./cross-instance-envelope.js";
58
61
  import { agendMessageInInput, bottomRowIsReady, inputAreaText, inputShowsPastedText, pastedTextSignature, pasteLeftInInput, strandedAgendMessageInInput } from "./pane-input-residue.js";
@@ -68,6 +71,7 @@ import { markerConsumed, scanTranscriptForDeliveryMarker } from "./delivery-reco
68
71
  import { QUEUED_HANDOFF_MAX_REDELIVERIES, QueuedHandoffStore } from "./queued-handoffs.js";
69
72
  import { measureSyncWork, noteSyncWork } from "./sync-work-attribution.js";
70
73
  import { TranscriptDeltaReader } from "./transcript-delta-reader.js";
74
+ import { checkpointCodexPane } from "./codex-pane-ownership.js";
71
75
  import { buildResumeContinuation, clearInFlightTurnMarker, consumeInFlightTurnMarker, decideTurnResume, normalizeResumeBackend, readResumeFingerprint, RESUME_BLOCKING_DELIVERY_STATES, writeInFlightTurnMarker, } from "./turn-resume.js";
72
76
  import { codexLiveRowMatches } from "./backend/codex.js";
73
77
  import { codexPackageProblemMessage } from "./backend/codex-package.js";
@@ -132,7 +136,7 @@ const TRANSCRIPT_RUNNING_HOLD_MAX_MS = 30 * 60_000;
132
136
  * often; a long silent tool run shows its own busy row on the pane.
133
137
  */
134
138
  export const TRANSCRIPT_OPEN_TURN_QUIET_MS = 15 * 60_000;
135
- const REPLY_RECOVERY_PROMPT = "[system:reply-required] The previous human-facing turn ended without a successfully delivered reply. Do not redo the work. React with an emoji or use the reply tool exactly once now to send the user a concise conclusion. If no substantive answer is needed, a brief react is sufficient. If you already replied to this message, do nothing. Do not reply to this system instruction except through the react or reply tool.";
139
+ const REPLY_RECOVERY_PROMPT = "[system:reply-required] Your last answer to the user hasn't reached them yet. Send it once now with the reply tool: what you did, the result, and the next step (the work itself is done; keep it as it is). If the message only needed an acknowledgement, an emoji react is enough; if you already replied, carry on. Answer this only through the react or reply tool.";
136
140
  /** The outbox evidence for a delivery the CLI's transcript shows taken (#758; #1201 absorbed; #1647 a raw paste's text). */
137
141
  function transcriptMarkerEvidence(kind, rawPaste = false) {
138
142
  if (rawPaste)
@@ -1587,6 +1591,9 @@ export class Daemon extends EventEmitter {
1587
1591
  pauseAdmissions = new Set();
1588
1592
  // Model failover: override model on next spawn when rate-limited
1589
1593
  modelOverride;
1594
+ claudeModelObserver = null;
1595
+ modelObservationBound = false;
1596
+ modelObservation() { return this.modelObservationBound ? this.claudeModelObserver?.snapshot() ?? null : null; }
1590
1597
  // Context rotation v3: ring buffers for daemon-side snapshot
1591
1598
  recentUserMessages = [];
1592
1599
  recentEvents = [];
@@ -2193,17 +2200,21 @@ export class Daemon extends EventEmitter {
2193
2200
  return outcome === "begun";
2194
2201
  }
2195
2202
  async durableAttemptEvidence(windowId, handingOffToNativeQueue, steer, rawPaste = false) {
2203
+ const backend = this.config.backend ?? this.backend?.binaryName ?? "unknown";
2196
2204
  let checkpoint = null;
2197
- try {
2198
- checkpoint = await this.transcriptMonitor?.reconciliationCheckpoint() ?? null;
2199
- }
2200
- catch (err) {
2201
- this.logger.debug({ err }, "Could not checkpoint transcript before durable delivery");
2205
+ // Local raw Codex uses only the bounded exact-UUID checkpoint acquired below;
2206
+ // do not first pay for the diagnostic newest-cwd source's synchronous walk.
2207
+ if (!(rawPaste && backend === "codex")) {
2208
+ try {
2209
+ checkpoint = await this.transcriptMonitor?.reconciliationCheckpoint() ?? null;
2210
+ }
2211
+ catch (err) {
2212
+ this.logger.debug({ err }, "Could not checkpoint transcript before durable delivery");
2213
+ }
2202
2214
  }
2203
2215
  const submissionMode = rawPaste ? "raw_paste" : steer
2204
2216
  ? "steer"
2205
2217
  : handingOffToNativeQueue ? "native_queue_handoff" : "idle_submit";
2206
- const backend = this.config.backend ?? this.backend?.binaryName ?? "unknown";
2207
2218
  // The daemon does not synchronously probe CLI versions on the delivery
2208
2219
  // path. Until lifecycle supplies a version tied to this exact process,
2209
2220
  // queue handoffs persist an unknown resume contract and reconciliation
@@ -2245,23 +2256,34 @@ export class Daemon extends EventEmitter {
2245
2256
  this.noteWorkActivity();
2246
2257
  this.deliveryOutbox?.complete(delivery.deliveryId, this.bootId, delivery.attemptNo, outcome, evidence);
2247
2258
  if (verdict && outcome !== "failed")
2248
- this.startConsumedWatch(delivery, verdict);
2259
+ this.startConsumedWatch(delivery, verdict, outcome);
2249
2260
  }
2250
2261
  /**
2251
2262
  * #1201: a steer or a native-queue hand-off was accepted into the CLI's input (or may have been) — not read. Watch
2252
2263
  * the transcript from this attempt's checkpoint for the moment the CLI takes it, and record that on the delivery;
2253
- * an `uncertain` row becomes `delivered` then. Only claude-code and codex write a transcript AgEnD can read. The
2264
+ * an `uncertain` row becomes `delivered` then. An uncertain idle submission is watched the same way (M-3098). Grok
2265
+ * idle submissions use only their exact launch-UUID lease (#3810). The
2254
2266
  * watch belongs to this CLI: a stop, pause or respawn ends it (restart reconciliation owns the row after that).
2255
2267
  */
2256
- startConsumedWatch(delivery, verdict) {
2268
+ startConsumedWatch(delivery, verdict, outcome = "delivered") {
2257
2269
  const checkpoint = verdict.transcriptCheckpoint;
2258
2270
  const outbox = this.deliveryOutbox;
2259
2271
  if (!checkpoint || !outbox?.markConsumed)
2260
2272
  return;
2261
- if (verdict.submissionMode !== "steer" && verdict.submissionMode !== "native_queue_handoff")
2262
- return;
2263
- if (!["claude-code", "codex"].includes(checkpoint.backend))
2264
- return;
2273
+ const grok = checkpoint.backend === "grok" ? checkpoint.ownedGrok : undefined;
2274
+ if (grok) {
2275
+ if (verdict.submissionMode !== "idle_submit")
2276
+ return;
2277
+ }
2278
+ else {
2279
+ // M-3098: an UNCERTAIN idle submission is watched too — the CLI's later marker is the same positive proof, and it
2280
+ // clears the row from Needs you. A delivered one is not: it needs no upgrade, and the fleet cap stays for real doubt.
2281
+ const lateIdle = verdict.submissionMode === "idle_submit" && outcome === "uncertain";
2282
+ if (verdict.submissionMode !== "steer" && verdict.submissionMode !== "native_queue_handoff" && !lateIdle)
2283
+ return;
2284
+ if (!["claude-code", "codex"].includes(checkpoint.backend))
2285
+ return;
2286
+ }
2265
2287
  const spawn = this.spawnGeneration, fence = this.launchFenceEpoch, boot = this.bootId;
2266
2288
  consumedWatches.start({
2267
2289
  deliveryId: delivery.deliveryId,
@@ -2269,7 +2291,8 @@ export class Daemon extends EventEmitter {
2269
2291
  backend: checkpoint.backend,
2270
2292
  path: checkpoint.path,
2271
2293
  offset: checkpoint.offset,
2272
- current: () => !this.deliveryWritesStopping && spawn === this.spawnGeneration && fence === this.launchFenceEpoch,
2294
+ ...(grok ? { grokSessionId: grok.sessionId, readChunk: grok.readChunk } : {}),
2295
+ current: () => !this.deliveryWritesStopping && spawn === this.spawnGeneration && fence === this.launchFenceEpoch && (grok?.current() ?? true),
2273
2296
  consumed: (via, evidence) => {
2274
2297
  try {
2275
2298
  const result = outbox.markConsumed(delivery.deliveryId, boot, delivery.attemptNo, via, evidence);
@@ -2307,7 +2330,7 @@ export class Daemon extends EventEmitter {
2307
2330
  if (!["claude-code", "codex"].includes(backend))
2308
2331
  return;
2309
2332
  const marker = durableAttempt ? `[agend-delivery-id:${durableAttempt.deliveryId}]`
2310
- : humanVerificationId ? `[agend-human-id:${humanVerificationId}]` : null;
2333
+ : humanVerificationId ? verdict.humanReceipt?.marker ?? `[agend-human-id:${humanVerificationId}]` : null;
2311
2334
  if (!marker || !formatted.startsWith(marker))
2312
2335
  return;
2313
2336
  let checkpoint = verdict.transcriptCheckpoint ?? null;
@@ -2323,7 +2346,7 @@ export class Daemon extends EventEmitter {
2323
2346
  return; // nothing could judge it later: it runs as before (✅ at the hand-off)
2324
2347
  const entry = {
2325
2348
  id: track.id ?? randomUUID(), marker, backend, path: checkpoint.path, offset: checkpoint.offset,
2326
- content: track.content, meta: track.meta, holder: this.handoffHolder(), createdAt: Date.now(),
2349
+ content: track.content, meta: track.meta, wire: formatted, holder: this.handoffHolder(), createdAt: Date.now(),
2327
2350
  redeliveries: track.redeliveries ?? 0,
2328
2351
  };
2329
2352
  try {
@@ -2591,19 +2614,25 @@ export class Daemon extends EventEmitter {
2591
2614
  // #1647: a raw paste has no marker; its text is the needle, and its pane proof already failed — so without the turn
2592
2615
  // in the transcript it stays uncertain (with the pane's reason), never the output-edge outcome.
2593
2616
  const needle = rawPaste ? { rawText: rawPaste.text } : delivery.deliveryId;
2617
+ const bound = checkpoint.ownedCodex;
2618
+ const reader = bound ? new TranscriptDeltaReader(checkpoint.path, checkpoint.offset, checkpoint.backend, needle, bound.identity, bound.retire) : null;
2594
2619
  let found = false;
2595
2620
  try {
2596
2621
  for (let polls = 0; polls <= TRANSCRIPT_PROOF_WINDOW_MS / TRANSCRIPT_PROOF_POLL_MS; polls++) {
2597
2622
  if (this.deliveryWritesStopping)
2598
2623
  return; // reconciliation owns the row now
2599
- const look = await scanTranscriptForDeliveryMarker(checkpoint.path, checkpoint.offset, checkpoint.backend, needle);
2624
+ if (bound && (!bound.current() || !await bound.validate()))
2625
+ break;
2626
+ const look = reader ? await reader.look() : await scanTranscriptForDeliveryMarker(checkpoint.path, checkpoint.offset, checkpoint.backend, needle);
2627
+ if (bound && (!await bound.validate() || !bound.current()))
2628
+ break;
2600
2629
  if (look === "user" || look === "absorbed" || look === "queued") {
2601
2630
  found = true;
2602
2631
  outcome = "delivered";
2603
2632
  evidence = transcriptMarkerEvidence(look, !!rawPaste);
2604
2633
  break;
2605
2634
  }
2606
- last = look;
2635
+ last = look === "pending" ? "unavailable" : look;
2607
2636
  if (spawn !== this.spawnGeneration || fence !== this.launchFenceEpoch) {
2608
2637
  last = "unavailable";
2609
2638
  break;
@@ -2634,6 +2663,10 @@ export class Daemon extends EventEmitter {
2634
2663
  try {
2635
2664
  if (this.deliveryWritesStopping)
2636
2665
  return;
2666
+ if (bound && (!await bound.validate() || !bound.current())) {
2667
+ outcome = "uncertain";
2668
+ evidence = "raw-paste-submit-proof:codex-session-binding-lost; not re-pasted";
2669
+ }
2637
2670
  this.finishDurableDelivery(delivery, outcome, evidence);
2638
2671
  }
2639
2672
  catch (err) {
@@ -4703,6 +4736,8 @@ export class Daemon extends EventEmitter {
4703
4736
  return;
4704
4737
  const outcome = follower.look(pane);
4705
4738
  if (outcome) {
4739
+ if (outcome === "done")
4740
+ this.resetInboundPresentation();
4706
4741
  this.ipcServer?.broadcast({ type: "compact_pane_result", id, owner, outcome });
4707
4742
  return;
4708
4743
  }
@@ -4719,10 +4754,17 @@ export class Daemon extends EventEmitter {
4719
4754
  isDeliveryEpochCurrent(epoch) {
4720
4755
  return epoch === this.deliveryEpoch;
4721
4756
  }
4722
- queueRawPaste(rawText, deliveryEpoch = this.deliveryEpoch, confirmClear = false, durableAttempt, ownSwitch, notifyWritten) {
4757
+ queueRawPaste(rawText, deliveryEpoch = this.deliveryEpoch, confirmClear = false, durableAttempt, ownSwitch, notifyWritten, contextReset) {
4758
+ const modelObserver = this.claudeModelObserver;
4759
+ const modelOwner = launchIdentity(this.interactionOwner());
4760
+ const currentModelOwner = () => modelObserver === this.claudeModelObserver && modelOwner === launchIdentity(this.interactionOwner());
4723
4761
  const reportSwitch = (result) => {
4724
4762
  if (!ownSwitch)
4725
4763
  return;
4764
+ if (currentModelOwner())
4765
+ modelObserver?.ownResult(result.outcome === "switched", ownSwitch.requested);
4766
+ if (result.outcome === "switched")
4767
+ this.resetInboundPresentation();
4726
4768
  this.ipcServer?.broadcast({ type: "runtime_switch_result", id: ownSwitch.id, ...result });
4727
4769
  };
4728
4770
  // Board 003648ac: the fleet follows a web /compact from just before its paste is written: the transcript's end then
@@ -4797,8 +4839,12 @@ export class Daemon extends EventEmitter {
4797
4839
  preserveExactBytes: true,
4798
4840
  // #1690: our own /model holds every other delivery from its write on — before the lock is released, so a steer
4799
4841
  // or /btw waiting on it cannot type into the gap before claude paints "Switch model?" (default cursor: Yes).
4800
- ...(ownSwitch || notifyWritten ? { onPaneWritten: () => { if (ownSwitch)
4801
- this.ownSwitch = ownSwitch; tellWritten(true); } } : {}),
4842
+ ...(ownSwitch || notifyWritten || contextReset ? { onPaneWritten: () => { if (contextReset)
4843
+ this.resetInboundPresentation(); if (ownSwitch) {
4844
+ this.ownSwitch = ownSwitch;
4845
+ if (currentModelOwner())
4846
+ modelObserver?.ownIntent(ownSwitch.requested);
4847
+ } tellWritten(true); } } : {}),
4802
4848
  ...(notifyWritten ? { beforePaneWrite: takeCheckpoint, ...(this.backend?.compactPaneUi?.() ? { lookBeforePaneWrite: lookBefore } : {}) } : {}),
4803
4849
  });
4804
4850
  tellWritten(false); // never written (once told, this says nothing)
@@ -4807,7 +4853,7 @@ export class Daemon extends EventEmitter {
4807
4853
  else if (durableAttempt && verdict.paneWriteStarted) {
4808
4854
  const unproven = `${verdict.phase ?? "raw-paste"}:${verdict.proof ?? "unverified"}`;
4809
4855
  const checkpoint = verdict.transcriptCheckpoint;
4810
- if (checkpoint && RAW_TEXT_TRANSCRIPT_BACKENDS.includes(checkpoint.backend)) {
4856
+ if (checkpoint && (checkpoint.ownedCodex || RAW_TEXT_TRANSCRIPT_BACKENDS.includes(checkpoint.backend))) {
4811
4857
  // #1647: the pane could not show it, but the CLI's transcript records the turn the paste started — later
4812
4858
  // than the pane window sometimes. Wait for it there (bounded), off the paste lock.
4813
4859
  this.logger.info({ deliveryId: durableAttempt.deliveryId, unproven }, "Raw paste not proven on the pane — asking the CLI's transcript for the turn it started");
@@ -4881,7 +4927,7 @@ export class Daemon extends EventEmitter {
4881
4927
  const ownSwitch = sw && typeof sw.id === "string" && sw.kind === "model" && typeof sw.requested === "string"
4882
4928
  ? { id: sw.id, kind: "model", requested: sw.requested } : undefined;
4883
4929
  const notifyWritten = typeof msg.notify_written === "string" && /^[0-9a-f]{16}$/.test(msg.notify_written) ? msg.notify_written : undefined;
4884
- this.queueRawPaste(msg.content, this.captureDeliveryEpoch(msg.delivery_epoch), msg.confirm_clear === true, durableAttempt ? { ...durableAttempt, submissionMode: "raw_paste", silentSchedule: msg.silent_schedule === true } : undefined, ownSwitch, notifyWritten);
4930
+ this.queueRawPaste(msg.content, this.captureDeliveryEpoch(msg.delivery_epoch), msg.confirm_clear === true, durableAttempt ? { ...durableAttempt, submissionMode: "raw_paste", silentSchedule: msg.silent_schedule === true } : undefined, ownSwitch, notifyWritten, msg.context_reset === "clear" || msg.context_reset === "compact" ? msg.context_reset : undefined);
4885
4931
  }
4886
4932
  /**
4887
4933
  * #1690 (the user's choice A): after AgEnD's own `/model <name>`, claude may ask "Switch model?" (a warm cache for
@@ -6486,7 +6532,55 @@ export class Daemon extends EventEmitter {
6486
6532
  * with it — a new monitor re-baselines at the transcript's end, so nothing the old one read can be attributed.
6487
6533
  */
6488
6534
  buildTranscriptMonitor(source) {
6489
- const monitor = new TranscriptMonitor(this.instanceDir, this.logger, source);
6535
+ const modelLaunch = this.backend?.modelObservationLaunch?.();
6536
+ const monitor = new TranscriptMonitor(this.instanceDir, this.logger, source, () => modelLaunch);
6537
+ let savedModel;
6538
+ try {
6539
+ const path = join(this.instanceDir, "claude-model-observation.json");
6540
+ if (statSync(path).size < 1_000_000)
6541
+ savedModel = JSON.parse(readFileSync(path, "utf-8"));
6542
+ }
6543
+ catch { /* No checkpoint. */ }
6544
+ const modelObserver = !source && this.isClaudeCodeBackend()
6545
+ ? new ClaudeModelObserver(this.config.model, this.backend?.modelObservationLaunch?.()?.model ?? this.runtimeIdentity?.model ?? this.config.model, savedModel) : null;
6546
+ this.claudeModelObserver = modelObserver;
6547
+ this.modelObservationBound = false;
6548
+ const owner = launchIdentity(this.interactionOwner());
6549
+ let reminderSession = modelObserver?.checkpoint().sessionId ?? null;
6550
+ const observeReminderBoundary = (sessionId, before, after) => {
6551
+ const selected = (s) => normalizeClaudeModel(s.session ?? s.launch);
6552
+ const served = (s) => normalizeClaudeModel(s.active?.served ?? s.lastServed ?? s.session ?? s.launch);
6553
+ const moved = (a, b) => a !== null && b !== null && a !== b;
6554
+ const changed = reminderSession !== null && reminderSession !== sessionId
6555
+ || moved(selected(before), selected(after)) || moved(served(before), served(after));
6556
+ reminderSession = sessionId;
6557
+ if (changed)
6558
+ this.resetInboundPresentation();
6559
+ };
6560
+ monitor.on("model_context", (sessionId, sessionModel) => {
6561
+ if (!modelObserver || this.transcriptMonitor !== monitor || owner !== launchIdentity(this.interactionOwner()))
6562
+ return;
6563
+ const before = modelObserver.snapshot();
6564
+ modelObserver.bindSession(sessionId, sessionModel);
6565
+ this.modelObservationBound = true;
6566
+ observeReminderBoundary(sessionId, before, modelObserver.snapshot());
6567
+ });
6568
+ monitor.on("model_observation", (record, sessionModel) => {
6569
+ if (!modelObserver || this.transcriptMonitor !== monitor || owner !== launchIdentity(this.interactionOwner()))
6570
+ return;
6571
+ const before = modelObserver.snapshot();
6572
+ const changed = modelObserver.observe(record, sessionModel);
6573
+ this.modelObservationBound = true;
6574
+ observeReminderBoundary(record.sessionId, before, modelObserver.snapshot());
6575
+ try {
6576
+ const path = join(this.instanceDir, "claude-model-observation.json"), temp = `${path}.tmp`;
6577
+ writeFileSync(temp, JSON.stringify(modelObserver.checkpoint()), { mode: 0o600 });
6578
+ renameSync(temp, path);
6579
+ }
6580
+ catch { /* Observation remains visible in memory. */ }
6581
+ if (changed)
6582
+ this.emit("model_observation");
6583
+ });
6490
6584
  this.transcriptTurns.reset();
6491
6585
  this.transcriptActivityAt = 0;
6492
6586
  // Monotonic: a wall-clock correction must neither end nor extend the open-turn hold (#1641 R1).
@@ -6496,7 +6590,12 @@ export class Daemon extends EventEmitter {
6496
6590
  monitor.on("reset", () => { if (this.transcriptMonitor === monitor) {
6497
6591
  this.transcriptTurns.reset();
6498
6592
  this.transcriptActivityAt = 0;
6593
+ this.resetInboundPresentation();
6499
6594
  } });
6595
+ monitor.on("context_reset", () => {
6596
+ if (this.transcriptMonitor === monitor && owner === launchIdentity(this.interactionOwner()))
6597
+ this.resetInboundPresentation();
6598
+ });
6500
6599
  for (const event of ["tool_use", "tool_result", "assistant_text"])
6501
6600
  monitor.on(event, touch);
6502
6601
  return monitor;
@@ -7585,12 +7684,59 @@ export class Daemon extends EventEmitter {
7585
7684
  */
7586
7685
  /** #1650: how this instance talks to the fleet — MCP tools, or agend-agent commands (agent_mode: cli). */
7587
7686
  agentMode() { return this.config.agent_mode === "cli" ? "cli" : "mcp"; }
7687
+ humanReminders = new HumanReminderState();
7688
+ compactInboundInstructions = false;
7689
+ inboundCompatibilityPending = false;
7690
+ humanPreparations = new Map();
7691
+ humanReminderAttempts = new Map();
7692
+ /** Manager-owned admission capability. Never derived from a body marker. */
7693
+ registerHumanReceiptPreparation(receiptId, prepare, abandon) {
7694
+ this.humanPreparations ??= new Map();
7695
+ this.humanReminderAttempts ??= new Map();
7696
+ this.humanReminders ??= new HumanReminderState();
7697
+ const token = randomUUID();
7698
+ this.humanPreparations.set(token, { receiptId, prepare, abandon });
7699
+ return token;
7700
+ }
7701
+ /** Called only when this launch has installed instructions teaching both dialects. */
7702
+ installCompactInboundInstructions() {
7703
+ this.compactInboundInstructions = true;
7704
+ this.inboundCompatibilityPending = false;
7705
+ this.humanReminders.reset();
7706
+ }
7707
+ resetInboundPresentation() { (this.humanReminders ??= new HumanReminderState()).reset(); }
7708
+ prepareHumanReceiptWrite(meta, fallback) {
7709
+ if (!meta.human_prepare_token)
7710
+ return fallback;
7711
+ const preparation = this.humanPreparations.get(meta.human_prepare_token);
7712
+ if (!preparation || preparation.receiptId !== meta.human_receipt_id)
7713
+ throw new Error("Human delivery preparation is unavailable");
7714
+ const stamp = preparation.prepared?.stamp ?? this.humanReminders.prepare(preparation.receiptId);
7715
+ if (!this.humanReminders.current(stamp))
7716
+ throw new Error("Human delivery context changed");
7717
+ const dialect = this.compactInboundInstructions ? "compact" : "legacy";
7718
+ const prepared = preparation.prepared ?? { ...preparation.prepare({ dialect, replyHint: stamp.replyHint, escape: true,
7719
+ ...(this.inboundCompatibilityPending ? { compatibilityNotice: "[system:headers] " + INBOUND_HEADER_RULE } : {}) }), stamp };
7720
+ preparation.prepared = prepared;
7721
+ Object.assign(meta, prepared.meta);
7722
+ this.humanReminderAttempts.set(preparation.receiptId, stamp);
7723
+ return prepared.wire;
7724
+ }
7588
7725
  formatInboundMessage(content, meta) {
7726
+ let historicalHandoff = false;
7727
+ if (meta.handoff_redelivery) {
7728
+ const owned = this.handoffStore().list().find(row => row.id === meta.handoff_redelivery && row.holder === this.handoffHolder());
7729
+ if (owned?.wire)
7730
+ return owned.wire;
7731
+ // Pre-wire records retain their historical rendering only after proving the owned handoff.
7732
+ historicalHandoff = !!owned;
7733
+ }
7734
+ // Receiptless bot/system traffic has no final receipt preparation to replace this fallback.
7589
7735
  if (!meta.from_instance)
7590
- return formatHumanInboundMessage(content, meta, this.agentMode());
7736
+ return formatHumanInboundMessage(content, meta, this.agentMode(), { dialect: "legacy", escape: !historicalHandoff });
7591
7737
  let formatted = formatCrossInstanceInboundMessage(content, meta, this.agentMode());
7592
7738
  if (meta.reply_to_text)
7593
- formatted += '\n(reply_to: "' + meta.reply_to_text + '")';
7739
+ formatted += '\n(reply_to: "' + escapeInboundField(meta.reply_to_text) + '")';
7594
7740
  if (meta.delivery_id)
7595
7741
  formatted = "[agend-delivery-id:" + meta.delivery_id + "]\n" + formatted;
7596
7742
  return formatted;
@@ -7613,10 +7759,13 @@ export class Daemon extends EventEmitter {
7613
7759
  }
7614
7760
  }
7615
7761
  /** The same formatter/sanitizer used by the actual write; snapshot only. */
7616
- humanReceiptWire(content, meta, kind) {
7762
+ humanReceiptWire(content, meta, kind, presentation) {
7617
7763
  let wire = kind === "raw_paste" ? content
7618
7764
  : !meta.from_instance && content.startsWith("/raw ") && kind === "fleet_inbound"
7619
- ? content.slice(5) : this.formatInboundMessage(content, meta);
7765
+ ? content.slice(5) : presentation && !meta.from_instance
7766
+ ? formatHumanInboundMessage(content, meta, this.agentMode(), presentation) : this.formatInboundMessage(content, meta);
7767
+ if (presentation?.compatibilityNotice)
7768
+ wire = withWhatsNew(wire, presentation.compatibilityNotice);
7620
7769
  if (kind === "steer")
7621
7770
  wire = Daemon.steerEnvelope(wire);
7622
7771
  else if (kind === "btw")
@@ -7630,8 +7779,10 @@ export class Daemon extends EventEmitter {
7630
7779
  || !daemonOwner || !meta.human_owner_key || !/^[a-f0-9]{64}$/.test(meta.human_wire_sha256 ?? "")
7631
7780
  || humanBodyHash(prepareDeliveryWire(wire)) !== meta.human_wire_sha256)
7632
7781
  return undefined;
7782
+ const stamp = this.humanReminderAttempts?.get(id);
7633
7783
  return { receiptId: id, verificationId: meta.verification_id, expectedWireHash: meta.human_wire_sha256,
7634
- ownerKey: meta.human_owner_key, current: () => this.captureHumanReceiptOwner() === daemonOwner };
7784
+ ownerKey: meta.human_owner_key, marker: humanReceiptMarker(meta.verification_id, meta.human_wire_dialect === "compact" ? "compact" : "legacy"), current: () => this.captureHumanReceiptOwner() === daemonOwner
7785
+ && (!stamp || this.humanReminders.current(stamp)) };
7635
7786
  }
7636
7787
  /**
7637
7788
  * #2770: a person's message a cancel dropped before it reached the CLI is told, not left as a silent "uncertain":
@@ -7654,8 +7805,15 @@ export class Daemon extends EventEmitter {
7654
7805
  this.cancelledHumansTimer.unref?.();
7655
7806
  }
7656
7807
  finishHumanReceipt(meta, verdict) {
7657
- if (!meta.human_receipt_id || !meta.human_owner_key)
7808
+ if (!meta.human_receipt_id)
7809
+ return;
7810
+ if (!meta.human_owner_key) {
7811
+ const preparation = meta.human_prepare_token ? this.humanPreparations?.get(meta.human_prepare_token) : undefined;
7812
+ preparation?.abandon?.();
7813
+ if (meta.human_prepare_token)
7814
+ this.humanPreparations?.delete(meta.human_prepare_token);
7658
7815
  return;
7816
+ }
7659
7817
  const attempt = verdict.humanReceipt;
7660
7818
  const proof = attempt?.current() && !["unverified", "output-edge", "unverifiable"].includes(verdict.proof ?? "")
7661
7819
  ? attempt.proof ?? null : null;
@@ -7665,6 +7823,22 @@ export class Daemon extends EventEmitter {
7665
7823
  catch (err) {
7666
7824
  this.logger.error({ err }, "Could not publish human delivery evidence");
7667
7825
  }
7826
+ finally {
7827
+ if (meta.human_prepare_token)
7828
+ this.humanPreparations.delete(meta.human_prepare_token);
7829
+ this.humanReminderAttempts.delete(meta.human_receipt_id);
7830
+ }
7831
+ }
7832
+ /** Synchronous acknowledgement from the manager after the existing receipt owner/authority checks. */
7833
+ noteHumanReceiptSettlement(id, positive) {
7834
+ const stamp = this.humanReminderAttempts?.get(id);
7835
+ if (!stamp || !positive || !this.humanReminders.current(stamp))
7836
+ return;
7837
+ this.humanReminders.settle(stamp, true);
7838
+ if (this.inboundCompatibilityPending) {
7839
+ this.compactInboundInstructions = true;
7840
+ this.inboundCompatibilityPending = false;
7841
+ }
7668
7842
  }
7669
7843
  /**
7670
7844
  * Whether ONE delivery reached a verdict, carried by that delivery.
@@ -7767,7 +7941,7 @@ export class Daemon extends EventEmitter {
7767
7941
  steer: true,
7768
7942
  deliveryEpoch,
7769
7943
  submissionId: meta.message_id,
7770
- ...(meta.verification_id ? { humanVerificationId: meta.verification_id } : {}),
7944
+ ...(meta.verification_id ? { humanVerificationId: meta.verification_id, humanMeta: meta } : {}),
7771
7945
  verdict,
7772
7946
  durableAttempt: durableAttempt || undefined,
7773
7947
  })) {
@@ -7845,7 +8019,7 @@ export class Daemon extends EventEmitter {
7845
8019
  let delivered = false;
7846
8020
  try {
7847
8021
  if (await this.deliverMessage(formatted, status, { steer: true, deliveryEpoch, submissionId: meta.message_id,
7848
- ...(meta.verification_id ? { humanVerificationId: meta.verification_id } : {}), verdict })) {
8022
+ ...(meta.verification_id ? { humanVerificationId: meta.verification_id, humanMeta: meta } : {}), verdict })) {
7849
8023
  delivered = true;
7850
8024
  this.markTurnStarted(meta, formatted, deliveryEpoch);
7851
8025
  }
@@ -7982,7 +8156,7 @@ export class Daemon extends EventEmitter {
7982
8156
  sent = await this.deliverMessage(pasted, status, {
7983
8157
  deliveryEpoch,
7984
8158
  submissionId: meta.message_id,
7985
- ...(meta.verification_id ? { humanVerificationId: meta.verification_id } : {}),
8159
+ ...(meta.verification_id ? { humanVerificationId: meta.verification_id, humanMeta: meta } : {}),
7986
8160
  verdict,
7987
8161
  durableAttempt: durableAttempt || undefined,
7988
8162
  });
@@ -8273,7 +8447,7 @@ export class Daemon extends EventEmitter {
8273
8447
  return stale();
8274
8448
  if (residue !== "clear")
8275
8449
  return this.failDelivery(verdict, status, "input-residue", residue);
8276
- const written = await this.writeMessageToPane(formatted, windowId, handingOffToNativeQueue, status, opts?.submissionId, verdict, opts?.durableAttempt, opts?.steer === true, writeCurrent, opts?.humanVerificationId, opts?.beforePaneWrite, opts?.lookBeforePaneWrite);
8450
+ const written = await this.writeMessageToPane(formatted, windowId, handingOffToNativeQueue, status, opts?.submissionId, verdict, opts?.durableAttempt, opts?.steer === true, writeCurrent, opts?.humanVerificationId, opts?.beforePaneWrite, opts?.lookBeforePaneWrite, opts?.humanMeta);
8277
8451
  // #1690: still under the lock — whatever waits on it next must already see what this write started.
8278
8452
  if (verdict.paneWriteStarted)
8279
8453
  opts?.onPaneWritten?.();
@@ -10265,13 +10439,34 @@ export class Daemon extends EventEmitter {
10265
10439
  // Board 003648ac: called synchronously right before each paste — after the last await and fence of that attempt.
10266
10440
  beforePaste,
10267
10441
  // Board 907c7899: awaited each attempt after its last capture, begin and fence; the fence is asked again after it.
10268
- lookBeforePaste) {
10269
- const signature = this.submissionSignature(formatted, humanVerificationId ?? submissionId, humanVerificationId !== undefined);
10442
+ lookBeforePaste, humanMeta) {
10443
+ if (humanMeta?.human_prepare_token) {
10444
+ if (stillCurrent && !stillCurrent())
10445
+ return false;
10446
+ formatted = this.prepareHumanReceiptWrite(humanMeta, formatted);
10447
+ if (verdict.trackHandoff) {
10448
+ const { human_prepare_token: _token, ...kept } = humanMeta;
10449
+ Object.assign(verdict.trackHandoff.meta, kept);
10450
+ delete verdict.trackHandoff.meta.human_prepare_token;
10451
+ }
10452
+ verdict.humanReceipt = this.humanReceiptAttempt(humanMeta, formatted);
10453
+ if (!verdict.humanReceipt?.current())
10454
+ return false;
10455
+ const writeOwner = stillCurrent;
10456
+ stillCurrent = () => (!writeOwner || writeOwner()) && verdict.humanReceipt.current();
10457
+ }
10458
+ const humanDialect = humanMeta?.human_wire_dialect === "compact" ? "compact" : "legacy";
10459
+ const signature = this.submissionSignature(formatted, humanVerificationId ?? submissionId, humanVerificationId !== undefined, humanDialect);
10460
+ // M-3098: the lead marker AgEnD put on this delivery, for a CLI that shows it as taken (Grok cuts its echo before
10461
+ // the trailing message_id). Only AgEnD's own value for this attempt, and only when the text really leads with it.
10462
+ const leadMarker = durableAttempt && humanVerificationId === undefined ? `[agend-delivery-id:${durableAttempt.deliveryId}]` : null;
10463
+ if (leadMarker && formatted.startsWith(leadMarker + "\n"))
10464
+ signature.takenMarker = leadMarker;
10270
10465
  const rawPaste = durableAttempt?.submissionMode === "raw_paste";
10271
10466
  const humanAttempt = verdict.humanReceipt;
10272
10467
  const humanMode = rawPaste ? "raw_paste" : steer ? "steer"
10273
10468
  : handingOffToNativeQueue ? "native_queue_handoff" : "idle_submit";
10274
- if (humanAttempt && signature.unique && signature.value === "agend-human-id:" + humanAttempt.verificationId
10469
+ if (humanAttempt && signature.unique && signature.value === humanReceiptMarker(humanAttempt.verificationId, humanDialect).slice(1, -1)
10275
10470
  && humanBodyHash(formatted) === humanAttempt.expectedWireHash) {
10276
10471
  signature.humanPositive = tag => {
10277
10472
  if (!humanAttempt.current() || (stillCurrent && !stillCurrent()))
@@ -10339,6 +10534,7 @@ export class Daemon extends EventEmitter {
10339
10534
  // first side effect; a crash during those waits remains safely replayable.
10340
10535
  if (durableAttempt && !beginChecked) {
10341
10536
  beginChecked = true;
10537
+ const proofOwner = this.interactionOwner();
10342
10538
  const attemptEvidence = {
10343
10539
  ...await this.durableAttemptEvidence(windowId, handingOffToNativeQueue, steer, durableAttempt.submissionMode === "raw_paste"),
10344
10540
  // #856: what arrived vs what is about to be written, taken at the
@@ -10346,7 +10542,24 @@ export class Daemon extends EventEmitter {
10346
10542
  pastedContentSha256: durableAttempt.contentSha256 ?? null,
10347
10543
  pastedBytesSha256: deliveryContentDigest(formatted),
10348
10544
  };
10349
- if (stillCurrent && !stillCurrent()) {
10545
+ const codexCheckpoint = rawPaste && attemptEvidence.backend === "codex" && windowId
10546
+ ? await this.bindCodexRawPaste(windowId, steerCurrent) : null;
10547
+ const grokCheckpoint = !rawPaste && attemptEvidence.backend === "grok" && attemptEvidence.submissionMode === "idle_submit"
10548
+ ? await checkpointGrokDelivery({ cwd: this.config.working_directory,
10549
+ sessionId: this.backend?.getDeliverySessionId?.() ?? null,
10550
+ current: () => steerCurrent() && sameInteractionOwner(proofOwner, this.interactionOwner()) }) : null;
10551
+ if (grokCheckpoint) {
10552
+ attemptEvidence.transcriptPath = grokCheckpoint.path;
10553
+ attemptEvidence.transcriptOffset = grokCheckpoint.offset;
10554
+ attemptEvidence.transcriptSessionId = grokCheckpoint.sessionId;
10555
+ }
10556
+ if (codexCheckpoint) {
10557
+ attemptEvidence.transcriptPath = codexCheckpoint.path;
10558
+ attemptEvidence.transcriptOffset = codexCheckpoint.offset;
10559
+ attemptEvidence.transcriptSessionId = codexCheckpoint.sessionId;
10560
+ }
10561
+ if ((stillCurrent && !stillCurrent()) || ((grokCheckpoint || (rawPaste && attemptEvidence.backend === "codex"))
10562
+ && (!sameInteractionOwner(proofOwner, this.interactionOwner()) || !steerCurrent()))) {
10350
10563
  verdict.fenced = true;
10351
10564
  return false;
10352
10565
  }
@@ -10363,12 +10576,14 @@ export class Daemon extends EventEmitter {
10363
10576
  backend: attemptEvidence.backend,
10364
10577
  path: attemptEvidence.transcriptPath,
10365
10578
  offset: attemptEvidence.transcriptOffset,
10579
+ ...(codexCheckpoint ? { ownedCodex: codexCheckpoint.ownedCodex } : {}),
10580
+ ...(grokCheckpoint ? { ownedGrok: grokCheckpoint.ownedGrok } : {}),
10366
10581
  };
10367
10582
  // From here every proof of this write may also ask the CLI's transcript (the pane can lose the echo to the
10368
10583
  // reply, or still be painting the paste) — this delivery's exact marker only, or a raw paste's exact text (#1647).
10369
10584
  // A raw paste's text only where the transcript is this instance's alone (RAW_TEXT_TRANSCRIPT_BACKENDS).
10370
10585
  if (["claude-code", "codex"].includes(attemptEvidence.backend)
10371
- && (!rawPaste || RAW_TEXT_TRANSCRIPT_BACKENDS.includes(attemptEvidence.backend))) {
10586
+ && (!rawPaste || codexCheckpoint || RAW_TEXT_TRANSCRIPT_BACKENDS.includes(attemptEvidence.backend))) {
10372
10587
  signature.transcript = this.transcriptProofFor(verdict.transcriptCheckpoint, rawPaste ? { rawText: formatted } : durableAttempt.deliveryId, spawnAtWrite, stillCurrent, kind => { verdict.transcriptProof = kind; });
10373
10588
  }
10374
10589
  }
@@ -10514,7 +10729,7 @@ export class Daemon extends EventEmitter {
10514
10729
  if (!this.steerPasteIsOurs(before.pane, formatted))
10515
10730
  return this.failDelivery(verdict, status, "steer-paste", "box-not-this-paste");
10516
10731
  const shown = this.backend?.readSteerComposerText?.(before.pane)?.replace(/\s+/g, " ").trim();
10517
- humanComposerOwned = !!humanAttempt && shown === "[agend-human-id:" + humanAttempt.verificationId + "]";
10732
+ humanComposerOwned = !!humanAttempt && shown === (humanAttempt.marker ?? "[agend-human-id:" + humanAttempt.verificationId + "]");
10518
10733
  // …and so is the Enter: the key is sent only while the reading is still within it.
10519
10734
  steerEnterDeadline = deadline;
10520
10735
  }
@@ -11098,6 +11313,10 @@ export class Daemon extends EventEmitter {
11098
11313
  pane = await this.tmux.capturePane();
11099
11314
  }
11100
11315
  catch { /* the transcript may still say */ }
11316
+ if (owned && !owned())
11317
+ return "unproven";
11318
+ if (signature.transcript?.validate && !await signature.transcript.validate())
11319
+ return "unproven";
11101
11320
  if (owned && !owned())
11102
11321
  return "unproven";
11103
11322
  const onPane = pane === null ? "unproven" : this.judgeSubmission(pane, signature, baseline);
@@ -11105,6 +11324,8 @@ export class Daemon extends EventEmitter {
11105
11324
  return onPane;
11106
11325
  const t = signature.transcript;
11107
11326
  const found = await this.transcriptLook(signature);
11327
+ if (t?.validate && !await t.validate())
11328
+ return "unproven";
11108
11329
  // One synchronous stretch from here: the fence is asked after the last await, and only then is the hit kept and the
11109
11330
  // spawn's guard retired — a stop or respawn that lands between the look and this line leaves both untouched.
11110
11331
  if (!found || !t?.current() || (owned && !owned()))
@@ -11138,12 +11359,62 @@ export class Daemon extends EventEmitter {
11138
11359
  transcriptProofFor(checkpoint, needle, spawnAtWrite, stillCurrent, onProof) {
11139
11360
  const launchAtWrite = this.launchFenceEpoch;
11140
11361
  return {
11141
- reader: new TranscriptDeltaReader(checkpoint.path, checkpoint.offset, checkpoint.backend, needle),
11362
+ reader: new TranscriptDeltaReader(checkpoint.path, checkpoint.offset, checkpoint.backend, needle, checkpoint.ownedCodex?.identity, checkpoint.ownedCodex?.retire),
11142
11363
  current: () => !this.deliveryWritesStopping && this.spawnGeneration === spawnAtWrite
11143
- && this.launchFenceEpoch === launchAtWrite && (stillCurrent?.() ?? true),
11364
+ && this.launchFenceEpoch === launchAtWrite && (stillCurrent?.() ?? true) && (checkpoint.ownedCodex?.current() ?? true),
11365
+ validate: checkpoint.ownedCodex?.validate,
11144
11366
  onProof,
11145
11367
  };
11146
11368
  }
11369
+ /** A footer observation authorizes only this pre-write delta under this exact pane/launch. No persisted lease. */
11370
+ async bindCodexRawPaste(windowId, stillCurrent) {
11371
+ const tmux = this.tmux, backend = this.backend, owner = this.interactionOwner();
11372
+ if (!tmux || !backend?.readRawPasteSession)
11373
+ return null;
11374
+ let retired = false;
11375
+ const current = () => {
11376
+ if (!retired && stillCurrent() && this.tmux === tmux && this.backend === backend && tmux.getWindowId() === windowId
11377
+ && sameInteractionOwner(owner, this.interactionOwner()) && !this.deliveryWritesStopping)
11378
+ return true;
11379
+ retired = true;
11380
+ return false;
11381
+ };
11382
+ const observe = async () => {
11383
+ if (!current() || await tmux.paneInMode?.() === true || !current())
11384
+ return null;
11385
+ const pane = await tmux.capturePane().catch(() => null);
11386
+ if (!current() || pane === null || this.ownSwitch
11387
+ || this.deliveryBlockingDialogs().some(dialog => Daemon.dialogMatches(dialog, pane)))
11388
+ return null;
11389
+ return backend.readRawPasteSession(pane);
11390
+ };
11391
+ const before = await observe();
11392
+ if (!before || !current())
11393
+ return null;
11394
+ const file = await checkpointCodexPane(before.sessionsDir, before.sessionId, this.config.working_directory || process.cwd());
11395
+ if (!file || !current())
11396
+ return null;
11397
+ const validate = async () => {
11398
+ if (!current())
11399
+ return false;
11400
+ const first = await observe();
11401
+ if (!first || first.sessionId !== before.sessionId || first.sessionsDir !== before.sessionsDir || !current()
11402
+ || !await file.validateFile() || !current()) {
11403
+ retired = true;
11404
+ return false;
11405
+ }
11406
+ const last = await observe();
11407
+ if (!last || last.sessionId !== before.sessionId || last.sessionsDir !== before.sessionsDir || !current()) {
11408
+ retired = true;
11409
+ return false;
11410
+ }
11411
+ return true;
11412
+ };
11413
+ if (!await validate())
11414
+ return null;
11415
+ return { backend: "codex", path: file.path, offset: file.offset, sessionId: file.sessionId,
11416
+ ownedCodex: { identity: file.identity, current, validate, retire: () => { retired = true; } } };
11417
+ }
11147
11418
  /** The CLI this daemon drives, for log lines shared by every backend ("claude-code", "codex", …). */
11148
11419
  cliLabel() {
11149
11420
  return this.config.backend ?? this.backend?.binaryName ?? "CLI";
@@ -11211,6 +11482,12 @@ export class Daemon extends EventEmitter {
11211
11482
  // Something sits in the box that cannot be attributed either way. Only a unique signature seen outside the box
11212
11483
  // (below) can still prove this delivery; nothing else on screen may.
11213
11484
  const unattributedResidue = !attributable && (after.strandedInput || after.collapsedPastes > 0);
11485
+ // M-3098: this delivery's own lead marker shown as TAKEN above the box — a Grok echo's first row, or its queue.
11486
+ // Grok cuts an echo to three rows, so the trailing message_id never shows after Enter; the marker always does.
11487
+ // Placed after the strand checks: text of ours still in the box (or its collapsed paste) outranks it.
11488
+ if (signature.takenMarker && after.inputReadable && this.backend?.readTakenMarkers?.(pane).includes(signature.takenMarker)) {
11489
+ return this.submittedProof();
11490
+ }
11214
11491
  // 2. Positive evidence. A unique signature needs no baseline: no earlier
11215
11492
  // message can carry this delivery's message_id, so finding it outside
11216
11493
  // the input row is proof in itself — which also means a momentary
@@ -11364,7 +11641,7 @@ export class Daemon extends EventEmitter {
11364
11641
  * paste that never landed. System pastes carry no envelope and fall back to
11365
11642
  * the body signature, which the baseline comparison still ties to this paste.
11366
11643
  */
11367
- submissionSignature(formatted, trustedId, verification = false) {
11644
+ submissionSignature(formatted, trustedId, verification = false, dialect = "legacy") {
11368
11645
  // The id must come from the message's own metadata, never from scanning the
11369
11646
  // rendered text: agents and users discuss message ids in the body all the
11370
11647
  // time ("check message_id: abc"), and a body-scanned value would match an
@@ -11373,7 +11650,7 @@ export class Daemon extends EventEmitter {
11373
11650
  // the handoff metadata identifies THIS delivery.
11374
11651
  const id = trustedId?.trim();
11375
11652
  if (id)
11376
- return { value: (verification ? "agend-human-id:" : "message_id:") + id, unique: true };
11653
+ return { value: verification ? humanReceiptMarker(id, dialect).slice(1, -1) : "message_id:" + id, unique: true };
11377
11654
  return { value: pastedTextSignature(formatted), unique: false };
11378
11655
  }
11379
11656
  /**
@@ -12268,6 +12545,13 @@ export class Daemon extends EventEmitter {
12268
12545
  this.clearReplyGuardConfirm();
12269
12546
  this.sawBlockedInput = false;
12270
12547
  if (this.spawnDepth === 0) {
12548
+ this.resetInboundPresentation();
12549
+ this.compactInboundInstructions = false;
12550
+ this.inboundCompatibilityPending = false;
12551
+ for (const p of this.humanPreparations?.values() ?? [])
12552
+ p.abandon?.();
12553
+ this.humanPreparations?.clear();
12554
+ this.humanReminderAttempts?.clear();
12271
12555
  this.cliOomObservation = null;
12272
12556
  this.spawnGeneration++;
12273
12557
  this.interactionObservation.reset(this.interactionOwner());
@@ -13467,7 +13751,8 @@ export class Daemon extends EventEmitter {
13467
13751
  this.emit("kiro_compatibility_hold", null);
13468
13752
  }
13469
13753
  // #1633: decided before prev-instructions is first written — its absence is what says "never launched before".
13470
- this.prepareWhatsNew(!existsSync(join(this.instanceDir, "prev-instructions")));
13754
+ const freshInboundInstructions = !existsSync(join(this.instanceDir, "prev-instructions"));
13755
+ this.prepareWhatsNew(freshInboundInstructions);
13471
13756
  // Record what this launch writes. #2787: a change is never announced in the pane; the CLI takes the new
13472
13757
  // instructions whenever it next reads its own file.
13473
13758
  if (backendConfig.instructions) {
@@ -13489,6 +13774,13 @@ export class Daemon extends EventEmitter {
13489
13774
  if (launchFence !== this.launchFenceEpoch)
13490
13775
  throw new Error("Launch cancelled: the instance was stopped or paused while the launch was being prepared");
13491
13776
  this.backend.writeConfig(backendConfig);
13777
+ if (freshInboundInstructions)
13778
+ this.installCompactInboundInstructions();
13779
+ else {
13780
+ this.compactInboundInstructions = false;
13781
+ this.inboundCompatibilityPending = true;
13782
+ this.resetInboundPresentation();
13783
+ }
13492
13784
  this.backend.preTrust?.(this.config.working_directory, backendConfig);
13493
13785
  // Resolve working directory (e.g. symlink for hidden paths)
13494
13786
  const resolvedCwd = this.backend.resolveWorkingDirectory?.(this.config.working_directory, this.name) ?? this.config.working_directory;
@@ -13855,7 +14147,7 @@ export class Daemon extends EventEmitter {
13855
14147
  // each have seen a respawn, pause or stop.
13856
14148
  if (!owned())
13857
14149
  return false;
13858
- if (key === "Up" || key === "Down" || key === "Enter" || key === "Escape") {
14150
+ if (key === "Up" || key === "Down" || key === "Enter" || key === "Escape" || key === "Right") {
13859
14151
  if (!await this.tmux.sendSpecialKey(key))
13860
14152
  return false;
13861
14153
  }
@@ -14065,8 +14357,11 @@ export class Daemon extends EventEmitter {
14065
14357
  // Idle observations happen after turns. Avoid needless writes (and mtime
14066
14358
  // churn) while still updating the marker when /new changes the session.
14067
14359
  try {
14068
- if (readFileSync(path, "utf-8").trim() === sid)
14360
+ const previous = readFileSync(path, "utf-8").trim();
14361
+ if (previous === sid)
14069
14362
  return;
14363
+ if (previous)
14364
+ this.resetInboundPresentation();
14070
14365
  }
14071
14366
  catch { /* first checkpoint */ }
14072
14367
  writeFileSync(path, sid);