@cortexkit/pi-magic-context 0.49.56 → 0.49.59

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 (55) hide show
  1. package/dist/auto-search-worker.js +5 -5
  2. package/dist/chunk-embedding-write-worker.js +12 -12
  3. package/dist/{compaction-marker-candidates-9yhrstyb.js → compaction-marker-candidates-nxaamfej.js} +2 -2
  4. package/dist/compaction-marker-candidates-worker.js +1 -1
  5. package/dist/{compartment-chunk-embedding-wg7emg3z.js → compartment-chunk-embedding-avkyp2df.js} +7 -7
  6. package/dist/{embedding-backfill-qde2zywg.js → embedding-backfill-3g3cm51d.js} +12 -12
  7. package/dist/embedding-worker-process.js +1 -1
  8. package/dist/embedding-worker.js +4 -4
  9. package/dist/historian-calibration-extension.js +1 -1
  10. package/dist/{index-j0eagxkz.js → index-1ts77n1b.js} +1 -1
  11. package/dist/{index-9x1jpjeb.js → index-2tk7e0bx.js} +100 -26
  12. package/dist/{index-xssjy4z9.js → index-3s39a1md.js} +1 -1
  13. package/dist/{index-xx1911hb.js → index-453s1hj6.js} +1 -1
  14. package/dist/{index-c3mms4dp.js → index-5hhhxck7.js} +10 -10
  15. package/dist/{index-qm139qq2.js → index-5rcjs14a.js} +2 -2
  16. package/dist/{index-yjgkjkjs.js → index-71rg8j43.js} +1 -1
  17. package/dist/{index-zxm7ckvc.js → index-79xfn84y.js} +2 -2
  18. package/dist/{index-5n3e2gq5.js → index-8gvbskcm.js} +27 -5
  19. package/dist/{index-b1q0h16h.js → index-9cqfbdgb.js} +3 -3
  20. package/dist/{index-ndg15t3x.js → index-cxczethe.js} +4 -4
  21. package/dist/{index-erkb5dee.js → index-e9wkbh8y.js} +8 -8
  22. package/dist/{index-9kaj9ty1.js → index-f4n7tnsf.js} +2 -2
  23. package/dist/{index-nhpvvdhw.js → index-fz4gexgk.js} +11 -3
  24. package/dist/{index-d40ecdbn.js → index-gavj3e6h.js} +4 -4
  25. package/dist/{index-6d0bby9d.js → index-ghp32f9m.js} +2 -2
  26. package/dist/{index-v858d5d1.js → index-jhmz9tgv.js} +1 -1
  27. package/dist/{index-awpx91y5.js → index-k7a8x7ba.js} +1 -1
  28. package/dist/{index-2pptpxq8.js → index-m6kszx0e.js} +4 -4
  29. package/dist/{index-7y60kyea.js → index-pefn1gt5.js} +1 -1
  30. package/dist/{index-jnh7a6a3.js → index-qdy49kwk.js} +4 -4
  31. package/dist/{index-yxeg8zaa.js → index-tm11k42a.js} +9 -4
  32. package/dist/{index-hec3bwev.js → index-txcs0vnj.js} +2 -2
  33. package/dist/{index-625kbnqd.js → index-w4sqw9mf.js} +8 -8
  34. package/dist/{index-rekymyxd.js → index-xan5mt5f.js} +5 -5
  35. package/dist/{index-szn2tac8.js → index-xjhq27z9.js} +1 -1
  36. package/dist/{index-ywmt8sdr.js → index-zgsemyph.js} +26 -11
  37. package/dist/index.js +1172 -373
  38. package/dist/{logger-hhgpkbx1.js → logger-93cnqyh0.js} +1 -1
  39. package/dist/{message-fts-rowid-map-tec2x7qe.js → message-fts-rowid-map-dtbragnt.js} +4 -4
  40. package/dist/{message-index-bounded-ac4qg6aw.js → message-index-bounded-behq385r.js} +9 -9
  41. package/dist/{message-time-backfill-krre2qnb.js → message-time-backfill-8zwv9byv.js} +2 -2
  42. package/dist/migration-worker.js +9 -9
  43. package/dist/{project-embedding-registry-qx2zjbgs.js → project-embedding-registry-63wsm3a8.js} +11 -11
  44. package/dist/raw-ordinal-warmup-worker.js +8 -8
  45. package/dist/{read-session-chunk-jyfcykg4.js → read-session-chunk-ksh32zfv.js} +7 -7
  46. package/dist/{read-session-raw-75dcxtdy.js → read-session-raw-0tytrjye.js} +2 -2
  47. package/dist/{render-gj0nzrg0.js → render-2qed2svq.js} +16 -16
  48. package/dist/{safe-notification-target-8s1xg0q9.js → safe-notification-target-fkyrd95h.js} +2 -2
  49. package/dist/{search-archive-vpxem4pj.js → search-archive-qqj7j1w1.js} +9 -9
  50. package/dist/{search-w12nc025.js → search-vmw1xbqx.js} +19 -19
  51. package/dist/{storage-tags-g0328gwp.js → storage-tags-s0m7e39a.js} +5 -5
  52. package/dist/subagent-entry.js +25 -25
  53. package/dist/tag-snapshot-worker-pi.js +11 -11
  54. package/dist/{v2-archive-reader-r96gp6nc.js → v2-archive-reader-cc7sx6dk.js} +1 -1
  55. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@ import {
4
4
  harnessOwnsOpenCodeStore2
5
5
  } from "./index-0h2mkab2.js";
6
6
  import {
7
+ getMagicContextHistorianSessionDir,
7
8
  ensureCortexKitArtifactGitignore,
8
- getProjectMagicContextHistorianDir,
9
9
  getMagicContextStorageDir,
10
10
  isMagicContextStorageOutsideEngram,
11
11
  claimStorageBackupWarningCheck,
@@ -15,7 +15,7 @@ import {
15
15
  log2,
16
16
  sessionLog2,
17
17
  flushLogger2
18
- } from "./index-yxeg8zaa.js";
18
+ } from "./index-tm11k42a.js";
19
19
  import {
20
20
  sanitizeDiagnosticText,
21
21
  hasShareabilitySensitiveText
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-9x1jpjeb.js";
157
+ } from "./index-2tk7e0bx.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -193,7 +193,7 @@ import {
193
193
  resolveProjectIdentityForSession,
194
194
  beginBootQuietPeriod,
195
195
  scheduleAfterBootQuiet
196
- } from "./index-xx1911hb.js";
196
+ } from "./index-453s1hj6.js";
197
197
  import {
198
198
  detectThinkingBindingMismatch,
199
199
  detectLatestTurnThinkingMismatch,
@@ -322,6 +322,7 @@ import {
322
322
  isProviderOverflowFailClosedProven,
323
323
  getEmergencyRecoveryArmedAt,
324
324
  describeProtectedTailDrainBudgetSkip,
325
+ loadPersistedUsage,
325
326
  loadProtectedTailMeta,
326
327
  markProtectedTailPolicyV3Seeded,
327
328
  recordProtectedTailPublicationFloor,
@@ -402,7 +403,7 @@ import {
402
403
  setSessionWorkMetrics,
403
404
  getSessionWorkMetrics,
404
405
  resolveEpochFloorForPass
405
- } from "./index-5n3e2gq5.js";
406
+ } from "./index-8gvbskcm.js";
406
407
  import {
407
408
  textMentionsRecentCommit,
408
409
  hasMeaningfulUserText2,
@@ -414,7 +415,7 @@ import {
414
415
  estimateTokens,
415
416
  estimateFixedPromptTokens,
416
417
  normalizeText
417
- } from "./index-7y60kyea.js";
418
+ } from "./index-pefn1gt5.js";
418
419
  import {
419
420
  stableStringify,
420
421
  BoundedSessionMap,
@@ -422,7 +423,7 @@ import {
422
423
  observeTemporalDecisions,
423
424
  freezeTemporalDecisions,
424
425
  tagIdentityRevisionKey
425
- } from "./index-v858d5d1.js";
426
+ } from "./index-jhmz9tgv.js";
426
427
  import {
427
428
  inRootAsyncContext2,
428
429
  Database2,
@@ -453,7 +454,7 @@ import {
453
454
  openCurrentDatabase,
454
455
  openDatabaseAsync,
455
456
  closeDatabase
456
- } from "./index-625kbnqd.js";
457
+ } from "./index-w4sqw9mf.js";
457
458
  import {
458
459
  LkgRecoveryFenceError,
459
460
  clearLkgFenceProcessState,
@@ -564,6 +565,7 @@ import {
564
565
  externalHistorianFailureReason,
565
566
  subprocessExitHistorianFailureReason,
566
567
  countHistorianRuns,
568
+ getRecentFailedHistorianRunTimes,
567
569
  recordHistorianRun,
568
570
  summarizeImportance,
569
571
  tallyFactsByCategory,
@@ -579,7 +581,7 @@ import {
579
581
  getSourceContents,
580
582
  recordSubagentInvocation,
581
583
  getLatestHistorianInvocationId
582
- } from "./index-ywmt8sdr.js";
584
+ } from "./index-zgsemyph.js";
583
585
  import {
584
586
  resolveOpenCodeDbPath,
585
587
  assertOpenCodeStoreGeneration,
@@ -597,7 +599,7 @@ import {
597
599
  } from "./index-x2n261wp.js";
598
600
  import {
599
601
  RAW_SUMMARY_TEXT_MAX_CHARS2
600
- } from "./index-szn2tac8.js";
602
+ } from "./index-xjhq27z9.js";
601
603
  import {
602
604
  askAnswerLines,
603
605
  removeUnsupportedCommitHashes,
@@ -645,12 +647,12 @@ import {
645
647
  getRawSessionTagKeysThrough2,
646
648
  getLegacyProtectedTailStartOrdinal2,
647
649
  readSessionChunk2
648
- } from "./index-rekymyxd.js";
650
+ } from "./index-xan5mt5f.js";
649
651
  import"./index-nvh6d3bz.js";
650
652
  import {
651
653
  formatSynapseLaneDescriptor
652
- } from "./index-qm139qq2.js";
653
- import"./index-6d0bby9d.js";
654
+ } from "./index-5rcjs14a.js";
655
+ import"./index-ghp32f9m.js";
654
656
  import {
655
657
  buildCanonicalChunkTextFromFts2,
656
658
  buildCompartmentSummaryFallbackText2,
@@ -660,7 +662,7 @@ import {
660
662
  replaceCompartmentChunkEmbeddings2,
661
663
  deleteChunkEmbedBackoffForSession2,
662
664
  chunkWindowSourceKey2
663
- } from "./index-ndg15t3x.js";
665
+ } from "./index-cxczethe.js";
664
666
  import {
665
667
  recordSessionProjectIdentity,
666
668
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -669,7 +671,7 @@ import {
669
671
  markGitSweepSuccessAndRelease,
670
672
  parkGitSweepNonIndexable,
671
673
  releaseGitSweepLease
672
- } from "./index-zxm7ckvc.js";
674
+ } from "./index-79xfn84y.js";
673
675
  import {
674
676
  embedPauseBySession,
675
677
  embedRunStateBySession,
@@ -685,7 +687,7 @@ import {
685
687
  clearCompressionDepthRange,
686
688
  cleanSearchText,
687
689
  matchedSearchSnippet
688
- } from "./index-2pptpxq8.js";
690
+ } from "./index-m6kszx0e.js";
689
691
  import {
690
692
  rememberV1HiddenRun
691
693
  } from "./index-6x556c2q.js";
@@ -700,7 +702,7 @@ import {
700
702
  expandWorkspaceIdentitySetWithAliases,
701
703
  sourceNameForMemory,
702
704
  computeWorkspaceEpochFingerprint
703
- } from "./index-d40ecdbn.js";
705
+ } from "./index-gavj3e6h.js";
704
706
  import {
705
707
  configureContextDatabasePragmas2
706
708
  } from "./index-fapenpch.js";
