@integrity-labs/agt-cli 0.28.1262 → 0.28.1263

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.
@@ -18867,7 +18867,7 @@ var require_filters = __commonJS({
18867
18867
  return r.copySafeness(str2, res);
18868
18868
  }
18869
18869
  _exports.indent = indent;
18870
- function join18(arr, del, attr) {
18870
+ function join19(arr, del, attr) {
18871
18871
  del = del || "";
18872
18872
  if (attr) {
18873
18873
  arr = lib.map(arr, function(v) {
@@ -18876,7 +18876,7 @@ var require_filters = __commonJS({
18876
18876
  }
18877
18877
  return arr.join(del);
18878
18878
  }
18879
- _exports.join = join18;
18879
+ _exports.join = join19;
18880
18880
  function last(arr) {
18881
18881
  return arr[arr.length - 1];
18882
18882
  }
@@ -36352,6 +36352,15 @@ function emitTransientApiErrorTelemetry(channel, match, original) {
36352
36352
  // src/direct-chat-claim-tracker.ts
36353
36353
  var DirectChatClaimTracker = class {
36354
36354
  bySession = /* @__PURE__ */ new Map();
36355
+ /**
36356
+ * ENG-12060 (CodeRabbit on #7625): restored claims whose message never
36357
+ * reached the session, waiting for their re-hand push. Tracked (and
36358
+ * persisted) so a later restart still recovers them, but kept out of
36359
+ * `peek`: a reply or consume in the same session would otherwise send their
36360
+ * ids, the API would flip them to delivered, and the re-hand (which skips
36361
+ * delivered rows) would never push them, silently.
36362
+ */
36363
+ unpushed = /* @__PURE__ */ new Set();
36355
36364
  onChange;
36356
36365
  now;
36357
36366
  constructor(opts = {}) {
@@ -36369,13 +36378,35 @@ var DirectChatClaimTracker = class {
36369
36378
  ids.set(messageId, this.now());
36370
36379
  this.onChange?.(this);
36371
36380
  }
36381
+ /**
36382
+ * ENG-12060 (Obi Wan 85f96c6e8620): record a RE-HANDED claim at the time of
36383
+ * the re-hand. Unlike `track`, it replaces an existing claim time and always
36384
+ * fires `onChange`, so the persisted claim says the message was pushed to the
36385
+ * session now running. Without it, a further MCP reload inside that session
36386
+ * would see the pre-restart time, treat the claim as stranded and re-hand it
36387
+ * a second time.
36388
+ */
36389
+ retrack(sessionId, messageId) {
36390
+ let ids = this.bySession.get(sessionId);
36391
+ if (!ids) {
36392
+ ids = /* @__PURE__ */ new Map();
36393
+ this.bySession.set(sessionId, ids);
36394
+ }
36395
+ ids.set(messageId, this.now());
36396
+ this.unpushed.delete(messageId);
36397
+ this.onChange?.(this);
36398
+ }
36372
36399
  /**
36373
36400
  * The claimed-but-unconsumed message ids for a session, WITHOUT clearing them.
36374
36401
  * Peek-then-clear-on-success (rather than drain-up-front) so a failed
36375
36402
  * reply/consume POST doesn't lose the ids — they stay tracked for the retry.
36376
36403
  */
36377
36404
  peek(sessionId) {
36378
- return [...this.bySession.get(sessionId)?.keys() ?? []];
36405
+ return [...this.bySession.get(sessionId)?.keys() ?? []].filter((id) => !this.unpushed.has(id));
36406
+ }
36407
+ /** Restored claims still waiting for their re-hand push (never acknowledged meanwhile). */
36408
+ awaitingPush(sessionId) {
36409
+ return [...this.bySession.get(sessionId)?.keys() ?? []].filter((id) => this.unpushed.has(id));
36379
36410
  }
36380
36411
  /**
36381
36412
  * Clear exactly the given ids for a session (call after a successful
@@ -36386,7 +36417,10 @@ var DirectChatClaimTracker = class {
36386
36417
  const tracked = this.bySession.get(sessionId);
36387
36418
  if (!tracked) return;
36388
36419
  let changed = false;
36389
- for (const id of ids) changed = tracked.delete(id) || changed;
36420
+ for (const id of ids) {
36421
+ changed = tracked.delete(id) || changed;
36422
+ this.unpushed.delete(id);
36423
+ }
36390
36424
  if (tracked.size === 0) this.bySession.delete(sessionId);
36391
36425
  if (changed) this.onChange?.(this);
36392
36426
  }
@@ -36409,8 +36443,10 @@ var DirectChatClaimTracker = class {
36409
36443
  * claim already tracked in this process) and does NOT fire `onChange` — the
36410
36444
  * entries came from the store, so writing them straight back is pointless.
36411
36445
  */
36412
- restore(entries) {
36446
+ restore(entries, opts = {}) {
36447
+ const awaiting = new Set(opts.unpushed ?? []);
36413
36448
  for (const e of entries) {
36449
+ if (awaiting.has(e.message_id)) this.unpushed.add(e.message_id);
36414
36450
  let ids = this.bySession.get(e.session_id);
36415
36451
  if (!ids) {
36416
36452
  ids = /* @__PURE__ */ new Map();
@@ -36421,86 +36457,99 @@ var DirectChatClaimTracker = class {
36421
36457
  }
36422
36458
  };
36423
36459
 
36424
- // src/direct-chat-claim-store.ts
36425
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
36426
- import { dirname, join } from "path";
36427
- var DIRECT_CHAT_CLAIMS_FILE = "direct-chat-claims.json";
36428
- var DEFAULT_CLAIM_MAX_AGE_MS = 6 * 60 * 60 * 1e3;
36429
- var DEFAULT_CLAIM_MAX_ENTRIES = 1e3;
36430
- var realFs = {
36431
- readFile: (p2) => readFileSync(p2, "utf8"),
36432
- writeFile: (p2, d) => writeFileSync(p2, d, "utf8"),
36433
- rename: (a, b) => renameSync(a, b),
36434
- mkdir: (d) => {
36435
- mkdirSync(d, { recursive: true });
36460
+ // src/direct-chat-rehand.ts
36461
+ import { readFileSync } from "fs";
36462
+ import { join } from "path";
36463
+ var MARKER = /message_id="([^"]+)"/g;
36464
+ function collectStrings(v, out) {
36465
+ if (typeof v === "string") out.push(v);
36466
+ else if (Array.isArray(v)) for (const x of v) collectStrings(x, out);
36467
+ else if (v && typeof v === "object") for (const x of Object.values(v)) collectStrings(x, out);
36468
+ }
36469
+ function deliveredMessageIds(transcriptText) {
36470
+ const ids = /* @__PURE__ */ new Set();
36471
+ for (const line of transcriptText.split("\n")) {
36472
+ if (!line.includes("message_id")) continue;
36473
+ let entry;
36474
+ try {
36475
+ entry = JSON.parse(line);
36476
+ } catch {
36477
+ continue;
36478
+ }
36479
+ const strings = [];
36480
+ collectStrings(entry, strings);
36481
+ for (const s of strings) {
36482
+ if (!s.includes("message_id=")) continue;
36483
+ for (const m of s.matchAll(MARKER)) ids.add(m[1]);
36484
+ }
36436
36485
  }
36437
- };
36438
- function directChatClaimsPath(dir) {
36439
- return dir ? join(dir, DIRECT_CHAT_CLAIMS_FILE) : null;
36440
- }
36441
- function isEntry(v) {
36442
- if (!v || typeof v !== "object") return false;
36443
- const o = v;
36444
- return typeof o.session_id === "string" && o.session_id.length > 0 && typeof o.message_id === "string" && o.message_id.length > 0 && typeof o.claimed_at_ms === "number" && Number.isFinite(o.claimed_at_ms);
36486
+ return ids;
36445
36487
  }
36446
- function boundClaims(entries, nowMs, bounds = {}) {
36447
- const maxAgeMs = bounds.maxAgeMs ?? DEFAULT_CLAIM_MAX_AGE_MS;
36448
- const maxEntries = bounds.maxEntries ?? DEFAULT_CLAIM_MAX_ENTRIES;
36449
- const seen = /* @__PURE__ */ new Set();
36450
- const kept = [];
36451
- for (const e of entries) {
36452
- if (!isEntry(e)) continue;
36453
- if (nowMs - e.claimed_at_ms > maxAgeMs) continue;
36454
- const key = `${e.session_id.length}|${e.session_id}|${e.message_id}`;
36455
- if (seen.has(key)) continue;
36456
- seen.add(key);
36457
- kept.push({ session_id: e.session_id, message_id: e.message_id, claimed_at_ms: e.claimed_at_ms });
36488
+ function planRehand(claims, transcriptText, sessionStartedAtMs) {
36489
+ const live = /* @__PURE__ */ new Set();
36490
+ const before = /* @__PURE__ */ new Set();
36491
+ for (const c of claims) {
36492
+ if (Number.isFinite(c.claimed_at_ms) && c.claimed_at_ms >= sessionStartedAtMs) live.add(c.message_id);
36493
+ else before.add(c.message_id);
36458
36494
  }
36459
- kept.sort((a, b) => b.claimed_at_ms - a.claimed_at_ms);
36460
- return kept.slice(0, Math.max(0, maxEntries));
36495
+ for (const id of live) before.delete(id);
36496
+ const candidates = [...before];
36497
+ if (transcriptText === null) return { present: [], live: [...live], rehand: candidates, unreadable: true };
36498
+ const delivered = deliveredMessageIds(transcriptText);
36499
+ return {
36500
+ present: candidates.filter((id) => delivered.has(id)),
36501
+ live: [...live],
36502
+ rehand: candidates.filter((id) => !delivered.has(id)),
36503
+ unreadable: false
36504
+ };
36461
36505
  }
36462
- function planClaimRecovery(state) {
36463
- if (!state.markerRead || !state.sessionId) return { restore: false, bindTo: null };
36464
- return { restore: true, bindTo: state.sessionId };
36506
+ function transcriptPathFor(transcriptDir, transcriptId) {
36507
+ return join(transcriptDir, `${transcriptId}.jsonl`);
36465
36508
  }
36466
- function loadDirectChatClaims(path, transcriptId, nowMs, bounds = {}, fs = realFs) {
36467
- if (!path || !transcriptId) return [];
36509
+ function readTranscriptText(path, read = (p2) => readFileSync(p2, "utf8")) {
36468
36510
  try {
36469
- const parsed = JSON.parse(fs.readFile(path));
36470
- if (!parsed || typeof parsed !== "object") return [];
36471
- const o = parsed;
36472
- if (o.transcript_session_id !== transcriptId) return [];
36473
- const claims = o.claims;
36474
- if (!Array.isArray(claims)) return [];
36475
- return boundClaims(claims, nowMs, bounds);
36511
+ return read(path);
36476
36512
  } catch {
36477
- return [];
36513
+ return null;
36478
36514
  }
36479
36515
  }
36480
- function writeAtomic(path, body, fs) {
36481
- try {
36482
- fs.mkdir(dirname(path));
36483
- const tmp = `${path}.tmp`;
36484
- fs.writeFile(tmp, JSON.stringify(body));
36485
- fs.rename(tmp, path);
36486
- return true;
36487
- } catch {
36488
- return false;
36516
+ var REHAND_MAX_IDS_PER_REQUEST = 100;
36517
+ function chunkIds(ids, size = REHAND_MAX_IDS_PER_REQUEST) {
36518
+ const out = [];
36519
+ for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
36520
+ return out;
36521
+ }
36522
+ var REHAND_MAX_ATTEMPTS = 20;
36523
+ var REHAND_MAX_DELAY_MS = 3e4;
36524
+ var REHAND_GUARD_WAIT_MS = 25 * 6e4;
36525
+ async function retryRehand(attempt, deps) {
36526
+ const max = deps.maxAttempts ?? REHAND_MAX_ATTEMPTS;
36527
+ const now = deps.now ?? Date.now;
36528
+ const giveUpAt = now() + (deps.guardWaitMs ?? REHAND_GUARD_WAIT_MS);
36529
+ let failures = 0;
36530
+ let tries = 0;
36531
+ for (; ; ) {
36532
+ tries += 1;
36533
+ const r = await attempt();
36534
+ if (r.ran && r.ok) return { ran: true, ok: true, attempts: tries };
36535
+ if (r.ran) failures += 1;
36536
+ if (failures >= max || now() >= giveUpAt) return { ran: r.ran, ok: false, attempts: tries };
36537
+ await deps.sleep(Math.min(1e3 * 2 ** (Math.min(tries, 16) - 1), REHAND_MAX_DELAY_MS));
36489
36538
  }
36490
36539
  }
36491
- function saveDirectChatClaims(path, transcriptId, entries, nowMs, bounds = {}, fs = realFs) {
36492
- if (!path || !transcriptId) return false;
36493
- return writeAtomic(
36494
- path,
36495
- { version: 2, transcript_session_id: transcriptId, claims: boundClaims(entries, nowMs, bounds) },
36496
- fs
36497
- );
36540
+ function rehandUnresolvedCount(returned, handled) {
36541
+ return returned.filter((m) => !handled.has(m.id)).length;
36498
36542
  }
36499
- function resetDirectChatClaims(path, fs = realFs) {
36500
- if (!path) return false;
36501
- return writeAtomic(path, { version: 2, transcript_session_id: null, claims: [] }, fs);
36543
+ function rehandSummaryLine(restored, plan, returned) {
36544
+ return `direct-chat-channel: rehand restored=${restored} present=${plan.present.length} live=${plan.live.length} absent=${plan.rehand.length}${plan.unreadable ? " (transcript unreadable)" : ""} rehand_returned=${returned === null ? "skipped" : returned}
36545
+ `;
36502
36546
  }
36503
36547
 
36548
+ // src/rate-limit-watch.ts
36549
+ import { closeSync, fstatSync, openSync, readSync, readdirSync, statSync } from "fs";
36550
+ import { homedir } from "os";
36551
+ import { join as join2 } from "path";
36552
+
36504
36553
  // ../core/dist/types/agent.js
36505
36554
  var FRAMEWORK_MODEL_SLOTS = {
36506
36555
  "claude-code": ["primary", "small_fast", "advisor"],
@@ -47598,6 +47647,216 @@ var HOST_KEY_ROTATION_GRACE_MAX_MS = 60 * 6e4;
47598
47647
  var TEAM_SLUG_MAX_ATTEMPTS = 20;
47599
47648
  var SUFFIX_RESERVE = `-${TEAM_SLUG_MAX_ATTEMPTS}`.length;
47600
47649
 
47650
+ // src/rate-limit-watch.ts
47651
+ var DEFAULT_WATCH_MS = 5e3;
47652
+ var DEFAULT_POLL_MS = 400;
47653
+ var INITIAL_TAIL_BYTES = 256 * 1024;
47654
+ var TAIL_WIDEN_FACTOR = 8;
47655
+ var TAIL_SKEW_TOLERANCE_MS = 5 * 6e4;
47656
+ function readClassifiableTail(path, sinceMs, opts) {
47657
+ let want = Math.max(1, opts?.initialBytes ?? INITIAL_TAIL_BYTES);
47658
+ for (; ; ) {
47659
+ const slice = readTailSlice(path, want);
47660
+ if (slice === null) return "";
47661
+ if (slice.fromStart) return slice.text;
47662
+ const oldest = oldestTimestampMs(slice.text);
47663
+ if (oldest !== null && oldest < sinceMs - TAIL_SKEW_TOLERANCE_MS) return slice.text;
47664
+ want *= TAIL_WIDEN_FACTOR;
47665
+ }
47666
+ }
47667
+ function readTailSlice(path, bytes) {
47668
+ let fd;
47669
+ try {
47670
+ fd = openSync(path, "r");
47671
+ } catch {
47672
+ return null;
47673
+ }
47674
+ try {
47675
+ const size = fstatSync(fd).size;
47676
+ const start = size > bytes ? size - bytes : 0;
47677
+ const len = size - start;
47678
+ if (len <= 0) return { text: "", fromStart: true };
47679
+ const buf = Buffer.allocUnsafe(len);
47680
+ let read = 0;
47681
+ while (read < len) {
47682
+ const n = readSync(fd, buf, read, len - read, start + read);
47683
+ if (n <= 0) break;
47684
+ read += n;
47685
+ }
47686
+ if (read < len) return null;
47687
+ let text = buf.subarray(0, read).toString("utf-8");
47688
+ if (start > 0) {
47689
+ const nl = text.indexOf("\n");
47690
+ text = nl === -1 ? "" : text.slice(nl + 1);
47691
+ }
47692
+ return { text, fromStart: start === 0 };
47693
+ } catch {
47694
+ return null;
47695
+ } finally {
47696
+ closeSync(fd);
47697
+ }
47698
+ }
47699
+ function oldestTimestampMs(text) {
47700
+ let idx = 0;
47701
+ while (idx < text.length) {
47702
+ const nl = text.indexOf("\n", idx);
47703
+ const line = (nl === -1 ? text.slice(idx) : text.slice(idx, nl)).trim();
47704
+ if (line) {
47705
+ try {
47706
+ const ts = JSON.parse(line).timestamp;
47707
+ if (typeof ts === "string") {
47708
+ const ms = new Date(ts).getTime();
47709
+ if (Number.isFinite(ms)) return ms;
47710
+ }
47711
+ } catch {
47712
+ }
47713
+ }
47714
+ if (nl === -1) break;
47715
+ idx = nl + 1;
47716
+ }
47717
+ return null;
47718
+ }
47719
+ function agentTranscriptDir(opts) {
47720
+ const cwd = opts?.cwd ?? process.cwd();
47721
+ const home = opts?.home ?? homedir();
47722
+ return join2(home, ".claude", "projects", encodeClaudeProjectPath(cwd));
47723
+ }
47724
+ function classifyTranscriptSince(opts) {
47725
+ const dir = opts.transcriptDir ?? agentTranscriptDir({ cwd: opts.cwd, home: opts.home });
47726
+ let entries;
47727
+ try {
47728
+ entries = readdirSync(dir);
47729
+ } catch {
47730
+ return UNKNOWN_RATE_LIMIT;
47731
+ }
47732
+ let newest = UNKNOWN_RATE_LIMIT;
47733
+ for (const name of entries) {
47734
+ if (!name.endsWith(".jsonl")) continue;
47735
+ const path = join2(dir, name);
47736
+ try {
47737
+ const st = statSync(path);
47738
+ if (!st.isFile() || st.mtimeMs < opts.sinceMs) continue;
47739
+ } catch {
47740
+ continue;
47741
+ }
47742
+ const content = readClassifiableTail(path, opts.sinceMs, {
47743
+ ...opts.initialTailBytes != null ? { initialBytes: opts.initialTailBytes } : {}
47744
+ });
47745
+ if (!content) continue;
47746
+ newest = pickNewerClassification(
47747
+ newest,
47748
+ classifyTranscriptRateLimit(content, opts.sinceMs, opts.nowMs, new Date(opts.nowMs))
47749
+ );
47750
+ }
47751
+ return newest;
47752
+ }
47753
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
47754
+ async function watchForRateLimitRefusal(opts) {
47755
+ const now = opts.now ?? (() => Date.now());
47756
+ const wait = opts.wait ?? sleep;
47757
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_WATCH_MS;
47758
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
47759
+ const deadline = now() + timeoutMs;
47760
+ for (; ; ) {
47761
+ let result;
47762
+ try {
47763
+ result = classifyTranscriptSince({
47764
+ sinceMs: opts.sinceMs,
47765
+ nowMs: now(),
47766
+ transcriptDir: opts.transcriptDir,
47767
+ cwd: opts.cwd,
47768
+ home: opts.home
47769
+ });
47770
+ } catch {
47771
+ return null;
47772
+ }
47773
+ if (result.verdict === "capped") return result;
47774
+ if (result.verdict === "serving") return null;
47775
+ if (now() >= deadline) return null;
47776
+ await wait(pollMs);
47777
+ }
47778
+ }
47779
+
47780
+ // src/direct-chat-claim-store.ts
47781
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
47782
+ import { dirname, join as join3 } from "path";
47783
+ var DIRECT_CHAT_CLAIMS_FILE = "direct-chat-claims.json";
47784
+ var DEFAULT_CLAIM_MAX_AGE_MS = 6 * 60 * 60 * 1e3;
47785
+ var DEFAULT_CLAIM_MAX_ENTRIES = 1e3;
47786
+ var realFs = {
47787
+ readFile: (p2) => readFileSync2(p2, "utf8"),
47788
+ writeFile: (p2, d) => writeFileSync(p2, d, "utf8"),
47789
+ rename: (a, b) => renameSync(a, b),
47790
+ mkdir: (d) => {
47791
+ mkdirSync(d, { recursive: true });
47792
+ }
47793
+ };
47794
+ function directChatClaimsPath(dir) {
47795
+ return dir ? join3(dir, DIRECT_CHAT_CLAIMS_FILE) : null;
47796
+ }
47797
+ function isEntry(v) {
47798
+ if (!v || typeof v !== "object") return false;
47799
+ const o = v;
47800
+ return typeof o.session_id === "string" && o.session_id.length > 0 && typeof o.message_id === "string" && o.message_id.length > 0 && typeof o.claimed_at_ms === "number" && Number.isFinite(o.claimed_at_ms);
47801
+ }
47802
+ function boundClaims(entries, nowMs, bounds = {}) {
47803
+ const maxAgeMs = bounds.maxAgeMs ?? DEFAULT_CLAIM_MAX_AGE_MS;
47804
+ const maxEntries = bounds.maxEntries ?? DEFAULT_CLAIM_MAX_ENTRIES;
47805
+ const seen = /* @__PURE__ */ new Set();
47806
+ const kept = [];
47807
+ for (const e of entries) {
47808
+ if (!isEntry(e)) continue;
47809
+ if (nowMs - e.claimed_at_ms > maxAgeMs) continue;
47810
+ const key = `${e.session_id.length}|${e.session_id}|${e.message_id}`;
47811
+ if (seen.has(key)) continue;
47812
+ seen.add(key);
47813
+ kept.push({ session_id: e.session_id, message_id: e.message_id, claimed_at_ms: e.claimed_at_ms });
47814
+ }
47815
+ kept.sort((a, b) => b.claimed_at_ms - a.claimed_at_ms);
47816
+ return kept.slice(0, Math.max(0, maxEntries));
47817
+ }
47818
+ function planClaimRecovery(state) {
47819
+ if (!state.markerRead || !state.sessionId) return { restore: false, bindTo: null };
47820
+ return { restore: true, bindTo: state.sessionId };
47821
+ }
47822
+ function loadDirectChatClaims(path, transcriptId, nowMs, bounds = {}, fs = realFs) {
47823
+ if (!path || !transcriptId) return [];
47824
+ try {
47825
+ const parsed = JSON.parse(fs.readFile(path));
47826
+ if (!parsed || typeof parsed !== "object") return [];
47827
+ const o = parsed;
47828
+ if (o.transcript_session_id !== transcriptId) return [];
47829
+ const claims = o.claims;
47830
+ if (!Array.isArray(claims)) return [];
47831
+ return boundClaims(claims, nowMs, bounds);
47832
+ } catch {
47833
+ return [];
47834
+ }
47835
+ }
47836
+ function writeAtomic(path, body, fs) {
47837
+ try {
47838
+ fs.mkdir(dirname(path));
47839
+ const tmp = `${path}.tmp`;
47840
+ fs.writeFile(tmp, JSON.stringify(body));
47841
+ fs.rename(tmp, path);
47842
+ return true;
47843
+ } catch {
47844
+ return false;
47845
+ }
47846
+ }
47847
+ function saveDirectChatClaims(path, transcriptId, entries, nowMs, bounds = {}, fs = realFs) {
47848
+ if (!path || !transcriptId) return false;
47849
+ return writeAtomic(
47850
+ path,
47851
+ { version: 2, transcript_session_id: transcriptId, claims: boundClaims(entries, nowMs, bounds) },
47852
+ fs
47853
+ );
47854
+ }
47855
+ function resetDirectChatClaims(path, fs = realFs) {
47856
+ if (!path) return false;
47857
+ return writeAtomic(path, { version: 2, transcript_session_id: null, claims: [] }, fs);
47858
+ }
47859
+
47601
47860
  // src/untrusted-fence.ts
47602
47861
  function fenceFor(body) {
47603
47862
  let longest = 0;
@@ -47777,14 +48036,14 @@ function renderHistoryResult(result, requestedNotices) {
47777
48036
  }
47778
48037
 
47779
48038
  // src/direct-chat-session-state.ts
47780
- import { existsSync, readFileSync as readFileSync2 } from "fs";
47781
- import { join as join2 } from "path";
48039
+ import { existsSync, readFileSync as readFileSync3 } from "fs";
48040
+ import { join as join4 } from "path";
47782
48041
  function readDirectChatSessionState(agentDir, nowMs) {
47783
- const path = join2(agentDir, "direct-chat-session.json");
48042
+ const path = join4(agentDir, "direct-chat-session.json");
47784
48043
  const fallback = { fresh: false, startedAtMs: nowMs, markerRead: false, sessionId: null };
47785
48044
  try {
47786
48045
  if (!existsSync(path)) return fallback;
47787
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
48046
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
47788
48047
  if (!parsed || typeof parsed !== "object") return fallback;
47789
48048
  const o = parsed;
47790
48049
  const fresh = o.fresh === true;
@@ -47812,6 +48071,8 @@ function buildDirectChatChannelMeta(input) {
47812
48071
  if (input.pageGated != null) page.page_gated = input.pageGated ? "true" : "false";
47813
48072
  return {
47814
48073
  session_id: input.sessionId,
48074
+ // ENG-12060: omit-when-absent like the identity and page fields.
48075
+ ...input.messageId ? { message_id: input.messageId } : {},
47815
48076
  user: "webapp",
47816
48077
  source: "direct-chat",
47817
48078
  ...identity,
@@ -47829,12 +48090,12 @@ function buildDirectChatChannelMeta(input) {
47829
48090
  }
47830
48091
 
47831
48092
  // src/turn-context.ts
47832
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "fs";
47833
- import { homedir } from "os";
47834
- import { dirname as dirname3, join as join6 } from "path";
48093
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync6 } from "fs";
48094
+ import { homedir as homedir2 } from "os";
48095
+ import { dirname as dirname3, join as join8 } from "path";
47835
48096
 
47836
48097
  // ../core/dist/provisioning/frameworks/claudecode/agent-dir-alias.js
47837
- import { isAbsolute, join as join3, relative, sep } from "path";
48098
+ import { isAbsolute, join as join5, relative, sep } from "path";
47838
48099
  var VALID_CODE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
47839
48100
  var VALID_AGENT_ID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
47840
48101
  var INITIATOR_BASENAME = ".current-turn-initiator.json";
@@ -47842,7 +48103,7 @@ function isSafeAgentSegment(segment) {
47842
48103
  return VALID_CODE_NAME.test(segment) || VALID_AGENT_ID.test(segment);
47843
48104
  }
47844
48105
  function initiatorDirSegment(initiatorFile, homeDir) {
47845
- const rel = relative(join3(homeDir, ".augmented"), initiatorFile);
48106
+ const rel = relative(join5(homeDir, ".augmented"), initiatorFile);
47846
48107
  if (!rel || isAbsolute(rel))
47847
48108
  return null;
47848
48109
  const parts = rel.split(sep);
@@ -47857,29 +48118,29 @@ function resolveAgentDirAlias(input) {
47857
48118
  const { codeName, turnInitiatorFile, agentId, homeDir } = input;
47858
48119
  const codeNameTrimmed = typeof codeName === "string" ? codeName.trim() : "";
47859
48120
  if (codeNameTrimmed && VALID_CODE_NAME.test(codeNameTrimmed)) {
47860
- return join3(homeDir, ".augmented", codeNameTrimmed);
48121
+ return join5(homeDir, ".augmented", codeNameTrimmed);
47861
48122
  }
47862
48123
  const initiator = typeof turnInitiatorFile === "string" ? turnInitiatorFile.trim() : "";
47863
48124
  if (initiator) {
47864
48125
  const segment = initiatorDirSegment(initiator, homeDir);
47865
48126
  if (segment)
47866
- return join3(homeDir, ".augmented", segment);
48127
+ return join5(homeDir, ".augmented", segment);
47867
48128
  }
47868
48129
  const agentIdTrimmed = typeof agentId === "string" ? agentId.trim() : "";
47869
48130
  if (agentIdTrimmed && VALID_AGENT_ID.test(agentIdTrimmed)) {
47870
- return join3(homeDir, ".augmented", agentIdTrimmed);
48131
+ return join5(homeDir, ".augmented", agentIdTrimmed);
47871
48132
  }
47872
48133
  return null;
47873
48134
  }
47874
48135
 
47875
48136
  // src/turn-initiator-marker.ts
47876
- import { writeFileSync as writeFileSync2, readFileSync as readFileSync3, mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
47877
- import { dirname as dirname2, join as join4 } from "path";
48137
+ import { writeFileSync as writeFileSync2, readFileSync as readFileSync4, mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
48138
+ import { dirname as dirname2, join as join6 } from "path";
47878
48139
  var TURN_INITIATOR_MAX_AGE_MS = 5 * 60 * 1e3;
47879
48140
  var TURN_INITIATOR_LEDGER_MAX_ENTRIES = 20;
47880
48141
  var TURN_INITIATOR_LEDGER_FILENAME = ".turn-initiator-ledger.json";
47881
48142
  function turnInitiatorLedgerPath(singleSlotFile) {
47882
- return join4(dirname2(singleSlotFile), TURN_INITIATOR_LEDGER_FILENAME);
48143
+ return join6(dirname2(singleSlotFile), TURN_INITIATOR_LEDGER_FILENAME);
47883
48144
  }
47884
48145
  function foldTurnInitiatorLedger(existing, marker, maxAgeMs = TURN_INITIATOR_MAX_AGE_MS, maxEntries = TURN_INITIATOR_LEDGER_MAX_ENTRIES) {
47885
48146
  const now = marker.ts;
@@ -47909,7 +48170,7 @@ function updateTurnInitiatorLedger(singleSlotFile, marker) {
47909
48170
  const ledgerFile = turnInitiatorLedgerPath(singleSlotFile);
47910
48171
  let existing = null;
47911
48172
  try {
47912
- const parsed = JSON.parse(readFileSync3(ledgerFile, "utf8"));
48173
+ const parsed = JSON.parse(readFileSync4(ledgerFile, "utf8"));
47913
48174
  if (parsed && parsed.v === 1 && Array.isArray(parsed.entries)) existing = parsed;
47914
48175
  } catch {
47915
48176
  }
@@ -47936,14 +48197,14 @@ function writeTurnInitiatorMarker(input) {
47936
48197
  }
47937
48198
 
47938
48199
  // src/scheduled-turn-marker.ts
47939
- import { readFileSync as readFileSync4, unlinkSync } from "fs";
47940
- import { join as join5 } from "path";
48200
+ import { readFileSync as readFileSync5, unlinkSync } from "fs";
48201
+ import { join as join7 } from "path";
47941
48202
  var SCHEDULED_TURN_MARKER_FILENAME2 = ".current-scheduled-turn.json";
47942
48203
  var SCHEDULED_TURN_MAX_AGE_MS = 15 * 60 * 1e3;
47943
48204
  function clearScheduledTurnMarker(agentDir) {
47944
48205
  if (!agentDir) return;
47945
48206
  try {
47946
- unlinkSync(join5(agentDir, SCHEDULED_TURN_MARKER_FILENAME2));
48207
+ unlinkSync(join7(agentDir, SCHEDULED_TURN_MARKER_FILENAME2));
47947
48208
  } catch {
47948
48209
  }
47949
48210
  }
@@ -47952,7 +48213,7 @@ function clearScheduledTurnMarker(agentDir) {
47952
48213
  var TURN_INITIATOR_MARKER_FILENAME = ".current-turn-initiator.json";
47953
48214
  function writeUnattributedTurnMarker(channel, opts = {}) {
47954
48215
  try {
47955
- const file = resolveTurnInitiatorFile(opts.env ?? process.env, opts.home ?? homedir());
48216
+ const file = resolveTurnInitiatorFile(opts.env ?? process.env, opts.home ?? homedir2());
47956
48217
  if (!file) return;
47957
48218
  mkdirSync3(dirname3(file), { recursive: true });
47958
48219
  updateTurnInitiatorLedger(file, {
@@ -47970,7 +48231,7 @@ function writeUnattributedTurnMarker(channel, opts = {}) {
47970
48231
  } catch {
47971
48232
  }
47972
48233
  }
47973
- function resolveTurnInitiatorFile(env2 = process.env, home = homedir()) {
48234
+ function resolveTurnInitiatorFile(env2 = process.env, home = homedir2()) {
47974
48235
  const injected = env2["AGT_TURN_INITIATOR_FILE"]?.trim();
47975
48236
  if (injected) return injected;
47976
48237
  const dir = resolveAgentDirAlias({
@@ -47979,7 +48240,7 @@ function resolveTurnInitiatorFile(env2 = process.env, home = homedir()) {
47979
48240
  turnInitiatorFile: null,
47980
48241
  homeDir: home
47981
48242
  });
47982
- return dir ? join6(dir, TURN_INITIATOR_MARKER_FILENAME) : null;
48243
+ return dir ? join8(dir, TURN_INITIATOR_MARKER_FILENAME) : null;
47983
48244
  }
47984
48245
 
47985
48246
  // src/direct-chat-turn-marker.ts
@@ -48014,13 +48275,13 @@ function writeDirectChatTurnMarker(msg) {
48014
48275
  import {
48015
48276
  existsSync as existsSync2,
48016
48277
  mkdirSync as mkdirSync4,
48017
- readdirSync,
48018
- readFileSync as readFileSync6,
48278
+ readdirSync as readdirSync2,
48279
+ readFileSync as readFileSync7,
48019
48280
  renameSync as renameSync3,
48020
48281
  unlinkSync as unlinkSync2,
48021
48282
  writeFileSync as writeFileSync3
48022
48283
  } from "fs";
48023
- import { join as join7 } from "path";
48284
+ import { join as join9 } from "path";
48024
48285
  function hexEncodeSegment(value) {
48025
48286
  return Buffer.from(value, "utf8").toString("hex");
48026
48287
  }
@@ -48047,7 +48308,7 @@ function writeDirectChatPendingInboundMarker(dir, sessionId, messageId) {
48047
48308
  received_at: (/* @__PURE__ */ new Date()).toISOString(),
48048
48309
  inbound_id: directChatInboundId(sessionId, messageId)
48049
48310
  };
48050
- const final = join7(dir, directChatMarkerName(sessionId, messageId));
48311
+ const final = join9(dir, directChatMarkerName(sessionId, messageId));
48051
48312
  const tmp = `${final}.tmp`;
48052
48313
  writeFileSync3(tmp, JSON.stringify(marker), "utf8");
48053
48314
  renameSync3(tmp, final);
@@ -48060,21 +48321,21 @@ function clearDirectChatPendingMarkersForSession(dir, sessionId, op = defaultCle
48060
48321
  let cleared = 0;
48061
48322
  let names;
48062
48323
  try {
48063
- names = readdirSync(dir);
48324
+ names = readdirSync2(dir);
48064
48325
  } catch {
48065
48326
  return 0;
48066
48327
  }
48067
48328
  for (const name of names) {
48068
48329
  if (!name.startsWith(prefix) || !name.endsWith(".json")) continue;
48069
- op(join7(dir, name));
48330
+ op(join9(dir, name));
48070
48331
  cleared += 1;
48071
48332
  }
48072
48333
  return cleared;
48073
48334
  }
48074
- function readDirectChatPendingInboundMarker(dir, sessionId, messageId, readFileImpl = (path) => readFileSync6(path, "utf8")) {
48335
+ function readDirectChatPendingInboundMarker(dir, sessionId, messageId, readFileImpl = (path) => readFileSync7(path, "utf8")) {
48075
48336
  if (!dir || !sessionId || !messageId) return null;
48076
48337
  try {
48077
- const raw = readFileImpl(join7(dir, directChatMarkerName(sessionId, messageId)));
48338
+ const raw = readFileImpl(join9(dir, directChatMarkerName(sessionId, messageId)));
48078
48339
  return JSON.parse(raw);
48079
48340
  } catch {
48080
48341
  return null;
@@ -48097,7 +48358,7 @@ function sweepAgedDirectChatMarkers(dir, deps) {
48097
48358
  }
48098
48359
  for (const name of names) {
48099
48360
  if (!name.endsWith(".json") || name.startsWith(".")) continue;
48100
- const full = join7(dir, name);
48361
+ const full = join9(dir, name);
48101
48362
  let marker;
48102
48363
  try {
48103
48364
  marker = JSON.parse(deps.readFile(full));
@@ -48196,8 +48457,8 @@ async function consumeDirectChatRecoveryFile(fullPath, filename, deps) {
48196
48457
  }
48197
48458
 
48198
48459
  // src/inbound-delivery-ledger.ts
48199
- import { existsSync as existsSync3, mkdirSync as mkdirSync5, readdirSync as readdirSync2, readFileSync as readFileSync7, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "fs";
48200
- import { join as join8 } from "path";
48460
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync8, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "fs";
48461
+ import { join as join10 } from "path";
48201
48462
  function safeInboundId(inboundId) {
48202
48463
  return inboundId.replace(/[^A-Za-z0-9_-]/g, "_");
48203
48464
  }
@@ -48205,8 +48466,8 @@ var defaultDeps = {
48205
48466
  mkdir: (dir) => mkdirSync5(dir, { recursive: true }),
48206
48467
  writeFile: (path, data) => writeFileSync4(path, data, "utf8"),
48207
48468
  rename: (from, to) => renameSync4(from, to),
48208
- readdir: (dir) => readdirSync2(dir),
48209
- readFile: (path) => readFileSync7(path, "utf8"),
48469
+ readdir: (dir) => readdirSync3(dir),
48470
+ readFile: (path) => readFileSync8(path, "utf8"),
48210
48471
  exists: (path) => existsSync3(path)
48211
48472
  };
48212
48473
  function writeInboundDeliveryLedgerEntry(dir, record2, deps = defaultDeps) {
@@ -48215,7 +48476,7 @@ function writeInboundDeliveryLedgerEntry(dir, record2, deps = defaultDeps) {
48215
48476
  if (!safe || safe.includes("/") || safe.includes("\\") || safe.includes("..")) return;
48216
48477
  try {
48217
48478
  deps.mkdir(dir);
48218
- const final = join8(dir, `${safe}.json`);
48479
+ const final = join10(dir, `${safe}.json`);
48219
48480
  const tmp = `${final}.tmp`;
48220
48481
  deps.writeFile(tmp, JSON.stringify(record2));
48221
48482
  deps.rename(tmp, final);
@@ -48227,24 +48488,24 @@ function inboundDeliveryLedgerHas(dir, inboundId, deps = defaultDeps) {
48227
48488
  const safe = safeInboundId(inboundId);
48228
48489
  if (!safe || safe.includes("/") || safe.includes("\\") || safe.includes("..")) return false;
48229
48490
  try {
48230
- return deps.exists(join8(dir, `${safe}.json`));
48491
+ return deps.exists(join10(dir, `${safe}.json`));
48231
48492
  } catch {
48232
48493
  return false;
48233
48494
  }
48234
48495
  }
48235
48496
 
48236
48497
  // src/ack-reaction.ts
48237
- import { readdirSync as readdirSync3, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
48238
- import { join as join10 } from "path";
48498
+ import { readdirSync as readdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
48499
+ import { join as join12 } from "path";
48239
48500
 
48240
48501
  // src/flags-cache-read.ts
48241
- import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
48242
- import { homedir as homedir2 } from "os";
48243
- import { join as join9 } from "path";
48502
+ import { existsSync as existsSync4, readFileSync as readFileSync9 } from "fs";
48503
+ import { homedir as homedir3 } from "os";
48504
+ import { join as join11 } from "path";
48244
48505
  function hasUsableFlags(path) {
48245
48506
  try {
48246
48507
  if (!existsSync4(path)) return false;
48247
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
48508
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
48248
48509
  if (!parsed || typeof parsed !== "object") return false;
48249
48510
  const flags = parsed.flags;
48250
48511
  return !!flags && typeof flags === "object" && !Array.isArray(flags);
@@ -48255,7 +48516,7 @@ function hasUsableFlags(path) {
48255
48516
  function cacheUpdatedAt(path) {
48256
48517
  try {
48257
48518
  if (!existsSync4(path)) return void 0;
48258
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
48519
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
48259
48520
  if (!parsed || typeof parsed !== "object") return void 0;
48260
48521
  const u = parsed.updated_at;
48261
48522
  return typeof u === "string" && u.length > 0 ? u : void 0;
@@ -48264,10 +48525,10 @@ function cacheUpdatedAt(path) {
48264
48525
  }
48265
48526
  }
48266
48527
  function defaultFlagsCachePath(env2 = process.env) {
48267
- const hostWide = join9(homedir2(), ".augmented", "flags-cache.json");
48528
+ const hostWide = join11(homedir3(), ".augmented", "flags-cache.json");
48268
48529
  const agentId = env2["AGT_AGENT_ID"]?.trim();
48269
48530
  if (!agentId) return hostWide;
48270
- const perAgent = join9(homedir2(), ".augmented", agentId, "flags-cache.json");
48531
+ const perAgent = join11(homedir3(), ".augmented", agentId, "flags-cache.json");
48271
48532
  if (!hasUsableFlags(perAgent)) return hostWide;
48272
48533
  const hostWideAt = cacheUpdatedAt(hostWide);
48273
48534
  const perAgentAt = cacheUpdatedAt(perAgent);
@@ -48285,7 +48546,7 @@ function envBoolean(raw) {
48285
48546
  function cachedBoolean(key, path) {
48286
48547
  try {
48287
48548
  if (!existsSync4(path)) return void 0;
48288
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
48549
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
48289
48550
  if (!parsed || typeof parsed !== "object") return void 0;
48290
48551
  const flags = parsed.flags;
48291
48552
  if (!flags || typeof flags !== "object") return void 0;
@@ -48317,7 +48578,7 @@ function parseMaintenanceMode(raw) {
48317
48578
  function cachedMaintenanceMode(path) {
48318
48579
  try {
48319
48580
  if (!existsSync4(path)) return void 0;
48320
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
48581
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
48321
48582
  if (!parsed || typeof parsed !== "object") return void 0;
48322
48583
  const flags = parsed.flags;
48323
48584
  if (!flags || typeof flags !== "object") return void 0;
@@ -48400,7 +48661,7 @@ function undeliverableNoticeTextForRepeat(i) {
48400
48661
  }
48401
48662
  return null;
48402
48663
  }
48403
- function channelInboundGateOpen(readFile = (p2) => readFileSync9(p2, "utf-8")) {
48664
+ function channelInboundGateOpen(readFile = (p2) => readFileSync10(p2, "utf-8")) {
48404
48665
  const path = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : "/etc/claude-code/managed-settings.json";
48405
48666
  let raw;
48406
48667
  try {
@@ -48465,7 +48726,7 @@ var GIVE_UP_SIGNAL_MAX_AGE_MS = 30 * 60 * 1e3;
48465
48726
  function readGiveUpSignal(path, now = Date.now()) {
48466
48727
  if (!path) return null;
48467
48728
  try {
48468
- const raw = JSON.parse(readFileSync9(path, "utf8"));
48729
+ const raw = JSON.parse(readFileSync10(path, "utf8"));
48469
48730
  if (typeof raw.gave_up_at !== "string") return null;
48470
48731
  const t = Date.parse(raw.gave_up_at);
48471
48732
  if (!Number.isFinite(t) || t > now) return null;
@@ -48479,12 +48740,12 @@ function readGiveUpSignal(path, now = Date.now()) {
48479
48740
  var USAGE_LIMIT_LIVE_WINDOW_MS = 3 * 6e4;
48480
48741
  function readUsageLimitForBusyAck(agentDir, now = Date.now()) {
48481
48742
  if (!agentDir) return null;
48482
- const path = join10(agentDir, GIVE_UP_SIGNAL_FILENAME);
48743
+ const path = join12(agentDir, GIVE_UP_SIGNAL_FILENAME);
48483
48744
  const sig = readGiveUpSignal(path, now);
48484
48745
  if (sig?.reason !== "usage_limit") return null;
48485
48746
  let lastSeenMs = null;
48486
48747
  try {
48487
- const raw = JSON.parse(readFileSync9(path, "utf8"));
48748
+ const raw = JSON.parse(readFileSync10(path, "utf8"));
48488
48749
  if (typeof raw.usage_limit_last_seen_at === "string") {
48489
48750
  const t = Date.parse(raw.usage_limit_last_seen_at);
48490
48751
  if (Number.isFinite(t) && t <= now) lastSeenMs = t;
@@ -48503,7 +48764,7 @@ function readBlockedPromptForBusyAck(agentDir, now = Date.now()) {
48503
48764
  if (!agentDir) return null;
48504
48765
  let raw;
48505
48766
  try {
48506
- raw = JSON.parse(readFileSync9(join10(agentDir, BLOCKED_PROMPT_SIGNAL_FILENAME), "utf8"));
48767
+ raw = JSON.parse(readFileSync10(join12(agentDir, BLOCKED_PROMPT_SIGNAL_FILENAME), "utf8"));
48507
48768
  } catch {
48508
48769
  return null;
48509
48770
  }
@@ -48547,7 +48808,7 @@ function oldestPendingMarkerAgeMs(dir, now = Date.now(), opts) {
48547
48808
  if (!dir) return null;
48548
48809
  let names;
48549
48810
  try {
48550
- names = readdirSync3(dir);
48811
+ names = readdirSync4(dir);
48551
48812
  } catch {
48552
48813
  return null;
48553
48814
  }
@@ -48557,7 +48818,7 @@ function oldestPendingMarkerAgeMs(dir, now = Date.now(), opts) {
48557
48818
  if (opts?.exclude?.(name)) continue;
48558
48819
  let receivedAt;
48559
48820
  try {
48560
- const raw = JSON.parse(readFileSync9(join10(dir, name), "utf-8"));
48821
+ const raw = JSON.parse(readFileSync10(join12(dir, name), "utf-8"));
48561
48822
  if (markerOwesNoReply(raw)) continue;
48562
48823
  if (!opts?.includeSeen && typeof raw.seen_at === "string" && raw.seen_at) continue;
48563
48824
  receivedAt = raw.received_at;
@@ -48611,14 +48872,14 @@ function isMarkerGenuinelyAged(receivedAt, nowMs, thresholdMs) {
48611
48872
  }
48612
48873
  var DEFLECTION_COUNTER_SUFFIX = "-deflections.json";
48613
48874
  function deflectionCounterPath(agentDir, channel) {
48614
- return join10(agentDir, `${channel}${DEFLECTION_COUNTER_SUFFIX}`);
48875
+ return join12(agentDir, `${channel}${DEFLECTION_COUNTER_SUFFIX}`);
48615
48876
  }
48616
48877
  function recordChannelDeflection(agentDir, channel, cause) {
48617
48878
  if (!agentDir) return;
48618
48879
  const path = deflectionCounterPath(agentDir, channel);
48619
48880
  let counts = {};
48620
48881
  try {
48621
- const parsed = JSON.parse(readFileSync9(path, "utf-8"));
48882
+ const parsed = JSON.parse(readFileSync10(path, "utf-8"));
48622
48883
  if (parsed && typeof parsed === "object") counts = parsed;
48623
48884
  } catch {
48624
48885
  }
@@ -48631,142 +48892,7 @@ function recordChannelDeflection(agentDir, channel, cause) {
48631
48892
 
48632
48893
  // src/turn-failure-watch.ts
48633
48894
  import { readdirSync as readdirSync5, statSync as statSync2 } from "fs";
48634
- import { join as join12 } from "path";
48635
-
48636
- // src/rate-limit-watch.ts
48637
- import { closeSync, fstatSync, openSync, readSync, readdirSync as readdirSync4, statSync } from "fs";
48638
- import { homedir as homedir3 } from "os";
48639
- import { join as join11 } from "path";
48640
- var DEFAULT_WATCH_MS = 5e3;
48641
- var DEFAULT_POLL_MS = 400;
48642
- var INITIAL_TAIL_BYTES = 256 * 1024;
48643
- var TAIL_WIDEN_FACTOR = 8;
48644
- var TAIL_SKEW_TOLERANCE_MS = 5 * 6e4;
48645
- function readClassifiableTail(path, sinceMs, opts) {
48646
- let want = Math.max(1, opts?.initialBytes ?? INITIAL_TAIL_BYTES);
48647
- for (; ; ) {
48648
- const slice = readTailSlice(path, want);
48649
- if (slice === null) return "";
48650
- if (slice.fromStart) return slice.text;
48651
- const oldest = oldestTimestampMs(slice.text);
48652
- if (oldest !== null && oldest < sinceMs - TAIL_SKEW_TOLERANCE_MS) return slice.text;
48653
- want *= TAIL_WIDEN_FACTOR;
48654
- }
48655
- }
48656
- function readTailSlice(path, bytes) {
48657
- let fd;
48658
- try {
48659
- fd = openSync(path, "r");
48660
- } catch {
48661
- return null;
48662
- }
48663
- try {
48664
- const size = fstatSync(fd).size;
48665
- const start = size > bytes ? size - bytes : 0;
48666
- const len = size - start;
48667
- if (len <= 0) return { text: "", fromStart: true };
48668
- const buf = Buffer.allocUnsafe(len);
48669
- let read = 0;
48670
- while (read < len) {
48671
- const n = readSync(fd, buf, read, len - read, start + read);
48672
- if (n <= 0) break;
48673
- read += n;
48674
- }
48675
- if (read < len) return null;
48676
- let text = buf.subarray(0, read).toString("utf-8");
48677
- if (start > 0) {
48678
- const nl = text.indexOf("\n");
48679
- text = nl === -1 ? "" : text.slice(nl + 1);
48680
- }
48681
- return { text, fromStart: start === 0 };
48682
- } catch {
48683
- return null;
48684
- } finally {
48685
- closeSync(fd);
48686
- }
48687
- }
48688
- function oldestTimestampMs(text) {
48689
- let idx = 0;
48690
- while (idx < text.length) {
48691
- const nl = text.indexOf("\n", idx);
48692
- const line = (nl === -1 ? text.slice(idx) : text.slice(idx, nl)).trim();
48693
- if (line) {
48694
- try {
48695
- const ts = JSON.parse(line).timestamp;
48696
- if (typeof ts === "string") {
48697
- const ms = new Date(ts).getTime();
48698
- if (Number.isFinite(ms)) return ms;
48699
- }
48700
- } catch {
48701
- }
48702
- }
48703
- if (nl === -1) break;
48704
- idx = nl + 1;
48705
- }
48706
- return null;
48707
- }
48708
- function agentTranscriptDir(opts) {
48709
- const cwd = opts?.cwd ?? process.cwd();
48710
- const home = opts?.home ?? homedir3();
48711
- return join11(home, ".claude", "projects", encodeClaudeProjectPath(cwd));
48712
- }
48713
- function classifyTranscriptSince(opts) {
48714
- const dir = opts.transcriptDir ?? agentTranscriptDir({ cwd: opts.cwd, home: opts.home });
48715
- let entries;
48716
- try {
48717
- entries = readdirSync4(dir);
48718
- } catch {
48719
- return UNKNOWN_RATE_LIMIT;
48720
- }
48721
- let newest = UNKNOWN_RATE_LIMIT;
48722
- for (const name of entries) {
48723
- if (!name.endsWith(".jsonl")) continue;
48724
- const path = join11(dir, name);
48725
- try {
48726
- const st = statSync(path);
48727
- if (!st.isFile() || st.mtimeMs < opts.sinceMs) continue;
48728
- } catch {
48729
- continue;
48730
- }
48731
- const content = readClassifiableTail(path, opts.sinceMs, {
48732
- ...opts.initialTailBytes != null ? { initialBytes: opts.initialTailBytes } : {}
48733
- });
48734
- if (!content) continue;
48735
- newest = pickNewerClassification(
48736
- newest,
48737
- classifyTranscriptRateLimit(content, opts.sinceMs, opts.nowMs, new Date(opts.nowMs))
48738
- );
48739
- }
48740
- return newest;
48741
- }
48742
- var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
48743
- async function watchForRateLimitRefusal(opts) {
48744
- const now = opts.now ?? (() => Date.now());
48745
- const wait = opts.wait ?? sleep;
48746
- const timeoutMs = opts.timeoutMs ?? DEFAULT_WATCH_MS;
48747
- const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
48748
- const deadline = now() + timeoutMs;
48749
- for (; ; ) {
48750
- let result;
48751
- try {
48752
- result = classifyTranscriptSince({
48753
- sinceMs: opts.sinceMs,
48754
- nowMs: now(),
48755
- transcriptDir: opts.transcriptDir,
48756
- cwd: opts.cwd,
48757
- home: opts.home
48758
- });
48759
- } catch {
48760
- return null;
48761
- }
48762
- if (result.verdict === "capped") return result;
48763
- if (result.verdict === "serving") return null;
48764
- if (now() >= deadline) return null;
48765
- await wait(pollMs);
48766
- }
48767
- }
48768
-
48769
- // src/turn-failure-watch.ts
48895
+ import { join as join13 } from "path";
48770
48896
  function turnFailureNoticeEnabled(env2) {
48771
48897
  return resolveHostBooleanFlag({
48772
48898
  key: "wedge-transient-notice",
@@ -48796,7 +48922,7 @@ function classifyTurnFailureSince(opts) {
48796
48922
  const unrecognised = /* @__PURE__ */ new Set();
48797
48923
  for (const name of entries) {
48798
48924
  if (!name.endsWith(".jsonl")) continue;
48799
- const path = join12(dir, name);
48925
+ const path = join13(dir, name);
48800
48926
  let fingerprint;
48801
48927
  try {
48802
48928
  const st = statSync2(path);
@@ -49039,14 +49165,14 @@ var PollFollowUps = class {
49039
49165
  import {
49040
49166
  existsSync as existsSync5,
49041
49167
  mkdirSync as mkdirSync6,
49042
- readFileSync as readFileSync10,
49168
+ readFileSync as readFileSync11,
49043
49169
  renameSync as renameSync5,
49044
49170
  statSync as statSync3,
49045
49171
  unlinkSync as unlinkSync3,
49046
49172
  utimesSync,
49047
49173
  writeFileSync as writeFileSync6
49048
49174
  } from "fs";
49049
- import { join as join13 } from "path";
49175
+ import { join as join14 } from "path";
49050
49176
  var STALE_LOCK_MS = 9e4;
49051
49177
  var HEARTBEAT_INTERVAL_MS = 3e4;
49052
49178
  function defaultIsPidAlive(pid) {
@@ -49069,7 +49195,7 @@ function acquireMcpSpawnLock(args) {
49069
49195
  const nowMs = options.nowMs ?? (() => Date.now());
49070
49196
  const lockMtimeMs = options.lockMtimeMs ?? defaultLockMtimeMs;
49071
49197
  const staleMs = options.staleMs ?? STALE_LOCK_MS;
49072
- const path = join13(agentDir, basename3);
49198
+ const path = join14(agentDir, basename3);
49073
49199
  const existing = readLockHolder(path);
49074
49200
  if (existing) {
49075
49201
  if (existing.pid === selfPid) {
@@ -49136,7 +49262,7 @@ function defaultLockMtimeMs(path) {
49136
49262
  function readLockHolder(path) {
49137
49263
  if (!existsSync5(path)) return null;
49138
49264
  try {
49139
- const raw = readFileSync10(path, "utf8");
49265
+ const raw = readFileSync11(path, "utf8");
49140
49266
  const parsed = JSON.parse(raw);
49141
49267
  const pid = typeof parsed.pid === "number" ? parsed.pid : Number(parsed.pid);
49142
49268
  if (!Number.isFinite(pid) || pid <= 0) return null;
@@ -49149,13 +49275,13 @@ function readLockHolder(path) {
49149
49275
 
49150
49276
  // src/direct-chat-channel.ts
49151
49277
  import { homedir as homedir5 } from "os";
49152
- import { basename as basename2, join as join17 } from "path";
49278
+ import { basename as basename2, join as join18 } from "path";
49153
49279
  import { randomUUID } from "crypto";
49154
49280
  import {
49155
49281
  watch,
49156
49282
  mkdirSync as mkdirSync7,
49157
49283
  writeFileSync as writeFileSync8,
49158
- readFileSync as readFileSync13,
49284
+ readFileSync as readFileSync14,
49159
49285
  readdirSync as readdirSync6,
49160
49286
  existsSync as existsSync6,
49161
49287
  renameSync as renameSync6,
@@ -49166,7 +49292,7 @@ import {
49166
49292
  } from "fs";
49167
49293
 
49168
49294
  // src/direct-chat-inbound-attachments.ts
49169
- import { join as join14 } from "path";
49295
+ import { join as join15 } from "path";
49170
49296
 
49171
49297
  // ../../node_modules/.pnpm/postal-mime@4.0.5/node_modules/postal-mime/dist/esm/decode-strings.js
49172
49298
  var textEncoder2 = new TextEncoder();
@@ -54411,7 +54537,7 @@ var OVER_CAP_ERROR = `exceeds the ${formatUploadSize(MAX_INBOUND_ATTACHMENT_BYTE
54411
54537
  var INBOUND_ATTACHMENTS_SUBDIR = "direct-chat-inbound";
54412
54538
  function resolveInboundAttachmentsDir(input) {
54413
54539
  const alias = resolveAgentDirAlias(input);
54414
- return alias === null ? null : join14(alias, INBOUND_ATTACHMENTS_SUBDIR);
54540
+ return alias === null ? null : join15(alias, INBOUND_ATTACHMENTS_SUBDIR);
54415
54541
  }
54416
54542
  function isImageContentType(contentType) {
54417
54543
  return typeof contentType === "string" && contentType.toLowerCase().startsWith("image/");
@@ -55371,19 +55497,19 @@ function shouldSendToolsOfflineNotice(opts) {
55371
55497
  var TOOLS_OFFLINE_USER_NOTICE = "Heads up \u2014 Ninjafy is in a maintenance window right now, so I can't save anything: no tasks, canvases, notes or scheduled items. I can still talk things through, and you can ask me to set it up once maintenance is done.";
55372
55498
 
55373
55499
  // src/account-enforcement-notice.ts
55374
- import { readFileSync as readFileSync11 } from "fs";
55500
+ import { readFileSync as readFileSync12 } from "fs";
55375
55501
  import { homedir as homedir4 } from "os";
55376
- import { join as join15 } from "path";
55502
+ import { join as join16 } from "path";
55377
55503
  function accountEnforcementMarkerPath(codeName) {
55378
55504
  if (!codeName) return null;
55379
- return join15(homedir4(), ".augmented", codeName, ACCOUNT_ENFORCEMENT_MARKER_FILENAME);
55505
+ return join16(homedir4(), ".augmented", codeName, ACCOUNT_ENFORCEMENT_MARKER_FILENAME);
55380
55506
  }
55381
55507
  function readAccountEnforcementMarker(opts) {
55382
55508
  const path = opts.filePath ?? accountEnforcementMarkerPath(opts.codeName);
55383
55509
  if (!path) return null;
55384
55510
  let raw;
55385
55511
  try {
55386
- raw = readFileSync11(path, "utf-8");
55512
+ raw = readFileSync12(path, "utf-8");
55387
55513
  } catch {
55388
55514
  return null;
55389
55515
  }
@@ -55409,8 +55535,8 @@ function shouldSendAccountWarn(opts) {
55409
55535
  }
55410
55536
 
55411
55537
  // ../core/dist/direct-chat/cursor-advance-telemetry.js
55412
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync7 } from "fs";
55413
- import { join as join16 } from "path";
55538
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "fs";
55539
+ import { join as join17 } from "path";
55414
55540
  var CURSOR_SHORTFALL_COUNTER_SUFFIX = "-cursor-advance-classifications.json";
55415
55541
  function recordCursorAdvanceOutcome(agentDir, source, route, verdict) {
55416
55542
  if (!agentDir)
@@ -55418,10 +55544,10 @@ function recordCursorAdvanceOutcome(agentDir, source, route, verdict) {
55418
55544
  const key = cursorAdvanceCounterKey(route, verdict);
55419
55545
  if (key === null)
55420
55546
  return;
55421
- const path = join16(agentDir, `${source}${CURSOR_SHORTFALL_COUNTER_SUFFIX}`);
55547
+ const path = join17(agentDir, `${source}${CURSOR_SHORTFALL_COUNTER_SUFFIX}`);
55422
55548
  const counts = {};
55423
55549
  try {
55424
- const parsed = JSON.parse(readFileSync12(path, "utf-8"));
55550
+ const parsed = JSON.parse(readFileSync13(path, "utf-8"));
55425
55551
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
55426
55552
  for (const [k, v] of Object.entries(parsed)) {
55427
55553
  if (typeof v === "number" && Number.isInteger(v) && v >= 0)
@@ -55558,7 +55684,7 @@ var DIRECT_CHAT_ACCOUNT_WARN_COOLDOWN_MS = (() => {
55558
55684
  var AGT_HOST = process.env.AGT_HOST;
55559
55685
  var AGT_API_KEY = process.env.AGT_API_KEY;
55560
55686
  var AGT_AGENT_ID = process.env.AGT_AGENT_ID;
55561
- var DIRECT_CHAT_AGENT_DIR = AGT_AGENT_ID ? join17(homedir5(), ".augmented", AGT_AGENT_ID) : null;
55687
+ var DIRECT_CHAT_AGENT_DIR = AGT_AGENT_ID ? join18(homedir5(), ".augmented", AGT_AGENT_ID) : null;
55562
55688
  var INBOUND_ATTACHMENTS_DIR = resolveInboundAttachmentsDir({
55563
55689
  codeName: process.env.AGT_AGENT_CODE_NAME,
55564
55690
  turnInitiatorFile: process.env.AGT_TURN_INITIATOR_FILE,
@@ -55575,10 +55701,10 @@ var AGT_AGENT_CODE_NAME = process.env.AGT_AGENT_CODE_NAME;
55575
55701
  var directChatStderrLogStream = null;
55576
55702
  if (AGT_AGENT_CODE_NAME) {
55577
55703
  try {
55578
- const logDir = join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME);
55704
+ const logDir = join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME);
55579
55705
  mkdirSync7(logDir, { recursive: true });
55580
55706
  directChatStderrLogStream = createWriteStream(
55581
- join17(logDir, "direct-chat-channel-stderr.log"),
55707
+ join18(logDir, "direct-chat-channel-stderr.log"),
55582
55708
  { flags: "a", mode: 384 }
55583
55709
  );
55584
55710
  directChatStderrLogStream.on("error", () => {
@@ -55597,10 +55723,10 @@ if (AGT_AGENT_CODE_NAME) {
55597
55723
  } catch {
55598
55724
  }
55599
55725
  }
55600
- var PROGRESS_HEARTBEAT_PATH = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "channel-progress-heartbeat.json") : null;
55601
- var DIRECT_CHAT_PENDING_INBOUND_DIR = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "direct-chat-pending-inbound") : null;
55602
- var DIRECT_CHAT_DELIVERY_LEDGER_DIR = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, ".agt-inbound-delivery-ledger") : null;
55603
- var DIRECT_CHAT_CODE_NAME_AGENT_DIR = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME) : null;
55726
+ var PROGRESS_HEARTBEAT_PATH = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "channel-progress-heartbeat.json") : null;
55727
+ var DIRECT_CHAT_PENDING_INBOUND_DIR = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "direct-chat-pending-inbound") : null;
55728
+ var DIRECT_CHAT_DELIVERY_LEDGER_DIR = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, ".agt-inbound-delivery-ledger") : null;
55729
+ var DIRECT_CHAT_CODE_NAME_AGENT_DIR = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME) : null;
55604
55730
  var DIRECT_CHAT_STALE_MARKER_MS = 24 * 60 * 60 * 1e3;
55605
55731
  function judgeCursorAdvance(input, ctx) {
55606
55732
  const verdict = classifyCursorAdvance(input);
@@ -55620,8 +55746,8 @@ function recordDirectChatDelivery(sessionId, messageIds) {
55620
55746
  delivered_at: (/* @__PURE__ */ new Date()).toISOString()
55621
55747
  });
55622
55748
  }
55623
- var DIRECT_CHAT_RECOVERY_OUTBOX_DIR = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "direct-chat-recovery-outbox") : null;
55624
- var DIRECT_CHAT_RECOVERY_LEDGER_DIR = AGT_AGENT_CODE_NAME ? join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, ".agt-direct-chat-recovery-ledger") : null;
55749
+ var DIRECT_CHAT_RECOVERY_OUTBOX_DIR = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, "direct-chat-recovery-outbox") : null;
55750
+ var DIRECT_CHAT_RECOVERY_LEDGER_DIR = AGT_AGENT_CODE_NAME ? join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME, ".agt-direct-chat-recovery-ledger") : null;
55625
55751
  var progressReceivedAt = /* @__PURE__ */ new Map();
55626
55752
  var directChatProgressState = { tracked: null };
55627
55753
  var directChatProgressTickRunning = false;
@@ -55640,7 +55766,7 @@ var directChatKanbanCardClient = createKanbanCardActiveClient({
55640
55766
  function readProgressHeartbeat() {
55641
55767
  if (!PROGRESS_HEARTBEAT_PATH || !existsSync6(PROGRESS_HEARTBEAT_PATH)) return null;
55642
55768
  try {
55643
- return parseProgressHeartbeat(readFileSync13(PROGRESS_HEARTBEAT_PATH, "utf-8"));
55769
+ return parseProgressHeartbeat(readFileSync14(PROGRESS_HEARTBEAT_PATH, "utf-8"));
55644
55770
  } catch {
55645
55771
  return null;
55646
55772
  }
@@ -55649,7 +55775,7 @@ function seedProgressHeartbeat() {
55649
55775
  if (!PROGRESS_HEARTBEAT_PATH) return;
55650
55776
  const tmp = `${PROGRESS_HEARTBEAT_PATH}.${process.pid}.tmp`;
55651
55777
  try {
55652
- mkdirSync7(join17(homedir5(), ".augmented", AGT_AGENT_CODE_NAME), { recursive: true });
55778
+ mkdirSync7(join18(homedir5(), ".augmented", AGT_AGENT_CODE_NAME), { recursive: true });
55653
55779
  writeFileSync8(tmp, serializeProgressHeartbeat(SEED_PROGRESS_STEP, Date.now()), { mode: 384 });
55654
55780
  renameSync6(tmp, PROGRESS_HEARTBEAT_PATH);
55655
55781
  } catch {
@@ -55881,7 +56007,7 @@ var inboundAttachmentDeps = {
55881
56007
  ensureDir: (dir) => mkdirSync7(dir, { recursive: true }),
55882
56008
  removeDir: (dir) => rmSync(dir, { recursive: true, force: true }),
55883
56009
  writeFile: (path, bytes) => writeFileSync8(path, bytes, { mode: 384 }),
55884
- joinPath: (...parts) => join17(...parts),
56010
+ joinPath: (...parts) => join18(...parts),
55885
56011
  warn: (msg) => process.stderr.write(`${msg}
55886
56012
  `)
55887
56013
  };
@@ -56399,7 +56525,7 @@ function directChatSessionReplayFacts(sessionId) {
56399
56525
  sessionId,
56400
56526
  (fullPath) => {
56401
56527
  try {
56402
- const marker = JSON.parse(readFileSync13(fullPath, "utf-8"));
56528
+ const marker = JSON.parse(readFileSync14(fullPath, "utf-8"));
56403
56529
  found.push({ hasPayload: Boolean(marker.payload), discretionary: marker.discretionary });
56404
56530
  } catch {
56405
56531
  found.push({ hasPayload: false });
@@ -56458,7 +56584,7 @@ function scheduleDirectChatBusyAck(sessionId, messageId, arrivedWhileBusy) {
56458
56584
  let paneLogFreshAgeMs = null;
56459
56585
  if (DIRECT_CHAT_CODE_NAME_AGENT_DIR) {
56460
56586
  try {
56461
- const paneMtimeMs = statSync4(join17(DIRECT_CHAT_CODE_NAME_AGENT_DIR, "pane.log")).mtimeMs;
56587
+ const paneMtimeMs = statSync4(join18(DIRECT_CHAT_CODE_NAME_AGENT_DIR, "pane.log")).mtimeMs;
56462
56588
  paneLogFreshAgeMs = Math.max(0, Date.now() - paneMtimeMs);
56463
56589
  } catch {
56464
56590
  }
@@ -56621,10 +56747,11 @@ var pollFollowUps = new PollFollowUps(
56621
56747
  },
56622
56748
  (t) => clearTimeout(t)
56623
56749
  );
56624
- async function pollForMessages(sinceMs) {
56750
+ var lastRehandReturned = null;
56751
+ async function pollForMessages(sinceMs, rehandIds) {
56625
56752
  let pushPendingId = null;
56626
56753
  try {
56627
- const res = await apiPost("/host/direct-chat/poll", {
56754
+ const res = rehandIds && rehandIds.length > 0 ? await apiPost("/host/direct-chat/rehand", { agent_id: AGT_AGENT_ID, message_ids: rehandIds }) : await apiPost("/host/direct-chat/poll", {
56628
56755
  agent_id: AGT_AGENT_ID,
56629
56756
  ...typeof sinceMs === "number" ? { since_ms: sinceMs } : {}
56630
56757
  });
@@ -56636,7 +56763,9 @@ async function pollForMessages(sinceMs) {
56636
56763
  return false;
56637
56764
  }
56638
56765
  const data = await res.json();
56766
+ const handledThisCall = /* @__PURE__ */ new Set();
56639
56767
  const markProcessed = (id) => {
56768
+ handledThisCall.add(id);
56640
56769
  processedIds.add(id);
56641
56770
  if (processedIds.size > 500) {
56642
56771
  const ids = [...processedIds];
@@ -56644,8 +56773,12 @@ async function pollForMessages(sinceMs) {
56644
56773
  }
56645
56774
  };
56646
56775
  lastPollRetryAfterMs = data.retry_after_ms;
56776
+ if (rehandIds && rehandIds.length > 0) lastRehandReturned = (data.messages ?? []).length;
56647
56777
  for (const msg of data.messages ?? []) {
56648
- if (processedIds.has(msg.id)) continue;
56778
+ if (processedIds.has(msg.id)) {
56779
+ handledThisCall.add(msg.id);
56780
+ continue;
56781
+ }
56649
56782
  const isNotice = msg.kind === "notice";
56650
56783
  const maintenanceActive = !isNotice && isMaintenanceModeActive();
56651
56784
  const accountMuted = !isNotice && !maintenanceActive ? readAccountEnforcementLevel({ codeName: AGT_AGENT_CODE_NAME ?? null }) === "mute" : false;
@@ -56776,6 +56909,8 @@ async function pollForMessages(sinceMs) {
56776
56909
  meta: {
56777
56910
  ...buildDirectChatChannelMeta({
56778
56911
  sessionId: msg.session_id,
56912
+ // ENG-12060: the exact transcript marker a resume checks claims against.
56913
+ messageId: msg.id,
56779
56914
  isNotice,
56780
56915
  // ENG-8047: pure passthrough of the server-resolved human identity.
56781
56916
  userName: msg.sender_name,
@@ -56801,7 +56936,8 @@ async function pollForMessages(sinceMs) {
56801
56936
  });
56802
56937
  if (!isNotice) {
56803
56938
  pushPendingId = null;
56804
- claimTracker.track(msg.session_id, msg.id);
56939
+ if (rehandIds && rehandIds.length > 0) claimTracker.retrack(msg.session_id, msg.id);
56940
+ else claimTracker.track(msg.session_id, msg.id);
56805
56941
  if (!progressReceivedAt.has(msg.session_id)) {
56806
56942
  progressReceivedAt.set(msg.session_id, Date.now());
56807
56943
  }
@@ -56871,6 +57007,14 @@ async function pollForMessages(sinceMs) {
56871
57007
  });
56872
57008
  }
56873
57009
  }
57010
+ const unresolved = rehandIds && rehandIds.length > 0 ? rehandUnresolvedCount(data.messages ?? [], handledThisCall) : 0;
57011
+ if (unresolved > 0) {
57012
+ process.stderr.write(
57013
+ `direct-chat-channel: rehand left ${unresolved} returned row(s) neither pushed nor acknowledged; retrying
57014
+ `
57015
+ );
57016
+ return false;
57017
+ }
56874
57018
  return true;
56875
57019
  } catch (err) {
56876
57020
  if (pushPendingId) processedIds.delete(pushPendingId);
@@ -56906,10 +57050,10 @@ var DOORBELL_ENABLED = resolveHostBooleanFlag({
56906
57050
  });
56907
57051
  var DOORBELL_FILE = "direct-chat-doorbell";
56908
57052
  var pollGuard = { inFlight: false, inFlightSinceMs: null, leaseUntilMs: null };
56909
- async function pollOnce(sinceMs) {
57053
+ async function pollOnce(sinceMs, rehandIds) {
56910
57054
  const decision = evaluatePollGuard(pollGuard, Date.now(), POLL_STUCK_MS);
56911
57055
  if (!decision.run) {
56912
- pollFollowUps.noteSkipped(sinceMs);
57056
+ if (!rehandIds) pollFollowUps.noteSkipped(sinceMs);
56913
57057
  return { ran: false, ok: false };
56914
57058
  }
56915
57059
  if (decision.stuck) {
@@ -56922,7 +57066,7 @@ async function pollOnce(sinceMs) {
56922
57066
  pollGuard.inFlightSinceMs = Date.now();
56923
57067
  lastPollRetryAfterMs = void 0;
56924
57068
  try {
56925
- const ok = await pollForMessages(sinceMs);
57069
+ const ok = await pollForMessages(sinceMs, rehandIds);
56926
57070
  return { ran: true, ok };
56927
57071
  } finally {
56928
57072
  pollGuard.inFlight = false;
@@ -56976,9 +57120,13 @@ if (DOORBELL_ENABLED && DIRECT_CHAT_AGENT_DIR) {
56976
57120
  const sinceMs = sessionState.startedAtMs;
56977
57121
  const claimPlan = planClaimRecovery(sessionState);
56978
57122
  claimsTranscriptId = claimPlan.bindTo;
57123
+ let rehandPlan = null;
56979
57124
  if (claimPlan.restore) {
56980
57125
  const recovered = loadDirectChatClaims(DIRECT_CHAT_CLAIMS_PATH, claimPlan.bindTo, Date.now());
56981
- claimTracker.restore(recovered);
57126
+ const transcriptText = recovered.length > 0 && claimPlan.bindTo ? readTranscriptText(transcriptPathFor(agentTranscriptDir(), claimPlan.bindTo)) : null;
57127
+ const plan = recovered.length > 0 ? planRehand(recovered, transcriptText, sessionState.startedAtMs) : null;
57128
+ claimTracker.restore(recovered, { unpushed: plan?.rehand ?? [] });
57129
+ rehandPlan = plan ? { restored: recovered.length, plan } : null;
56982
57130
  if (recovered.length > 0) {
56983
57131
  process.stderr.write(
56984
57132
  `direct-chat-channel: restored ${recovered.length} pre-restart claim(s) for resumed session
@@ -57030,6 +57178,33 @@ if (DOORBELL_ENABLED && DIRECT_CHAT_AGENT_DIR) {
57030
57178
  `)
57031
57179
  });
57032
57180
  }
57181
+ if (rehandPlan) {
57182
+ const { restored, plan } = rehandPlan;
57183
+ if (plan.rehand.length === 0) {
57184
+ process.stderr.write(rehandSummaryLine(restored, plan, null));
57185
+ } else {
57186
+ void (async () => {
57187
+ let returned = null;
57188
+ for (const chunk of chunkIds(plan.rehand)) {
57189
+ lastRehandReturned = null;
57190
+ const attempts = await retryRehand(() => pollOnce(void 0, chunk), {
57191
+ sleep: (ms) => new Promise((resolve2) => {
57192
+ const t = setTimeout(resolve2, ms);
57193
+ t.unref?.();
57194
+ })
57195
+ });
57196
+ if (!attempts.ok) {
57197
+ process.stderr.write(
57198
+ `direct-chat-channel: rehand gave up on ${chunk.length} id(s) after ${attempts.attempts} attempt(s): ${attempts.ran ? "the rehand request kept failing" : "the poll guard stayed busy"}
57199
+ `
57200
+ );
57201
+ }
57202
+ if (lastRehandReturned !== null) returned = (returned ?? 0) + lastRehandReturned;
57203
+ }
57204
+ process.stderr.write(rehandSummaryLine(restored, plan, returned));
57205
+ })();
57206
+ }
57207
+ }
57033
57208
  process.stderr.write(
57034
57209
  `direct-chat-channel: Started (agent=${AGT_AGENT_ID}, delivery=doorbell+pull, session=${sessionState.fresh ? "fresh\u2192backlog-drain (unscoped, retried)" : "resumed\u2192new-only"}, new_message_watermark_since=${sinceMs} \u2014 watching ${DOORBELL_FILE}, safety-net ${safetyNetMs}ms)
57035
57210
  `
@@ -57054,7 +57229,7 @@ function sweepAgedDirectChatMarkersNow(thresholdMs) {
57054
57229
  const now = Date.now();
57055
57230
  const res = sweepAgedDirectChatMarkers(DIRECT_CHAT_PENDING_INBOUND_DIR, {
57056
57231
  readdir: (dir) => readdirSync6(dir),
57057
- readFile: (p2) => readFileSync13(p2, "utf8"),
57232
+ readFile: (p2) => readFileSync14(p2, "utf8"),
57058
57233
  unlink: (p2) => {
57059
57234
  if (existsSync6(p2)) unlinkSync4(p2);
57060
57235
  },
@@ -57103,7 +57278,7 @@ function sanitizeRecoveryText(text) {
57103
57278
  }
57104
57279
  function directChatRecoveryDeps() {
57105
57280
  return {
57106
- readFile: (p2) => readFileSync13(p2, "utf-8"),
57281
+ readFile: (p2) => readFileSync14(p2, "utf-8"),
57107
57282
  renameFile: (from, to) => renameSync6(from, to),
57108
57283
  unlinkFile: (p2) => {
57109
57284
  if (existsSync6(p2)) unlinkSync4(p2);
@@ -57116,7 +57291,7 @@ function directChatRecoveryDeps() {
57116
57291
  if (!DIRECT_CHAT_RECOVERY_LEDGER_DIR) return;
57117
57292
  if (markerName.includes("/") || markerName.includes("\\") || markerName.includes("..")) return;
57118
57293
  try {
57119
- const p2 = join17(DIRECT_CHAT_RECOVERY_LEDGER_DIR, markerName);
57294
+ const p2 = join18(DIRECT_CHAT_RECOVERY_LEDGER_DIR, markerName);
57120
57295
  if (existsSync6(p2)) unlinkSync4(p2);
57121
57296
  } catch {
57122
57297
  }
@@ -57167,7 +57342,7 @@ async function processDirectChatRecoveryOutboxFile(filename) {
57167
57342
  if (!enabled) return;
57168
57343
  directChatRecoveryInFlight.add(filename);
57169
57344
  try {
57170
- const fullPath = join17(DIRECT_CHAT_RECOVERY_OUTBOX_DIR, filename);
57345
+ const fullPath = join18(DIRECT_CHAT_RECOVERY_OUTBOX_DIR, filename);
57171
57346
  await consumeDirectChatRecoveryFile(fullPath, filename, directChatRecoveryDeps());
57172
57347
  } catch (err) {
57173
57348
  process.stderr.write(
@@ -57195,7 +57370,7 @@ if (DIRECT_CHAT_RECOVERY_OUTBOX_DIR) {
57195
57370
  if (!filename) return;
57196
57371
  const name = filename.toString();
57197
57372
  if (!name.endsWith(".json")) return;
57198
- if (existsSync6(join17(DIRECT_CHAT_RECOVERY_OUTBOX_DIR, name))) {
57373
+ if (existsSync6(join18(DIRECT_CHAT_RECOVERY_OUTBOX_DIR, name))) {
57199
57374
  void processDirectChatRecoveryOutboxFile(name);
57200
57375
  }
57201
57376
  });