@@ -725,7 +727,7 @@ import {
725
727
  createPrimer,
726
728
  updatePrimerSupport,
727
729
  updatePrimerAnswer
728
- } from "./index-awpx91y5.js";
730
+ } from "./index-k7a8x7ba.js";
729
731
  import {
730
732
  setEmbeddingSessionBusy2,
731
733
  isEmbeddingHostBusy2
@@ -759,7 +761,7 @@ import {
759
761
  } from "./index-q1yc6bs0.js";
760
762
  import {
761
763
  getCachedLocalEmbeddingPooling
762
- } from "./index-hec3bwev.js";
764
+ } from "./index-txcs0vnj.js";
763
765
  import {
764
766
  describeShadowBackfillWriteRefusal2,
765
767
  contentSha2562,
@@ -777,10 +779,10 @@ import {
777
779
  embedSessionCompartmentChunks2,
778
780
  getEmbeddingCoverageStatus2,
779
781
  getAutoEmbeddingSessionCoverage2
780
- } from "./index-erkb5dee.js";
782
+ } from "./index-e9wkbh8y.js";
781
783
  import {
782
784
  cosineSimilarity
783
- } from "./index-jnh7a6a3.js";
785
+ } from "./index-qdy49kwk.js";
784
786
  import {
785
787
  USER_FACING_FAILURES,
786
788
  renderUserFacingFailure,
@@ -814,8 +816,8 @@ import {
814
816
  scheduleClearAndReindex,
815
817
  clearSessionTracking,
816
818
  createAutoSearchDiagnostics
817
- } from "./index-c3mms4dp.js";
818
- import"./index-xssjy4z9.js";
819
+ } from "./index-5hhhxck7.js";
820
+ import"./index-3s39a1md.js";
819
821
  import {
820
822
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
821
823
  buildHiddenAgentRegistrations,
@@ -831,6 +833,7 @@ import {
831
833
  import {
832
834
  PI_CONTEXT_BUDGET,
833
835
  PiContextDeadlineError,
836
+ PiHistorianJoinDeadlineError,
834
837
  PiContextSupersededError,
835
838
  PiContextBudget,
836
839
  PiTagHydrationError,
@@ -842,11 +845,11 @@ import {
842
845
  drainPiTagSnapshotSession,
843
846
  assertPiTagSnapshotReady,
844
847
  ensurePiTagSnapshotReady
845
- } from "./index-nhpvvdhw.js";
846
- import"./index-yjgkjkjs.js";
848
+ } from "./index-fz4gexgk.js";
849
+ import"./index-71rg8j43.js";
847
850
  import"./index-8d2z6503.js";
848
- import"./index-b1q0h16h.js";
849
- import"./index-9kaj9ty1.js";
851
+ import"./index-9cqfbdgb.js";
852
+ import"./index-f4n7tnsf.js";
850
853
  import {
851
854
  __toESM
852
855
  } from "./index-22jkk6wg.js";
@@ -866,7 +869,7 @@ import {
866
869
  import {
867
870
  logSlowWriteTransaction,
868
871
  WriteTransactionSteps
869
- } from "./index-j0eagxkz.js";
872
+ } from "./index-1ts77n1b.js";
870
873
  import {
871
874
  setStoragePrivatePermissionEnforcement,
872
875
  ensureStorageDirectorySync,
@@ -3598,7 +3601,7 @@ function startHostStallProfilerSwitch() {
3598
3601
  // package.json
3599
3602
  var package_default = {
3600
3603
  name: "@cortexkit/pi-magic-context",
3601
- version: "0.49.56",
3604
+ version: "0.49.59",
3602
3605
  type: "module",
3603
3606
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3604
3607
  main: "dist/index.js",
@@ -3678,6 +3681,8 @@ var package_default = {
3678
3681
  "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
3679
3682
  "omp-pi-ai-18186": "npm:@oh-my-pi/pi-ai@18.18.6",
3680
3683
  "omp-pi-ai-18190": "npm:@oh-my-pi/pi-ai@18.19.0",
3684
+ "omp-pi-ai-18200": "npm:@oh-my-pi/pi-ai@18.20.0",
3685
+ "omp-pi-ai-18203": "npm:@oh-my-pi/pi-ai@18.20.3",
3681
3686
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3682
3687
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3683
3688
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -9754,9 +9759,6 @@ function fitHistorianPrompt(args) {
9754
9759
  }
9755
9760
 
9756
9761
  // ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
9757
- function historianResponseDumpDir(directory) {
9758
- return getProjectMagicContextHistorianDir(directory);
9759
- }
9760
9762
  var MAX_HISTORIAN_RETRIES = 2;
9761
9763
  var unknownProducerWindows = new Set;
9762
9764
  var HISTORIAN_REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
@@ -10230,7 +10232,7 @@ async function runHistorianPrompt(args) {
10230
10232
  invocationId: invocationId ?? undefined
10231
10233
  };
10232
10234
  }
10233
- const dumpPath = dumpHistorianResponse(parentSessionId, sessionDirectory, dumpLabel ?? "historian-response", result);
10235
+ const dumpPath = dumpHistorianResponse(parentSessionId, dumpLabel ?? "historian-response", result);
10234
10236
  return { ok: true, result, dumpPath, invocationId: invocationId ?? undefined };
10235
10237
  } catch (modelError) {
10236
10238
  hiddenModelCooldowns.record(handle?.attemptedModel ?? toModelEntry(modelOverride)?.model, modelError);
@@ -10384,14 +10386,12 @@ function cleanupHistorianDump(sessionId, dumpPath) {
10384
10386
  });
10385
10387
  }
10386
10388
  }
10387
- function dumpHistorianResponse(sessionId, directory, label, text) {
10389
+ function dumpHistorianResponse(sessionId, label, text) {
10388
10390
  try {
10389
- const dumpDir = historianResponseDumpDir(directory);
10391
+ const dumpDir = getMagicContextHistorianSessionDir(sessionId);
10390
10392
  mkdirSync(dumpDir, { recursive: true });
10391
- ensureCortexKitArtifactGitignore(directory);
10392
- const safeSessionId = sanitizeDumpName(sessionId);
10393
10393
  const safeLabel = sanitizeDumpName(label);
10394
- const dumpPath = join7(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
10394
+ const dumpPath = join7(dumpDir, `${safeLabel}-${Date.now()}.xml`);
10395
10395
  writeFileSync(dumpPath, text, "utf8");
10396
10396
  sessionLog2(sessionId, "compartment agent: historian response dumped", {
10397
10397
  label,
@@ -27183,6 +27183,140 @@ function foldExecutesThisPass(foldDue, materialized) {
27183
27183
  return foldDue && materialized;
27184
27184
  }
27185
27185
 
27186
+ // ../plugin/src/hooks/magic-context/historian-failure-report.ts
27187
+ var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
27188
+ var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
27189
+ var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
27190
+ var REFUSAL_ERROR_MAX_CHARS = 500;
27191
+ var WARNING_ERROR_MAX_CHARS = 200;
27192
+ function readHistorianFailureStreak(db, sessionId, options = {}) {
27193
+ const state = getHistorianFailureState(db, sessionId);
27194
+ const count = state.failureCount;
27195
+ let since = null;
27196
+ if (count > 0) {
27197
+ const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
27198
+ if (recorded <= 0) {
27199
+ since = state.lastFailureAt;
27200
+ } else {
27201
+ const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
27202
+ since = times.length === recorded ? times[recorded - 1] ?? null : null;
27203
+ }
27204
+ }
27205
+ return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
27206
+ }
27207
+ function formatHistorianClockTime(at, now = Date.now()) {
27208
+ const date = new Date(at);
27209
+ const pad = (value) => String(value).padStart(2, "0");
27210
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
27211
+ const today = new Date(now);
27212
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
27213
+ return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
27214
+ }
27215
+ function formatHistorianSeconds(ms) {
27216
+ const seconds = Math.max(0, ms) / 1000;
27217
+ return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
27218
+ }
27219
+ function singleLine(text) {
27220
+ return text.replace(/\s+/g, " ").trim();
27221
+ }
27222
+ function quoteError(error, maxChars) {
27223
+ const text = sanitizeDiagnosticText(singleLine(error));
27224
+ return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
27225
+ }
27226
+ function endSentence(text) {
27227
+ return /[.!?]$/.test(text) ? text : `${text}.`;
27228
+ }
27229
+ function usageClause(usagePercentage) {
27230
+ return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
27231
+ }
27232
+ function capitalize(text) {
27233
+ return text.charAt(0).toUpperCase() + text.slice(1);
27234
+ }
27235
+ function chunkLabel(chunk) {
27236
+ return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
27237
+ }
27238
+ function streakSentence(failures, now) {
27239
+ if (failures.count <= 0)
27240
+ return null;
27241
+ const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
27242
+ return `Summary runs failed in a row: ${failures.count}${since}.`;
27243
+ }
27244
+ function failureBelongsToRun(failures, run) {
27245
+ return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
27246
+ }
27247
+ function describeHistorianJoinRefusal(input) {
27248
+ const now = input.now ?? Date.now();
27249
+ const { run, failures } = input;
27250
+ const sentences = [
27251
+ `This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
27252
+ ];
27253
+ const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
27254
+ const ownFailure = failureBelongsToRun(failures, run);
27255
+ const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
27256
+ if (ownFailure) {
27257
+ sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
27258
+ } else if (run && run.endedAt === undefined) {
27259
+ sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
27260
+ } else if (run) {
27261
+ sentences.push(`${subject} finished after the wait ended.`);
27262
+ }
27263
+ if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
27264
+ sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
27265
+ }
27266
+ const streak = streakSentence(failures, now);
27267
+ if (streak)
27268
+ sentences.push(streak);
27269
+ sentences.push(ACTIONS);
27270
+ return sentences.join(" ");
27271
+ }
27272
+ function describeRepeatedHistorianFailures(input) {
27273
+ const now = input.now ?? Date.now();
27274
+ const { failures } = input;
27275
+ const facts = [
27276
+ streakSentence(failures, now) ?? "Summary runs are failing.",
27277
+ ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
27278
+ ...failures.lastError ? [
27279
+ endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
27280
+ ] : [],
27281
+ `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
27282
+ ];
27283
+ return [
27284
+ "## Magic Context — History summaries keep failing",
27285
+ "",
27286
+ facts.join(" "),
27287
+ "",
27288
+ ACTIONS
27289
+ ].join(`
27290
+ `);
27291
+ }
27292
+ var repeatedFailureWarnings = new Map;
27293
+ function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
27294
+ const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
27295
+ if (failureCount < step || failureCount % step !== 0)
27296
+ return false;
27297
+ const last = repeatedFailureWarnings.get(sessionId);
27298
+ if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
27299
+ return false;
27300
+ }
27301
+ repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
27302
+ return true;
27303
+ }
27304
+ function takeRepeatedHistorianFailureWarning(input) {
27305
+ const now = input.now ?? Date.now();
27306
+ if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
27307
+ return null;
27308
+ }
27309
+ const failures = readHistorianFailureStreak(input.db, input.sessionId, {
27310
+ unrecordedFailures: input.unrecordedFailures
27311
+ });
27312
+ return describeRepeatedHistorianFailures({
27313
+ chunk: input.chunk,
27314
+ failures: { ...failures, count: input.failureCount },
27315
+ usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
27316
+ now
27317
+ });
27318
+ }
27319
+
27186
27320
  // ../plugin/src/hooks/magic-context/reasoning-removal.ts
27187
27321
  var REMOVABLE_REASONING_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
27188
27322
 
@@ -30853,6 +30987,37 @@ async function runPiHistorian(deps) {
30853
30987
  });
30854
30988
  }
30855
30989
  };
30990
+ let selectedChunk;
30991
+ const notifyCountedFailure = async (failureCount, notice) => {
30992
+ let warning = null;
30993
+ try {
30994
+ warning = takeRepeatedHistorianFailureWarning({
30995
+ db,
30996
+ sessionId,
30997
+ failureCount,
30998
+ chunk: selectedChunk,
30999
+ unrecordedFailures: 1
31000
+ });
31001
+ } catch (error) {
31002
+ sessionLog2(sessionId, "historian repeated-failure warning failed", {
31003
+ error: describeError(error).brief
31004
+ });
31005
+ }
31006
+ if (!warning) {
31007
+ await notify(notice);
31008
+ return;
31009
+ }
31010
+ issueNotified = true;
31011
+ lastHistorianAlertBySession.set(sessionId, Date.now());
31012
+ sessionLog2(sessionId, `historian repeated-failure warning sent: count=${failureCount}`);
31013
+ try {
31014
+ await notifyIssue?.(warning);
31015
+ } catch (error) {
31016
+ sessionLog2(sessionId, "historian notify failed", {
31017
+ error: describeError(error).brief
31018
+ });
31019
+ }
31020
+ };
30856
31021
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
30857
31022
  const invocationBaseline = getLatestHistorianInvocationId(db, sessionId);
30858
31023
  const telemetry = {
@@ -30878,7 +31043,7 @@ async function runPiHistorian(deps) {
30878
31043
  sessionLog2(sessionId, `historian failure: source=existing-validation reason="${existingValidationError}"`);
30879
31044
  {
30880
31045
  const failCount = incrementHistorianFailure(db, sessionId, existingValidationError);
30881
- await notify(buildHistorianFailureNotice(failCount, existingValidationError));
31046
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, existingValidationError));
30882
31047
  }
30883
31048
  return;
30884
31049
  }
@@ -30979,9 +31144,9 @@ async function runPiHistorian(deps) {
30979
31144
  return;
30980
31145
  }
30981
31146
  sessionLog2(sessionId, `historian failure: source=prompt-fit reason="${promptFit.reason}"`);
30982
- incrementHistorianFailure(db, sessionId, promptFit.reason);
31147
+ const failCount = incrementHistorianFailure(db, sessionId, promptFit.reason);
30983
31148
  retainDrainReservationForRetryThrottle = true;
30984
- await notify(buildHistorianWindowTooSmallNotice());
31149
+ await notifyCountedFailure(failCount, buildHistorianWindowTooSmallNotice());
30985
31150
  return;
30986
31151
  }
30987
31152
  const chunkTokens = promptFit.chunkTokens;
@@ -31009,6 +31174,8 @@ async function runPiHistorian(deps) {
31009
31174
  drainReservation = reserve.reservation;
31010
31175
  const chunk = readSessionChunk2(sessionId, chunkTokens, offset, eligibleEndOrdinal, { expandTools: deps.expandTools });
31011
31176
  const forceKeepLastCompartmentForChunk = forceKeepLastCompartment === true && !chunk.hasMore;
31177
+ selectedChunk = { start: chunk.startIndex, end: chunk.endIndex };
31178
+ deps.onChunkSelected?.(selectedChunk);
31012
31179
  if (!chunk.text || chunk.messageCount === 0) {
31013
31180
  if (persistFilteredNoise(db, sessionId, chunk, eligibleEndOrdinal)) {
31014
31181
  telemetry.status = "noop";
@@ -31037,7 +31204,7 @@ async function runPiHistorian(deps) {
31037
31204
  sessionLog2(sessionId, `historian failure: source=chunk-coverage reason="${chunkCoverageError}" chunkRange=${chunk.startIndex}-${chunk.endIndex}`);
31038
31205
  {
31039
31206
  const failCount = incrementHistorianFailure(db, sessionId, chunkCoverageError);
31040
- await notify(buildHistorianFailureNotice(failCount, chunkCoverageError));
31207
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, chunkCoverageError));
31041
31208
  }
31042
31209
  rollbackDrainReservation();
31043
31210
  return;
@@ -31236,7 +31403,7 @@ ${chunkText}`,
31236
31403
  sessionLog2(sessionId, `historian failure: ${errorMsg}`);
31237
31404
  {
31238
31405
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31239
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31406
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31240
31407
  }
31241
31408
  return;
31242
31409
  }
@@ -31293,7 +31460,7 @@ ${chunkText}`,
31293
31460
  sessionLog2(sessionId, `historian failure: source=no-progress newCompartmentCount=${newCompartments.length} lastNewEnd=${lastNewEnd} priorEnd=${offset - 1}`);
31294
31461
  {
31295
31462
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31296
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31463
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31297
31464
  }
31298
31465
  recordHistorianNoProgress(boundarySnapshot, inEmergency);
31299
31466
  rollbackDrainReservation();
@@ -31508,7 +31675,7 @@ ${chunkText}`,
31508
31675
  sessionLog2(sessionId, `historian failure: source=exception ${desc.brief}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
31509
31676
  if (!issueNotified) {
31510
31677
  const failCount = incrementHistorianFailure(db, sessionId, desc.brief);
31511
- await notify(buildHistorianFailureNotice(failCount, desc.brief));
31678
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, desc.brief));
31512
31679
  }
31513
31680
  } finally {
31514
31681
  if (!completedSuccessfully) {
@@ -31856,6 +32023,230 @@ function recordPiTransformTiming(sample) {
31856
32023
  timingObserver?.(sample);
31857
32024
  }
31858
32025
 
32026
+ // src/pi-request-tools.ts
32027
+ var schemaDigests = {
32028
+ omp: new WeakMap,
32029
+ anthropic: new WeakMap,
32030
+ "anthropic-strict": new WeakMap,
32031
+ raw: new WeakMap
32032
+ };
32033
+ function anthropicWireSchema(parameters, strict) {
32034
+ const schema = typeof parameters === "object" && parameters !== null ? parameters : {};
32035
+ const legacy = {
32036
+ type: "object",
32037
+ properties: schema.properties ?? {},
32038
+ required: schema.required ?? []
32039
+ };
32040
+ return strict ? { ...schema, ...legacy } : legacy;
32041
+ }
32042
+ function schemaDigest(tool, mode, wireSchema) {
32043
+ const key = tool.parameters;
32044
+ const cacheable = typeof key === "object" && key !== null || typeof key === "function";
32045
+ const cache = schemaDigests[mode];
32046
+ if (cacheable) {
32047
+ const cached = cache.get(key);
32048
+ if (cached !== undefined)
32049
+ return cached;
32050
+ }
32051
+ const digest = requestToolSchemaDigest(mode === "omp" && wireSchema ? wireSchema(tool) : mode === "anthropic" || mode === "anthropic-strict" ? anthropicWireSchema(tool.parameters, mode === "anthropic-strict") : tool.parameters);
32052
+ if (cacheable)
32053
+ cache.set(key, digest);
32054
+ return digest;
32055
+ }
32056
+ var CLAUDE_CODE_TOOL_NAMES = new Map([
32057
+ "Read",
32058
+ "Write",
32059
+ "Edit",
32060
+ "Bash",
32061
+ "Grep",
32062
+ "Glob",
32063
+ "AskUserQuestion",
32064
+ "EnterPlanMode",
32065
+ "ExitPlanMode",
32066
+ "KillShell",
32067
+ "NotebookEdit",
32068
+ "Skill",
32069
+ "Task",
32070
+ "TaskOutput",
32071
+ "TodoWrite",
32072
+ "WebFetch",
32073
+ "WebSearch"
32074
+ ].map((name) => [name.toLowerCase(), name]));
32075
+ var identityName = (name) => name;
32076
+ var claudeCodeName = (name) => CLAUDE_CODE_TOOL_NAMES.get(name.toLowerCase()) ?? name;
32077
+ function compatFlag(model, flag) {
32078
+ const value = model?.compat?.[flag];
32079
+ return typeof value === "boolean" ? value : undefined;
32080
+ }
32081
+ function supportsToolReferences(model) {
32082
+ const declared = compatFlag(model, "supportsToolReferences");
32083
+ if (declared !== undefined)
32084
+ return declared;
32085
+ if (model.provider !== "anthropic" || typeof model.id !== "string")
32086
+ return false;
32087
+ if (model.id.includes("haiku"))
32088
+ return false;
32089
+ const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
32090
+ if (!version)
32091
+ return false;
32092
+ const major = Number(version[1]);
32093
+ const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
32094
+ return major > 4 || major === 4 && minor >= 5;
32095
+ }
32096
+ function deferredAndReferencedNames(messages, normalizeName) {
32097
+ const deferred = new Set;
32098
+ const referenced = new Set;
32099
+ for (const message of messages) {
32100
+ const { role, content, addedToolNames } = message ?? {};
32101
+ if (role === "assistant" && Array.isArray(content)) {
32102
+ for (const block of content) {
32103
+ const { type, name } = block ?? {};
32104
+ if (type === "toolCall" && typeof name === "string")
32105
+ referenced.add(normalizeName(name));
32106
+ }
32107
+ } else if (role === "toolResult" && Array.isArray(addedToolNames)) {
32108
+ for (const name of addedToolNames) {
32109
+ if (typeof name !== "string")
32110
+ continue;
32111
+ const normalized = normalizeName(name);
32112
+ if (!referenced.has(normalized))
32113
+ deferred.add(normalized);
32114
+ }
32115
+ }
32116
+ }
32117
+ for (const name of deferred)
32118
+ referenced.add(name);
32119
+ return { deferred, referenced };
32120
+ }
32121
+ function calledToolNames(messages) {
32122
+ const names = new Set;
32123
+ for (const message of messages) {
32124
+ const content = message?.content;
32125
+ if (!Array.isArray(content))
32126
+ continue;
32127
+ for (const part of content) {
32128
+ const { type, name } = part ?? {};
32129
+ if (typeof type === "string" && type.toLowerCase().includes("tool") && typeof name === "string")
32130
+ names.add(name);
32131
+ }
32132
+ }
32133
+ return names;
32134
+ }
32135
+ function readPiRequestSendsTool(pi, name) {
32136
+ try {
32137
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
32138
+ return;
32139
+ const active = pi.getActiveTools();
32140
+ if (!Array.isArray(active))
32141
+ return;
32142
+ if (!active.includes(name))
32143
+ return false;
32144
+ const all = pi.getAllTools();
32145
+ if (!Array.isArray(all))
32146
+ return;
32147
+ return all.some((tool) => typeof tool === "object" && tool !== null && tool.name === name);
32148
+ } catch {
32149
+ return;
32150
+ }
32151
+ }
32152
+ function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
32153
+ try {
32154
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
32155
+ return;
32156
+ const all = pi.getAllTools();
32157
+ const active = pi.getActiveTools();
32158
+ if (!Array.isArray(all) || !Array.isArray(active))
32159
+ return;
32160
+ const registered = new Map;
32161
+ for (const tool of all) {
32162
+ if (!tool || typeof tool !== "object")
32163
+ return;
32164
+ const { name } = tool;
32165
+ if (typeof name !== "string")
32166
+ return;
32167
+ registered.set(name, tool);
32168
+ }
32169
+ const model = route.model;
32170
+ const anthropicWriter = route.host === "pi" && wireSchema === undefined && model?.api === "anthropic-messages";
32171
+ const mode = wireSchema ? "omp" : anthropicWriter ? compatFlag(model, "supportsStrictTools") === true ? "anthropic-strict" : "anthropic" : "raw";
32172
+ const normalizeName = anthropicWriter && route.oauth === true ? claudeCodeName : identityName;
32173
+ const sent = new Map;
32174
+ for (const name of active) {
32175
+ if (typeof name !== "string")
32176
+ return;
32177
+ const tool = registered.get(name);
32178
+ if (!tool)
32179
+ continue;
32180
+ sent.set(normalizeName(name), tool);
32181
+ }
32182
+ const split = anthropicWriter && model && supportsToolReferences(model) ? deferredAndReferencedNames(messages, normalizeName) : undefined;
32183
+ const anyImmediate = [...sent.keys()].some((name) => !split?.deferred.has(name));
32184
+ const tools = [];
32185
+ for (const [name, tool] of sent) {
32186
+ const description = typeof tool.description === "string" ? tool.description : "";
32187
+ tools.push({
32188
+ name,
32189
+ description,
32190
+ schemaDigest: schemaDigest({
32191
+ name: tool.name,
32192
+ description,
32193
+ parameters: tool.parameters
32194
+ }, mode, wireSchema),
32195
+ deferLoading: split ? anyImmediate && split.deferred.has(name) : tool.defer_loading === true || tool.deferLoading === true
32196
+ });
32197
+ }
32198
+ return requestToolsFingerprint(tools, () => split?.referenced ?? calledToolNames(messages));
32199
+ } catch {
32200
+ return;
32201
+ }
32202
+ }
32203
+
32204
+ // src/ctx-reduce-callable-pi.ts
32205
+ var CTX_REDUCE = "ctx_reduce";
32206
+ function piCtxReduceCallable(pi, compactionOff, session) {
32207
+ if (compactionOff)
32208
+ return false;
32209
+ const sent = readPiRequestSendsTool(pi, CTX_REDUCE);
32210
+ if (sent !== undefined)
32211
+ return sent;
32212
+ return session ? readServedPiCtxReduceCallable(session.db, session.sessionId) : true;
32213
+ }
32214
+ var NAMESPACE4 = "piCtxReduceCallable";
32215
+ var servedBySession = new BoundedSessionMap(1000);
32216
+ function readServedPiCtxReduceCallable(db, sessionId) {
32217
+ const cached = servedBySession.get(sessionId);
32218
+ if (cached !== undefined)
32219
+ return cached;
32220
+ let served = true;
32221
+ try {
32222
+ const stored = readReplayEnvelope(db, sessionId, "read")[NAMESPACE4];
32223
+ if (typeof stored === "boolean")
32224
+ served = stored;
32225
+ } catch (error) {
32226
+ sessionLog2(sessionId, "ctx_reduce served record unreadable:", error);
32227
+ }
32228
+ servedBySession.set(sessionId, served);
32229
+ return served;
32230
+ }
32231
+ function recordServedPiCtxReduceCallable(db, sessionId, callable) {
32232
+ if (readServedPiCtxReduceCallable(db, sessionId) === callable)
32233
+ return;
32234
+ servedBySession.set(sessionId, callable);
32235
+ const written = updateReplayDocument(db, sessionId, (doc) => {
32236
+ const stored = doc[NAMESPACE4];
32237
+ if ((typeof stored === "boolean" ? stored : true) === callable)
32238
+ return false;
32239
+ doc.version = 2;
32240
+ doc[NAMESPACE4] = callable;
32241
+ return true;
32242
+ });
32243
+ if (!written)
32244
+ sessionLog2(sessionId, "ctx_reduce served record not written");
32245
+ }
32246
+ function clearPiCtxReduceCallableSession(sessionId) {
32247
+ servedBySession.delete(sessionId);
32248
+ }
32249
+
31859
32250
  // src/ctx-reduce-nudge-pi.ts
31860
32251
  import { randomUUID as randomUUID3 } from "node:crypto";
31861
32252
 
@@ -37039,12 +37430,93 @@ function isOmpAdvisorRequest(payload) {
37039
37430
  `) === true;
37040
37431
  }
37041
37432
  function isOmpUnmanagedCaptureRequest(payload) {
37433
+ return isOmpLegacyCaptureRequest(payload) || isOmpAutolearnCapture(payload);
37434
+ }
37435
+ function isOmpLegacyCaptureRequest(payload) {
37042
37436
  const request = providerRequest(payload);
37043
37437
  if (!request?.tools.length || !request.tools.every((name) => name === "manage_skill" || name === "learn"))
37044
37438
  return false;
37045
37439
  const last = record3(request.messages.at(-1));
37046
37440
  return last?.role === "user" && firstText(last.content, request.textType)?.startsWith(CAPTURE_PREFIX) === true;
37047
37441
  }
37442
+ var OMP_AUTOLEARN_CAPTURE_PROMPT = "Automated capture turn — not a user reply; user has not responded to your previous turn. Do not treat this prompt as their answer, approval to continue, or acceptance of any pending action; only the user can do so.\n\nIf your previous turn produced reusable output, capture it now only if it will genuinely help next time: repeatable procedure → managed skill (`manage_skill`); durable fact, convention, or user preference → remember with `learn` when memory enabled. If nothing worth keeping, do nothing.\n\nThen stop. Do not run other tools, resume prior work, answer pending questions, or produce a continuation reply. Yield; wait for the user's next prompt.";
37443
+ var DATE_CWD_REMINDER = /^<system-reminder>\nToday: [^\n]*; current working directory: '[^\n]*'\. Do not repeat this information in your reply\.\n<\/system-reminder>(?:\n|$)/;
37444
+ function textBlocks(value, type) {
37445
+ if (typeof value === "string")
37446
+ return [value];
37447
+ if (!Array.isArray(value))
37448
+ return;
37449
+ const texts = [];
37450
+ for (const block of value) {
37451
+ const part = record3(block);
37452
+ if (part?.type !== type || typeof part.text !== "string")
37453
+ return;
37454
+ texts.push(part.text);
37455
+ }
37456
+ return texts;
37457
+ }
37458
+ function isCapturePrompt(row, type) {
37459
+ if (row.role !== "user" && row.role !== "developer")
37460
+ return false;
37461
+ const texts = textBlocks(row.content, type);
37462
+ if (!texts?.length)
37463
+ return false;
37464
+ let [first, ...rest] = texts;
37465
+ first = first.replace(DATE_CWD_REMINDER, "");
37466
+ if (first === "" && rest.length)
37467
+ [first, ...rest] = rest;
37468
+ return rest.length === 0 && first === OMP_AUTOLEARN_CAPTURE_PROMPT;
37469
+ }
37470
+ var RESPONSES_TURN_ITEMS = new Set([
37471
+ "reasoning",
37472
+ "function_call",
37473
+ "function_call_output",
37474
+ "custom_tool_call",
37475
+ "custom_tool_call_output"
37476
+ ]);
37477
+ function isCaptureTurnRow(row) {
37478
+ if (row.role === "assistant" || row.role === "tool")
37479
+ return true;
37480
+ if (typeof row.type === "string" && RESPONSES_TURN_ITEMS.has(row.type))
37481
+ return true;
37482
+ if (isOmpJuiceItem(row))
37483
+ return true;
37484
+ return row.role === "user" && Array.isArray(row.content) && row.content.length > 0 && row.content.every((block) => record3(block)?.type === "tool_result");
37485
+ }
37486
+ function isOmpAutolearnCapture(payload) {
37487
+ const request = providerRequest(payload);
37488
+ if (!request?.tools.some((name) => name === "manage_skill" || name === "learn"))
37489
+ return false;
37490
+ for (let index = request.messages.length - 1;index >= 0; index--) {
37491
+ const row = record3(request.messages[index]);
37492
+ if (!row)
37493
+ return false;
37494
+ if (isCaptureTurnRow(row))
37495
+ continue;
37496
+ return isCapturePrompt(row, request.textType);
37497
+ }
37498
+ return false;
37499
+ }
37500
+ var JUICE_VALUES = new Set(["0", "2", "4", "8", "48", "112", "960"]);
37501
+ function isOmpJuiceItem(value) {
37502
+ const item = record3(value);
37503
+ if (!item || Object.keys(item).length !== 2 || item.role !== "developer")
37504
+ return false;
37505
+ const content = item.content;
37506
+ if (!Array.isArray(content) || content.length !== 1)
37507
+ return false;
37508
+ const part = record3(content[0]);
37509
+ if (!part || Object.keys(part).length !== 2 || part.type !== "input_text")
37510
+ return false;
37511
+ const juice = /^# Juice: (\d+) !important$/.exec(String(part.text));
37512
+ return juice !== null && JUICE_VALUES.has(juice[1]);
37513
+ }
37514
+ function piWithoutOmpJuice(payload, model) {
37515
+ const body = record3(payload);
37516
+ if (model?.api !== "openai-responses" || record3(model.compat)?.requiresReasoningOffJuiceInstruction !== true || !body || !Array.isArray(body.input) || !isOmpJuiceItem(body.input.at(-1)))
37517
+ return payload;
37518
+ return { ...body, input: body.input.slice(0, -1) };
37519
+ }
37048
37520
 
37049
37521
  // src/pi-dispatch-date-reminder.ts
37050
37522
  function object(value) {
@@ -37857,7 +38329,7 @@ ${wellFormed2(text)}
37857
38329
  </think>`;
37858
38330
  return;
37859
38331
  }
37860
- function coldReplayable(items) {
38332
+ function piResponsesColdReplayable(items) {
37861
38333
  let reasoning = false;
37862
38334
  for (const value of items) {
37863
38335
  const item = object8(value);
@@ -37979,7 +38451,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
37979
38451
  return texts;
37980
38452
  if (unsigned && alternatives) {
37981
38453
  alternatives.fallback = texts;
37982
- alternatives.cold = coldReplayable(payload.items) ? replay : texts;
38454
+ alternatives.cold = piResponsesColdReplayable(payload.items) ? replay : texts;
37983
38455
  }
37984
38456
  return replay;
37985
38457
  }
@@ -38004,15 +38476,270 @@ function piResponsesWireTexts(value, phase) {
38004
38476
  return texts;
38005
38477
  }
38006
38478
 
38479
+ // src/pi-dispatch-responses-replay.ts
38480
+ function object9(value) {
38481
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38482
+ }
38483
+ var RESPONSES_APIS3 = ["openai-responses", "azure-openai-responses"];
38484
+ function callBase(id) {
38485
+ const separator = id.search(/[\n|]/);
38486
+ return separator > 0 ? id.slice(0, separator) : separator === 0 ? id.slice(1) : id;
38487
+ }
38488
+ function piResponsesReplayedCalls(value, calls, wireCalls, model) {
38489
+ const message = object9(value);
38490
+ if (message?.role !== "assistant" || !model?.api)
38491
+ return;
38492
+ if (!RESPONSES_APIS3.includes(model.api))
38493
+ return;
38494
+ if (message.api !== model.api || message.model !== model.id || typeof model.provider !== "string")
38495
+ return;
38496
+ const payload = object9(message.providerPayload);
38497
+ if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items) || (payload.provider ?? message.provider ?? model.provider) !== model.provider)
38498
+ return;
38499
+ const stored = [];
38500
+ const order = [];
38501
+ let output = false;
38502
+ for (const value of payload.items) {
38503
+ const item = object9(value);
38504
+ if (item?.type === "reasoning")
38505
+ continue;
38506
+ if (item?.type === "function_call" || item?.type === "custom_tool_call") {
38507
+ if (typeof item.call_id !== "string" || !item.call_id.trim())
38508
+ return;
38509
+ stored.push(item.call_id);
38510
+ order.push("call");
38511
+ output = true;
38512
+ continue;
38513
+ }
38514
+ if (item?.type !== "message" || item.role !== "assistant" || !Array.isArray(item.content))
38515
+ return;
38516
+ const texts = [];
38517
+ for (const value of item.content) {
38518
+ const part = object9(value);
38519
+ if (part?.type !== "output_text" || typeof part.text !== "string")
38520
+ return;
38521
+ texts.push(part.text);
38522
+ }
38523
+ if (!texts.some((text) => /\S/u.test(text)))
38524
+ continue;
38525
+ output = true;
38526
+ for (const _text of texts)
38527
+ order.push("text");
38528
+ }
38529
+ if (!output)
38530
+ return;
38531
+ const recorded = new Set(stored.map(callBase));
38532
+ const replayed = [...stored];
38533
+ const wires = [...stored];
38534
+ for (let index = 0;index < calls.length; index++) {
38535
+ if (recorded.has(callBase(calls[index])))
38536
+ continue;
38537
+ const wire = wireCalls?.[index];
38538
+ if (wire === undefined)
38539
+ return;
38540
+ replayed.push(calls[index]);
38541
+ wires.push(wire);
38542
+ order.push("call");
38543
+ }
38544
+ if (wireCalls && wires.length === wireCalls.length && wires.every((id, index) => id === wireCalls[index]))
38545
+ return;
38546
+ return {
38547
+ calls: replayed,
38548
+ wireCalls: wires,
38549
+ stored: stored.length,
38550
+ order,
38551
+ cold: piResponsesColdReplayable(payload.items)
38552
+ };
38553
+ }
38554
+ function batchKind(item) {
38555
+ return item.kind === "text" ? "assistant-message" : item.kind === "call" || item.kind === "output" ? item.kind : "other";
38556
+ }
38557
+ function batchCallId(item) {
38558
+ return item.kind === "call" ? item.wire : item.kind === "output" ? item.id : undefined;
38559
+ }
38560
+ function hoistBatchMessages(items) {
38561
+ const hasEarlierBatchCall = (index, callId) => {
38562
+ for (let probe = index - 1;probe >= 0; probe--) {
38563
+ const kind = batchKind(items[probe]);
38564
+ if (kind === "other")
38565
+ return false;
38566
+ if (kind === "call" && batchCallId(items[probe]) === callId)
38567
+ return true;
38568
+ }
38569
+ return false;
38570
+ };
38571
+ const bucketOf = new Map;
38572
+ const insertBefore = new Map;
38573
+ for (let index = 0;index < items.length; index++) {
38574
+ if (batchKind(items[index]) !== "output")
38575
+ continue;
38576
+ if (index > 0 && batchKind(items[index - 1]) === "output")
38577
+ continue;
38578
+ const pending = new Set;
38579
+ for (let probe = index;probe < items.length; probe++) {
38580
+ if (batchKind(items[probe]) !== "output")
38581
+ break;
38582
+ const callId = batchCallId(items[probe]);
38583
+ if (callId)
38584
+ pending.add(callId);
38585
+ }
38586
+ let start = index;
38587
+ let sawCall = false;
38588
+ const messageIndexes = [];
38589
+ while (start > 0) {
38590
+ const item = items[start - 1];
38591
+ const kind = batchKind(item);
38592
+ if (kind === "call") {
38593
+ sawCall = true;
38594
+ const callId = batchCallId(item);
38595
+ if (callId)
38596
+ pending.delete(callId);
38597
+ } else if (kind === "output") {
38598
+ const callId = batchCallId(item);
38599
+ if (!callId || !hasEarlierBatchCall(start - 1, callId))
38600
+ break;
38601
+ let ownsEarlierCall = false;
38602
+ for (const owned of pending) {
38603
+ if (hasEarlierBatchCall(start - 1, owned)) {
38604
+ ownsEarlierCall = true;
38605
+ break;
38606
+ }
38607
+ }
38608
+ if (!ownsEarlierCall)
38609
+ break;
38610
+ pending.add(callId);
38611
+ } else if (kind === "assistant-message") {
38612
+ messageIndexes.push(start - 1);
38613
+ } else {
38614
+ break;
38615
+ }
38616
+ start -= 1;
38617
+ }
38618
+ if (!sawCall || messageIndexes.length === 0)
38619
+ continue;
38620
+ messageIndexes.reverse();
38621
+ const target = insertBefore.get(start) ?? [];
38622
+ for (const messageIndex of messageIndexes) {
38623
+ const previousStart = bucketOf.get(messageIndex);
38624
+ if (previousStart !== undefined) {
38625
+ const previous = insertBefore.get(previousStart);
38626
+ const slot = previous?.indexOf(messageIndex) ?? -1;
38627
+ if (previous && slot >= 0)
38628
+ previous.splice(slot, 1);
38629
+ }
38630
+ bucketOf.set(messageIndex, start);
38631
+ target.push(messageIndex);
38632
+ }
38633
+ insertBefore.set(start, target);
38634
+ }
38635
+ if (bucketOf.size === 0)
38636
+ return items.slice();
38637
+ const result = [];
38638
+ for (let index = 0;index < items.length; index++) {
38639
+ const pending = insertBefore.get(index);
38640
+ if (pending)
38641
+ for (const messageIndex of pending)
38642
+ result.push(items[messageIndex]);
38643
+ if (bucketOf.has(index))
38644
+ continue;
38645
+ result.push(items[index]);
38646
+ }
38647
+ return result;
38648
+ }
38649
+ function piResponsesReplayRows(entries, placeholder, assistant) {
38650
+ const items = [];
38651
+ for (const entry of entries) {
38652
+ const row = entry.row;
38653
+ if (entry.texts === undefined) {
38654
+ if (row.role !== "toolResult") {
38655
+ items.push({ kind: "other", row });
38656
+ continue;
38657
+ }
38658
+ const wire = row.wireResults?.[0];
38659
+ if (row.results.length !== 1 || wire === undefined)
38660
+ return;
38661
+ items.push({ kind: "output", id: wire, row });
38662
+ continue;
38663
+ }
38664
+ const { texts, replayed } = entry;
38665
+ if (replayed) {
38666
+ const textSlots = replayed.order.filter((kind) => kind === "text");
38667
+ if (textSlots.length !== texts.length)
38668
+ return;
38669
+ let text = 0;
38670
+ let call = 0;
38671
+ for (const kind of replayed.order) {
38672
+ if (kind === "text")
38673
+ items.push({ kind: "text", text: texts[text++], source: row });
38674
+ else {
38675
+ items.push({
38676
+ kind: "call",
38677
+ id: replayed.calls[call],
38678
+ wire: replayed.wireCalls[call],
38679
+ source: row
38680
+ });
38681
+ call++;
38682
+ }
38683
+ }
38684
+ continue;
38685
+ }
38686
+ for (const text of texts)
38687
+ items.push({ kind: "text", text, source: row });
38688
+ for (let index = 0;index < row.calls.length; index++) {
38689
+ const wire = row.wireCalls?.[index];
38690
+ if (wire === undefined)
38691
+ return;
38692
+ items.push({ kind: "call", id: row.calls[index], wire, source: row });
38693
+ }
38694
+ }
38695
+ const preceding = new Set;
38696
+ for (const item of items) {
38697
+ if (item.kind === "call")
38698
+ preceding.add(item.wire);
38699
+ else if (item.kind === "output" && !preceding.has(item.id))
38700
+ return;
38701
+ }
38702
+ const later = new Set;
38703
+ const orphans = new Set;
38704
+ for (let index = items.length - 1;index >= 0; index--) {
38705
+ const item = items[index];
38706
+ if (item.kind === "output")
38707
+ later.add(item.id);
38708
+ else if (item.kind === "call" && !later.has(item.wire))
38709
+ orphans.add(index);
38710
+ }
38711
+ const repaired = items.flatMap((item, index) => item.kind === "call" && orphans.has(index) ? [item, { kind: "output", id: item.wire }] : [item]);
38712
+ const rows = [];
38713
+ let open;
38714
+ for (const item of hoistBatchMessages(repaired)) {
38715
+ if (item.kind === "other" || item.kind === "output") {
38716
+ rows.push(item.kind === "other" ? item.row : item.row ?? placeholder(item.id));
38717
+ open = undefined;
38718
+ continue;
38719
+ }
38720
+ if (!open) {
38721
+ open = assistant(item.source);
38722
+ rows.push(open);
38723
+ }
38724
+ if (item.kind === "text")
38725
+ open.responseTexts?.push(item.text);
38726
+ else {
38727
+ open.calls.push(item.id);
38728
+ open.wireCalls?.push(item.wire);
38729
+ }
38730
+ }
38731
+ return rows;
38732
+ }
38733
+
38007
38734
  // src/pi-dispatch-row-diagnostic.ts
38008
- var object9 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38735
+ var object10 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38009
38736
  function piDispatchRowDiagnostic(role, content) {
38010
38737
  const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : [];
38011
38738
  let kinds = 0;
38012
38739
  let chars = 0;
38013
38740
  let onlyText;
38014
38741
  for (const part of parts) {
38015
- const block = object9(part);
38742
+ const block = object10(part);
38016
38743
  const text = typeof part === "string" ? part : block?.text;
38017
38744
  if (typeof text === "string") {
38018
38745
  kinds |= block?.thought === true ? 16 : 1;
@@ -38143,11 +38870,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
38143
38870
  "devin-agent",
38144
38871
  "apple-foundation-models"
38145
38872
  ]);
38146
- function object10(value) {
38873
+ function object11(value) {
38147
38874
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38148
38875
  }
38149
38876
  function messageStructure(value) {
38150
- const message = object10(value);
38877
+ const message = object11(value);
38151
38878
  if (!message)
38152
38879
  return;
38153
38880
  const role = [
@@ -38177,7 +38904,7 @@ function messageStructure(value) {
38177
38904
  }
38178
38905
  if (role === "assistant" && Array.isArray(message.content)) {
38179
38906
  for (const value of message.content) {
38180
- const block = object10(value);
38907
+ const block = object11(value);
38181
38908
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
38182
38909
  continue;
38183
38910
  if (typeof block.id !== "string")
@@ -38193,7 +38920,7 @@ function windowCalls(message) {
38193
38920
  if (!Array.isArray(message.content))
38194
38921
  return [];
38195
38922
  return message.content.flatMap((value) => {
38196
- const block = object10(value);
38923
+ const block = object11(value);
38197
38924
  return block?.type === "toolCall" && typeof block.id === "string" ? [
38198
38925
  {
38199
38926
  id: block.id,
@@ -38203,7 +38930,7 @@ function windowCalls(message) {
38203
38930
  });
38204
38931
  }
38205
38932
  function duplicateSuffix(model) {
38206
- const compat = object10(model?.compat);
38933
+ const compat = object11(model?.compat);
38207
38934
  if (model?.api === "openai-completions") {
38208
38935
  if (compat?.requiresMistralToolIds === true)
38209
38936
  return { prefix: "dup", max: 9 };
@@ -38218,24 +38945,14 @@ function appendDuplicateSuffix(id, suffix, max) {
38218
38945
  const segment = (part) => part.length + suffix.length <= max ? `${part}${suffix}` : `${part.slice(0, Math.max(0, max - suffix.length))}${suffix}`;
38219
38946
  return id.includes("|") ? id.split("|").map(segment).join("|") : segment(id);
38220
38947
  }
38221
- function projectMissingToolResults(messages, model, host = "omp") {
38222
- const input = messages.filter((value) => {
38223
- const message = object10(value);
38224
- return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
38225
- });
38226
- if (host === "pi")
38227
- return projectPiToolResults(input);
38228
- const api = model?.api;
38229
- if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
38230
- return projectUnmodeledToolResults(messages);
38231
- const pairingId = piToolCallPairing(input);
38948
+ function deduplicateToolCallIds(input, pairingId, model) {
38232
38949
  const { prefix, max } = duplicateSuffix(model);
38233
38950
  const seen = new Map;
38234
38951
  const renames = new Map;
38235
38952
  const realResults = new Map;
38236
38953
  const validToolUseIds = new Set;
38237
38954
  const deduplicated = input.map((value, index) => {
38238
- const message = object10(value);
38955
+ const message = object11(value);
38239
38956
  if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
38240
38957
  let key = pairingId(message.toolCallId);
38241
38958
  let output = value;
@@ -38262,7 +38979,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38262
38979
  const touched = new Set;
38263
38980
  let changed = false;
38264
38981
  const content = message.content.map((part) => {
38265
- const block = object10(part);
38982
+ const block = object11(part);
38266
38983
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38267
38984
  return part;
38268
38985
  const key = pairingId(block.id);
@@ -38294,6 +39011,25 @@ function projectMissingToolResults(messages, model, host = "omp") {
38294
39011
  validToolUseIds.add(pairingId(call.id));
38295
39012
  return changed ? { ...message, content } : value;
38296
39013
  });
39014
+ return { deduplicated, realResults, validToolUseIds };
39015
+ }
39016
+ function piDeduplicatedToolCallIds(messages, model) {
39017
+ if (!TRANSFORM_MESSAGES_APIS.has(model?.api ?? ""))
39018
+ return [...messages];
39019
+ return deduplicateToolCallIds(messages, piToolCallPairing(messages), model).deduplicated;
39020
+ }
39021
+ function projectMissingToolResults(messages, model, host = "omp") {
39022
+ const input = messages.filter((value) => {
39023
+ const message = object11(value);
39024
+ return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
39025
+ });
39026
+ if (host === "pi")
39027
+ return projectPiToolResults(input);
39028
+ const api = model?.api;
39029
+ if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
39030
+ return projectUnmodeledToolResults(messages);
39031
+ const pairingId = piToolCallPairing(input);
39032
+ const { deduplicated, realResults, validToolUseIds } = deduplicateToolCallIds(input, pairingId, model);
38297
39033
  const takeRealResult = (id, afterIndex) => {
38298
39034
  for (const entry of realResults.get(pairingId(id)) ?? []) {
38299
39035
  if (entry.consumed || entry.index <= afterIndex)
@@ -38341,7 +39077,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38341
39077
  };
38342
39078
  for (let index = 0;index < deduplicated.length; index++) {
38343
39079
  const value = deduplicated[index];
38344
- const message = object10(value);
39080
+ const message = object11(value);
38345
39081
  if (message?.role === "assistant") {
38346
39082
  flush(message.timestamp);
38347
39083
  if (piOmitsTruncatedAssistant(message))
@@ -38382,7 +39118,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38382
39118
  if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
38383
39119
  continue;
38384
39120
  const parts = message.content.flatMap((value) => {
38385
- const part = object10(value);
39121
+ const part = object11(value);
38386
39122
  return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
38387
39123
  });
38388
39124
  if (!parts.length)
@@ -38410,11 +39146,11 @@ function projectUnmodeledToolResults(messages) {
38410
39146
  return pipe > 0 ? id.slice(0, pipe) : id;
38411
39147
  };
38412
39148
  for (const value of messages) {
38413
- const message = object10(value);
39149
+ const message = object11(value);
38414
39150
  if (message?.role !== "assistant" || !Array.isArray(message.content))
38415
39151
  continue;
38416
39152
  for (const value of message.content) {
38417
- const block = object10(value);
39153
+ const block = object11(value);
38418
39154
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38419
39155
  continue;
38420
39156
  if ([
@@ -38430,7 +39166,7 @@ function projectUnmodeledToolResults(messages) {
38430
39166
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
38431
39167
  const lastResult = new Map;
38432
39168
  messages.forEach((value, index) => {
38433
- const message = object10(value);
39169
+ const message = object11(value);
38434
39170
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
38435
39171
  lastResult.set(pairingId(message.toolCallId), index);
38436
39172
  });
@@ -38461,7 +39197,7 @@ function projectUnmodeledToolResults(messages) {
38461
39197
  };
38462
39198
  for (let index = 0;index < messages.length; index++) {
38463
39199
  const value = messages[index];
38464
- const message = object10(value);
39200
+ const message = object11(value);
38465
39201
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
38466
39202
  continue;
38467
39203
  if (message?.role !== "toolResult")
@@ -38503,7 +39239,7 @@ function projectPiToolResults(messages) {
38503
39239
  held.length = 0;
38504
39240
  };
38505
39241
  for (const value of messages) {
38506
- const message = object10(value);
39242
+ const message = object11(value);
38507
39243
  const role = message?.role;
38508
39244
  if (role === "assistant") {
38509
39245
  close(message?.timestamp);
@@ -38534,7 +39270,7 @@ function projectPiToolResults(messages) {
38534
39270
  function preparePiDispatch(messages, model, omp, cwd) {
38535
39271
  let output = messages;
38536
39272
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
38537
- if (object10(source.providerPayload)?.type !== "openaiResponsesHistory")
39273
+ if (object11(source.providerPayload)?.type !== "openaiResponsesHistory")
38538
39274
  return;
38539
39275
  if (output === messages)
38540
39276
  output = messages.slice();
@@ -38555,7 +39291,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38555
39291
  if (!messages.length || messages.length > MAX_MESSAGES)
38556
39292
  return;
38557
39293
  for (let index = 0;index < messages.length; index++) {
38558
- const source = object10(messages[index]);
39294
+ const source = object11(messages[index]);
38559
39295
  if (source?.role === "user" || source?.role === "compactionSummary")
38560
39296
  prepareUser?.(index, source);
38561
39297
  }
@@ -38572,7 +39308,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38572
39308
  let valid = true;
38573
39309
  for (let index = 0;index < projectedMessages.length; index++) {
38574
39310
  const message = projectedMessages[index];
38575
- const source = object10(message);
39311
+ const source = object11(message);
38576
39312
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
38577
39313
  continue;
38578
39314
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -38596,7 +39332,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38596
39332
  "azure-openai-responses",
38597
39333
  "openai-codex-responses"
38598
39334
  ].includes(model?.api ?? "") && (source?.role === "user" || source?.role === "developer") && (typeof source.content === "string" ? !source.content.trim() : Array.isArray(source.content) && !source.content.some((value) => {
38599
- const block = object10(value);
39335
+ const block = object11(value);
38600
39336
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
38601
39337
  })))
38602
39338
  continue;
@@ -38640,12 +39376,12 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38640
39376
  const positionedRows = [...byIndex];
38641
39377
  for (let position = positionedRows.length - 1;position >= 0; position--) {
38642
39378
  const [index, row] = positionedRows[position];
38643
- const source = object10(projectedMessages[index]);
39379
+ const source = object11(projectedMessages[index]);
38644
39380
  if (!source)
38645
39381
  return;
38646
39382
  const content = source.content;
38647
39383
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
38648
- const textOnly = Array.isArray(parts) && parts.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string");
39384
+ const textOnly = Array.isArray(parts) && parts.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string");
38649
39385
  const systemTexts = () => {
38650
39386
  const texts = parts.map((part) => part.text);
38651
39387
  return model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
@@ -38653,7 +39389,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38653
39389
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
38654
39390
  const previous = rows[position - 1];
38655
39391
  const next = rows[position + 1];
38656
- const anthropicPromotable = model?.api === "anthropic-messages" && object10(model.compat)?.supportsMidConversationSystem === true && textOnly;
39392
+ const anthropicPromotable = model?.api === "anthropic-messages" && object11(model.compat)?.supportsMidConversationSystem === true && textOnly;
38657
39393
  if (anthropicPromotable)
38658
39394
  promotable.set(row, systemTexts());
38659
39395
  if (model?.api === "ollama-chat" || anthropicPromotable && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
@@ -38682,6 +39418,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38682
39418
  const fallbackMessages = [];
38683
39419
  const coldMessages = [];
38684
39420
  let unsignedAlternatives = false;
39421
+ const planRows = [];
38685
39422
  const appendResponse = (output, row, texts) => {
38686
39423
  if (!texts.length && !row.calls.length)
38687
39424
  return;
@@ -38704,6 +39441,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38704
39441
  responsesMessages.push(row);
38705
39442
  fallbackMessages.push(row);
38706
39443
  coldMessages.push(row);
39444
+ planRows.push({ row });
38707
39445
  continue;
38708
39446
  }
38709
39447
  const alternatives = {};
@@ -38716,8 +39454,42 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38716
39454
  appendResponse(responsesMessages, row, texts);
38717
39455
  appendResponse(fallbackMessages, row, alternatives.fallback ?? texts);
38718
39456
  appendResponse(coldMessages, row, alternatives.cold ?? texts);
39457
+ planRows.push({
39458
+ row,
39459
+ texts: {
39460
+ warm: texts,
39461
+ fallback: alternatives.fallback ?? texts,
39462
+ cold: alternatives.cold ?? texts
39463
+ },
39464
+ replayed: host === "omp" ? piResponsesReplayedCalls(projectedMessages[index], row.calls, row.wireCalls, model) : undefined
39465
+ });
38719
39466
  }
38720
39467
  }
39468
+ const replays = planRows.some((entry) => entry.replayed);
39469
+ const replayPlan = (rows, plan) => {
39470
+ if (!replays)
39471
+ return rows;
39472
+ const replayedIn = (entry) => plan === "warm" || plan === "cold" && entry.replayed?.cold ? entry.replayed : undefined;
39473
+ if (!planRows.some(replayedIn))
39474
+ return rows;
39475
+ return piResponsesReplayRows(planRows.map((entry) => entry.texts ? {
39476
+ row: entry.row,
39477
+ texts: entry.texts[plan],
39478
+ replayed: replayedIn(entry)
39479
+ } : { row: entry.row }), (callId) => ({
39480
+ role: "toolResult",
39481
+ calls: [],
39482
+ results: [callId],
39483
+ wireResults: [callId]
39484
+ }), (source) => ({
39485
+ ...source,
39486
+ calls: [],
39487
+ wireCalls: [],
39488
+ responseTexts: []
39489
+ })) ?? rows;
39490
+ };
39491
+ if (responsesMessages)
39492
+ responsesMessages = replayPlan(responsesMessages, "warm");
38721
39493
  const plan = piChatHistoryPlan(projectedMessages, model);
38722
39494
  let pendingToolImages = [];
38723
39495
  const chatMessages = plan?.flatMap((step) => {
@@ -38750,12 +39522,17 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38750
39522
  ...responsesApi && !responsesMessages ? { structuralSkipReason: "Responses history transform is not modeled" } : model?.api === "openai-completions" && !chatMessages ? { structuralSkipReason: "Chat history transform is not modeled" } : {},
38751
39523
  ...chatMessages ? { chatMessages } : {},
38752
39524
  ...responsesMessages ? { responsesMessages } : {},
38753
- ...responsesMessages && unsignedAlternatives ? { responsesAlternatives: [fallbackMessages, coldMessages] } : {},
39525
+ ...responsesMessages && (unsignedAlternatives || replays) ? {
39526
+ responsesAlternatives: [
39527
+ replayPlan(fallbackMessages, "fallback"),
39528
+ replayPlan(coldMessages, "cold")
39529
+ ]
39530
+ } : {},
38754
39531
  ...model?.api ? { api: model.api } : {},
38755
39532
  ...modelsContinuePad ? { anthropicContinuePad: true } : {},
38756
39533
  ...modelsContinuePad && baseRows.some((row) => row.optionalThinking) ? { anthropicOptional: { rows: baseRows, promotable } } : {},
38757
39534
  ...model?.api?.startsWith("google-") ? {
38758
- googleFunctionIds: object10(model.compat)?.supportsFunctionPartId === true
39535
+ googleFunctionIds: object11(model.compat)?.supportsFunctionPartId === true
38759
39536
  } : {}
38760
39537
  };
38761
39538
  preparedSources.set(prepared, { messages: projectedMessages, rows: byIndex });
@@ -38763,8 +39540,8 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38763
39540
  dateReminderPlans.set(prepared, {
38764
39541
  ...modelsContinuePad ? { plan: { rows: baseRows, promotable } } : {},
38765
39542
  firstUser: firstUserRow ? baseRows.indexOf(firstUserRow) : -1,
38766
- midConversationSystem: object10(model?.compat)?.supportsMidConversationSystem === true,
38767
- developerRole: object10(model?.compat)?.supportsDeveloperRole === true
39543
+ midConversationSystem: object11(model?.compat)?.supportsMidConversationSystem === true,
39544
+ developerRole: object11(model?.compat)?.supportsDeveloperRole === true
38768
39545
  });
38769
39546
  return prepared;
38770
39547
  }
@@ -38784,7 +39561,7 @@ function responsesLane(api) {
38784
39561
  ].includes(api ?? "");
38785
39562
  }
38786
39563
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false, trackRows = false) {
38787
- const body = object10(payload);
39564
+ const body = object11(payload);
38788
39565
  if (!body)
38789
39566
  return;
38790
39567
  const google = piGoogleConversation(payload);
@@ -38799,12 +39576,12 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38799
39576
  return;
38800
39577
  const rows = [];
38801
39578
  for (const value of messages) {
38802
- const message = object10(value);
39579
+ const message = object11(value);
38803
39580
  if (!message)
38804
39581
  return;
38805
39582
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
38806
39583
  continue;
38807
- if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object10(block)?.type))))
39584
+ if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object11(block)?.type))))
38808
39585
  continue;
38809
39586
  if (responses && message.type === "reasoning")
38810
39587
  continue;
@@ -38881,7 +39658,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38881
39658
  continue;
38882
39659
  }
38883
39660
  if (message.role === "user" && Array.isArray(message.content)) {
38884
- const results = message.content.filter((block) => object10(block)?.type === "tool_result" || bedrock && object10(block)?.toolResult);
39661
+ const results = message.content.filter((block) => object11(block)?.type === "tool_result" || bedrock && object11(block)?.toolResult);
38885
39662
  if (results.length) {
38886
39663
  for (const block of results) {
38887
39664
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -38938,11 +39715,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38938
39715
  }
38939
39716
  if (Array.isArray(message.tool_calls)) {
38940
39717
  for (const call of message.tool_calls) {
38941
- const source = object10(call);
39718
+ const source = object11(call);
38942
39719
  if (!source)
38943
39720
  return;
38944
39721
  if (source.id === undefined && ollama) {
38945
- const fn = object10(source.function);
39722
+ const fn = object11(source.function);
38946
39723
  if (typeof fn?.name !== "string")
38947
39724
  return;
38948
39725
  row.calls.push("");
@@ -38982,7 +39759,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38982
39759
  return;
38983
39760
  const rows = [];
38984
39761
  for (const value of contents) {
38985
- const message = object10(value);
39762
+ const message = object11(value);
38986
39763
  if (!message || !Array.isArray(message.parts))
38987
39764
  return;
38988
39765
  if (message.role !== "user" && message.role !== "model")
@@ -38998,11 +39775,11 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38998
39775
  };
38999
39776
  const results = [];
39000
39777
  for (const value of message.parts) {
39001
- const part = object10(value);
39778
+ const part = object11(value);
39002
39779
  if (!part)
39003
39780
  return;
39004
39781
  if (part.functionCall) {
39005
- const call = object10(part.functionCall);
39782
+ const call = object11(part.functionCall);
39006
39783
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
39007
39784
  return;
39008
39785
  row.calls.push(call.id ?? "");
@@ -39010,7 +39787,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39010
39787
  row.callNames.push(call.name);
39011
39788
  }
39012
39789
  if (part.functionResponse) {
39013
- const result = object10(part.functionResponse);
39790
+ const result = object11(part.functionResponse);
39014
39791
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
39015
39792
  return;
39016
39793
  results.push({
@@ -39025,7 +39802,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39025
39802
  role: "tool-result",
39026
39803
  parts: 1,
39027
39804
  kinds: 8,
39028
- chars: typeof result.response === "string" ? result.response.length : Object.values(object10(result.response) ?? {}).reduce((count, value) => count + (typeof value === "string" ? value.length : 0), 0),
39805
+ chars: typeof result.response === "string" ? result.response.length : Object.values(object11(result.response) ?? {}).reduce((count, value) => count + (typeof value === "string" ? value.length : 0), 0),
39029
39806
  injector: "none"
39030
39807
  });
39031
39808
  }
@@ -39045,6 +39822,10 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39045
39822
  }
39046
39823
  return rows;
39047
39824
  }
39825
+ function sameResponsesIds(expected, actual) {
39826
+ const same = (ids, wire) => ids.length === wire.length && ids.every((id, index) => id === wire[index]);
39827
+ return expected.every((row, index) => !!actual[index] && same(row.wireCalls ?? row.calls.map((id) => wireId(id, false, true)), actual[index].calls) && same(row.wireResults ?? row.results.map((id) => wireId(id, false, true)), actual[index].results));
39828
+ }
39048
39829
  function wireId(id, anthropic, responses) {
39049
39830
  if (anthropic)
39050
39831
  return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
@@ -39058,11 +39839,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
39058
39839
  if (responses || googleOrBedrock) {
39059
39840
  if (!Array.isArray(content) || content.length !== 1)
39060
39841
  return false;
39061
- const block = object10(content[0]);
39842
+ const block = object11(content[0]);
39062
39843
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
39063
39844
  }
39064
39845
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
39065
- const block = content.length === 1 ? object10(content[0]) : undefined;
39846
+ const block = content.length === 1 ? object11(content[0]) : undefined;
39066
39847
  return block?.type === "text" && block.text === text;
39067
39848
  }
39068
39849
  return content === text;
@@ -39248,15 +40029,15 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39248
40029
  }))) : undefined;
39249
40030
  const plan = prepared && dateReminderPlans.get(prepared);
39250
40031
  try {
39251
- const body = plan ? object10(payload) : undefined;
40032
+ const body = plan ? object11(payload) : undefined;
39252
40033
  const messages = body?.messages ?? body?.input;
39253
40034
  if (Array.isArray(messages)) {
39254
40035
  for (const value of messages) {
39255
- const message = object10(value);
40036
+ const message = object11(value);
39256
40037
  if (message?.role !== "system" && message?.role !== "developer")
39257
40038
  break;
39258
40039
  const content = message.content;
39259
- const inputText = Array.isArray(content) && content.length === 1 && object10(content[0])?.type === "input_text" ? object10(content[0])?.text : undefined;
40040
+ const inputText = Array.isArray(content) && content.length === 1 && object11(content[0])?.type === "input_text" ? object11(content[0])?.text : undefined;
39260
40041
  if (piDateReminderWireText(content, plan?.cwd) !== undefined || piDateReminderText(inputText, plan?.cwd))
39261
40042
  return "comparison=role";
39262
40043
  }
@@ -39272,7 +40053,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39272
40053
  if (plan.firstUser < 0)
39273
40054
  return mismatch;
39274
40055
  const root = prepared.messages[plan.firstUser];
39275
- const body = object10(payload);
40056
+ const body = object11(payload);
39276
40057
  const routeRows = Array.isArray(body?.input) ? prepared.responsesMessages ?? prepared.messages : prepared.api === "openai-completions" ? prepared.chatMessages ?? prepared.messages : prepared.messages;
39277
40058
  const firstUser = routeRows.indexOf(root);
39278
40059
  if (firstUser < 0)
@@ -39283,11 +40064,11 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39283
40064
  });
39284
40065
  return filtered === undefined ? mismatch : preparedStructureMismatch(filtered, prepared, onImageTrim, undefined, undefined, undefined, aligned);
39285
40066
  }
39286
- const messages = object10(payload)?.messages;
40067
+ const messages = object11(payload)?.messages;
39287
40068
  if (!Array.isArray(messages))
39288
40069
  return mismatch;
39289
40070
  for (const value of messages) {
39290
- const message = object10(value);
40071
+ const message = object11(value);
39291
40072
  if (piDateReminderWireText(message?.content, plan.cwd) !== undefined && Object.keys(message ?? {}).some((key) => !["role", "content"].includes(key)))
39292
40073
  return mismatch;
39293
40074
  }
@@ -39327,7 +40108,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39327
40108
  return "comparison=image count";
39328
40109
  const imageProjection = trimmed > 0;
39329
40110
  stage = "wire rows";
39330
- const body = object10(payload);
40111
+ const body = object11(payload);
39331
40112
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
39332
40113
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39333
40114
  rows = reminderWire ?? payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection, !!onAlignment);
@@ -39336,7 +40117,12 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39336
40117
  expectedRows = responses && prepared?.responsesMessages ? prepared.responsesMessages : chat && prepared?.chatMessages ? prepared.chatMessages : prepared?.messages;
39337
40118
  if (responses && rows && prepared?.responsesAlternatives) {
39338
40119
  const actual = rows;
39339
- expectedRows = [prepared.responsesMessages, ...prepared.responsesAlternatives].find((candidate) => candidate?.length === actual.length && candidate.every((expected, index) => JSON.stringify(expected.responseTexts) === JSON.stringify(actual[index].responseTexts))) ?? expectedRows;
40120
+ const candidates = [
40121
+ prepared.responsesMessages,
40122
+ ...prepared.responsesAlternatives
40123
+ ];
40124
+ const sameTexts = (candidate) => candidate?.length === actual.length && candidate.every((expected, index) => JSON.stringify(expected.responseTexts) === JSON.stringify(actual[index].responseTexts));
40125
+ expectedRows = candidates.find((candidate) => sameTexts(candidate) && !!candidate && sameResponsesIds(candidate, actual)) ?? candidates.find(sameTexts) ?? expectedRows;
39340
40126
  }
39341
40127
  const optionalPlan = expectedRows === prepared?.messages ? prepared?.anthropicOptional : undefined;
39342
40128
  if (expectedRows && imageProjection && imageBudget)
@@ -39354,7 +40140,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39354
40140
  if (expected.systemText !== undefined) {
39355
40141
  const texts = expected.systemText;
39356
40142
  const content = actual.wireContent;
39357
- const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string") ? content.map((part) => part.text) : undefined;
40143
+ const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string") ? content.map((part) => part.text) : undefined;
39358
40144
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
39359
40145
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
39360
40146
  return "content";
@@ -39451,7 +40237,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39451
40237
  }
39452
40238
  function piDispatchRowCount(payload, prepared) {
39453
40239
  try {
39454
- const body = object10(payload);
40240
+ const body = object11(payload);
39455
40241
  return payloadStructure(payload, prepared?.api === "ollama-chat", body?.messages === undefined && Array.isArray(body?.input) && !!prepared?.responsesMessages)?.length;
39456
40242
  } catch {
39457
40243
  return;
@@ -39473,7 +40259,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
39473
40259
  let expected = prepared?.messages;
39474
40260
  let actual;
39475
40261
  try {
39476
- const body = object10(payload);
40262
+ const body = object11(payload);
39477
40263
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39478
40264
  if (responses)
39479
40265
  expected = prepared?.responsesMessages ?? expected;
@@ -40949,20 +41735,59 @@ function piCheckPreparedDispatch(payload, prepared, evidence, onImageTrim, onCom
40949
41735
  import { isDeepStrictEqual } from "node:util";
40950
41736
 
40951
41737
  // src/pi-dispatch-chain-tail.ts
40952
- function object11(value) {
41738
+ function object12(value) {
40953
41739
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
40954
41740
  }
40955
41741
  var OMITTED_IMAGE = "[image omitted: model does not support vision]";
41742
+ var ORPHAN_TOOL_CALL_PLACEHOLDER = "[No tool output recorded: the tool call was interrupted before it produced a result.]";
41743
+ function replayedTurnItems(assistant, responseItems, outputs, model) {
41744
+ const blocks = Array.isArray(assistant.content) ? assistant.content.map(object12) : [];
41745
+ const calls = blocks.flatMap((block) => block?.type === "toolCall" && typeof block.id === "string" ? [block] : []);
41746
+ const replayed = piResponsesReplayedCalls(assistant, calls.map((block) => block.id), calls.map((block) => piToolCallWireId(block.id, model, assistant)), model);
41747
+ const types = new Map;
41748
+ if (!replayed)
41749
+ return { items: [], calls: types };
41750
+ const items = [];
41751
+ const orphans = replayed.wireCalls.slice(0, replayed.stored).flatMap((id, index) => outputs.has(id) ? [] : [index]);
41752
+ if (orphans.length) {
41753
+ const last = object12(responseItems.at(-1));
41754
+ const id = replayed.wireCalls[orphans[0]];
41755
+ if (orphans.length !== 1 || orphans[0] !== replayed.stored - 1 || last?.type !== "function_call" && last?.type !== "custom_tool_call" || last.call_id !== id)
41756
+ return;
41757
+ items.push({
41758
+ type: last.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41759
+ call_id: id,
41760
+ output: ORPHAN_TOOL_CALL_PLACEHOLDER
41761
+ });
41762
+ }
41763
+ if (object12(model.compat)?.toolNamePrefix)
41764
+ return;
41765
+ for (let index = replayed.stored;index < replayed.calls.length; index++) {
41766
+ const id = replayed.wireCalls[index];
41767
+ const block = calls.find((call) => call.id === replayed.calls[index]);
41768
+ if (!block || typeof block.name !== "string" || block.customWireName !== undefined || object12(block.providerMetadata)?.type === "computer" || !outputs.has(id))
41769
+ return;
41770
+ items.push({
41771
+ type: "function_call",
41772
+ call_id: id,
41773
+ name: block.name,
41774
+ ...block.namespace ? { namespace: block.namespace } : {},
41775
+ arguments: JSON.stringify(block.arguments) ?? "null"
41776
+ });
41777
+ types.set(id, "function_call");
41778
+ }
41779
+ return { items, calls: types };
41780
+ }
40956
41781
  function piEncodeChainTail(messages, assistant, responseItems, model) {
40957
- const harmony = object11(model.identity)?.class === "gpt-oss";
41782
+ const harmony = object12(model.identity)?.class === "gpt-oss";
40958
41783
  const text = (value) => {
40959
41784
  const wellFormed = value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
40960
41785
  return harmony ? wellFormed.replace(/<\|(start|end|message|channel|constrain|return|call)\|>/g, "<\\|$1\\|>") : wellFormed;
40961
41786
  };
40962
41787
  const supportsImages = model.input?.includes("image") === true;
40963
41788
  const image = (block) => {
40964
- const detail = block.detail === "original" && object11(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
40965
- const file = object11(block.providerFile);
41789
+ const detail = block.detail === "original" && object12(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
41790
+ const file = object12(block.providerFile);
40966
41791
  if (file?.provider === "openai" && typeof file.id === "string" && file.id)
40967
41792
  return { type: "input_image", detail, file_id: file.id };
40968
41793
  if (typeof block.url !== "string" && (typeof block.mimeType !== "string" || typeof block.data !== "string"))
@@ -40973,9 +41798,21 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40973
41798
  image_url: block.url ?? `data:${block.mimeType};base64,${block.data}`
40974
41799
  };
40975
41800
  };
40976
- const items = [];
41801
+ const outputs = new Set;
40977
41802
  for (const value of messages) {
40978
- let message = object11(value);
41803
+ const message = object12(value);
41804
+ if (message?.role !== "toolResult" || typeof message.toolCallId !== "string")
41805
+ continue;
41806
+ const id = piToolCallWireId(message.toolCallId, model, assistant);
41807
+ if (id)
41808
+ outputs.add(id);
41809
+ }
41810
+ const replayed = replayedTurnItems(assistant, responseItems, outputs, model);
41811
+ if (!replayed)
41812
+ return;
41813
+ const items = [...replayed.items];
41814
+ for (const value of messages) {
41815
+ let message = object12(value);
40979
41816
  if (!message || message.providerPayload !== undefined)
40980
41817
  return;
40981
41818
  message = piOmpUserHistory(message);
@@ -40983,7 +41820,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40983
41820
  if (typeof message.customType !== "string" || message.attribution === "user")
40984
41821
  return;
40985
41822
  const converted = piAgentHistory([message], model.api);
40986
- const developer = object11(converted[0]);
41823
+ const developer = object12(converted[0]);
40987
41824
  if (converted.length !== 1 || !developer || !piIsDeveloperHistory(developer))
40988
41825
  return;
40989
41826
  message = {
@@ -41001,7 +41838,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
41001
41838
  const images = [];
41002
41839
  const ordered = [];
41003
41840
  for (const value of content) {
41004
- const block = object11(value);
41841
+ const block = object12(value);
41005
41842
  if (block?.type === "text" && typeof block.text === "string") {
41006
41843
  texts.push(block.text);
41007
41844
  if (!user || block.text.trim())
@@ -41029,15 +41866,15 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
41029
41866
  if (typeof message.toolCallId !== "string" || message.providerMetadata !== undefined)
41030
41867
  return;
41031
41868
  const id = piToolCallWireId(message.toolCallId, model, assistant);
41032
- const call = responseItems.map(object11).find((item) => item?.call_id === id);
41033
- if (!id || call?.type !== "function_call" && call?.type !== "custom_tool_call")
41869
+ const callType = id ? replayed.calls.get(id) ?? responseItems.map(object12).find((item) => item?.call_id === id)?.type : undefined;
41870
+ if (!id || callType !== "function_call" && callType !== "custom_tool_call")
41034
41871
  return;
41035
41872
  const joined = texts.join(`
41036
41873
  `);
41037
41874
  const output = images.length && supportsImages ? ordered : text(images.length && !supportsImages ? joined ? `${joined}
41038
41875
  ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41039
41876
  items.push({
41040
- type: call.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41877
+ type: callType === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41041
41878
  call_id: id,
41042
41879
  output
41043
41880
  });
@@ -41045,8 +41882,18 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41045
41882
  return items;
41046
41883
  }
41047
41884
 
41885
+ // src/pi-provider-input.ts
41886
+ function piProviderInput(message) {
41887
+ if (!message || typeof message !== "object" || Array.isArray(message))
41888
+ return message;
41889
+ const descriptors = Object.getOwnPropertyDescriptors(message);
41890
+ delete descriptors.completedAt;
41891
+ delete descriptors.contextSnapshot;
41892
+ return Object.create(Object.getPrototypeOf(message), descriptors);
41893
+ }
41894
+
41048
41895
  // src/pi-dispatch-chain.ts
41049
- function object12(value) {
41896
+ function object13(value) {
41050
41897
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41051
41898
  }
41052
41899
  function piChainCapableApi(api) {
@@ -41054,10 +41901,10 @@ function piChainCapableApi(api) {
41054
41901
  }
41055
41902
  function injectedHeadIndex(messages) {
41056
41903
  let index = 0;
41057
- while (object12(messages[index])?.role === "system")
41904
+ while (object13(messages[index])?.role === "system")
41058
41905
  index++;
41059
- const m0 = object12(messages[index]);
41060
- const m1 = object12(messages[index + 1]);
41906
+ const m0 = object13(messages[index]);
41907
+ const m1 = object13(messages[index + 1]);
41061
41908
  const syntheticUser = (message) => message?.role === "user" && Object.keys(message).every((key) => ["role", "content", "timestamp"].includes(key));
41062
41909
  if (!syntheticUser(m0) || !syntheticUser(m1))
41063
41910
  return -1;
@@ -41065,18 +41912,18 @@ function injectedHeadIndex(messages) {
41065
41912
  const m1Content = m1?.content;
41066
41913
  if (!Array.isArray(m0Content) || !Array.isArray(m1Content))
41067
41914
  return -1;
41068
- const m0Text = object12(m0Content[0]);
41069
- const m1Text = object12(m1Content[0]);
41070
- return m0Content.length >= 1 && m0Content.length <= 2 && (m0Content.length === 1 || object12(m0Content[1])?.type === "image") && m1Content.length === 1 && m0Text?.type === "text" && typeof m0Text.text === "string" && /^(<project-docs>|<user-profile>|<covered-system-messages>|<session-history>)/.test(m0Text.text) && m0Text.text.includes("</session-history>") && m1Text?.type === "text" && typeof m1Text.text === "string" && /^(<session-history-since>|<knowledge-updates>)/.test(m1Text.text) ? index : -1;
41915
+ const m0Text = object13(m0Content[0]);
41916
+ const m1Text = object13(m1Content[0]);
41917
+ return m0Content.length >= 1 && m0Content.length <= 2 && (m0Content.length === 1 || object13(m0Content[1])?.type === "image") && m1Content.length === 1 && m0Text?.type === "text" && typeof m0Text.text === "string" && /^(<project-docs>|<user-profile>|<covered-system-messages>|<session-history>)/.test(m0Text.text) && m0Text.text.includes("</session-history>") && m1Text?.type === "text" && typeof m1Text.text === "string" && /^(<session-history-since>|<knowledge-updates>)/.test(m1Text.text) ? index : -1;
41071
41918
  }
41072
41919
  function piPreparedHistory(messages, model) {
41073
41920
  const snapshots = [];
41074
41921
  const responseIds = [];
41075
41922
  const head = injectedHeadIndex(messages);
41076
41923
  for (const [index, message] of messages.entries()) {
41077
- const source = object12(message);
41924
+ const source = object13(message);
41078
41925
  const identity = head >= 0 && (index === head || index === head + 1) ? Object.fromEntries(Object.entries(source ?? {}).filter(([key]) => key !== "timestamp")) : message;
41079
- const fields = lkgContentFields(identity);
41926
+ const fields = lkgContentFields(piProviderInput(identity));
41080
41927
  if (!fields)
41081
41928
  return;
41082
41929
  snapshots.push({ id: "", fields });
@@ -41086,17 +41933,18 @@ function piPreparedHistory(messages, model) {
41086
41933
  let index = responseIds.length - 1;
41087
41934
  while (index >= 0 && responseIds[index] === undefined)
41088
41935
  index--;
41089
- const assistant = object12(messages[index]);
41936
+ const assistant = object13(messages[index]);
41090
41937
  const response = piChainResponse(assistant);
41091
41938
  if (model && assistant && response) {
41092
- const delta = piEncodeChainTail(messages.slice(index + 1), assistant, response.responseItems, model);
41939
+ const renamed = piDeduplicatedToolCallIds(messages, model);
41940
+ const delta = piEncodeChainTail(renamed.slice(index + 1), object13(renamed[index]) ?? assistant, response.responseItems, model);
41093
41941
  if (delta)
41094
41942
  prepared.continuation = { index, ...response, delta };
41095
41943
  }
41096
41944
  return prepared;
41097
41945
  }
41098
41946
  function piChainedRequest(payload) {
41099
- const body = object12(payload);
41947
+ const body = object13(payload);
41100
41948
  if (!body || body.previous_response_id === undefined)
41101
41949
  return;
41102
41950
  const id = body.previous_response_id;
@@ -41105,14 +41953,14 @@ function piChainedRequest(payload) {
41105
41953
  return { previousResponseId: id, delta: body.input };
41106
41954
  }
41107
41955
  function piChainResponse(message) {
41108
- const source = object12(message);
41956
+ const source = object13(message);
41109
41957
  if (source?.role !== "assistant")
41110
41958
  return;
41111
41959
  if (source.stopReason !== "stop" && source.stopReason !== "toolUse")
41112
41960
  return;
41113
41961
  if (typeof source.responseId !== "string" || !source.responseId)
41114
41962
  return;
41115
- const payload = object12(source.providerPayload);
41963
+ const payload = object13(source.providerPayload);
41116
41964
  if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
41117
41965
  return;
41118
41966
  return {
@@ -41160,14 +42008,14 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
41160
42008
  import { createHash as createHash16 } from "node:crypto";
41161
42009
  var MAX_BYTES = 32 * 1024 * 1024;
41162
42010
  var MAX_ENTRIES = 1e5;
41163
- function object13(value) {
42011
+ function object14(value) {
41164
42012
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41165
42013
  }
41166
42014
  function piCursorConversation(payload) {
41167
- const body = object13(payload);
42015
+ const body = object14(payload);
41168
42016
  if (body?.messages !== undefined || body?.input !== undefined || body?.contents !== undefined || body?.request !== undefined)
41169
42017
  return;
41170
- const state = object13(body?.conversationState);
42018
+ const state = object14(body?.conversationState);
41171
42019
  if (!state || !Array.isArray(state.rootPromptMessagesJson) || !Array.isArray(state.turns))
41172
42020
  return;
41173
42021
  let bytes = 0;
@@ -41187,7 +42035,7 @@ function piCursorConversation(payload) {
41187
42035
  }
41188
42036
  if (Array.isArray(value))
41189
42037
  return value.map((entry) => decode(entry, depth + 1));
41190
- const record = object13(value);
42038
+ const record = object14(value);
41191
42039
  if (record)
41192
42040
  return Object.fromEntries(Object.entries(record).map(([key, child]) => [
41193
42041
  key,
@@ -41198,7 +42046,7 @@ function piCursorConversation(payload) {
41198
42046
  try {
41199
42047
  const decoded = decode(state);
41200
42048
  for (const root of decoded.rootPromptMessagesJson) {
41201
- const record = object13(root);
42049
+ const record = object14(root);
41202
42050
  if (typeof record?.blobId === "string")
41203
42051
  rootIds.push(record.blobId);
41204
42052
  else if (record && typeof record.role === "string")
@@ -41207,19 +42055,19 @@ function piCursorConversation(payload) {
41207
42055
  return;
41208
42056
  }
41209
42057
  for (const value of decoded.turns.slice(0, 8)) {
41210
- const turn = object13(value);
41211
- const agent = object13(object13(turn?.turn)?.value) ?? turn;
41212
- const user = object13(agent?.userMessage);
42058
+ const turn = object14(value);
42059
+ const agent = object14(object14(turn?.turn)?.value) ?? turn;
42060
+ const user = object14(agent?.userMessage);
41213
42061
  if (typeof user?.text === "string")
41214
42062
  messages.push({ role: "user", content: user.text });
41215
42063
  }
41216
- const action = object13(object13(body?.action)?.action);
42064
+ const action = object14(object14(body?.action)?.action);
41217
42065
  if (!action || !["userMessageAction", "resumeAction"].includes(String(action.case)))
41218
42066
  return;
41219
42067
  let active = decode(body?.action);
41220
42068
  let activeText;
41221
42069
  if (action.case === "userMessageAction") {
41222
- const user = object13(object13(action.value)?.userMessage);
42070
+ const user = object14(object14(action.value)?.userMessage);
41223
42071
  if (!user || typeof user.text !== "string")
41224
42072
  return;
41225
42073
  messages.push({ role: "user", content: user.text });
@@ -41228,7 +42076,7 @@ function piCursorConversation(payload) {
41228
42076
  active = decode({
41229
42077
  action: {
41230
42078
  case: action.case,
41231
- value: { ...object13(action.value), userMessage: content }
42079
+ value: { ...object14(action.value), userMessage: content }
41232
42080
  }
41233
42081
  });
41234
42082
  }
@@ -41256,7 +42104,7 @@ function piCursorManagedRoots(messages, signature, cwd) {
41256
42104
  Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not repeat this information in your reply.
41257
42105
  </system-reminder>`;
41258
42106
  for (const value of messages.slice(0, 8)) {
41259
- const source = object13(value);
42107
+ const source = object14(value);
41260
42108
  if (!source || !["user", "developer"].includes(String(source.role)))
41261
42109
  continue;
41262
42110
  const message = piOmpUserHistory(source);
@@ -41733,14 +42581,6 @@ function omitsRootBookkeeping(args) {
41733
42581
  }
41734
42582
  return typeof api === "string" && bookkeepingOmittingApis.has(api);
41735
42583
  }
41736
- function piProviderInput(message) {
41737
- if (!message || typeof message !== "object" || Array.isArray(message))
41738
- return message;
41739
- const descriptors = Object.getOwnPropertyDescriptors(message);
41740
- delete descriptors.completedAt;
41741
- delete descriptors.contextSnapshot;
41742
- return Object.create(Object.getPrototypeOf(message), descriptors);
41743
- }
41744
42584
  function restorePiLkgInputForFit(snapshot, branchEntries) {
41745
42585
  if (!snapshot || snapshot.preparationFailure || !branchEntries || !snapshot.inputs.length)
41746
42586
  return;
@@ -42585,7 +43425,7 @@ class PiDegradedPassError extends Error {
42585
43425
  code = "PI_DEGRADED_PASS";
42586
43426
  recoverable = true;
42587
43427
  constructor(site, options) {
42588
- super(describeDegradedPassFailure(site, options?.cause), options);
43428
+ super(options?.message ?? describeDegradedPassFailure(site, options?.cause), options);
42589
43429
  this.site = site;
42590
43430
  this.name = "PiDegradedPassError";
42591
43431
  }
@@ -42787,6 +43627,7 @@ function classifyPiOutgoingFit(estimate, limit) {
42787
43627
  // src/pi-context-refusal.ts
42788
43628
  var ENTRY_TYPE = "magic-context-turn-refused";
42789
43629
  var RETRY_MESSAGE = "Magic Context could not safely prepare this turn; send your message again.";
43630
+ var PI_OMP_CAPTURE_REFUSAL = "Magic Context does not send OMP's auto-learn capture: it carries the raw, unmanaged conversation.";
42790
43631
  var MAX_UNSENDABLE_NONCES_PER_SESSION = 32;
42791
43632
  var receiptMaps = new Set;
42792
43633
  function clearPiContextReceipt(sessionId) {
@@ -42989,6 +43830,8 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42989
43830
  receiptMaps.add(imageTrimNotices);
42990
43831
  const foreignNotices = new Map;
42991
43832
  receiptMaps.add(foreignNotices);
43833
+ const captureNotices = new Map;
43834
+ receiptMaps.add(captureNotices);
42992
43835
  const foreignIndexes = new Map;
42993
43836
  receiptMaps.add(foreignIndexes);
42994
43837
  const chains = new Map;
@@ -43068,7 +43911,18 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43068
43911
  }
43069
43912
  });
43070
43913
  pi.on("before_provider_request", (event, ctx) => {
43071
- const cancelledOperation = operations.get(operationKey(ctx));
43914
+ const payload = event.payload;
43915
+ const key = operationKey(ctx);
43916
+ if (isOmpUnmanagedCaptureRequest(payload)) {
43917
+ if (options.compactionOff?.(ctx) || sideSessions.get(key)?.sides)
43918
+ return;
43919
+ if (!captureNotices.has(key)) {
43920
+ captureNotices.set(key, true);
43921
+ log2(`[magic-context][pi] OMP auto-learn capture refused for session=${String(key)}: it sends the raw conversation, which Magic Context does not manage; auto-learn capture stays off while Magic Context manages this session`);
43922
+ }
43923
+ return piRefusedPayload(PI_OMP_CAPTURE_REFUSAL);
43924
+ }
43925
+ const cancelledOperation = operations.get(key);
43072
43926
  const signal = ctx.signal;
43073
43927
  if (signal ? signal.aborted : cancelledOperation?.pass?.isCancelled()) {
43074
43928
  cancelledOperation?.pass?.cancel();
@@ -43077,11 +43931,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43077
43931
  return piRefusedPayload("Magic Context request cancelled before provider dispatch.");
43078
43932
  }
43079
43933
  if (options.compactionOff?.(ctx)) {
43080
- chains.delete(operationKey(ctx));
43934
+ chains.delete(key);
43081
43935
  return;
43082
43936
  }
43083
- const payload = event.payload;
43084
- const key = operationKey(ctx);
43085
43937
  if (sideSessions.get(key)?.sides)
43086
43938
  return;
43087
43939
  const nonces = unsendableNonces.get(key);
@@ -43110,15 +43962,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43110
43962
  }
43111
43963
  const active = operation;
43112
43964
  const isCurrent = () => operations.get(key) === active;
43113
- const capture = isOmpUnmanagedCaptureRequest(payload);
43114
- const budget = (capture ? undefined : active.pass) ?? new PiContextBudget;
43965
+ const budget = active.pass ?? new PiContextBudget;
43115
43966
  if (active.refused && active.pass === budget) {
43116
43967
  return piRefusedPayload(active.refusalMessage ?? RETRY_MESSAGE);
43117
43968
  }
43118
43969
  let refusalOrigin;
43119
43970
  try {
43120
- if (capture)
43121
- throw new Error("no context pass ran for OMP auto-learn capture; raw conversation refused");
43122
43971
  if (!active.pass)
43123
43972
  throw new Error("no context pass ran for this operation");
43124
43973
  if (!budget.completed && (budget.abandoned || budget.elapsed() >= PI_CONTEXT_BUDGET.outcomeMs))
@@ -43129,11 +43978,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43129
43978
  }
43130
43979
  if (!budget.completed || !active.ready || active.refused || budget.abandoned)
43131
43980
  throw new Error("context pass ran without a managed context receipt");
43132
- const chained = piChainedRequest(payload);
43133
- let checked = payload;
43981
+ const managed = piWithoutOmpJuice(payload, ctx.model);
43982
+ const chained = piChainedRequest(managed);
43983
+ let checked = managed;
43134
43984
  let chainInput;
43135
43985
  if (chained) {
43136
- const expanded = piExpandChainedRequest(payload, chained, chains.get(key)?.anchor, active.preparedHistory, {
43986
+ const expanded = piExpandChainedRequest(managed, chained, chains.get(key)?.anchor, active.preparedHistory, {
43137
43987
  current: active.pass,
43138
43988
  resend: active.chainDispatchFields !== undefined
43139
43989
  });
@@ -44752,167 +45602,6 @@ function resolvePiProvenInputFloor(args) {
44752
45602
  return observed;
44753
45603
  }
44754
45604
 
44755
- // src/pi-request-tools.ts
44756
- var schemaDigests = {
44757
- omp: new WeakMap,
44758
- anthropic: new WeakMap,
44759
- "anthropic-strict": new WeakMap,
44760
- raw: new WeakMap
44761
- };
44762
- function anthropicWireSchema(parameters, strict) {
44763
- const schema = typeof parameters === "object" && parameters !== null ? parameters : {};
44764
- const legacy = {
44765
- type: "object",
44766
- properties: schema.properties ?? {},
44767
- required: schema.required ?? []
44768
- };
44769
- return strict ? { ...schema, ...legacy } : legacy;
44770
- }
44771
- function schemaDigest(tool, mode, wireSchema) {
44772
- const key = tool.parameters;
44773
- const cacheable = typeof key === "object" && key !== null || typeof key === "function";
44774
- const cache = schemaDigests[mode];
44775
- if (cacheable) {
44776
- const cached = cache.get(key);
44777
- if (cached !== undefined)
44778
- return cached;
44779
- }
44780
- const digest = requestToolSchemaDigest(mode === "omp" && wireSchema ? wireSchema(tool) : mode === "anthropic" || mode === "anthropic-strict" ? anthropicWireSchema(tool.parameters, mode === "anthropic-strict") : tool.parameters);
44781
- if (cacheable)
44782
- cache.set(key, digest);
44783
- return digest;
44784
- }
44785
- var CLAUDE_CODE_TOOL_NAMES = new Map([
44786
- "Read",
44787
- "Write",
44788
- "Edit",
44789
- "Bash",
44790
- "Grep",
44791
- "Glob",
44792
- "AskUserQuestion",
44793
- "EnterPlanMode",
44794
- "ExitPlanMode",
44795
- "KillShell",
44796
- "NotebookEdit",
44797
- "Skill",
44798
- "Task",
44799
- "TaskOutput",
44800
- "TodoWrite",
44801
- "WebFetch",
44802
- "WebSearch"
44803
- ].map((name) => [name.toLowerCase(), name]));
44804
- var identityName = (name) => name;
44805
- var claudeCodeName = (name) => CLAUDE_CODE_TOOL_NAMES.get(name.toLowerCase()) ?? name;
44806
- function compatFlag(model, flag) {
44807
- const value = model?.compat?.[flag];
44808
- return typeof value === "boolean" ? value : undefined;
44809
- }
44810
- function supportsToolReferences(model) {
44811
- const declared = compatFlag(model, "supportsToolReferences");
44812
- if (declared !== undefined)
44813
- return declared;
44814
- if (model.provider !== "anthropic" || typeof model.id !== "string")
44815
- return false;
44816
- if (model.id.includes("haiku"))
44817
- return false;
44818
- const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
44819
- if (!version)
44820
- return false;
44821
- const major = Number(version[1]);
44822
- const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
44823
- return major > 4 || major === 4 && minor >= 5;
44824
- }
44825
- function deferredAndReferencedNames(messages, normalizeName) {
44826
- const deferred = new Set;
44827
- const referenced = new Set;
44828
- for (const message of messages) {
44829
- const { role, content, addedToolNames } = message ?? {};
44830
- if (role === "assistant" && Array.isArray(content)) {
44831
- for (const block of content) {
44832
- const { type, name } = block ?? {};
44833
- if (type === "toolCall" && typeof name === "string")
44834
- referenced.add(normalizeName(name));
44835
- }
44836
- } else if (role === "toolResult" && Array.isArray(addedToolNames)) {
44837
- for (const name of addedToolNames) {
44838
- if (typeof name !== "string")
44839
- continue;
44840
- const normalized = normalizeName(name);
44841
- if (!referenced.has(normalized))
44842
- deferred.add(normalized);
44843
- }
44844
- }
44845
- }
44846
- for (const name of deferred)
44847
- referenced.add(name);
44848
- return { deferred, referenced };
44849
- }
44850
- function calledToolNames(messages) {
44851
- const names = new Set;
44852
- for (const message of messages) {
44853
- const content = message?.content;
44854
- if (!Array.isArray(content))
44855
- continue;
44856
- for (const part of content) {
44857
- const { type, name } = part ?? {};
44858
- if (typeof type === "string" && type.toLowerCase().includes("tool") && typeof name === "string")
44859
- names.add(name);
44860
- }
44861
- }
44862
- return names;
44863
- }
44864
- function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
44865
- try {
44866
- if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
44867
- return;
44868
- const all = pi.getAllTools();
44869
- const active = pi.getActiveTools();
44870
- if (!Array.isArray(all) || !Array.isArray(active))
44871
- return;
44872
- const registered = new Map;
44873
- for (const tool of all) {
44874
- if (!tool || typeof tool !== "object")
44875
- return;
44876
- const { name } = tool;
44877
- if (typeof name !== "string")
44878
- return;
44879
- registered.set(name, tool);
44880
- }
44881
- const model = route.model;
44882
- const anthropicWriter = route.host === "pi" && wireSchema === undefined && model?.api === "anthropic-messages";
44883
- const mode = wireSchema ? "omp" : anthropicWriter ? compatFlag(model, "supportsStrictTools") === true ? "anthropic-strict" : "anthropic" : "raw";
44884
- const normalizeName = anthropicWriter && route.oauth === true ? claudeCodeName : identityName;
44885
- const sent = new Map;
44886
- for (const name of active) {
44887
- if (typeof name !== "string")
44888
- return;
44889
- const tool = registered.get(name);
44890
- if (!tool)
44891
- continue;
44892
- sent.set(normalizeName(name), tool);
44893
- }
44894
- const split = anthropicWriter && model && supportsToolReferences(model) ? deferredAndReferencedNames(messages, normalizeName) : undefined;
44895
- const anyImmediate = [...sent.keys()].some((name) => !split?.deferred.has(name));
44896
- const tools = [];
44897
- for (const [name, tool] of sent) {
44898
- const description = typeof tool.description === "string" ? tool.description : "";
44899
- tools.push({
44900
- name,
44901
- description,
44902
- schemaDigest: schemaDigest({
44903
- name: tool.name,
44904
- description,
44905
- parameters: tool.parameters
44906
- }, mode, wireSchema),
44907
- deferLoading: split ? anyImmediate && split.deferred.has(name) : tool.defer_loading === true || tool.deferLoading === true
44908
- });
44909
- }
44910
- return requestToolsFingerprint(tools, () => split?.referenced ?? calledToolNames(messages));
44911
- } catch {
44912
- return;
44913
- }
44914
- }
44915
-
44916
45605
  // src/pi-tag-identity-repair.ts
44917
45606
  var PI_TAG_IDENTITY_REPAIR_REASON = "tag_identity_repair";
44918
45607
  var unreadableLedgerLogged = new Set;
@@ -49152,6 +49841,7 @@ function registerPiContextHandler(pi, baseOptions) {
49152
49841
  }
49153
49842
  }));
49154
49843
  assertCurrentPass();
49844
+ const historyHead = sessionMetaForUsage.isSubagent ? undefined : options.injection;
49155
49845
  updateSessionProjectTracking(sessionId, projectIdentity, options.db, projectDirectory);
49156
49846
  const lkgInputIdByRef = new Map;
49157
49847
  for (const input of lkgPassSnapshot.inputs)
@@ -49202,25 +49892,17 @@ function registerPiContextHandler(pi, baseOptions) {
49202
49892
  }
49203
49893
  }
49204
49894
  const tMeta = performance.now();
49205
- const historianStateForPass = options.compactionOff ? EMPTY_PI_HISTORIAN_STATE_SNAPSHOT : (() => {
49206
- try {
49207
- return loadPiHistorianStateSnapshot(options.db, sessionId);
49208
- } catch (error) {
49209
- sessionLog2(sessionId, `historian state snapshot failed; using safe defaults: ${error instanceof Error ? error.message : String(error)}`);
49210
- return EMPTY_PI_HISTORIAN_STATE_SNAPSHOT;
49211
- }
49212
- })();
49213
- let piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
49895
+ let piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
49214
49896
  db: options.db,
49215
49897
  sessionId,
49216
49898
  compactionOff: options.compactionOff === true,
49217
49899
  sessionMeta: sessionMetaForUsage
49218
49900
  }) : undefined;
49219
49901
  logTransformTiming(sessionId, "getOrCreateSessionMeta", tMeta);
49220
- if (strictEntryIds && branchEntries && options.injection && !options.compactionOff && stripMcOwnedPiCompactionSummary(event.messages, strictEntryIds, branchEntries)) {
49902
+ if (strictEntryIds && branchEntries && historyHead && !options.compactionOff && stripMcOwnedPiCompactionSummary(event.messages, strictEntryIds, branchEntries)) {
49221
49903
  logTransformTiming(sessionId, "mcCompactionSummarySuppression", tEntryBranch);
49222
49904
  }
49223
- if (strictEntryIds && options.injection && !options.compactionOff) {
49905
+ if (strictEntryIds && historyHead && !options.compactionOff) {
49224
49906
  const removed = trimPiMessagesToCachedBoundary(options.db, sessionId, event.messages, strictEntryIds, piM0M1PassSnapshot);
49225
49907
  if (removed > 0) {
49226
49908
  logTransformTiming(sessionId, "cachedBoundaryEarlyTrim", tEntryBranch, `removed=${removed}`);
@@ -49282,7 +49964,7 @@ function registerPiContextHandler(pi, baseOptions) {
49282
49964
  clearPiInjectionTokenCountCache(sessionId);
49283
49965
  sessionMetaForUsage.cachedM0Bytes = null;
49284
49966
  sessionMetaForUsage.cachedM1Bytes = null;
49285
- piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
49967
+ piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
49286
49968
  db: options.db,
49287
49969
  sessionId,
49288
49970
  compactionOff: options.compactionOff === true,
@@ -49331,6 +50013,14 @@ function registerPiContextHandler(pi, baseOptions) {
49331
50013
  sessionMetaForUsage.lastContextPercentage = 0;
49332
50014
  sessionMetaForUsage.lastInputTokens = 0;
49333
50015
  }
50016
+ const historianStateForPass = options.compactionOff ? EMPTY_PI_HISTORIAN_STATE_SNAPSHOT : (() => {
50017
+ try {
50018
+ return loadPiHistorianStateSnapshot(options.db, sessionId);
50019
+ } catch (error) {
50020
+ sessionLog2(sessionId, `historian state snapshot failed; using safe defaults: ${error instanceof Error ? error.message : String(error)}`);
50021
+ return EMPTY_PI_HISTORIAN_STATE_SNAPSHOT;
50022
+ }
50023
+ })();
49334
50024
  let usagePercentage = 0;
49335
50025
  let usageInputTokens = 0;
49336
50026
  let usedPersistedUsage = false;
@@ -49483,10 +50173,22 @@ function registerPiContextHandler(pi, baseOptions) {
49483
50173
  const hasToolReclaim = event.messages.some((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && visibleToolResults.has(part.id) && (!knownTools.has(part.id) || activeTools.has(part.id))));
49484
50174
  if (historian && !hasToolReclaim && getPendingOps(options.db, sessionId).length === 0 && !historyRefreshSessions.has(sessionId) && !deferredHistoryRefreshSessions.has(sessionId)) {
49485
50175
  budget.stage = "emergency historian";
49486
- await budget.wait(historian);
50176
+ const historianProgress = inFlightHistorianProgress.get(sessionId);
50177
+ const historianWaitMs = budget.remainingWork();
50178
+ try {
50179
+ await budget.wait(historian);
50180
+ } catch (error) {
50181
+ throw describeHistorianJoinDeadline(error, {
50182
+ db: options.db,
50183
+ sessionId,
50184
+ waitedMs: historianWaitMs,
50185
+ usagePercentage,
50186
+ run: historianProgress
50187
+ });
50188
+ }
49487
50189
  assertCurrentPass();
49488
50190
  sessionMeta = getOrCreateSessionMeta(options.db, sessionId);
49489
- piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
50191
+ piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
49490
50192
  db: options.db,
49491
50193
  sessionId,
49492
50194
  compactionOff: false,
@@ -49530,7 +50232,7 @@ function registerPiContextHandler(pi, baseOptions) {
49530
50232
  recoveryArmed: emergencyRecoveryArmed || !!recovery.rebuildReason,
49531
50233
  forceMaterialization,
49532
50234
  imported: looksLikeImportedSession || usageInputTokens <= 0 && (isFirstContextPassForSession || lkgPassSnapshot?.replayFailure !== null),
49533
- coldInjection: !!options.injection && !sessionMeta.cachedM0Bytes,
50235
+ coldInjection: !!historyHead && !sessionMeta.cachedM0Bytes,
49534
50236
  cacheBusting: isCacheBusting,
49535
50237
  sessionId,
49536
50238
  appendedMessages: lkgPassSnapshot?.pristineTail ?? event.messages.slice(-1),
@@ -49552,7 +50254,13 @@ function registerPiContextHandler(pi, baseOptions) {
49552
50254
  }
49553
50255
  maintainExecuteFloorMark(options.db, sessionId, promptId, usagePercentage < effectiveExecuteThresholdPercentage);
49554
50256
  }
50257
+ const ctxReduceCallable = piCtxReduceCallable(pi, options.compactionOff === true, { db: options.db, sessionId });
50258
+ const servedCtxReduceCallable = options.compactionOff || budget.sideTurn ? ctxReduceCallable : readServedPiCtxReduceCallable(options.db, sessionId);
50259
+ if (!ctxReduceCallable && !budget.sideTurn)
50260
+ clearPiChannel1State(sessionId);
49555
50261
  const pipelineArgs = {
50262
+ ctxReduceCallable,
50263
+ servedCtxReduceCallable,
49556
50264
  providerOverflowRecovery: emergencyRecoveryArmed && historianStateForPass.emergencyRecoveryOrigin === "provider_overflow",
49557
50265
  dropBranchEntries: branchEntries ?? undefined,
49558
50266
  recoveryPrefix: recovery.prefix,
@@ -49577,9 +50285,9 @@ function registerPiContextHandler(pi, baseOptions) {
49577
50285
  reclaimUsableWindow: windowGeometry?.usableSoft ?? usageContextLimit ?? 0,
49578
50286
  heuristics: options.heuristics,
49579
50287
  emergencyCeilingTokens,
49580
- injection: options.injection ? {
49581
- ...options.injection,
49582
- memoryEnabled: options.injection.memoryEnabled,
50288
+ injection: historyHead ? {
50289
+ ...historyHead,
50290
+ memoryEnabled: historyHead.memoryEnabled,
49583
50291
  historyBudgetPolicyIdentity: historyBudgetPolicyIdentity(options.historian?.historyBudgetPercentage, options.historian?.executeThresholdPercentage, liveModelBySession.get(sessionId), options.historian?.executeThresholdTokens),
49584
50292
  historyBudgetTokens: resolveHistoryBudgetTokensForPi({
49585
50293
  historyBudgetPercentage: options.historian?.historyBudgetPercentage,
@@ -49600,7 +50308,7 @@ function registerPiContextHandler(pi, baseOptions) {
49600
50308
  schedulerDeferReason,
49601
50309
  forceMaterialization: forceMaterialization || isEmergency,
49602
50310
  forceMaterializationPercentage,
49603
- signedThinkingHold: requestToolsChange === null && resolvePiSignedThinkingHold({
50311
+ signedThinkingHold: requestToolsChange === null && ctxReduceCallable === servedCtxReduceCallable && resolvePiSignedThinkingHold({
49604
50312
  sessionId,
49605
50313
  db: options.db,
49606
50314
  messages: event.messages,
@@ -49663,7 +50371,7 @@ function registerPiContextHandler(pi, baseOptions) {
49663
50371
  if (!options.compactionOff)
49664
50372
  assertPiTagSnapshotReady(options.db, sessionId);
49665
50373
  let historianEvaluatedThisPass = false;
49666
- const historian = options.historian;
50374
+ const historian = sessionMeta.isSubagent ? undefined : options.historian;
49667
50375
  const scheduleHistorian = (result) => {
49668
50376
  if (historianEvaluatedThisPass)
49669
50377
  return;
@@ -49785,7 +50493,7 @@ function registerPiContextHandler(pi, baseOptions) {
49785
50493
  const todoAnchorBefore = JSON.stringify(getPersistedTodoSyntheticAnchor(options.db, sessionId));
49786
50494
  const tNoteNudges = performance.now();
49787
50495
  try {
49788
- if (!options.compactionOff) {
50496
+ if (!options.compactionOff && !sessionMeta.isSubagent) {
49789
50497
  outputMessages = applyNoteNudges({
49790
50498
  sessionId,
49791
50499
  db: options.db,
@@ -49804,7 +50512,7 @@ function registerPiContextHandler(pi, baseOptions) {
49804
50512
  logTransformTiming(sessionId, "noteNudges", tNoteNudges);
49805
50513
  const tAutoSearch = performance.now();
49806
50514
  budget.stage = "auto-search";
49807
- if (options.autoSearch?.enabled && !options.compactionOff && result.prefixMutationAllowed && budget.remainingWork() > PI_CONTEXT_BUDGET.searchMs) {
50515
+ if (options.autoSearch?.enabled && !options.compactionOff && !sessionMeta.isSubagent && result.prefixMutationAllowed && budget.remainingWork() > PI_CONTEXT_BUDGET.searchMs) {
49808
50516
  guardSqliteTransformPass2({
49809
50517
  assert: budget.assert,
49810
50518
  remainingMs: budget.remainingWork
@@ -49941,7 +50649,7 @@ function registerPiContextHandler(pi, baseOptions) {
49941
50649
  const tChannelAccounting = performance.now();
49942
50650
  try {
49943
50651
  const sessionMetaForCh1 = sessionMeta;
49944
- if (!options.compactionOff && !sessionMetaForCh1.isSubagent) {
50652
+ if (ctxReduceCallable) {
49945
50653
  const { tags, protectedTagNumbers, pendingDropTagNumbers } = result.channelBaselineSnapshot;
49946
50654
  const stableId = (message) => message && typeof message === "object" ? result.postCommitEntryIdByRef.get(message) : undefined;
49947
50655
  const hygieneCalibration = sessionDecisionCalibration(options.db, sessionId);
@@ -50208,7 +50916,7 @@ function registerPiContextHandler(pi, baseOptions) {
50208
50916
  upperEstimateOnly: !recoverUnknownUsage && fitCase === "upper-estimate-pressure",
50209
50917
  forceSignedRebuildForFit: fitCase === "over-window-proof",
50210
50918
  isCacheBusting: historyRefreshSessions.has(sessionId) || deferredHistoryRefreshSessions.has(sessionId),
50211
- injectionPassSnapshot: options.injection ? createPiM0M1PassSnapshot({
50919
+ injectionPassSnapshot: historyHead ? createPiM0M1PassSnapshot({
50212
50920
  db: options.db,
50213
50921
  sessionId,
50214
50922
  compactionOff: false,
@@ -50365,6 +51073,8 @@ function registerPiContextHandler(pi, baseOptions) {
50365
51073
  sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
50366
51074
  });
50367
51075
  afterCapture(sessionId, "served system hash record", recordServedSystemHash);
51076
+ if (!budget.sideTurn && !options.compactionOff)
51077
+ afterCapture(sessionId, "ctx_reduce served record", () => recordServedPiCtxReduceCallable(options.db, sessionId, ctxReduceCallable));
50368
51078
  return { messages: outputMessages };
50369
51079
  } catch (err) {
50370
51080
  if (budget.isCancelled(err))
@@ -50490,6 +51200,12 @@ function registerPiContextHandler(pi, baseOptions) {
50490
51200
  if (err instanceof PiDegradedPassError && err.site === "outgoing-over-window")
50491
51201
  throw contextRefusalError("The request exceeds the model's context window after reclaim, and no fitting saved request is available; this turn was not sent.");
50492
51202
  if (!lkgCompactionOff && sessionIdForError) {
51203
+ const historianJoin = findPiHistorianJoinDeadline(err);
51204
+ if (historianJoin)
51205
+ throw new PiDegradedPassError("emergency-historian-join", {
51206
+ cause: err,
51207
+ message: `${historianJoin.refusal} (${historianJoin.message})`
51208
+ });
50493
51209
  throw piFallbackRefusal("context-handler-failed", err);
50494
51210
  }
50495
51211
  log2(`[magic-context][pi] context handler failed (continuing without mutation): ${message}`, stack);
@@ -50519,6 +51235,7 @@ function registerPiContextHandler(pi, baseOptions) {
50519
51235
  log2("[magic-context][pi] registered context handler (tagging + drops + nudges)");
50520
51236
  }
50521
51237
  var inFlightHistorian = new Map;
51238
+ var inFlightHistorianProgress = new Map;
50522
51239
  var historianAbortControllers = new Map;
50523
51240
  function abortInFlightHistorians(sessionId) {
50524
51241
  historianAbortControllers.get(sessionId)?.abort();
@@ -50608,6 +51325,32 @@ function hasEligiblePiCompartmentHistory(db, sessionId, boundarySnapshot) {
50608
51325
  return false;
50609
51326
  }
50610
51327
  }
51328
+ function describeHistorianJoinDeadline(error, facts) {
51329
+ if (!(error instanceof PiContextDeadlineError))
51330
+ return error;
51331
+ try {
51332
+ return new PiHistorianJoinDeadlineError(error.message, describeHistorianJoinRefusal({
51333
+ waitedMs: facts.waitedMs,
51334
+ usagePercentage: facts.usagePercentage,
51335
+ run: facts.run,
51336
+ failures: readHistorianFailureStreak(facts.db, facts.sessionId)
51337
+ }));
51338
+ } catch (readError) {
51339
+ sessionLog2(facts.sessionId, `historian join refusal could not read the failure record: ${readError instanceof Error ? readError.message : String(readError)}`);
51340
+ return error;
51341
+ }
51342
+ }
51343
+ function findPiHistorianJoinDeadline(error) {
51344
+ const seen = new Set;
51345
+ let current = error;
51346
+ while (current && typeof current === "object" && !seen.has(current)) {
51347
+ if (current instanceof PiHistorianJoinDeadlineError)
51348
+ return current;
51349
+ seen.add(current);
51350
+ current = current.cause;
51351
+ }
51352
+ return;
51353
+ }
50611
51354
  function sendPiIgnoredNotification(ctx, message) {
50612
51355
  const uiNotify = ctx.ui?.notify;
50613
51356
  if (typeof uiNotify === "function") {
@@ -50639,6 +51382,7 @@ function spawnPiHistorianRun(args) {
50639
51382
  const holderId = crypto3.randomUUID();
50640
51383
  const controller = new AbortController;
50641
51384
  historianAbortControllers.set(sessionId, controller);
51385
+ const progress = { startedAt: Date.now() };
50642
51386
  const runPromise = inPiHistorianRootContext(sessionId, () => (async () => {
50643
51387
  await new Promise((resolve) => setTimeout(resolve, 0));
50644
51388
  if (controller.signal.aborted)
@@ -50703,6 +51447,9 @@ function spawnPiHistorianRun(args) {
50703
51447
  userObservationsRequested: historian.userObservationsRequested,
50704
51448
  language: historian.language,
50705
51449
  compartmentLeaseHolderId: holderId,
51450
+ onChunkSelected: (chunk) => {
51451
+ progress.chunk = chunk;
51452
+ },
50706
51453
  notifyIssue: (text) => {
50707
51454
  if (!isContextHandlerSessionActive(sessionId)) {
50708
51455
  sessionLog2(sessionId, "historian failure notice skipped after session context cleared");
@@ -50737,8 +51484,11 @@ function spawnPiHistorianRun(args) {
50737
51484
  })().catch((error) => {
50738
51485
  sessionLog2(sessionId, `pi historian run failed: ${error instanceof Error ? error.message : String(error)}`);
50739
51486
  }).finally(() => {
51487
+ progress.endedAt = Date.now();
50740
51488
  try {
50741
51489
  inFlightHistorian.delete(sessionId);
51490
+ if (inFlightHistorianProgress.get(sessionId) === progress)
51491
+ inFlightHistorianProgress.delete(sessionId);
50742
51492
  if (historianAbortControllers.get(sessionId) === controller)
50743
51493
  historianAbortControllers.delete(sessionId);
50744
51494
  unregister();
@@ -50750,6 +51500,7 @@ function spawnPiHistorianRun(args) {
50750
51500
  }
50751
51501
  }));
50752
51502
  inFlightHistorian.set(sessionId, runPromise);
51503
+ inFlightHistorianProgress.set(sessionId, progress);
50753
51504
  historian.onStatusChange?.(ctx, sessionId);
50754
51505
  }
50755
51506
  function resolvePiAppendCompaction(ctx) {
@@ -51570,7 +52321,10 @@ async function runPipeline(args) {
51570
52321
  return findLatestUserMessageIdPi(args.messages, ids)?.messageId ?? null;
51571
52322
  })();
51572
52323
  const alreadyRanHeuristicsThisTurn = currentTurnId !== null && lastHeuristicsTurnIdBySession.get(args.sessionId) === currentTurnId;
51573
- const ctxReduceCallable = !args.sessionMeta.isSubagent;
52324
+ const ctxReduceCallable = args.ctxReduceCallable;
52325
+ const requestToolListChanged = args.ctxReduceCallable !== args.servedCtxReduceCallable;
52326
+ if (requestToolListChanged)
52327
+ sessionLog2(args.sessionId, `request tool list changed: ctx_reduce ${args.ctxReduceCallable ? "added; tag prefixes return" : "removed; tag prefixes stop"} on this rebuild`);
51574
52328
  const canConsumeDeferredLate = args.schedulerDecision === "execute" || args.forceMaterialization === true || args.contextUsage.percentage >= forceMaterializationPercentage;
51575
52329
  let deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId) && !protectedSignedPrefix;
51576
52330
  const executePressureEligible = args.schedulerDecision === "execute" || emergencyDropEligible;
@@ -51585,7 +52339,7 @@ async function runPipeline(args) {
51585
52339
  const rideSignals = {
51586
52340
  executeReclaim: false,
51587
52341
  subagentExecute: args.sessionMeta.isSubagent && args.schedulerDecision === "execute",
51588
- hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || firstRenderBust || isCacheBustingPass,
52342
+ hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || requestToolListChanged || firstRenderBust || isCacheBustingPass,
51589
52343
  force: (args.forceMaterialization === true || emergencyDropEligible) && (args.contextUsage.percentage >= 95 || getEmergencyInputSample(args.db, args.sessionId) === 0),
51590
52344
  explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_flush")),
51591
52345
  publishedHistory: !prefixPreflightContended && publishedM1RefreshedThisPass
@@ -51618,7 +52372,7 @@ async function runPipeline(args) {
51618
52372
  onRejectedProjectOverride: (warning) => sessionLog2(args.sessionId, warning)
51619
52373
  });
51620
52374
  let protectionFloorResolution = resolveProtectionFloor();
51621
- let shouldRunHeuristics = args.heuristics !== undefined && isCacheBustingPass && (rideSignals.publishedHistory || systemPrefixChangedThisPass || rideSignals.explicitFlush || args.forceMaterialization === true || hasPendingMaterializeSignal || deferredMaterializeEligible || foldBustsServedPrefixThisPass || firstRenderBust || args.recoveryRebuildReason !== undefined && isCacheBustingPass || rideSignals.subagentExecute || args.schedulerDecision === "execute" && !alreadyRanHeuristicsThisTurn);
52375
+ let shouldRunHeuristics = args.heuristics !== undefined && isCacheBustingPass && (rideSignals.publishedHistory || systemPrefixChangedThisPass || requestToolListChanged || rideSignals.explicitFlush || args.forceMaterialization === true || hasPendingMaterializeSignal || deferredMaterializeEligible || foldBustsServedPrefixThisPass || firstRenderBust || args.recoveryRebuildReason !== undefined && isCacheBustingPass || rideSignals.subagentExecute || args.schedulerDecision === "execute" && !alreadyRanHeuristicsThisTurn);
51622
52376
  let unavoidableCarriedIdentityRebuild = false;
51623
52377
  if (protectedSignedPrefix && readPiIdentityRebuilds(args.db, args.sessionId).length > 0) {
51624
52378
  args.tryReplayHeldIdentityRebuild?.();
@@ -52132,7 +52886,7 @@ async function runPipeline(args) {
52132
52886
  const tHeuristic = performance.now();
52133
52887
  const providerOverflow = args.providerOverflowRecovery === true;
52134
52888
  const recoveryCalibration = sessionDecisionCalibration(args.db, args.sessionId);
52135
- const independentMutationBeforeHeuristics = pendingOpsDidMutate || systemPrefixChangedThisPass || foldBustsServedPrefixThisPass || identityRebuild || firstRenderBust;
52889
+ const independentMutationBeforeHeuristics = pendingOpsDidMutate || systemPrefixChangedThisPass || requestToolListChanged || foldBustsServedPrefixThisPass || identityRebuild || firstRenderBust;
52136
52890
  if (args.forceMaterialization === true && independentMutationBeforeHeuristics && getEmergencyInputSample(args.db, args.sessionId) > 0) {
52137
52891
  clearEmergencyDropSample(args.db, args.sessionId);
52138
52892
  }
@@ -53035,6 +53789,7 @@ function clearContextHandlerSession(sessionId) {
53035
53789
  dropServedRecord(sessionId, "session_cleared");
53036
53790
  cancelPiTagSnapshotSession(sessionId);
53037
53791
  lastServedSystemHashBySession.delete(sessionId);
53792
+ clearPiCtxReduceCallableSession(sessionId);
53038
53793
  clearPiHistoryBoundaryRepairSession(sessionId);
53039
53794
  clearPiUpperReclaimSession(sessionId);
53040
53795
  invalidateTrueRawTokenCache({ sessionId, reason: "pi.branch.changed" });
@@ -56154,6 +56909,34 @@ function schedulePiAssistantIndexOnMessageEnd(db, sessionId, endedMessage, sessi
56154
56909
  });
56155
56910
  }
56156
56911
 
56912
+ // src/pi-agent-identity.ts
56913
+ var checkedSessions = new BoundedSessionMap(1000);
56914
+ function readAgentKind(ctx) {
56915
+ try {
56916
+ return ctx?.agent?.kind;
56917
+ } catch {
56918
+ return;
56919
+ }
56920
+ }
56921
+ function recordPiSpawnedSession(db, sessionId, ctx) {
56922
+ if (checkedSessions.has(sessionId))
56923
+ return;
56924
+ checkedSessions.set(sessionId, true);
56925
+ if (readAgentKind(ctx) !== "sub")
56926
+ return;
56927
+ if (getOrCreateSessionMeta(db, sessionId).isSubagent)
56928
+ return;
56929
+ if (hasCompartments(db, sessionId)) {
56930
+ sessionLog2(sessionId, "Oh My Pi spawned session (agent kind sub) has compartments from its source session: kept primary");
56931
+ return;
56932
+ }
56933
+ updateSessionMeta(db, sessionId, { isSubagent: true });
56934
+ sessionLog2(sessionId, "Oh My Pi spawned session (agent kind sub): recorded as a subagent");
56935
+ }
56936
+ function hasCompartments(db, sessionId) {
56937
+ return db.prepare("SELECT 1 AS present FROM compartments WHERE session_id = ? LIMIT 1").get(sessionId) != null;
56938
+ }
56939
+
56157
56940
  // ../plugin/src/plugin/boot-deadline.ts
56158
56941
  async function runBootPhaseWithDeadline(phase, operation, timeoutMs, report, deadlineDescription = `its ${timeoutMs}ms deadline`) {
56159
56942
  const startedAt = performance.now();
@@ -56793,6 +57576,27 @@ async function persistPiPressureFromMessageEnd(args) {
56793
57576
  const activeModel = args.piModel ?? { provider, id: model };
56794
57577
  const modelKey = activeModel.provider && activeModel.id ? piModelRefToCanonical(`${activeModel.provider}/${activeModel.id}`) : undefined;
56795
57578
  const usage = extractAssistantUsage(args.message);
57579
+ const msg = args.message && typeof args.message === "object" ? args.message : undefined;
57580
+ const messageHadOverflowError = typeof msg?.errorMessage === "string" && detectOverflow(msg.errorMessage).isOverflow;
57581
+ const requestAccepted = !messageHadOverflowError && !providerResponseFailed({
57582
+ finish: args.message?.stopReason,
57583
+ error: msg?.errorMessage
57584
+ });
57585
+ if (requestAccepted) {
57586
+ const rawOverflow = getOverflowState(args.db, args.sessionId);
57587
+ const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
57588
+ if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel) {
57589
+ const uncappedPressure = computePiPressure(usage, args.piContextWindow, piPressureEvidenceLimit(resolvePiWindowGeometry({
57590
+ rawContextWindow: args.piContextWindow,
57591
+ rawContextWindowSource: args.piContextWindowSource,
57592
+ model: activeModel
57593
+ })));
57594
+ if (uncappedPressure && uncappedPressure.inputTokens > rawOverflow.detectedContextLimit) {
57595
+ clearDetectedContextLimit(args.db, args.sessionId);
57596
+ info(`message_end: detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${uncappedPressure.inputTokens}-token request; using Pi contextWindow`);
57597
+ }
57598
+ }
57599
+ }
56796
57600
  const detectedContextLimit = getOverflowState(args.db, args.sessionId, modelKey).detectedContextLimit;
56797
57601
  const reportedGeometry = resolvePiWindowGeometry({
56798
57602
  rawContextWindow: args.piContextWindow,
@@ -56809,21 +57613,7 @@ async function persistPiPressureFromMessageEnd(args) {
56809
57613
  if (rejectedUsage) {
56810
57614
  noteRejectedPiUsage(args.sessionId, reportedInput, providerInputLimit, "message_end");
56811
57615
  }
56812
- const msg = args.message && typeof args.message === "object" ? args.message : undefined;
56813
- const messageHadOverflowError = typeof msg?.errorMessage === "string" && detectOverflow(msg.errorMessage).isOverflow;
56814
- const requestAccepted = !messageHadOverflowError && !providerResponseFailed({
56815
- finish: args.message?.stopReason,
56816
- error: msg?.errorMessage
56817
- });
56818
57616
  const requestSucceeded = requestAccepted && !rejectedUsage;
56819
- if (requestAccepted && unboundedPressure) {
56820
- const rawOverflow = getOverflowState(args.db, args.sessionId);
56821
- const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
56822
- if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel && unboundedPressure.inputTokens > rawOverflow.detectedContextLimit) {
56823
- clearDetectedContextLimit(args.db, args.sessionId);
56824
- info(`message_end: detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${unboundedPressure.inputTokens}-token request; using Pi contextWindow`);
56825
- }
56826
- }
56827
57617
  const floorModelKey = piProvenFloorModelKey(activeModel);
56828
57618
  const observedSafeInputTokens = resolvePiProvenInputFloor({
56829
57619
  db: args.db,
@@ -57480,6 +58270,8 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
57480
58270
  onInherited: (sessionId) => prewarmPiTagSnapshot(db, sessionId, "pass")
57481
58271
  });
57482
58272
  const sessionId = resolveSessionId(ctx);
58273
+ if (sessionId)
58274
+ recordPiSpawnedSession(db, sessionId, ctx);
57483
58275
  if (!piMarkerRehydrationLogged && pendingPiMarkerSessions.length > 0 && sessionId) {
57484
58276
  log2(formatPiMarkerRehydrationLine(pendingPiMarkerSessions, sessionId));
57485
58277
  piMarkerRehydrationLogged = true;
@@ -57742,6 +58534,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
57742
58534
  }
57743
58535
  }
57744
58536
  if (sessionId) {
58537
+ recordPiSpawnedSession(db, sessionId, ctx);
57745
58538
  trackSessionForProject(currentProject.projectIdentity, sessionId);
57746
58539
  try {
57747
58540
  const smForDrain = sm;
@@ -57769,7 +58562,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
57769
58562
  memoryEnabled: effectiveConfig.memory.enabled,
57770
58563
  includeGuidance: true,
57771
58564
  protectedTags: effectiveConfig.protected_tags,
57772
- ctxReduceCallable: !compactionOff,
58565
+ ctxReduceCallable: piCtxReduceCallable(pi, compactionOff, sessionId ? { db, sessionId } : undefined),
57773
58566
  dreamerEnabled: effectiveProjectDeps.dreamerEnabled,
57774
58567
  smartNotesEnabled: config.smart_notes.enabled,
57775
58568
  temporalAwarenessEnabled: effectiveConfig.temporal_awareness ?? false,
@@ -57824,8 +58617,12 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
57824
58617
  const lastAssistant = Array.isArray(msgs) ? [...msgs].reverse().find((m) => m?.role === "assistant") : undefined;
57825
58618
  if (lastAssistant?.stopReason === "stop") {
57826
58619
  const sessionId = ctx.sessionManager?.getSessionId?.();
57827
- if (sessionId && db && !compactionOff)
57828
- maybeDeliverChannel2Pi(pi, db, sessionId);
58620
+ if (sessionId && db) {
58621
+ if (piCtxReduceCallable(pi, compactionOff, { db, sessionId }))
58622
+ maybeDeliverChannel2Pi(pi, db, sessionId);
58623
+ else
58624
+ clearPiChannel1State(sessionId);
58625
+ }
57829
58626
  }
57830
58627
  } catch (err) {
57831
58628
  log2(`agent_end: channel2 delivery skipped: ${String(err)}`);
@@ -57879,8 +58676,10 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
57879
58676
  const sessionId = ctx.sessionManager.getSessionId();
57880
58677
  if (typeof sessionId !== "string" || sessionId.length === 0)
57881
58678
  return;
57882
- if (compactionOff)
58679
+ if (!piCtxReduceCallable(pi, compactionOff, db ? { db, sessionId } : undefined)) {
58680
+ clearPiChannel1State(sessionId);
57883
58681
  return;
58682
+ }
57884
58683
  const block = maybeChannel1ReminderForToolResult({
57885
58684
  db,
57886
58685
  sessionId,