@cortexkit/pi-magic-context 0.49.55 → 0.49.57

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 (25) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{index-625kbnqd.js → index-0133ybm6.js} +1 -1
  4. package/dist/{index-6ahmfva8.js → index-15eq9z3a.js} +3 -3
  5. package/dist/{index-2pptpxq8.js → index-15rx61th.js} +1 -1
  6. package/dist/{index-rekymyxd.js → index-7mvsg371.js} +1 -1
  7. package/dist/{index-c3mms4dp.js → index-8ej7crnf.js} +1 -1
  8. package/dist/{index-k2z7r444.js → index-mbzqrp0s.js} +44 -4
  9. package/dist/{index-nhpvvdhw.js → index-mmwgmz8f.js} +10 -2
  10. package/dist/{index-9kaj9ty1.js → index-prhdb9c5.js} +1 -1
  11. package/dist/{index-tn38he5d.js → index-tz8431zx.js} +88 -14
  12. package/dist/{index-5n3e2gq5.js → index-xgkq843e.js} +23 -1
  13. package/dist/index.js +1272 -269
  14. package/dist/{message-index-bounded-ac4qg6aw.js → message-index-bounded-q6dyk780.js} +3 -3
  15. package/dist/migration-worker.js +1 -1
  16. package/dist/raw-ordinal-warmup-worker.js +4 -4
  17. package/dist/{read-session-chunk-jyfcykg4.js → read-session-chunk-ksn2r664.js} +2 -2
  18. package/dist/{render-bqqx15n8.js → render-nejsk0az.js} +5 -5
  19. package/dist/{search-archive-31054zxj.js → search-archive-4yfsc0xb.js} +4 -4
  20. package/dist/{search-w12nc025.js → search-h61ec8kh.js} +4 -4
  21. package/dist/{storage-tags-g0328gwp.js → storage-tags-jfewemtk.js} +1 -1
  22. package/dist/subagent-entry.js +9 -9
  23. package/dist/tag-snapshot-worker-pi.js +3 -3
  24. package/dist/{v2-archive-reader-hg4c36em.js → v2-archive-reader-hveb3ajf.js} +1 -1
  25. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-tn38he5d.js";
157
+ } from "./index-tz8431zx.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -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-xgkq843e.js";
406
407
  import {
407
408
  textMentionsRecentCommit,
408
409
  hasMeaningfulUserText2,
@@ -453,7 +454,7 @@ import {
453
454
  openCurrentDatabase,
454
455
  openDatabaseAsync,
455
456
  closeDatabase
456
- } from "./index-625kbnqd.js";
457
+ } from "./index-0133ybm6.js";
457
458
  import {
458
459
  LkgRecoveryFenceError,
459
460
  clearLkgFenceProcessState,
@@ -467,6 +468,9 @@ import {
467
468
  forgetUnpublishedAutoSearchNoHint,
468
469
  registerAutoSearchWork,
469
470
  cancelAutoSearchWork,
471
+ PI_IDENTITY_FOLD_GUARD_LIMIT,
472
+ readPiIdentityFoldGuards,
473
+ writePiIdentityFoldGuards,
470
474
  readSessionActivity,
471
475
  observeSessionActivity,
472
476
  backfillSessionActivity,
@@ -561,6 +565,7 @@ import {
561
565
  externalHistorianFailureReason,
562
566
  subprocessExitHistorianFailureReason,
563
567
  countHistorianRuns,
568
+ getRecentFailedHistorianRunTimes,
564
569
  recordHistorianRun,
565
570
  summarizeImportance,
566
571
  tallyFactsByCategory,
@@ -576,7 +581,7 @@ import {
576
581
  getSourceContents,
577
582
  recordSubagentInvocation,
578
583
  getLatestHistorianInvocationId
579
- } from "./index-k2z7r444.js";
584
+ } from "./index-mbzqrp0s.js";
580
585
  import {
581
586
  resolveOpenCodeDbPath,
582
587
  assertOpenCodeStoreGeneration,
@@ -642,7 +647,7 @@ import {
642
647
  getRawSessionTagKeysThrough2,
643
648
  getLegacyProtectedTailStartOrdinal2,
644
649
  readSessionChunk2
645
- } from "./index-rekymyxd.js";
650
+ } from "./index-7mvsg371.js";
646
651
  import"./index-nvh6d3bz.js";
647
652
  import {
648
653
  formatSynapseLaneDescriptor
@@ -682,7 +687,7 @@ import {
682
687
  clearCompressionDepthRange,
683
688
  cleanSearchText,
684
689
  matchedSearchSnippet
685
- } from "./index-2pptpxq8.js";
690
+ } from "./index-15rx61th.js";
686
691
  import {
687
692
  rememberV1HiddenRun
688
693
  } from "./index-6x556c2q.js";
@@ -811,7 +816,7 @@ import {
811
816
  scheduleClearAndReindex,
812
817
  clearSessionTracking,
813
818
  createAutoSearchDiagnostics
814
- } from "./index-c3mms4dp.js";
819
+ } from "./index-8ej7crnf.js";
815
820
  import"./index-xssjy4z9.js";
816
821
  import {
817
822
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -828,6 +833,7 @@ import {
828
833
  import {
829
834
  PI_CONTEXT_BUDGET,
830
835
  PiContextDeadlineError,
836
+ PiHistorianJoinDeadlineError,
831
837
  PiContextSupersededError,
832
838
  PiContextBudget,
833
839
  PiTagHydrationError,
@@ -839,11 +845,11 @@ import {
839
845
  drainPiTagSnapshotSession,
840
846
  assertPiTagSnapshotReady,
841
847
  ensurePiTagSnapshotReady
842
- } from "./index-nhpvvdhw.js";
848
+ } from "./index-mmwgmz8f.js";
843
849
  import"./index-yjgkjkjs.js";
844
850
  import"./index-8d2z6503.js";
845
- import"./index-6ahmfva8.js";
846
- import"./index-9kaj9ty1.js";
851
+ import"./index-15eq9z3a.js";
852
+ import"./index-prhdb9c5.js";
847
853
  import {
848
854
  __toESM
849
855
  } from "./index-22jkk6wg.js";
@@ -3595,7 +3601,7 @@ function startHostStallProfilerSwitch() {
3595
3601
  // package.json
3596
3602
  var package_default = {
3597
3603
  name: "@cortexkit/pi-magic-context",
3598
- version: "0.49.55",
3604
+ version: "0.49.57",
3599
3605
  type: "module",
3600
3606
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3601
3607
  main: "dist/index.js",
@@ -3675,6 +3681,8 @@ var package_default = {
3675
3681
  "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
3676
3682
  "omp-pi-ai-18186": "npm:@oh-my-pi/pi-ai@18.18.6",
3677
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",
3678
3686
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3679
3687
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3680
3688
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -27180,6 +27188,140 @@ function foldExecutesThisPass(foldDue, materialized) {
27180
27188
  return foldDue && materialized;
27181
27189
  }
27182
27190
 
27191
+ // ../plugin/src/hooks/magic-context/historian-failure-report.ts
27192
+ var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
27193
+ var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
27194
+ 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.";
27195
+ var REFUSAL_ERROR_MAX_CHARS = 500;
27196
+ var WARNING_ERROR_MAX_CHARS = 200;
27197
+ function readHistorianFailureStreak(db, sessionId, options = {}) {
27198
+ const state = getHistorianFailureState(db, sessionId);
27199
+ const count = state.failureCount;
27200
+ let since = null;
27201
+ if (count > 0) {
27202
+ const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
27203
+ if (recorded <= 0) {
27204
+ since = state.lastFailureAt;
27205
+ } else {
27206
+ const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
27207
+ since = times.length === recorded ? times[recorded - 1] ?? null : null;
27208
+ }
27209
+ }
27210
+ return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
27211
+ }
27212
+ function formatHistorianClockTime(at, now = Date.now()) {
27213
+ const date = new Date(at);
27214
+ const pad = (value) => String(value).padStart(2, "0");
27215
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
27216
+ const today = new Date(now);
27217
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
27218
+ return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
27219
+ }
27220
+ function formatHistorianSeconds(ms) {
27221
+ const seconds = Math.max(0, ms) / 1000;
27222
+ return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
27223
+ }
27224
+ function singleLine(text) {
27225
+ return text.replace(/\s+/g, " ").trim();
27226
+ }
27227
+ function quoteError(error, maxChars) {
27228
+ const text = sanitizeDiagnosticText(singleLine(error));
27229
+ return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
27230
+ }
27231
+ function endSentence(text) {
27232
+ return /[.!?]$/.test(text) ? text : `${text}.`;
27233
+ }
27234
+ function usageClause(usagePercentage) {
27235
+ return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
27236
+ }
27237
+ function capitalize(text) {
27238
+ return text.charAt(0).toUpperCase() + text.slice(1);
27239
+ }
27240
+ function chunkLabel(chunk) {
27241
+ return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
27242
+ }
27243
+ function streakSentence(failures, now) {
27244
+ if (failures.count <= 0)
27245
+ return null;
27246
+ const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
27247
+ return `Summary runs failed in a row: ${failures.count}${since}.`;
27248
+ }
27249
+ function failureBelongsToRun(failures, run) {
27250
+ return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
27251
+ }
27252
+ function describeHistorianJoinRefusal(input) {
27253
+ const now = input.now ?? Date.now();
27254
+ const { run, failures } = input;
27255
+ const sentences = [
27256
+ `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.`
27257
+ ];
27258
+ const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
27259
+ const ownFailure = failureBelongsToRun(failures, run);
27260
+ const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
27261
+ if (ownFailure) {
27262
+ sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
27263
+ } else if (run && run.endedAt === undefined) {
27264
+ sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
27265
+ } else if (run) {
27266
+ sentences.push(`${subject} finished after the wait ended.`);
27267
+ }
27268
+ if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
27269
+ sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
27270
+ }
27271
+ const streak = streakSentence(failures, now);
27272
+ if (streak)
27273
+ sentences.push(streak);
27274
+ sentences.push(ACTIONS);
27275
+ return sentences.join(" ");
27276
+ }
27277
+ function describeRepeatedHistorianFailures(input) {
27278
+ const now = input.now ?? Date.now();
27279
+ const { failures } = input;
27280
+ const facts = [
27281
+ streakSentence(failures, now) ?? "Summary runs are failing.",
27282
+ ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
27283
+ ...failures.lastError ? [
27284
+ endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
27285
+ ] : [],
27286
+ `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
27287
+ ];
27288
+ return [
27289
+ "## Magic Context — History summaries keep failing",
27290
+ "",
27291
+ facts.join(" "),
27292
+ "",
27293
+ ACTIONS
27294
+ ].join(`
27295
+ `);
27296
+ }
27297
+ var repeatedFailureWarnings = new Map;
27298
+ function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
27299
+ const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
27300
+ if (failureCount < step || failureCount % step !== 0)
27301
+ return false;
27302
+ const last = repeatedFailureWarnings.get(sessionId);
27303
+ if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
27304
+ return false;
27305
+ }
27306
+ repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
27307
+ return true;
27308
+ }
27309
+ function takeRepeatedHistorianFailureWarning(input) {
27310
+ const now = input.now ?? Date.now();
27311
+ if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
27312
+ return null;
27313
+ }
27314
+ const failures = readHistorianFailureStreak(input.db, input.sessionId, {
27315
+ unrecordedFailures: input.unrecordedFailures
27316
+ });
27317
+ return describeRepeatedHistorianFailures({
27318
+ chunk: input.chunk,
27319
+ failures: { ...failures, count: input.failureCount },
27320
+ usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
27321
+ now
27322
+ });
27323
+ }
27324
+
27183
27325
  // ../plugin/src/hooks/magic-context/reasoning-removal.ts
27184
27326
  var REMOVABLE_REASONING_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
27185
27327
 
@@ -30850,6 +30992,37 @@ async function runPiHistorian(deps) {
30850
30992
  });
30851
30993
  }
30852
30994
  };
30995
+ let selectedChunk;
30996
+ const notifyCountedFailure = async (failureCount, notice) => {
30997
+ let warning = null;
30998
+ try {
30999
+ warning = takeRepeatedHistorianFailureWarning({
31000
+ db,
31001
+ sessionId,
31002
+ failureCount,
31003
+ chunk: selectedChunk,
31004
+ unrecordedFailures: 1
31005
+ });
31006
+ } catch (error) {
31007
+ sessionLog2(sessionId, "historian repeated-failure warning failed", {
31008
+ error: describeError(error).brief
31009
+ });
31010
+ }
31011
+ if (!warning) {
31012
+ await notify(notice);
31013
+ return;
31014
+ }
31015
+ issueNotified = true;
31016
+ lastHistorianAlertBySession.set(sessionId, Date.now());
31017
+ sessionLog2(sessionId, `historian repeated-failure warning sent: count=${failureCount}`);
31018
+ try {
31019
+ await notifyIssue?.(warning);
31020
+ } catch (error) {
31021
+ sessionLog2(sessionId, "historian notify failed", {
31022
+ error: describeError(error).brief
31023
+ });
31024
+ }
31025
+ };
30853
31026
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
30854
31027
  const invocationBaseline = getLatestHistorianInvocationId(db, sessionId);
30855
31028
  const telemetry = {
@@ -30875,7 +31048,7 @@ async function runPiHistorian(deps) {
30875
31048
  sessionLog2(sessionId, `historian failure: source=existing-validation reason="${existingValidationError}"`);
30876
31049
  {
30877
31050
  const failCount = incrementHistorianFailure(db, sessionId, existingValidationError);
30878
- await notify(buildHistorianFailureNotice(failCount, existingValidationError));
31051
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, existingValidationError));
30879
31052
  }
30880
31053
  return;
30881
31054
  }
@@ -30976,9 +31149,9 @@ async function runPiHistorian(deps) {
30976
31149
  return;
30977
31150
  }
30978
31151
  sessionLog2(sessionId, `historian failure: source=prompt-fit reason="${promptFit.reason}"`);
30979
- incrementHistorianFailure(db, sessionId, promptFit.reason);
31152
+ const failCount = incrementHistorianFailure(db, sessionId, promptFit.reason);
30980
31153
  retainDrainReservationForRetryThrottle = true;
30981
- await notify(buildHistorianWindowTooSmallNotice());
31154
+ await notifyCountedFailure(failCount, buildHistorianWindowTooSmallNotice());
30982
31155
  return;
30983
31156
  }
30984
31157
  const chunkTokens = promptFit.chunkTokens;
@@ -31006,6 +31179,8 @@ async function runPiHistorian(deps) {
31006
31179
  drainReservation = reserve.reservation;
31007
31180
  const chunk = readSessionChunk2(sessionId, chunkTokens, offset, eligibleEndOrdinal, { expandTools: deps.expandTools });
31008
31181
  const forceKeepLastCompartmentForChunk = forceKeepLastCompartment === true && !chunk.hasMore;
31182
+ selectedChunk = { start: chunk.startIndex, end: chunk.endIndex };
31183
+ deps.onChunkSelected?.(selectedChunk);
31009
31184
  if (!chunk.text || chunk.messageCount === 0) {
31010
31185
  if (persistFilteredNoise(db, sessionId, chunk, eligibleEndOrdinal)) {
31011
31186
  telemetry.status = "noop";
@@ -31034,7 +31209,7 @@ async function runPiHistorian(deps) {
31034
31209
  sessionLog2(sessionId, `historian failure: source=chunk-coverage reason="${chunkCoverageError}" chunkRange=${chunk.startIndex}-${chunk.endIndex}`);
31035
31210
  {
31036
31211
  const failCount = incrementHistorianFailure(db, sessionId, chunkCoverageError);
31037
- await notify(buildHistorianFailureNotice(failCount, chunkCoverageError));
31212
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, chunkCoverageError));
31038
31213
  }
31039
31214
  rollbackDrainReservation();
31040
31215
  return;
@@ -31233,7 +31408,7 @@ ${chunkText}`,
31233
31408
  sessionLog2(sessionId, `historian failure: ${errorMsg}`);
31234
31409
  {
31235
31410
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31236
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31411
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31237
31412
  }
31238
31413
  return;
31239
31414
  }
@@ -31290,7 +31465,7 @@ ${chunkText}`,
31290
31465
  sessionLog2(sessionId, `historian failure: source=no-progress newCompartmentCount=${newCompartments.length} lastNewEnd=${lastNewEnd} priorEnd=${offset - 1}`);
31291
31466
  {
31292
31467
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31293
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31468
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31294
31469
  }
31295
31470
  recordHistorianNoProgress(boundarySnapshot, inEmergency);
31296
31471
  rollbackDrainReservation();
@@ -31505,7 +31680,7 @@ ${chunkText}`,
31505
31680
  sessionLog2(sessionId, `historian failure: source=exception ${desc.brief}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
31506
31681
  if (!issueNotified) {
31507
31682
  const failCount = incrementHistorianFailure(db, sessionId, desc.brief);
31508
- await notify(buildHistorianFailureNotice(failCount, desc.brief));
31683
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, desc.brief));
31509
31684
  }
31510
31685
  } finally {
31511
31686
  if (!completedSuccessfully) {
@@ -37036,12 +37211,93 @@ function isOmpAdvisorRequest(payload) {
37036
37211
  `) === true;
37037
37212
  }
37038
37213
  function isOmpUnmanagedCaptureRequest(payload) {
37214
+ return isOmpLegacyCaptureRequest(payload) || isOmpAutolearnCapture(payload);
37215
+ }
37216
+ function isOmpLegacyCaptureRequest(payload) {
37039
37217
  const request = providerRequest(payload);
37040
37218
  if (!request?.tools.length || !request.tools.every((name) => name === "manage_skill" || name === "learn"))
37041
37219
  return false;
37042
37220
  const last = record3(request.messages.at(-1));
37043
37221
  return last?.role === "user" && firstText(last.content, request.textType)?.startsWith(CAPTURE_PREFIX) === true;
37044
37222
  }
37223
+ 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.";
37224
+ var DATE_CWD_REMINDER = /^<system-reminder>\nToday: [^\n]*; current working directory: '[^\n]*'\. Do not repeat this information in your reply\.\n<\/system-reminder>(?:\n|$)/;
37225
+ function textBlocks(value, type) {
37226
+ if (typeof value === "string")
37227
+ return [value];
37228
+ if (!Array.isArray(value))
37229
+ return;
37230
+ const texts = [];
37231
+ for (const block of value) {
37232
+ const part = record3(block);
37233
+ if (part?.type !== type || typeof part.text !== "string")
37234
+ return;
37235
+ texts.push(part.text);
37236
+ }
37237
+ return texts;
37238
+ }
37239
+ function isCapturePrompt(row, type) {
37240
+ if (row.role !== "user" && row.role !== "developer")
37241
+ return false;
37242
+ const texts = textBlocks(row.content, type);
37243
+ if (!texts?.length)
37244
+ return false;
37245
+ let [first, ...rest] = texts;
37246
+ first = first.replace(DATE_CWD_REMINDER, "");
37247
+ if (first === "" && rest.length)
37248
+ [first, ...rest] = rest;
37249
+ return rest.length === 0 && first === OMP_AUTOLEARN_CAPTURE_PROMPT;
37250
+ }
37251
+ var RESPONSES_TURN_ITEMS = new Set([
37252
+ "reasoning",
37253
+ "function_call",
37254
+ "function_call_output",
37255
+ "custom_tool_call",
37256
+ "custom_tool_call_output"
37257
+ ]);
37258
+ function isCaptureTurnRow(row) {
37259
+ if (row.role === "assistant" || row.role === "tool")
37260
+ return true;
37261
+ if (typeof row.type === "string" && RESPONSES_TURN_ITEMS.has(row.type))
37262
+ return true;
37263
+ if (isOmpJuiceItem(row))
37264
+ return true;
37265
+ return row.role === "user" && Array.isArray(row.content) && row.content.length > 0 && row.content.every((block) => record3(block)?.type === "tool_result");
37266
+ }
37267
+ function isOmpAutolearnCapture(payload) {
37268
+ const request = providerRequest(payload);
37269
+ if (!request?.tools.some((name) => name === "manage_skill" || name === "learn"))
37270
+ return false;
37271
+ for (let index = request.messages.length - 1;index >= 0; index--) {
37272
+ const row = record3(request.messages[index]);
37273
+ if (!row)
37274
+ return false;
37275
+ if (isCaptureTurnRow(row))
37276
+ continue;
37277
+ return isCapturePrompt(row, request.textType);
37278
+ }
37279
+ return false;
37280
+ }
37281
+ var JUICE_VALUES = new Set(["0", "2", "4", "8", "48", "112", "960"]);
37282
+ function isOmpJuiceItem(value) {
37283
+ const item = record3(value);
37284
+ if (!item || Object.keys(item).length !== 2 || item.role !== "developer")
37285
+ return false;
37286
+ const content = item.content;
37287
+ if (!Array.isArray(content) || content.length !== 1)
37288
+ return false;
37289
+ const part = record3(content[0]);
37290
+ if (!part || Object.keys(part).length !== 2 || part.type !== "input_text")
37291
+ return false;
37292
+ const juice = /^# Juice: (\d+) !important$/.exec(String(part.text));
37293
+ return juice !== null && JUICE_VALUES.has(juice[1]);
37294
+ }
37295
+ function piWithoutOmpJuice(payload, model) {
37296
+ const body = record3(payload);
37297
+ if (model?.api !== "openai-responses" || record3(model.compat)?.requiresReasoningOffJuiceInstruction !== true || !body || !Array.isArray(body.input) || !isOmpJuiceItem(body.input.at(-1)))
37298
+ return payload;
37299
+ return { ...body, input: body.input.slice(0, -1) };
37300
+ }
37045
37301
 
37046
37302
  // src/pi-dispatch-date-reminder.ts
37047
37303
  function object(value) {
@@ -37854,7 +38110,7 @@ ${wellFormed2(text)}
37854
38110
  </think>`;
37855
38111
  return;
37856
38112
  }
37857
- function coldReplayable(items) {
38113
+ function piResponsesColdReplayable(items) {
37858
38114
  let reasoning = false;
37859
38115
  for (const value of items) {
37860
38116
  const item = object8(value);
@@ -37976,7 +38232,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
37976
38232
  return texts;
37977
38233
  if (unsigned && alternatives) {
37978
38234
  alternatives.fallback = texts;
37979
- alternatives.cold = coldReplayable(payload.items) ? replay : texts;
38235
+ alternatives.cold = piResponsesColdReplayable(payload.items) ? replay : texts;
37980
38236
  }
37981
38237
  return replay;
37982
38238
  }
@@ -38001,15 +38257,270 @@ function piResponsesWireTexts(value, phase) {
38001
38257
  return texts;
38002
38258
  }
38003
38259
 
38260
+ // src/pi-dispatch-responses-replay.ts
38261
+ function object9(value) {
38262
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38263
+ }
38264
+ var RESPONSES_APIS3 = ["openai-responses", "azure-openai-responses"];
38265
+ function callBase(id) {
38266
+ const separator = id.search(/[\n|]/);
38267
+ return separator > 0 ? id.slice(0, separator) : separator === 0 ? id.slice(1) : id;
38268
+ }
38269
+ function piResponsesReplayedCalls(value, calls, wireCalls, model) {
38270
+ const message = object9(value);
38271
+ if (message?.role !== "assistant" || !model?.api)
38272
+ return;
38273
+ if (!RESPONSES_APIS3.includes(model.api))
38274
+ return;
38275
+ if (message.api !== model.api || message.model !== model.id || typeof model.provider !== "string")
38276
+ return;
38277
+ const payload = object9(message.providerPayload);
38278
+ if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items) || (payload.provider ?? message.provider ?? model.provider) !== model.provider)
38279
+ return;
38280
+ const stored = [];
38281
+ const order = [];
38282
+ let output = false;
38283
+ for (const value of payload.items) {
38284
+ const item = object9(value);
38285
+ if (item?.type === "reasoning")
38286
+ continue;
38287
+ if (item?.type === "function_call" || item?.type === "custom_tool_call") {
38288
+ if (typeof item.call_id !== "string" || !item.call_id.trim())
38289
+ return;
38290
+ stored.push(item.call_id);
38291
+ order.push("call");
38292
+ output = true;
38293
+ continue;
38294
+ }
38295
+ if (item?.type !== "message" || item.role !== "assistant" || !Array.isArray(item.content))
38296
+ return;
38297
+ const texts = [];
38298
+ for (const value of item.content) {
38299
+ const part = object9(value);
38300
+ if (part?.type !== "output_text" || typeof part.text !== "string")
38301
+ return;
38302
+ texts.push(part.text);
38303
+ }
38304
+ if (!texts.some((text) => /\S/u.test(text)))
38305
+ continue;
38306
+ output = true;
38307
+ for (const _text of texts)
38308
+ order.push("text");
38309
+ }
38310
+ if (!output)
38311
+ return;
38312
+ const recorded = new Set(stored.map(callBase));
38313
+ const replayed = [...stored];
38314
+ const wires = [...stored];
38315
+ for (let index = 0;index < calls.length; index++) {
38316
+ if (recorded.has(callBase(calls[index])))
38317
+ continue;
38318
+ const wire = wireCalls?.[index];
38319
+ if (wire === undefined)
38320
+ return;
38321
+ replayed.push(calls[index]);
38322
+ wires.push(wire);
38323
+ order.push("call");
38324
+ }
38325
+ if (wireCalls && wires.length === wireCalls.length && wires.every((id, index) => id === wireCalls[index]))
38326
+ return;
38327
+ return {
38328
+ calls: replayed,
38329
+ wireCalls: wires,
38330
+ stored: stored.length,
38331
+ order,
38332
+ cold: piResponsesColdReplayable(payload.items)
38333
+ };
38334
+ }
38335
+ function batchKind(item) {
38336
+ return item.kind === "text" ? "assistant-message" : item.kind === "call" || item.kind === "output" ? item.kind : "other";
38337
+ }
38338
+ function batchCallId(item) {
38339
+ return item.kind === "call" ? item.wire : item.kind === "output" ? item.id : undefined;
38340
+ }
38341
+ function hoistBatchMessages(items) {
38342
+ const hasEarlierBatchCall = (index, callId) => {
38343
+ for (let probe = index - 1;probe >= 0; probe--) {
38344
+ const kind = batchKind(items[probe]);
38345
+ if (kind === "other")
38346
+ return false;
38347
+ if (kind === "call" && batchCallId(items[probe]) === callId)
38348
+ return true;
38349
+ }
38350
+ return false;
38351
+ };
38352
+ const bucketOf = new Map;
38353
+ const insertBefore = new Map;
38354
+ for (let index = 0;index < items.length; index++) {
38355
+ if (batchKind(items[index]) !== "output")
38356
+ continue;
38357
+ if (index > 0 && batchKind(items[index - 1]) === "output")
38358
+ continue;
38359
+ const pending = new Set;
38360
+ for (let probe = index;probe < items.length; probe++) {
38361
+ if (batchKind(items[probe]) !== "output")
38362
+ break;
38363
+ const callId = batchCallId(items[probe]);
38364
+ if (callId)
38365
+ pending.add(callId);
38366
+ }
38367
+ let start = index;
38368
+ let sawCall = false;
38369
+ const messageIndexes = [];
38370
+ while (start > 0) {
38371
+ const item = items[start - 1];
38372
+ const kind = batchKind(item);
38373
+ if (kind === "call") {
38374
+ sawCall = true;
38375
+ const callId = batchCallId(item);
38376
+ if (callId)
38377
+ pending.delete(callId);
38378
+ } else if (kind === "output") {
38379
+ const callId = batchCallId(item);
38380
+ if (!callId || !hasEarlierBatchCall(start - 1, callId))
38381
+ break;
38382
+ let ownsEarlierCall = false;
38383
+ for (const owned of pending) {
38384
+ if (hasEarlierBatchCall(start - 1, owned)) {
38385
+ ownsEarlierCall = true;
38386
+ break;
38387
+ }
38388
+ }
38389
+ if (!ownsEarlierCall)
38390
+ break;
38391
+ pending.add(callId);
38392
+ } else if (kind === "assistant-message") {
38393
+ messageIndexes.push(start - 1);
38394
+ } else {
38395
+ break;
38396
+ }
38397
+ start -= 1;
38398
+ }
38399
+ if (!sawCall || messageIndexes.length === 0)
38400
+ continue;
38401
+ messageIndexes.reverse();
38402
+ const target = insertBefore.get(start) ?? [];
38403
+ for (const messageIndex of messageIndexes) {
38404
+ const previousStart = bucketOf.get(messageIndex);
38405
+ if (previousStart !== undefined) {
38406
+ const previous = insertBefore.get(previousStart);
38407
+ const slot = previous?.indexOf(messageIndex) ?? -1;
38408
+ if (previous && slot >= 0)
38409
+ previous.splice(slot, 1);
38410
+ }
38411
+ bucketOf.set(messageIndex, start);
38412
+ target.push(messageIndex);
38413
+ }
38414
+ insertBefore.set(start, target);
38415
+ }
38416
+ if (bucketOf.size === 0)
38417
+ return items.slice();
38418
+ const result = [];
38419
+ for (let index = 0;index < items.length; index++) {
38420
+ const pending = insertBefore.get(index);
38421
+ if (pending)
38422
+ for (const messageIndex of pending)
38423
+ result.push(items[messageIndex]);
38424
+ if (bucketOf.has(index))
38425
+ continue;
38426
+ result.push(items[index]);
38427
+ }
38428
+ return result;
38429
+ }
38430
+ function piResponsesReplayRows(entries, placeholder, assistant) {
38431
+ const items = [];
38432
+ for (const entry of entries) {
38433
+ const row = entry.row;
38434
+ if (entry.texts === undefined) {
38435
+ if (row.role !== "toolResult") {
38436
+ items.push({ kind: "other", row });
38437
+ continue;
38438
+ }
38439
+ const wire = row.wireResults?.[0];
38440
+ if (row.results.length !== 1 || wire === undefined)
38441
+ return;
38442
+ items.push({ kind: "output", id: wire, row });
38443
+ continue;
38444
+ }
38445
+ const { texts, replayed } = entry;
38446
+ if (replayed) {
38447
+ const textSlots = replayed.order.filter((kind) => kind === "text");
38448
+ if (textSlots.length !== texts.length)
38449
+ return;
38450
+ let text = 0;
38451
+ let call = 0;
38452
+ for (const kind of replayed.order) {
38453
+ if (kind === "text")
38454
+ items.push({ kind: "text", text: texts[text++], source: row });
38455
+ else {
38456
+ items.push({
38457
+ kind: "call",
38458
+ id: replayed.calls[call],
38459
+ wire: replayed.wireCalls[call],
38460
+ source: row
38461
+ });
38462
+ call++;
38463
+ }
38464
+ }
38465
+ continue;
38466
+ }
38467
+ for (const text of texts)
38468
+ items.push({ kind: "text", text, source: row });
38469
+ for (let index = 0;index < row.calls.length; index++) {
38470
+ const wire = row.wireCalls?.[index];
38471
+ if (wire === undefined)
38472
+ return;
38473
+ items.push({ kind: "call", id: row.calls[index], wire, source: row });
38474
+ }
38475
+ }
38476
+ const preceding = new Set;
38477
+ for (const item of items) {
38478
+ if (item.kind === "call")
38479
+ preceding.add(item.wire);
38480
+ else if (item.kind === "output" && !preceding.has(item.id))
38481
+ return;
38482
+ }
38483
+ const later = new Set;
38484
+ const orphans = new Set;
38485
+ for (let index = items.length - 1;index >= 0; index--) {
38486
+ const item = items[index];
38487
+ if (item.kind === "output")
38488
+ later.add(item.id);
38489
+ else if (item.kind === "call" && !later.has(item.wire))
38490
+ orphans.add(index);
38491
+ }
38492
+ const repaired = items.flatMap((item, index) => item.kind === "call" && orphans.has(index) ? [item, { kind: "output", id: item.wire }] : [item]);
38493
+ const rows = [];
38494
+ let open;
38495
+ for (const item of hoistBatchMessages(repaired)) {
38496
+ if (item.kind === "other" || item.kind === "output") {
38497
+ rows.push(item.kind === "other" ? item.row : item.row ?? placeholder(item.id));
38498
+ open = undefined;
38499
+ continue;
38500
+ }
38501
+ if (!open) {
38502
+ open = assistant(item.source);
38503
+ rows.push(open);
38504
+ }
38505
+ if (item.kind === "text")
38506
+ open.responseTexts?.push(item.text);
38507
+ else {
38508
+ open.calls.push(item.id);
38509
+ open.wireCalls?.push(item.wire);
38510
+ }
38511
+ }
38512
+ return rows;
38513
+ }
38514
+
38004
38515
  // src/pi-dispatch-row-diagnostic.ts
38005
- var object9 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38516
+ var object10 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38006
38517
  function piDispatchRowDiagnostic(role, content) {
38007
38518
  const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : [];
38008
38519
  let kinds = 0;
38009
38520
  let chars = 0;
38010
38521
  let onlyText;
38011
38522
  for (const part of parts) {
38012
- const block = object9(part);
38523
+ const block = object10(part);
38013
38524
  const text = typeof part === "string" ? part : block?.text;
38014
38525
  if (typeof text === "string") {
38015
38526
  kinds |= block?.thought === true ? 16 : 1;
@@ -38140,11 +38651,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
38140
38651
  "devin-agent",
38141
38652
  "apple-foundation-models"
38142
38653
  ]);
38143
- function object10(value) {
38654
+ function object11(value) {
38144
38655
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38145
38656
  }
38146
38657
  function messageStructure(value) {
38147
- const message = object10(value);
38658
+ const message = object11(value);
38148
38659
  if (!message)
38149
38660
  return;
38150
38661
  const role = [
@@ -38174,7 +38685,7 @@ function messageStructure(value) {
38174
38685
  }
38175
38686
  if (role === "assistant" && Array.isArray(message.content)) {
38176
38687
  for (const value of message.content) {
38177
- const block = object10(value);
38688
+ const block = object11(value);
38178
38689
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
38179
38690
  continue;
38180
38691
  if (typeof block.id !== "string")
@@ -38190,7 +38701,7 @@ function windowCalls(message) {
38190
38701
  if (!Array.isArray(message.content))
38191
38702
  return [];
38192
38703
  return message.content.flatMap((value) => {
38193
- const block = object10(value);
38704
+ const block = object11(value);
38194
38705
  return block?.type === "toolCall" && typeof block.id === "string" ? [
38195
38706
  {
38196
38707
  id: block.id,
@@ -38200,7 +38711,7 @@ function windowCalls(message) {
38200
38711
  });
38201
38712
  }
38202
38713
  function duplicateSuffix(model) {
38203
- const compat = object10(model?.compat);
38714
+ const compat = object11(model?.compat);
38204
38715
  if (model?.api === "openai-completions") {
38205
38716
  if (compat?.requiresMistralToolIds === true)
38206
38717
  return { prefix: "dup", max: 9 };
@@ -38215,24 +38726,14 @@ function appendDuplicateSuffix(id, suffix, max) {
38215
38726
  const segment = (part) => part.length + suffix.length <= max ? `${part}${suffix}` : `${part.slice(0, Math.max(0, max - suffix.length))}${suffix}`;
38216
38727
  return id.includes("|") ? id.split("|").map(segment).join("|") : segment(id);
38217
38728
  }
38218
- function projectMissingToolResults(messages, model, host = "omp") {
38219
- const input = messages.filter((value) => {
38220
- const message = object10(value);
38221
- return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
38222
- });
38223
- if (host === "pi")
38224
- return projectPiToolResults(input);
38225
- const api = model?.api;
38226
- if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
38227
- return projectUnmodeledToolResults(messages);
38228
- const pairingId = piToolCallPairing(input);
38729
+ function deduplicateToolCallIds(input, pairingId, model) {
38229
38730
  const { prefix, max } = duplicateSuffix(model);
38230
38731
  const seen = new Map;
38231
38732
  const renames = new Map;
38232
38733
  const realResults = new Map;
38233
38734
  const validToolUseIds = new Set;
38234
38735
  const deduplicated = input.map((value, index) => {
38235
- const message = object10(value);
38736
+ const message = object11(value);
38236
38737
  if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
38237
38738
  let key = pairingId(message.toolCallId);
38238
38739
  let output = value;
@@ -38259,7 +38760,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38259
38760
  const touched = new Set;
38260
38761
  let changed = false;
38261
38762
  const content = message.content.map((part) => {
38262
- const block = object10(part);
38763
+ const block = object11(part);
38263
38764
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38264
38765
  return part;
38265
38766
  const key = pairingId(block.id);
@@ -38291,6 +38792,25 @@ function projectMissingToolResults(messages, model, host = "omp") {
38291
38792
  validToolUseIds.add(pairingId(call.id));
38292
38793
  return changed ? { ...message, content } : value;
38293
38794
  });
38795
+ return { deduplicated, realResults, validToolUseIds };
38796
+ }
38797
+ function piDeduplicatedToolCallIds(messages, model) {
38798
+ if (!TRANSFORM_MESSAGES_APIS.has(model?.api ?? ""))
38799
+ return [...messages];
38800
+ return deduplicateToolCallIds(messages, piToolCallPairing(messages), model).deduplicated;
38801
+ }
38802
+ function projectMissingToolResults(messages, model, host = "omp") {
38803
+ const input = messages.filter((value) => {
38804
+ const message = object11(value);
38805
+ return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
38806
+ });
38807
+ if (host === "pi")
38808
+ return projectPiToolResults(input);
38809
+ const api = model?.api;
38810
+ if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
38811
+ return projectUnmodeledToolResults(messages);
38812
+ const pairingId = piToolCallPairing(input);
38813
+ const { deduplicated, realResults, validToolUseIds } = deduplicateToolCallIds(input, pairingId, model);
38294
38814
  const takeRealResult = (id, afterIndex) => {
38295
38815
  for (const entry of realResults.get(pairingId(id)) ?? []) {
38296
38816
  if (entry.consumed || entry.index <= afterIndex)
@@ -38338,7 +38858,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38338
38858
  };
38339
38859
  for (let index = 0;index < deduplicated.length; index++) {
38340
38860
  const value = deduplicated[index];
38341
- const message = object10(value);
38861
+ const message = object11(value);
38342
38862
  if (message?.role === "assistant") {
38343
38863
  flush(message.timestamp);
38344
38864
  if (piOmitsTruncatedAssistant(message))
@@ -38379,7 +38899,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38379
38899
  if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
38380
38900
  continue;
38381
38901
  const parts = message.content.flatMap((value) => {
38382
- const part = object10(value);
38902
+ const part = object11(value);
38383
38903
  return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
38384
38904
  });
38385
38905
  if (!parts.length)
@@ -38407,11 +38927,11 @@ function projectUnmodeledToolResults(messages) {
38407
38927
  return pipe > 0 ? id.slice(0, pipe) : id;
38408
38928
  };
38409
38929
  for (const value of messages) {
38410
- const message = object10(value);
38930
+ const message = object11(value);
38411
38931
  if (message?.role !== "assistant" || !Array.isArray(message.content))
38412
38932
  continue;
38413
38933
  for (const value of message.content) {
38414
- const block = object10(value);
38934
+ const block = object11(value);
38415
38935
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38416
38936
  continue;
38417
38937
  if ([
@@ -38427,7 +38947,7 @@ function projectUnmodeledToolResults(messages) {
38427
38947
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
38428
38948
  const lastResult = new Map;
38429
38949
  messages.forEach((value, index) => {
38430
- const message = object10(value);
38950
+ const message = object11(value);
38431
38951
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
38432
38952
  lastResult.set(pairingId(message.toolCallId), index);
38433
38953
  });
@@ -38458,7 +38978,7 @@ function projectUnmodeledToolResults(messages) {
38458
38978
  };
38459
38979
  for (let index = 0;index < messages.length; index++) {
38460
38980
  const value = messages[index];
38461
- const message = object10(value);
38981
+ const message = object11(value);
38462
38982
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
38463
38983
  continue;
38464
38984
  if (message?.role !== "toolResult")
@@ -38500,7 +39020,7 @@ function projectPiToolResults(messages) {
38500
39020
  held.length = 0;
38501
39021
  };
38502
39022
  for (const value of messages) {
38503
- const message = object10(value);
39023
+ const message = object11(value);
38504
39024
  const role = message?.role;
38505
39025
  if (role === "assistant") {
38506
39026
  close(message?.timestamp);
@@ -38531,7 +39051,7 @@ function projectPiToolResults(messages) {
38531
39051
  function preparePiDispatch(messages, model, omp, cwd) {
38532
39052
  let output = messages;
38533
39053
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
38534
- if (object10(source.providerPayload)?.type !== "openaiResponsesHistory")
39054
+ if (object11(source.providerPayload)?.type !== "openaiResponsesHistory")
38535
39055
  return;
38536
39056
  if (output === messages)
38537
39057
  output = messages.slice();
@@ -38552,7 +39072,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38552
39072
  if (!messages.length || messages.length > MAX_MESSAGES)
38553
39073
  return;
38554
39074
  for (let index = 0;index < messages.length; index++) {
38555
- const source = object10(messages[index]);
39075
+ const source = object11(messages[index]);
38556
39076
  if (source?.role === "user" || source?.role === "compactionSummary")
38557
39077
  prepareUser?.(index, source);
38558
39078
  }
@@ -38569,7 +39089,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38569
39089
  let valid = true;
38570
39090
  for (let index = 0;index < projectedMessages.length; index++) {
38571
39091
  const message = projectedMessages[index];
38572
- const source = object10(message);
39092
+ const source = object11(message);
38573
39093
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
38574
39094
  continue;
38575
39095
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -38593,7 +39113,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38593
39113
  "azure-openai-responses",
38594
39114
  "openai-codex-responses"
38595
39115
  ].includes(model?.api ?? "") && (source?.role === "user" || source?.role === "developer") && (typeof source.content === "string" ? !source.content.trim() : Array.isArray(source.content) && !source.content.some((value) => {
38596
- const block = object10(value);
39116
+ const block = object11(value);
38597
39117
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
38598
39118
  })))
38599
39119
  continue;
@@ -38637,12 +39157,12 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38637
39157
  const positionedRows = [...byIndex];
38638
39158
  for (let position = positionedRows.length - 1;position >= 0; position--) {
38639
39159
  const [index, row] = positionedRows[position];
38640
- const source = object10(projectedMessages[index]);
39160
+ const source = object11(projectedMessages[index]);
38641
39161
  if (!source)
38642
39162
  return;
38643
39163
  const content = source.content;
38644
39164
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
38645
- const textOnly = Array.isArray(parts) && parts.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string");
39165
+ const textOnly = Array.isArray(parts) && parts.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string");
38646
39166
  const systemTexts = () => {
38647
39167
  const texts = parts.map((part) => part.text);
38648
39168
  return model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
@@ -38650,7 +39170,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38650
39170
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
38651
39171
  const previous = rows[position - 1];
38652
39172
  const next = rows[position + 1];
38653
- const anthropicPromotable = model?.api === "anthropic-messages" && object10(model.compat)?.supportsMidConversationSystem === true && textOnly;
39173
+ const anthropicPromotable = model?.api === "anthropic-messages" && object11(model.compat)?.supportsMidConversationSystem === true && textOnly;
38654
39174
  if (anthropicPromotable)
38655
39175
  promotable.set(row, systemTexts());
38656
39176
  if (model?.api === "ollama-chat" || anthropicPromotable && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
@@ -38679,6 +39199,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38679
39199
  const fallbackMessages = [];
38680
39200
  const coldMessages = [];
38681
39201
  let unsignedAlternatives = false;
39202
+ const planRows = [];
38682
39203
  const appendResponse = (output, row, texts) => {
38683
39204
  if (!texts.length && !row.calls.length)
38684
39205
  return;
@@ -38701,6 +39222,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38701
39222
  responsesMessages.push(row);
38702
39223
  fallbackMessages.push(row);
38703
39224
  coldMessages.push(row);
39225
+ planRows.push({ row });
38704
39226
  continue;
38705
39227
  }
38706
39228
  const alternatives = {};
@@ -38713,8 +39235,42 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38713
39235
  appendResponse(responsesMessages, row, texts);
38714
39236
  appendResponse(fallbackMessages, row, alternatives.fallback ?? texts);
38715
39237
  appendResponse(coldMessages, row, alternatives.cold ?? texts);
39238
+ planRows.push({
39239
+ row,
39240
+ texts: {
39241
+ warm: texts,
39242
+ fallback: alternatives.fallback ?? texts,
39243
+ cold: alternatives.cold ?? texts
39244
+ },
39245
+ replayed: host === "omp" ? piResponsesReplayedCalls(projectedMessages[index], row.calls, row.wireCalls, model) : undefined
39246
+ });
38716
39247
  }
38717
39248
  }
39249
+ const replays = planRows.some((entry) => entry.replayed);
39250
+ const replayPlan = (rows, plan) => {
39251
+ if (!replays)
39252
+ return rows;
39253
+ const replayedIn = (entry) => plan === "warm" || plan === "cold" && entry.replayed?.cold ? entry.replayed : undefined;
39254
+ if (!planRows.some(replayedIn))
39255
+ return rows;
39256
+ return piResponsesReplayRows(planRows.map((entry) => entry.texts ? {
39257
+ row: entry.row,
39258
+ texts: entry.texts[plan],
39259
+ replayed: replayedIn(entry)
39260
+ } : { row: entry.row }), (callId) => ({
39261
+ role: "toolResult",
39262
+ calls: [],
39263
+ results: [callId],
39264
+ wireResults: [callId]
39265
+ }), (source) => ({
39266
+ ...source,
39267
+ calls: [],
39268
+ wireCalls: [],
39269
+ responseTexts: []
39270
+ })) ?? rows;
39271
+ };
39272
+ if (responsesMessages)
39273
+ responsesMessages = replayPlan(responsesMessages, "warm");
38718
39274
  const plan = piChatHistoryPlan(projectedMessages, model);
38719
39275
  let pendingToolImages = [];
38720
39276
  const chatMessages = plan?.flatMap((step) => {
@@ -38747,12 +39303,17 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38747
39303
  ...responsesApi && !responsesMessages ? { structuralSkipReason: "Responses history transform is not modeled" } : model?.api === "openai-completions" && !chatMessages ? { structuralSkipReason: "Chat history transform is not modeled" } : {},
38748
39304
  ...chatMessages ? { chatMessages } : {},
38749
39305
  ...responsesMessages ? { responsesMessages } : {},
38750
- ...responsesMessages && unsignedAlternatives ? { responsesAlternatives: [fallbackMessages, coldMessages] } : {},
39306
+ ...responsesMessages && (unsignedAlternatives || replays) ? {
39307
+ responsesAlternatives: [
39308
+ replayPlan(fallbackMessages, "fallback"),
39309
+ replayPlan(coldMessages, "cold")
39310
+ ]
39311
+ } : {},
38751
39312
  ...model?.api ? { api: model.api } : {},
38752
39313
  ...modelsContinuePad ? { anthropicContinuePad: true } : {},
38753
39314
  ...modelsContinuePad && baseRows.some((row) => row.optionalThinking) ? { anthropicOptional: { rows: baseRows, promotable } } : {},
38754
39315
  ...model?.api?.startsWith("google-") ? {
38755
- googleFunctionIds: object10(model.compat)?.supportsFunctionPartId === true
39316
+ googleFunctionIds: object11(model.compat)?.supportsFunctionPartId === true
38756
39317
  } : {}
38757
39318
  };
38758
39319
  preparedSources.set(prepared, { messages: projectedMessages, rows: byIndex });
@@ -38760,8 +39321,8 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38760
39321
  dateReminderPlans.set(prepared, {
38761
39322
  ...modelsContinuePad ? { plan: { rows: baseRows, promotable } } : {},
38762
39323
  firstUser: firstUserRow ? baseRows.indexOf(firstUserRow) : -1,
38763
- midConversationSystem: object10(model?.compat)?.supportsMidConversationSystem === true,
38764
- developerRole: object10(model?.compat)?.supportsDeveloperRole === true
39324
+ midConversationSystem: object11(model?.compat)?.supportsMidConversationSystem === true,
39325
+ developerRole: object11(model?.compat)?.supportsDeveloperRole === true
38765
39326
  });
38766
39327
  return prepared;
38767
39328
  }
@@ -38781,7 +39342,7 @@ function responsesLane(api) {
38781
39342
  ].includes(api ?? "");
38782
39343
  }
38783
39344
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false, trackRows = false) {
38784
- const body = object10(payload);
39345
+ const body = object11(payload);
38785
39346
  if (!body)
38786
39347
  return;
38787
39348
  const google = piGoogleConversation(payload);
@@ -38796,12 +39357,12 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38796
39357
  return;
38797
39358
  const rows = [];
38798
39359
  for (const value of messages) {
38799
- const message = object10(value);
39360
+ const message = object11(value);
38800
39361
  if (!message)
38801
39362
  return;
38802
39363
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
38803
39364
  continue;
38804
- if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object10(block)?.type))))
39365
+ if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object11(block)?.type))))
38805
39366
  continue;
38806
39367
  if (responses && message.type === "reasoning")
38807
39368
  continue;
@@ -38878,7 +39439,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38878
39439
  continue;
38879
39440
  }
38880
39441
  if (message.role === "user" && Array.isArray(message.content)) {
38881
- const results = message.content.filter((block) => object10(block)?.type === "tool_result" || bedrock && object10(block)?.toolResult);
39442
+ const results = message.content.filter((block) => object11(block)?.type === "tool_result" || bedrock && object11(block)?.toolResult);
38882
39443
  if (results.length) {
38883
39444
  for (const block of results) {
38884
39445
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -38935,11 +39496,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38935
39496
  }
38936
39497
  if (Array.isArray(message.tool_calls)) {
38937
39498
  for (const call of message.tool_calls) {
38938
- const source = object10(call);
39499
+ const source = object11(call);
38939
39500
  if (!source)
38940
39501
  return;
38941
39502
  if (source.id === undefined && ollama) {
38942
- const fn = object10(source.function);
39503
+ const fn = object11(source.function);
38943
39504
  if (typeof fn?.name !== "string")
38944
39505
  return;
38945
39506
  row.calls.push("");
@@ -38979,7 +39540,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38979
39540
  return;
38980
39541
  const rows = [];
38981
39542
  for (const value of contents) {
38982
- const message = object10(value);
39543
+ const message = object11(value);
38983
39544
  if (!message || !Array.isArray(message.parts))
38984
39545
  return;
38985
39546
  if (message.role !== "user" && message.role !== "model")
@@ -38995,11 +39556,11 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38995
39556
  };
38996
39557
  const results = [];
38997
39558
  for (const value of message.parts) {
38998
- const part = object10(value);
39559
+ const part = object11(value);
38999
39560
  if (!part)
39000
39561
  return;
39001
39562
  if (part.functionCall) {
39002
- const call = object10(part.functionCall);
39563
+ const call = object11(part.functionCall);
39003
39564
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
39004
39565
  return;
39005
39566
  row.calls.push(call.id ?? "");
@@ -39007,7 +39568,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39007
39568
  row.callNames.push(call.name);
39008
39569
  }
39009
39570
  if (part.functionResponse) {
39010
- const result = object10(part.functionResponse);
39571
+ const result = object11(part.functionResponse);
39011
39572
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
39012
39573
  return;
39013
39574
  results.push({
@@ -39022,7 +39583,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39022
39583
  role: "tool-result",
39023
39584
  parts: 1,
39024
39585
  kinds: 8,
39025
- chars: typeof result.response === "string" ? result.response.length : Object.values(object10(result.response) ?? {}).reduce((count, value) => count + (typeof value === "string" ? value.length : 0), 0),
39586
+ chars: typeof result.response === "string" ? result.response.length : Object.values(object11(result.response) ?? {}).reduce((count, value) => count + (typeof value === "string" ? value.length : 0), 0),
39026
39587
  injector: "none"
39027
39588
  });
39028
39589
  }
@@ -39042,6 +39603,10 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39042
39603
  }
39043
39604
  return rows;
39044
39605
  }
39606
+ function sameResponsesIds(expected, actual) {
39607
+ const same = (ids, wire) => ids.length === wire.length && ids.every((id, index) => id === wire[index]);
39608
+ 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));
39609
+ }
39045
39610
  function wireId(id, anthropic, responses) {
39046
39611
  if (anthropic)
39047
39612
  return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
@@ -39055,11 +39620,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
39055
39620
  if (responses || googleOrBedrock) {
39056
39621
  if (!Array.isArray(content) || content.length !== 1)
39057
39622
  return false;
39058
- const block = object10(content[0]);
39623
+ const block = object11(content[0]);
39059
39624
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
39060
39625
  }
39061
39626
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
39062
- const block = content.length === 1 ? object10(content[0]) : undefined;
39627
+ const block = content.length === 1 ? object11(content[0]) : undefined;
39063
39628
  return block?.type === "text" && block.text === text;
39064
39629
  }
39065
39630
  return content === text;
@@ -39245,15 +39810,15 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39245
39810
  }))) : undefined;
39246
39811
  const plan = prepared && dateReminderPlans.get(prepared);
39247
39812
  try {
39248
- const body = plan ? object10(payload) : undefined;
39813
+ const body = plan ? object11(payload) : undefined;
39249
39814
  const messages = body?.messages ?? body?.input;
39250
39815
  if (Array.isArray(messages)) {
39251
39816
  for (const value of messages) {
39252
- const message = object10(value);
39817
+ const message = object11(value);
39253
39818
  if (message?.role !== "system" && message?.role !== "developer")
39254
39819
  break;
39255
39820
  const content = message.content;
39256
- const inputText = Array.isArray(content) && content.length === 1 && object10(content[0])?.type === "input_text" ? object10(content[0])?.text : undefined;
39821
+ const inputText = Array.isArray(content) && content.length === 1 && object11(content[0])?.type === "input_text" ? object11(content[0])?.text : undefined;
39257
39822
  if (piDateReminderWireText(content, plan?.cwd) !== undefined || piDateReminderText(inputText, plan?.cwd))
39258
39823
  return "comparison=role";
39259
39824
  }
@@ -39269,7 +39834,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39269
39834
  if (plan.firstUser < 0)
39270
39835
  return mismatch;
39271
39836
  const root = prepared.messages[plan.firstUser];
39272
- const body = object10(payload);
39837
+ const body = object11(payload);
39273
39838
  const routeRows = Array.isArray(body?.input) ? prepared.responsesMessages ?? prepared.messages : prepared.api === "openai-completions" ? prepared.chatMessages ?? prepared.messages : prepared.messages;
39274
39839
  const firstUser = routeRows.indexOf(root);
39275
39840
  if (firstUser < 0)
@@ -39280,11 +39845,11 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39280
39845
  });
39281
39846
  return filtered === undefined ? mismatch : preparedStructureMismatch(filtered, prepared, onImageTrim, undefined, undefined, undefined, aligned);
39282
39847
  }
39283
- const messages = object10(payload)?.messages;
39848
+ const messages = object11(payload)?.messages;
39284
39849
  if (!Array.isArray(messages))
39285
39850
  return mismatch;
39286
39851
  for (const value of messages) {
39287
- const message = object10(value);
39852
+ const message = object11(value);
39288
39853
  if (piDateReminderWireText(message?.content, plan.cwd) !== undefined && Object.keys(message ?? {}).some((key) => !["role", "content"].includes(key)))
39289
39854
  return mismatch;
39290
39855
  }
@@ -39324,7 +39889,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39324
39889
  return "comparison=image count";
39325
39890
  const imageProjection = trimmed > 0;
39326
39891
  stage = "wire rows";
39327
- const body = object10(payload);
39892
+ const body = object11(payload);
39328
39893
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
39329
39894
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39330
39895
  rows = reminderWire ?? payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection, !!onAlignment);
@@ -39333,7 +39898,12 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39333
39898
  expectedRows = responses && prepared?.responsesMessages ? prepared.responsesMessages : chat && prepared?.chatMessages ? prepared.chatMessages : prepared?.messages;
39334
39899
  if (responses && rows && prepared?.responsesAlternatives) {
39335
39900
  const actual = rows;
39336
- 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;
39901
+ const candidates = [
39902
+ prepared.responsesMessages,
39903
+ ...prepared.responsesAlternatives
39904
+ ];
39905
+ const sameTexts = (candidate) => candidate?.length === actual.length && candidate.every((expected, index) => JSON.stringify(expected.responseTexts) === JSON.stringify(actual[index].responseTexts));
39906
+ expectedRows = candidates.find((candidate) => sameTexts(candidate) && !!candidate && sameResponsesIds(candidate, actual)) ?? candidates.find(sameTexts) ?? expectedRows;
39337
39907
  }
39338
39908
  const optionalPlan = expectedRows === prepared?.messages ? prepared?.anthropicOptional : undefined;
39339
39909
  if (expectedRows && imageProjection && imageBudget)
@@ -39351,7 +39921,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39351
39921
  if (expected.systemText !== undefined) {
39352
39922
  const texts = expected.systemText;
39353
39923
  const content = actual.wireContent;
39354
- 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;
39924
+ 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;
39355
39925
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
39356
39926
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
39357
39927
  return "content";
@@ -39448,7 +40018,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39448
40018
  }
39449
40019
  function piDispatchRowCount(payload, prepared) {
39450
40020
  try {
39451
- const body = object10(payload);
40021
+ const body = object11(payload);
39452
40022
  return payloadStructure(payload, prepared?.api === "ollama-chat", body?.messages === undefined && Array.isArray(body?.input) && !!prepared?.responsesMessages)?.length;
39453
40023
  } catch {
39454
40024
  return;
@@ -39470,7 +40040,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
39470
40040
  let expected = prepared?.messages;
39471
40041
  let actual;
39472
40042
  try {
39473
- const body = object10(payload);
40043
+ const body = object11(payload);
39474
40044
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39475
40045
  if (responses)
39476
40046
  expected = prepared?.responsesMessages ?? expected;
@@ -40946,20 +41516,59 @@ function piCheckPreparedDispatch(payload, prepared, evidence, onImageTrim, onCom
40946
41516
  import { isDeepStrictEqual } from "node:util";
40947
41517
 
40948
41518
  // src/pi-dispatch-chain-tail.ts
40949
- function object11(value) {
41519
+ function object12(value) {
40950
41520
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
40951
41521
  }
40952
41522
  var OMITTED_IMAGE = "[image omitted: model does not support vision]";
41523
+ var ORPHAN_TOOL_CALL_PLACEHOLDER = "[No tool output recorded: the tool call was interrupted before it produced a result.]";
41524
+ function replayedTurnItems(assistant, responseItems, outputs, model) {
41525
+ const blocks = Array.isArray(assistant.content) ? assistant.content.map(object12) : [];
41526
+ const calls = blocks.flatMap((block) => block?.type === "toolCall" && typeof block.id === "string" ? [block] : []);
41527
+ const replayed = piResponsesReplayedCalls(assistant, calls.map((block) => block.id), calls.map((block) => piToolCallWireId(block.id, model, assistant)), model);
41528
+ const types = new Map;
41529
+ if (!replayed)
41530
+ return { items: [], calls: types };
41531
+ const items = [];
41532
+ const orphans = replayed.wireCalls.slice(0, replayed.stored).flatMap((id, index) => outputs.has(id) ? [] : [index]);
41533
+ if (orphans.length) {
41534
+ const last = object12(responseItems.at(-1));
41535
+ const id = replayed.wireCalls[orphans[0]];
41536
+ if (orphans.length !== 1 || orphans[0] !== replayed.stored - 1 || last?.type !== "function_call" && last?.type !== "custom_tool_call" || last.call_id !== id)
41537
+ return;
41538
+ items.push({
41539
+ type: last.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41540
+ call_id: id,
41541
+ output: ORPHAN_TOOL_CALL_PLACEHOLDER
41542
+ });
41543
+ }
41544
+ if (object12(model.compat)?.toolNamePrefix)
41545
+ return;
41546
+ for (let index = replayed.stored;index < replayed.calls.length; index++) {
41547
+ const id = replayed.wireCalls[index];
41548
+ const block = calls.find((call) => call.id === replayed.calls[index]);
41549
+ if (!block || typeof block.name !== "string" || block.customWireName !== undefined || object12(block.providerMetadata)?.type === "computer" || !outputs.has(id))
41550
+ return;
41551
+ items.push({
41552
+ type: "function_call",
41553
+ call_id: id,
41554
+ name: block.name,
41555
+ ...block.namespace ? { namespace: block.namespace } : {},
41556
+ arguments: JSON.stringify(block.arguments) ?? "null"
41557
+ });
41558
+ types.set(id, "function_call");
41559
+ }
41560
+ return { items, calls: types };
41561
+ }
40953
41562
  function piEncodeChainTail(messages, assistant, responseItems, model) {
40954
- const harmony = object11(model.identity)?.class === "gpt-oss";
41563
+ const harmony = object12(model.identity)?.class === "gpt-oss";
40955
41564
  const text = (value) => {
40956
41565
  const wellFormed = value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
40957
41566
  return harmony ? wellFormed.replace(/<\|(start|end|message|channel|constrain|return|call)\|>/g, "<\\|$1\\|>") : wellFormed;
40958
41567
  };
40959
41568
  const supportsImages = model.input?.includes("image") === true;
40960
41569
  const image = (block) => {
40961
- const detail = block.detail === "original" && object11(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
40962
- const file = object11(block.providerFile);
41570
+ const detail = block.detail === "original" && object12(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
41571
+ const file = object12(block.providerFile);
40963
41572
  if (file?.provider === "openai" && typeof file.id === "string" && file.id)
40964
41573
  return { type: "input_image", detail, file_id: file.id };
40965
41574
  if (typeof block.url !== "string" && (typeof block.mimeType !== "string" || typeof block.data !== "string"))
@@ -40970,9 +41579,21 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40970
41579
  image_url: block.url ?? `data:${block.mimeType};base64,${block.data}`
40971
41580
  };
40972
41581
  };
40973
- const items = [];
41582
+ const outputs = new Set;
41583
+ for (const value of messages) {
41584
+ const message = object12(value);
41585
+ if (message?.role !== "toolResult" || typeof message.toolCallId !== "string")
41586
+ continue;
41587
+ const id = piToolCallWireId(message.toolCallId, model, assistant);
41588
+ if (id)
41589
+ outputs.add(id);
41590
+ }
41591
+ const replayed = replayedTurnItems(assistant, responseItems, outputs, model);
41592
+ if (!replayed)
41593
+ return;
41594
+ const items = [...replayed.items];
40974
41595
  for (const value of messages) {
40975
- let message = object11(value);
41596
+ let message = object12(value);
40976
41597
  if (!message || message.providerPayload !== undefined)
40977
41598
  return;
40978
41599
  message = piOmpUserHistory(message);
@@ -40980,7 +41601,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40980
41601
  if (typeof message.customType !== "string" || message.attribution === "user")
40981
41602
  return;
40982
41603
  const converted = piAgentHistory([message], model.api);
40983
- const developer = object11(converted[0]);
41604
+ const developer = object12(converted[0]);
40984
41605
  if (converted.length !== 1 || !developer || !piIsDeveloperHistory(developer))
40985
41606
  return;
40986
41607
  message = {
@@ -40998,7 +41619,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40998
41619
  const images = [];
40999
41620
  const ordered = [];
41000
41621
  for (const value of content) {
41001
- const block = object11(value);
41622
+ const block = object12(value);
41002
41623
  if (block?.type === "text" && typeof block.text === "string") {
41003
41624
  texts.push(block.text);
41004
41625
  if (!user || block.text.trim())
@@ -41026,15 +41647,15 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
41026
41647
  if (typeof message.toolCallId !== "string" || message.providerMetadata !== undefined)
41027
41648
  return;
41028
41649
  const id = piToolCallWireId(message.toolCallId, model, assistant);
41029
- const call = responseItems.map(object11).find((item) => item?.call_id === id);
41030
- if (!id || call?.type !== "function_call" && call?.type !== "custom_tool_call")
41650
+ const callType = id ? replayed.calls.get(id) ?? responseItems.map(object12).find((item) => item?.call_id === id)?.type : undefined;
41651
+ if (!id || callType !== "function_call" && callType !== "custom_tool_call")
41031
41652
  return;
41032
41653
  const joined = texts.join(`
41033
41654
  `);
41034
41655
  const output = images.length && supportsImages ? ordered : text(images.length && !supportsImages ? joined ? `${joined}
41035
41656
  ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41036
41657
  items.push({
41037
- type: call.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41658
+ type: callType === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output",
41038
41659
  call_id: id,
41039
41660
  output
41040
41661
  });
@@ -41043,7 +41664,7 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41043
41664
  }
41044
41665
 
41045
41666
  // src/pi-dispatch-chain.ts
41046
- function object12(value) {
41667
+ function object13(value) {
41047
41668
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41048
41669
  }
41049
41670
  function piChainCapableApi(api) {
@@ -41051,10 +41672,10 @@ function piChainCapableApi(api) {
41051
41672
  }
41052
41673
  function injectedHeadIndex(messages) {
41053
41674
  let index = 0;
41054
- while (object12(messages[index])?.role === "system")
41675
+ while (object13(messages[index])?.role === "system")
41055
41676
  index++;
41056
- const m0 = object12(messages[index]);
41057
- const m1 = object12(messages[index + 1]);
41677
+ const m0 = object13(messages[index]);
41678
+ const m1 = object13(messages[index + 1]);
41058
41679
  const syntheticUser = (message) => message?.role === "user" && Object.keys(message).every((key) => ["role", "content", "timestamp"].includes(key));
41059
41680
  if (!syntheticUser(m0) || !syntheticUser(m1))
41060
41681
  return -1;
@@ -41062,16 +41683,16 @@ function injectedHeadIndex(messages) {
41062
41683
  const m1Content = m1?.content;
41063
41684
  if (!Array.isArray(m0Content) || !Array.isArray(m1Content))
41064
41685
  return -1;
41065
- const m0Text = object12(m0Content[0]);
41066
- const m1Text = object12(m1Content[0]);
41067
- 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;
41686
+ const m0Text = object13(m0Content[0]);
41687
+ const m1Text = object13(m1Content[0]);
41688
+ 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;
41068
41689
  }
41069
41690
  function piPreparedHistory(messages, model) {
41070
41691
  const snapshots = [];
41071
41692
  const responseIds = [];
41072
41693
  const head = injectedHeadIndex(messages);
41073
41694
  for (const [index, message] of messages.entries()) {
41074
- const source = object12(message);
41695
+ const source = object13(message);
41075
41696
  const identity = head >= 0 && (index === head || index === head + 1) ? Object.fromEntries(Object.entries(source ?? {}).filter(([key]) => key !== "timestamp")) : message;
41076
41697
  const fields = lkgContentFields(identity);
41077
41698
  if (!fields)
@@ -41083,17 +41704,18 @@ function piPreparedHistory(messages, model) {
41083
41704
  let index = responseIds.length - 1;
41084
41705
  while (index >= 0 && responseIds[index] === undefined)
41085
41706
  index--;
41086
- const assistant = object12(messages[index]);
41707
+ const assistant = object13(messages[index]);
41087
41708
  const response = piChainResponse(assistant);
41088
41709
  if (model && assistant && response) {
41089
- const delta = piEncodeChainTail(messages.slice(index + 1), assistant, response.responseItems, model);
41710
+ const renamed = piDeduplicatedToolCallIds(messages, model);
41711
+ const delta = piEncodeChainTail(renamed.slice(index + 1), object13(renamed[index]) ?? assistant, response.responseItems, model);
41090
41712
  if (delta)
41091
41713
  prepared.continuation = { index, ...response, delta };
41092
41714
  }
41093
41715
  return prepared;
41094
41716
  }
41095
41717
  function piChainedRequest(payload) {
41096
- const body = object12(payload);
41718
+ const body = object13(payload);
41097
41719
  if (!body || body.previous_response_id === undefined)
41098
41720
  return;
41099
41721
  const id = body.previous_response_id;
@@ -41102,14 +41724,14 @@ function piChainedRequest(payload) {
41102
41724
  return { previousResponseId: id, delta: body.input };
41103
41725
  }
41104
41726
  function piChainResponse(message) {
41105
- const source = object12(message);
41727
+ const source = object13(message);
41106
41728
  if (source?.role !== "assistant")
41107
41729
  return;
41108
41730
  if (source.stopReason !== "stop" && source.stopReason !== "toolUse")
41109
41731
  return;
41110
41732
  if (typeof source.responseId !== "string" || !source.responseId)
41111
41733
  return;
41112
- const payload = object12(source.providerPayload);
41734
+ const payload = object13(source.providerPayload);
41113
41735
  if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
41114
41736
  return;
41115
41737
  return {
@@ -41157,14 +41779,14 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
41157
41779
  import { createHash as createHash16 } from "node:crypto";
41158
41780
  var MAX_BYTES = 32 * 1024 * 1024;
41159
41781
  var MAX_ENTRIES = 1e5;
41160
- function object13(value) {
41782
+ function object14(value) {
41161
41783
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41162
41784
  }
41163
41785
  function piCursorConversation(payload) {
41164
- const body = object13(payload);
41786
+ const body = object14(payload);
41165
41787
  if (body?.messages !== undefined || body?.input !== undefined || body?.contents !== undefined || body?.request !== undefined)
41166
41788
  return;
41167
- const state = object13(body?.conversationState);
41789
+ const state = object14(body?.conversationState);
41168
41790
  if (!state || !Array.isArray(state.rootPromptMessagesJson) || !Array.isArray(state.turns))
41169
41791
  return;
41170
41792
  let bytes = 0;
@@ -41184,7 +41806,7 @@ function piCursorConversation(payload) {
41184
41806
  }
41185
41807
  if (Array.isArray(value))
41186
41808
  return value.map((entry) => decode(entry, depth + 1));
41187
- const record = object13(value);
41809
+ const record = object14(value);
41188
41810
  if (record)
41189
41811
  return Object.fromEntries(Object.entries(record).map(([key, child]) => [
41190
41812
  key,
@@ -41195,7 +41817,7 @@ function piCursorConversation(payload) {
41195
41817
  try {
41196
41818
  const decoded = decode(state);
41197
41819
  for (const root of decoded.rootPromptMessagesJson) {
41198
- const record = object13(root);
41820
+ const record = object14(root);
41199
41821
  if (typeof record?.blobId === "string")
41200
41822
  rootIds.push(record.blobId);
41201
41823
  else if (record && typeof record.role === "string")
@@ -41204,19 +41826,19 @@ function piCursorConversation(payload) {
41204
41826
  return;
41205
41827
  }
41206
41828
  for (const value of decoded.turns.slice(0, 8)) {
41207
- const turn = object13(value);
41208
- const agent = object13(object13(turn?.turn)?.value) ?? turn;
41209
- const user = object13(agent?.userMessage);
41829
+ const turn = object14(value);
41830
+ const agent = object14(object14(turn?.turn)?.value) ?? turn;
41831
+ const user = object14(agent?.userMessage);
41210
41832
  if (typeof user?.text === "string")
41211
41833
  messages.push({ role: "user", content: user.text });
41212
41834
  }
41213
- const action = object13(object13(body?.action)?.action);
41835
+ const action = object14(object14(body?.action)?.action);
41214
41836
  if (!action || !["userMessageAction", "resumeAction"].includes(String(action.case)))
41215
41837
  return;
41216
41838
  let active = decode(body?.action);
41217
41839
  let activeText;
41218
41840
  if (action.case === "userMessageAction") {
41219
- const user = object13(object13(action.value)?.userMessage);
41841
+ const user = object14(object14(action.value)?.userMessage);
41220
41842
  if (!user || typeof user.text !== "string")
41221
41843
  return;
41222
41844
  messages.push({ role: "user", content: user.text });
@@ -41225,7 +41847,7 @@ function piCursorConversation(payload) {
41225
41847
  active = decode({
41226
41848
  action: {
41227
41849
  case: action.case,
41228
- value: { ...object13(action.value), userMessage: content }
41850
+ value: { ...object14(action.value), userMessage: content }
41229
41851
  }
41230
41852
  });
41231
41853
  }
@@ -41253,7 +41875,7 @@ function piCursorManagedRoots(messages, signature, cwd) {
41253
41875
  Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not repeat this information in your reply.
41254
41876
  </system-reminder>`;
41255
41877
  for (const value of messages.slice(0, 8)) {
41256
- const source = object13(value);
41878
+ const source = object14(value);
41257
41879
  if (!source || !["user", "developer"].includes(String(source.role)))
41258
41880
  continue;
41259
41881
  const message = piOmpUserHistory(source);
@@ -42582,7 +43204,7 @@ class PiDegradedPassError extends Error {
42582
43204
  code = "PI_DEGRADED_PASS";
42583
43205
  recoverable = true;
42584
43206
  constructor(site, options) {
42585
- super(describeDegradedPassFailure(site, options?.cause), options);
43207
+ super(options?.message ?? describeDegradedPassFailure(site, options?.cause), options);
42586
43208
  this.site = site;
42587
43209
  this.name = "PiDegradedPassError";
42588
43210
  }
@@ -42784,6 +43406,7 @@ function classifyPiOutgoingFit(estimate, limit) {
42784
43406
  // src/pi-context-refusal.ts
42785
43407
  var ENTRY_TYPE = "magic-context-turn-refused";
42786
43408
  var RETRY_MESSAGE = "Magic Context could not safely prepare this turn; send your message again.";
43409
+ var PI_OMP_CAPTURE_REFUSAL = "Magic Context does not send OMP's auto-learn capture: it carries the raw, unmanaged conversation.";
42787
43410
  var MAX_UNSENDABLE_NONCES_PER_SESSION = 32;
42788
43411
  var receiptMaps = new Set;
42789
43412
  function clearPiContextReceipt(sessionId) {
@@ -42986,6 +43609,8 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42986
43609
  receiptMaps.add(imageTrimNotices);
42987
43610
  const foreignNotices = new Map;
42988
43611
  receiptMaps.add(foreignNotices);
43612
+ const captureNotices = new Map;
43613
+ receiptMaps.add(captureNotices);
42989
43614
  const foreignIndexes = new Map;
42990
43615
  receiptMaps.add(foreignIndexes);
42991
43616
  const chains = new Map;
@@ -43065,7 +43690,18 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43065
43690
  }
43066
43691
  });
43067
43692
  pi.on("before_provider_request", (event, ctx) => {
43068
- const cancelledOperation = operations.get(operationKey(ctx));
43693
+ const payload = event.payload;
43694
+ const key = operationKey(ctx);
43695
+ if (isOmpUnmanagedCaptureRequest(payload)) {
43696
+ if (options.compactionOff?.(ctx) || sideSessions.get(key)?.sides)
43697
+ return;
43698
+ if (!captureNotices.has(key)) {
43699
+ captureNotices.set(key, true);
43700
+ 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`);
43701
+ }
43702
+ return piRefusedPayload(PI_OMP_CAPTURE_REFUSAL);
43703
+ }
43704
+ const cancelledOperation = operations.get(key);
43069
43705
  const signal = ctx.signal;
43070
43706
  if (signal ? signal.aborted : cancelledOperation?.pass?.isCancelled()) {
43071
43707
  cancelledOperation?.pass?.cancel();
@@ -43074,11 +43710,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43074
43710
  return piRefusedPayload("Magic Context request cancelled before provider dispatch.");
43075
43711
  }
43076
43712
  if (options.compactionOff?.(ctx)) {
43077
- chains.delete(operationKey(ctx));
43713
+ chains.delete(key);
43078
43714
  return;
43079
43715
  }
43080
- const payload = event.payload;
43081
- const key = operationKey(ctx);
43082
43716
  if (sideSessions.get(key)?.sides)
43083
43717
  return;
43084
43718
  const nonces = unsendableNonces.get(key);
@@ -43107,15 +43741,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43107
43741
  }
43108
43742
  const active = operation;
43109
43743
  const isCurrent = () => operations.get(key) === active;
43110
- const capture = isOmpUnmanagedCaptureRequest(payload);
43111
- const budget = (capture ? undefined : active.pass) ?? new PiContextBudget;
43744
+ const budget = active.pass ?? new PiContextBudget;
43112
43745
  if (active.refused && active.pass === budget) {
43113
43746
  return piRefusedPayload(active.refusalMessage ?? RETRY_MESSAGE);
43114
43747
  }
43115
43748
  let refusalOrigin;
43116
43749
  try {
43117
- if (capture)
43118
- throw new Error("no context pass ran for OMP auto-learn capture; raw conversation refused");
43119
43750
  if (!active.pass)
43120
43751
  throw new Error("no context pass ran for this operation");
43121
43752
  if (!budget.completed && (budget.abandoned || budget.elapsed() >= PI_CONTEXT_BUDGET.outcomeMs))
@@ -43126,11 +43757,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43126
43757
  }
43127
43758
  if (!budget.completed || !active.ready || active.refused || budget.abandoned)
43128
43759
  throw new Error("context pass ran without a managed context receipt");
43129
- const chained = piChainedRequest(payload);
43130
- let checked = payload;
43760
+ const managed = piWithoutOmpJuice(payload, ctx.model);
43761
+ const chained = piChainedRequest(managed);
43762
+ let checked = managed;
43131
43763
  let chainInput;
43132
43764
  if (chained) {
43133
- const expanded = piExpandChainedRequest(payload, chained, chains.get(key)?.anchor, active.preparedHistory, {
43765
+ const expanded = piExpandChainedRequest(managed, chained, chains.get(key)?.anchor, active.preparedHistory, {
43134
43766
  current: active.pass,
43135
43767
  resend: active.chainDispatchFields !== undefined
43136
43768
  });
@@ -44194,16 +44826,15 @@ function piRenderedTagNumbers(messages) {
44194
44826
  }
44195
44827
  return numbers;
44196
44828
  }
44197
- function piCachedToolSurvivor(sessionId, callId, timestamp, rows) {
44198
- const cached = readPiServedCachedArray(sessionId);
44829
+ function piCachedToolSurvivor(sessionId, callId, timestamp, rows, view) {
44830
+ const cached = view === undefined ? createPiServedCachedView(sessionId) : view;
44199
44831
  if (!cached)
44200
44832
  return;
44201
- const { messages } = cached;
44202
- const owners = messages.filter((m) => m.role === "assistant" && contentParts(m).some((p) => p.type === "toolCall" && p.id === callId));
44833
+ const owners = cached.toolCallOwners().get(callId) ?? [];
44203
44834
  const owner = owners[0];
44204
44835
  if (!owner || owners.length !== 1 || owner.timestamp !== timestamp || contentParts(owner).filter((p) => p.type === "toolCall" && p.id === callId).length !== 1)
44205
44836
  return;
44206
- const rendered = piRenderedTagNumbers(messages);
44837
+ const rendered = cached.rendered();
44207
44838
  const present = rows.filter((row) => rendered.has(row.tagNumber));
44208
44839
  const winner = present[0];
44209
44840
  if (present.length !== 1 || !winner)
@@ -44211,11 +44842,62 @@ function piCachedToolSurvivor(sessionId, callId, timestamp, rows) {
44211
44842
  const { tagNumber: number, status } = winner;
44212
44843
  if (status !== "active" && status !== "dropped")
44213
44844
  return;
44214
- const results = messages.filter((m) => m.role === "toolResult" && m.toolCallId === callId);
44845
+ const results = cached.toolResults().get(callId) ?? [];
44215
44846
  if (!results.some((m) => contentParts(m).some((p) => p.type === "text" && (status === "dropped" ? p.text === `[dropped §${number}§]` : typeof p.text === "string" && p.text.startsWith(`§${number}§ `)))))
44216
44847
  return;
44217
44848
  return number;
44218
44849
  }
44850
+ function createPiServedCachedView(sessionId) {
44851
+ const cached = readPiServedCachedArray(sessionId);
44852
+ if (!cached)
44853
+ return null;
44854
+ const { messages } = cached;
44855
+ const memos = new Map;
44856
+ const memo = (key, build) => {
44857
+ if (!memos.has(key))
44858
+ memos.set(key, build());
44859
+ return memos.get(key);
44860
+ };
44861
+ return {
44862
+ messages,
44863
+ rendered: () => memo("rendered", () => piRenderedTagNumbers(messages)),
44864
+ toolCallOwners: () => memo("toolCallOwners", () => {
44865
+ const owners = new Map;
44866
+ for (const message of messages) {
44867
+ if (message.role !== "assistant")
44868
+ continue;
44869
+ const ids = new Set;
44870
+ for (const part of contentParts(message))
44871
+ if (part.type === "toolCall")
44872
+ ids.add(part.id);
44873
+ for (const id of ids) {
44874
+ if (typeof id !== "string")
44875
+ continue;
44876
+ const list = owners.get(id);
44877
+ if (list)
44878
+ list.push(message);
44879
+ else
44880
+ owners.set(id, [message]);
44881
+ }
44882
+ }
44883
+ return owners;
44884
+ }),
44885
+ toolResults: () => memo("toolResults", () => {
44886
+ const results = new Map;
44887
+ for (const message of messages) {
44888
+ if (message.role !== "toolResult" || typeof message.toolCallId !== "string")
44889
+ continue;
44890
+ const list = results.get(message.toolCallId);
44891
+ if (list)
44892
+ list.push(message);
44893
+ else
44894
+ results.set(message.toolCallId, [message]);
44895
+ }
44896
+ return results;
44897
+ }),
44898
+ memo
44899
+ };
44900
+ }
44219
44901
  function readPiServedCachedArray(sessionId) {
44220
44902
  const memory = getPiLastServedArray(sessionId);
44221
44903
  const slot = memory === undefined ? getSlot(sessionId) : undefined;
@@ -44277,14 +44959,14 @@ function textParts(message) {
44277
44959
  return p.type === "text" && typeof p.text === "string" ? [p.text] : [];
44278
44960
  }) : [];
44279
44961
  }
44280
- function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows) {
44281
- const cached = readPiServedCachedArray(sessionId);
44962
+ function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows, view) {
44963
+ const cached = view === undefined ? createPiServedCachedView(sessionId) : view;
44282
44964
  if (!cached)
44283
44965
  return;
44284
44966
  const header = fingerprintHeader(fingerprint);
44285
44967
  if (header === undefined)
44286
44968
  return;
44287
- const rendered = piRenderedTagNumbers(cached.messages);
44969
+ const rendered = cached.rendered();
44288
44970
  const present = rows.filter((row) => rendered.has(row.tagNumber));
44289
44971
  const winner = present[0];
44290
44972
  if (present.length !== 1 || !winner)
@@ -44292,7 +44974,18 @@ function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows) {
44292
44974
  if (winner.status !== "active" && winner.status !== "dropped")
44293
44975
  return;
44294
44976
  const shows = (text) => winner.status === "dropped" ? text === `[dropped §${winner.tagNumber}§]` : text?.startsWith(`§${winner.tagNumber}§ `) === true;
44295
- const carriers = cached.messages.filter((message) => messageHeader(message) === header && shows(textParts(message)[ordinal]));
44977
+ const carriers = (cached.memo("messagesByHeader", () => {
44978
+ const byHeader = new Map;
44979
+ for (const message of cached.messages) {
44980
+ const key = messageHeader(message);
44981
+ const list = byHeader.get(key);
44982
+ if (list)
44983
+ list.push(message);
44984
+ else
44985
+ byHeader.set(key, [message]);
44986
+ }
44987
+ return byHeader;
44988
+ }).get(header) ?? []).filter((message) => shows(textParts(message)[ordinal]));
44296
44989
  return carriers.length === 1 ? winner.tagNumber : undefined;
44297
44990
  }
44298
44991
 
@@ -44852,10 +45545,15 @@ function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
44852
45545
  // src/pi-tag-identity-repair.ts
44853
45546
  var PI_TAG_IDENTITY_REPAIR_REASON = "tag_identity_repair";
44854
45547
  var unreadableLedgerLogged = new Set;
45548
+ function isPiPassEndingError(error) {
45549
+ return error instanceof PiContextDeadlineError || error instanceof PiContextSupersededError || error instanceof Error && error.name === "AbortError";
45550
+ }
44855
45551
  function readPiIdentityDecisions(db, sessionId) {
44856
45552
  try {
44857
45553
  return getPiContentDecisions(db, sessionId);
44858
45554
  } catch (error) {
45555
+ if (isPiPassEndingError(error))
45556
+ throw error;
44859
45557
  if (!unreadableLedgerLogged.has(sessionId)) {
44860
45558
  if (unreadableLedgerLogged.size > 1e4)
44861
45559
  unreadableLedgerLogged.clear();
@@ -44871,25 +45569,109 @@ function freezeIdentityDecision(db, sessionId, kind, value) {
44871
45569
  try {
44872
45570
  return freezePiContentDecision(db, sessionId, kind, value);
44873
45571
  } catch (error) {
45572
+ if (isPiPassEndingError(error))
45573
+ throw error;
44874
45574
  sessionLog2(sessionId, `tag identity decision ${kind} could not be written; serving duplicates unmerged: ${error instanceof Error ? error.message : String(error)}`);
44875
45575
  return false;
44876
45576
  }
44877
45577
  }
45578
+ var unreadableGuardsLogged = new Set;
45579
+ function readFoldGuards(db, sessionId) {
45580
+ try {
45581
+ return readPiIdentityFoldGuards(db, sessionId);
45582
+ } catch (error) {
45583
+ if (isPiPassEndingError(error))
45584
+ throw error;
45585
+ if (!unreadableGuardsLogged.has(sessionId)) {
45586
+ if (unreadableGuardsLogged.size > 1e4)
45587
+ unreadableGuardsLogged.clear();
45588
+ unreadableGuardsLogged.add(sessionId);
45589
+ sessionLog2(sessionId, `Pi identity fold guards unreadable: tag identity duplicates are served unmerged and the stored row is left untouched: ${error instanceof Error ? error.message : String(error)}`);
45590
+ }
45591
+ return null;
45592
+ }
45593
+ }
45594
+
45595
+ class PiIdentityRepairBatch {
45596
+ db;
45597
+ sessionId;
45598
+ ledger = null;
45599
+ guards = null;
45600
+ pending = false;
45601
+ refuseNewGuards = false;
45602
+ constructor(db, sessionId) {
45603
+ this.db = db;
45604
+ this.sessionId = sessionId;
45605
+ }
45606
+ load() {
45607
+ this.pending = false;
45608
+ this.ledger = readPiIdentityDecisions(this.db, this.sessionId);
45609
+ this.guards = readFoldGuards(this.db, this.sessionId);
45610
+ }
45611
+ decisions() {
45612
+ return this.ledger;
45613
+ }
45614
+ peek(key, legacyKeys = []) {
45615
+ const ledger = this.ledger;
45616
+ const guards = this.guards;
45617
+ if (ledger === null)
45618
+ return "unpersisted";
45619
+ const candidates = [key, ...legacyKeys];
45620
+ if (candidates.some((candidate) => ledger.has(encodePiContentDecision("tag-identity-repair-once", candidate))))
45621
+ return "recurring";
45622
+ if (guards === null)
45623
+ return "unpersisted";
45624
+ if (candidates.some((candidate) => guards.has(candidate)))
45625
+ return "recurring";
45626
+ if (this.refuseNewGuards || guards.size >= PI_IDENTITY_FOLD_GUARD_LIMIT)
45627
+ return "unpersisted";
45628
+ return "claimed";
45629
+ }
45630
+ claim(key, legacyKeys = []) {
45631
+ const claim = this.peek(key, legacyKeys);
45632
+ if (claim !== "claimed")
45633
+ return claim;
45634
+ this.guards?.add(key);
45635
+ this.pending = true;
45636
+ return "claimed";
45637
+ }
45638
+ flush() {
45639
+ if (!this.pending || !this.guards)
45640
+ return;
45641
+ writePiIdentityFoldGuards(this.db, this.sessionId, this.guards);
45642
+ this.pending = false;
45643
+ }
45644
+ recordRecurrence(key) {
45645
+ return recordPiIdentityRecurrence(this.db, this.sessionId, key, this.ledger);
45646
+ }
45647
+ }
44878
45648
  function claimPiIdentityRepair(db, sessionId, key, legacyKeys = []) {
44879
- const decisions = readPiIdentityDecisions(db, sessionId);
44880
- if (decisions === null)
45649
+ try {
45650
+ return db.transaction(() => {
45651
+ const batch = new PiIdentityRepairBatch(db, sessionId);
45652
+ batch.load();
45653
+ const claim = batch.claim(key, legacyKeys);
45654
+ if (claim === "claimed")
45655
+ batch.flush();
45656
+ return claim;
45657
+ }).immediate();
45658
+ } catch (error) {
45659
+ if (isPiPassEndingError(error))
45660
+ throw error;
45661
+ sessionLog2(sessionId, `tag identity fold guard could not be written; serving the duplicate unmerged: ${error instanceof Error ? error.message : String(error)}`);
44881
45662
  return "unpersisted";
44882
- if ([key, ...legacyKeys].some((candidate) => decisions.has(encodePiContentDecision("tag-identity-repair-once", candidate))))
44883
- return "recurring";
44884
- return freezeIdentityDecision(db, sessionId, "tag-identity-repair-once", key) ? "claimed" : "unpersisted";
45663
+ }
44885
45664
  }
44886
45665
  var unrecordedRecurrenceLogged = new Set;
44887
- function recordPiIdentityRecurrence(db, sessionId, key) {
45666
+ function recordPiIdentityRecurrence(db, sessionId, key, decisions) {
44888
45667
  const entry = encodePiContentDecision("tag-identity-recurring", key);
44889
- if (readPiIdentityDecisions(db, sessionId)?.has(entry))
45668
+ const known = decisions === undefined ? readPiIdentityDecisions(db, sessionId) : decisions;
45669
+ if (known?.has(entry))
44890
45670
  return false;
44891
- if (freezeIdentityDecision(db, sessionId, "tag-identity-recurring", key))
45671
+ if (freezeIdentityDecision(db, sessionId, "tag-identity-recurring", key)) {
45672
+ decisions?.add(entry);
44892
45673
  return true;
45674
+ }
44893
45675
  const logKey = `${sessionId}\x00${key}`;
44894
45676
  if (unrecordedRecurrenceLogged.has(logKey))
44895
45677
  return false;
@@ -48198,6 +48980,13 @@ function settlePiFallbackOccurrences(db, sessionId, ids) {
48198
48980
 
48199
48981
  class PiIdentityRebuildUnrecorded extends Error {
48200
48982
  }
48983
+ var PI_ADOPTION_RESERVE_MS = 1e4;
48984
+ var piAdoptionReserveMs = PI_ADOPTION_RESERVE_MS;
48985
+ var PI_ADOPTION_CHUNK_ROWS = 256;
48986
+ var PI_ADOPTION_CHUNK_MS = 250;
48987
+
48988
+ class PiIdentityGuardsUnwritten extends Error {
48989
+ }
48201
48990
  function readPiAdoptionRevision(db) {
48202
48991
  return {
48203
48992
  external: db.prepare("PRAGMA data_version").get(),
@@ -48305,8 +49094,17 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48305
49094
  };
48306
49095
  const claimed = new Set;
48307
49096
  const repairing = new Set;
49097
+ const unguardedKeys = new Set;
48308
49098
  let servedNumbers;
48309
49099
  const readServedNumbers = () => servedNumbers ??= getPiServedTagNumbers(sessionId, undefined, db);
49100
+ let servedView;
49101
+ const readServedView = () => {
49102
+ if (servedView === undefined)
49103
+ servedView = createPiServedCachedView(sessionId);
49104
+ return servedView;
49105
+ };
49106
+ const batch = new PiIdentityRepairBatch(db, sessionId);
49107
+ let afterCommit = [];
48310
49108
  const newRebuilds = [];
48311
49109
  const recurrences = [];
48312
49110
  const plan = (rows, key, legacyKeys, served, cached) => {
@@ -48314,24 +49112,26 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48314
49112
  if (!proven && options.deferUnprovenRebuild)
48315
49113
  return null;
48316
49114
  if (proven && options.allowUnprovenRebuild) {
48317
- const decisions = readPiIdentityDecisions(db, sessionId);
48318
- let unmerged = decisions === null || decisions.has(encodePiContentDecision("tag-identity-recurring", key));
48319
- if (!unmerged && !claimed.has(key)) {
48320
- unmerged = claimPiIdentityRepair(db, sessionId, key, legacyKeys) === "unpersisted";
49115
+ const decisions = batch.decisions();
49116
+ if (decisions?.has(encodePiContentDecision("tag-identity-recurring", key)))
49117
+ return null;
49118
+ if (decisions === null || unguardedKeys.has(key)) {
49119
+ unguardedKeys.add(key);
49120
+ return null;
49121
+ }
49122
+ if (!claimed.has(key)) {
49123
+ const claim = batch.claim(key, legacyKeys);
48321
49124
  claimed.add(key);
49125
+ if (claim === "unpersisted") {
49126
+ unguardedKeys.add(key);
49127
+ return null;
49128
+ }
48322
49129
  }
48323
- if (!unmerged)
48324
- return { rebuilding: undefined };
48325
- recurrences.push({
48326
- key,
48327
- numbers: rows.map((row) => row.tagNumber).sort((x, y) => x - y),
48328
- fresh: recordPiIdentityRecurrence(db, sessionId, key)
48329
- });
48330
- return null;
49130
+ return { rebuilding: undefined };
48331
49131
  }
48332
49132
  if (proven || !options.allowUnprovenRebuild) {
48333
49133
  if (!claimed.has(key)) {
48334
- claimPiIdentityRepair(db, sessionId, key, legacyKeys);
49134
+ batch.claim(key, legacyKeys);
48335
49135
  claimed.add(key);
48336
49136
  }
48337
49137
  return { rebuilding: undefined };
@@ -48339,16 +49139,22 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48339
49139
  const newest = Math.max(...rows.map((row) => row.tagNumber));
48340
49140
  if (repairing.has(key))
48341
49141
  return { rebuilding: newest };
48342
- const claim = claimed.has(key) ? "recurring" : claimPiIdentityRepair(db, sessionId, key, legacyKeys);
49142
+ if (unguardedKeys.has(key))
49143
+ return null;
49144
+ const claim = claimed.has(key) ? "recurring" : batch.claim(key, legacyKeys);
48343
49145
  claimed.add(key);
48344
49146
  if (claim === "claimed") {
48345
49147
  repairing.add(key);
48346
49148
  return { rebuilding: newest };
48347
49149
  }
49150
+ if (claim === "unpersisted") {
49151
+ unguardedKeys.add(key);
49152
+ return null;
49153
+ }
48348
49154
  recurrences.push({
48349
49155
  key,
48350
49156
  numbers: rows.map((row) => row.tagNumber).sort((x, y) => x - y),
48351
- fresh: recordPiIdentityRecurrence(db, sessionId, key)
49157
+ fresh: batch.recordRecurrence(key)
48352
49158
  });
48353
49159
  return null;
48354
49160
  };
@@ -48372,6 +49178,8 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48372
49178
  return result;
48373
49179
  }).immediate();
48374
49180
  } catch (error) {
49181
+ if (isPiPassEndingError(error))
49182
+ throw error;
48375
49183
  if (!(error instanceof PiIdentityRebuildUnrecorded) && !options.allowUnprovenRebuild)
48376
49184
  throw error;
48377
49185
  if (!(error instanceof PiIdentityRebuildUnrecorded))
@@ -48379,14 +49187,18 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48379
49187
  recurrences.push({
48380
49188
  key: guardKey,
48381
49189
  numbers: [],
48382
- fresh: recordPiIdentityRecurrence(db, sessionId, guardKey)
49190
+ fresh: batch.recordRecurrence(guardKey)
48383
49191
  });
48384
49192
  return { action: "skipped" };
48385
49193
  }
48386
49194
  if (adoption.action === "folded") {
48387
- outcome.protectedTagNumbers.add(adoption.tagNumber);
48388
- if (repair)
48389
- newRebuilds.push(repair);
49195
+ const folded = adoption;
49196
+ const declared = repair;
49197
+ afterCommit.push(() => {
49198
+ outcome.protectedTagNumbers.add(folded.tagNumber);
49199
+ if (declared)
49200
+ newRebuilds.push(declared);
49201
+ });
48390
49202
  }
48391
49203
  return adoption;
48392
49204
  };
@@ -48402,43 +49214,130 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48402
49214
  const targetsFor = (fingerprints) => [...fingerprints].flatMap((fingerprint) => (realIdsByFingerprint.get(fingerprint) ?? []).map((id) => [id, fingerprint]));
48403
49215
  const fallbackTargetsFor = (fingerprints) => [...fingerprints].flatMap((fingerprint) => (fallbackIdsByFingerprint.get(fingerprint) ?? []).map((id) => [id, fingerprint]));
48404
49216
  const discoveredTargets = targetsFor(discovered);
48405
- const adoptMessageCandidates = (targetId, fingerprint, candidates) => {
48406
- for (const c of candidates) {
48407
- const ordinalMatch = /:p(\d+)$/.exec(c.messageId);
48408
- if (!ordinalMatch)
48409
- continue;
48410
- const realContentId = `${targetId}:p${ordinalMatch[1]}`;
48411
- const served = readServedNumbers();
48412
- const canonical = getPiMessageTagCandidates2(db, sessionId, realContentId);
48413
- const collisionRows = [
48414
- ...getTagsByNumbers2(db, sessionId, [c.tagNumber]),
48415
- ...canonical
48416
- ];
48417
- const cachedSurvivor = canonical.length ? piCachedMessageSurvivor(sessionId, fingerprint, Number(ordinalMatch[1]), collisionRows) : undefined;
48418
- const repairKey = JSON.stringify(["message", realContentId]);
48419
- const guardKey = JSON.stringify([
48420
- "message",
48421
- fingerprint,
48422
- Number(ordinalMatch[1])
48423
- ]);
48424
- const decision = canonical.length ? plan(collisionRows, guardKey, [repairKey], served, cachedSurvivor) : { rebuilding: undefined };
48425
- if (decision === null)
48426
- continue;
48427
- const rebuilding = decision.rebuilding;
48428
- if (canonical.length && !collisionRows.some((row) => served.has(row.tagNumber)) && cachedSurvivor === undefined && rebuilding === undefined) {
48429
- throw new PiTagIdentityConflictError2("duplicate message identities have no proven served-byte survivor", "message");
48430
- }
48431
- const adoption = fold(() => adoptPiFallbackMessageTag2(db, sessionId, c.tagNumber, c.messageId, realContentId, served, cachedSurvivor, rebuilding), repairKey, guardKey, "message", rebuilding);
48432
- if (adoption.action !== "skipped") {
48433
- tagger.unbindTag(sessionId, c.messageId);
48434
- if (adoption.action === "folded") {
48435
- tagger.unbindTag(sessionId, realContentId);
48436
- }
48437
- tagger.bindTag(sessionId, realContentId, adoption.tagNumber);
48438
- }
49217
+ let messageItems = [];
49218
+ let toolRows = [];
49219
+ let prepared = false;
49220
+ let next = 0;
49221
+ let pausedDuplicates = 0;
49222
+ let chunkRows = 0;
49223
+ const passBudgetSpent = () => options.remainingMs !== undefined && options.remainingMs() <= piAdoptionReserveMs;
49224
+ const awaitsFold = (rows, key, legacyKeys, served, cached) => {
49225
+ const proven = cached !== undefined || rows.filter((row) => served.has(row.tagNumber)).length === 1;
49226
+ if (!proven && options.deferUnprovenRebuild)
49227
+ return false;
49228
+ if (unguardedKeys.has(key))
49229
+ return false;
49230
+ const decisions = batch.decisions();
49231
+ if (proven && options.allowUnprovenRebuild) {
49232
+ if (decisions === null || decisions.has(encodePiContentDecision("tag-identity-recurring", key)))
49233
+ return false;
49234
+ return claimed.has(key) || batch.peek(key, legacyKeys) !== "unpersisted";
49235
+ }
49236
+ if (proven || !options.allowUnprovenRebuild)
49237
+ return true;
49238
+ if (repairing.has(key))
49239
+ return true;
49240
+ return !claimed.has(key) && batch.peek(key, legacyKeys) === "claimed";
49241
+ };
49242
+ const adoptMessageCandidate = ({
49243
+ targetId,
49244
+ fingerprint,
49245
+ candidate: c
49246
+ }) => {
49247
+ const ordinalMatch = /:p(\d+)$/.exec(c.messageId);
49248
+ if (!ordinalMatch)
49249
+ return;
49250
+ const realContentId = `${targetId}:p${ordinalMatch[1]}`;
49251
+ const served = readServedNumbers();
49252
+ const canonical = getPiMessageTagCandidates2(db, sessionId, realContentId);
49253
+ if (canonical.length)
49254
+ chunkRows++;
49255
+ const collisionRows = [
49256
+ ...getTagsByNumbers2(db, sessionId, [c.tagNumber]),
49257
+ ...canonical
49258
+ ];
49259
+ const cachedSurvivor = canonical.length ? piCachedMessageSurvivor(sessionId, fingerprint, Number(ordinalMatch[1]), collisionRows, readServedView()) : undefined;
49260
+ const repairKey = JSON.stringify(["message", realContentId]);
49261
+ const guardKey = JSON.stringify([
49262
+ "message",
49263
+ fingerprint,
49264
+ Number(ordinalMatch[1])
49265
+ ]);
49266
+ if (canonical.length && passBudgetSpent()) {
49267
+ if (awaitsFold(collisionRows, guardKey, [repairKey], served, cachedSurvivor))
49268
+ pausedDuplicates++;
49269
+ return;
49270
+ }
49271
+ const decision = canonical.length ? plan(collisionRows, guardKey, [repairKey], served, cachedSurvivor) : { rebuilding: undefined };
49272
+ if (decision === null)
49273
+ return;
49274
+ const rebuilding = decision.rebuilding;
49275
+ if (canonical.length && !collisionRows.some((row) => served.has(row.tagNumber)) && cachedSurvivor === undefined && rebuilding === undefined) {
49276
+ throw new PiTagIdentityConflictError2("duplicate message identities have no proven served-byte survivor", "message");
49277
+ }
49278
+ const adoption = fold(() => adoptPiFallbackMessageTag2(db, sessionId, c.tagNumber, c.messageId, realContentId, served, cachedSurvivor, rebuilding), repairKey, guardKey, "message", rebuilding);
49279
+ if (adoption.action === "skipped")
49280
+ return;
49281
+ const { action, tagNumber } = adoption;
49282
+ afterCommit.push(() => {
49283
+ tagger.unbindTag(sessionId, c.messageId);
49284
+ if (action === "folded")
49285
+ tagger.unbindTag(sessionId, realContentId);
49286
+ tagger.bindTag(sessionId, realContentId, tagNumber);
49287
+ });
49288
+ };
49289
+ const adoptToolRow = (row) => {
49290
+ if (!ownerMap)
49291
+ return;
49292
+ const parsed = parsePiFallbackToolOwnerId(row.toolOwnerMessageId);
49293
+ if (parsed?.role !== "assistant")
49294
+ return;
49295
+ const owners = ownerMap.get(piToolOwnerMapKey(parsed.timestamp, row.callId));
49296
+ if (owners?.size !== 1)
49297
+ return;
49298
+ const [realOwnerId] = owners;
49299
+ if (!realOwnerId || realOwnerId === row.toolOwnerMessageId)
49300
+ return;
49301
+ const existingNumber = getToolTagNumberByOwner2(db, sessionId, row.callId, realOwnerId);
49302
+ if (existingNumber !== null)
49303
+ chunkRows++;
49304
+ const served = readServedNumbers();
49305
+ const cachedSurvivor = existingNumber === null ? undefined : piCachedToolSurvivor(sessionId, row.callId, parsed.timestamp, getTagsByNumbers2(db, sessionId, [row.tagNumber, existingNumber]), readServedView());
49306
+ const repairKey = JSON.stringify(["tool", parsed.timestamp, row.callId]);
49307
+ const legacyKeys = [JSON.stringify(["tool", realOwnerId, row.callId])];
49308
+ const rows = [
49309
+ { tagNumber: row.tagNumber },
49310
+ { tagNumber: existingNumber ?? row.tagNumber }
49311
+ ];
49312
+ if (existingNumber !== null && passBudgetSpent()) {
49313
+ if (awaitsFold(rows, repairKey, legacyKeys, served, cachedSurvivor))
49314
+ pausedDuplicates++;
49315
+ return;
49316
+ }
49317
+ const decision = existingNumber === null ? { rebuilding: undefined } : plan(rows, repairKey, legacyKeys, served, cachedSurvivor);
49318
+ if (decision === null)
49319
+ return;
49320
+ const rebuilding = decision.rebuilding;
49321
+ if (existingNumber !== null && !served.has(existingNumber) && !served.has(row.tagNumber) && cachedSurvivor === undefined && rebuilding === undefined) {
49322
+ throw new PiTagIdentityConflictError2("duplicate tool identities have no proven served-byte survivor");
48439
49323
  }
49324
+ const adoption = fold(() => adoptPiFallbackToolOwnerTag2(db, sessionId, row.tagNumber, row.callId, row.toolOwnerMessageId, realOwnerId, served.size === 0 && cachedSurvivor !== undefined ? new Set([cachedSurvivor]) : served, cachedSurvivor, rebuilding), repairKey, repairKey, "tool", rebuilding);
49325
+ if (adoption.action === "skipped")
49326
+ return;
49327
+ const { action, tagNumber } = adoption;
49328
+ const accounting = getPersistedToolTagAccounting2(db, sessionId, tagNumber);
49329
+ afterCommit.push(() => {
49330
+ tagger.unbindToolTag(sessionId, row.toolOwnerMessageId, row.callId);
49331
+ if (action === "folded")
49332
+ tagger.unbindToolTag(sessionId, realOwnerId, row.callId);
49333
+ tagger.bindToolTag(sessionId, row.callId, realOwnerId, tagNumber);
49334
+ if (accounting)
49335
+ tagger.setToolTagAccounting(sessionId, tagNumber, accounting);
49336
+ });
48440
49337
  };
48441
- runImmediateTransaction(db, () => {
49338
+ const prepare = () => {
49339
+ messageItems = [];
49340
+ toolRows = [];
48442
49341
  const admitted = revision();
48443
49342
  const unchangedSinceDiscovery = beforeDiscovery.external.data_version === admitted.external.data_version && beforeDiscovery.local.changes === admitted.local.changes;
48444
49343
  const preflight = options.preflightRevision;
@@ -48494,7 +49393,13 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48494
49393
  }
48495
49394
  if (base === undefined)
48496
49395
  continue;
48497
- adoptMessageCandidates(realMessageId, fingerprint, candidates.filter((c) => piFallbackBaseId(c.messageId) === base));
49396
+ for (const candidate of candidates)
49397
+ if (piFallbackBaseId(candidate.messageId) === base)
49398
+ messageItems.push({
49399
+ targetId: realMessageId,
49400
+ fingerprint,
49401
+ candidate
49402
+ });
48498
49403
  }
48499
49404
  for (const [fallbackId, fingerprint] of fallbackTargetsFor(adoptable)) {
48500
49405
  if (realIdsByFingerprint.has(fingerprint))
@@ -48504,54 +49409,90 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48504
49409
  const legacy = findAdoptableFallbackTags2(db, sessionId, fingerprint).filter((c) => isPiIndexFallbackId(piFallbackBaseId(c.messageId)));
48505
49410
  legacy.sort((left, right) => left.tagNumber - right.tagNumber);
48506
49411
  for (const base of new Set(legacy.map((c) => piFallbackBaseId(c.messageId))))
48507
- adoptMessageCandidates(fallbackId, fingerprint, legacy.filter((c) => piFallbackBaseId(c.messageId) === base));
49412
+ for (const candidate of legacy)
49413
+ if (piFallbackBaseId(candidate.messageId) === base)
49414
+ messageItems.push({
49415
+ targetId: fallbackId,
49416
+ fingerprint,
49417
+ candidate
49418
+ });
48508
49419
  }
48509
49420
  }
48510
- if (ownerMap && (unchangedSinceDiscovery ? discoveredToolOwnerFallback : hasPiFallbackToolOwnerTags2(db, sessionId))) {
48511
- for (const row of findPiFallbackToolOwnerTags2(db, sessionId)) {
48512
- const parsed = parsePiFallbackToolOwnerId(row.toolOwnerMessageId);
48513
- if (parsed?.role !== "assistant")
48514
- continue;
48515
- const owners = ownerMap.get(piToolOwnerMapKey(parsed.timestamp, row.callId));
48516
- if (owners?.size !== 1)
48517
- continue;
48518
- const [realOwnerId] = owners;
48519
- if (!realOwnerId || realOwnerId === row.toolOwnerMessageId)
48520
- continue;
48521
- const existingNumber = getToolTagNumberByOwner2(db, sessionId, row.callId, realOwnerId);
48522
- const served = readServedNumbers();
48523
- const cachedSurvivor = existingNumber === null ? undefined : piCachedToolSurvivor(sessionId, row.callId, parsed.timestamp, getTagsByNumbers2(db, sessionId, [
48524
- row.tagNumber,
48525
- existingNumber
48526
- ]));
48527
- const repairKey = JSON.stringify([
48528
- "tool",
48529
- parsed.timestamp,
48530
- row.callId
48531
- ]);
48532
- const legacyKeys = [JSON.stringify(["tool", realOwnerId, row.callId])];
48533
- const decision = existingNumber === null ? { rebuilding: undefined } : plan([{ tagNumber: row.tagNumber }, { tagNumber: existingNumber }], repairKey, legacyKeys, served, cachedSurvivor);
48534
- if (decision === null)
48535
- continue;
48536
- const rebuilding = decision.rebuilding;
48537
- if (existingNumber !== null && !served.has(existingNumber) && !served.has(row.tagNumber) && cachedSurvivor === undefined && rebuilding === undefined) {
48538
- throw new PiTagIdentityConflictError2("duplicate tool identities have no proven served-byte survivor");
48539
- }
48540
- const adoption = fold(() => adoptPiFallbackToolOwnerTag2(db, sessionId, row.tagNumber, row.callId, row.toolOwnerMessageId, realOwnerId, served.size === 0 && cachedSurvivor !== undefined ? new Set([cachedSurvivor]) : served, cachedSurvivor, rebuilding), repairKey, repairKey, "tool", rebuilding);
48541
- if (adoption.action !== "skipped") {
48542
- tagger.unbindToolTag(sessionId, row.toolOwnerMessageId, row.callId);
48543
- if (adoption.action === "folded") {
48544
- tagger.unbindToolTag(sessionId, realOwnerId, row.callId);
48545
- }
48546
- tagger.bindToolTag(sessionId, row.callId, realOwnerId, adoption.tagNumber);
48547
- const accounting = getPersistedToolTagAccounting2(db, sessionId, adoption.tagNumber);
48548
- if (accounting) {
48549
- tagger.setToolTagAccounting(sessionId, adoption.tagNumber, accounting);
49421
+ if (ownerMap && (unchangedSinceDiscovery ? discoveredToolOwnerFallback : hasPiFallbackToolOwnerTags2(db, sessionId)))
49422
+ toolRows = findPiFallbackToolOwnerTags2(db, sessionId);
49423
+ };
49424
+ const runSlice = () => {
49425
+ if (!prepared) {
49426
+ prepare();
49427
+ prepared = true;
49428
+ }
49429
+ const started = performance.now();
49430
+ chunkRows = 0;
49431
+ while (next < messageItems.length + toolRows.length && chunkRows < PI_ADOPTION_CHUNK_ROWS && performance.now() - started < PI_ADOPTION_CHUNK_MS) {
49432
+ const index = next++;
49433
+ chunkRows++;
49434
+ const message = messageItems[index];
49435
+ if (message)
49436
+ adoptMessageCandidate(message);
49437
+ else {
49438
+ const row = toolRows[index - messageItems.length];
49439
+ if (row)
49440
+ adoptToolRow(row);
49441
+ }
49442
+ }
49443
+ };
49444
+ const runChunk = () => {
49445
+ const start = {
49446
+ next,
49447
+ prepared,
49448
+ pausedDuplicates,
49449
+ recurrences: recurrences.length
49450
+ };
49451
+ for (let attempt = 0;; attempt++) {
49452
+ afterCommit = [];
49453
+ try {
49454
+ runImmediateTransaction(db, () => {
49455
+ batch.load();
49456
+ runSlice();
49457
+ try {
49458
+ batch.flush();
49459
+ } catch (error) {
49460
+ if (isPiPassEndingError(error))
49461
+ throw error;
49462
+ throw new PiIdentityGuardsUnwritten(error instanceof Error ? error.message : String(error));
48550
49463
  }
48551
- }
49464
+ });
49465
+ } catch (error) {
49466
+ afterCommit = [];
49467
+ if (!(error instanceof PiIdentityGuardsUnwritten))
49468
+ throw error;
49469
+ next = start.next;
49470
+ prepared = start.prepared;
49471
+ pausedDuplicates = start.pausedDuplicates;
49472
+ recurrences.length = start.recurrences;
49473
+ if (attempt > 0)
49474
+ return false;
49475
+ sessionLog2(sessionId, `tag identity fold guards could not be written; duplicates that need one are served unmerged this pass: ${error.message}`);
49476
+ batch.refuseNewGuards = true;
49477
+ claimed.clear();
49478
+ repairing.clear();
49479
+ continue;
48552
49480
  }
49481
+ const committed = afterCommit;
49482
+ afterCommit = [];
49483
+ for (const effect of committed)
49484
+ effect();
49485
+ return true;
48553
49486
  }
48554
- });
49487
+ };
49488
+ do {
49489
+ if (!runChunk())
49490
+ break;
49491
+ } while (next < messageItems.length + toolRows.length);
49492
+ if (pausedDuplicates > 0)
49493
+ sessionLog2(sessionId, `tag identity adoption reached the pass budget: session=${sessionId} ${pausedDuplicates} duplicated identities stay unmerged until the next pass`);
49494
+ if (unguardedKeys.size > 0)
49495
+ sessionLog2(sessionId, `tag identity repairs without a stored guard: ${unguardedKeys.size} duplicated identities served unmerged this pass (guard store full or unreadable)`);
48555
49496
  for (const recurrence of recurrences) {
48556
49497
  if (!recurrence.fresh)
48557
49498
  continue;
@@ -48890,14 +49831,6 @@ function registerPiContextHandler(pi, baseOptions) {
48890
49831
  }
48891
49832
  }
48892
49833
  const tMeta = performance.now();
48893
- const historianStateForPass = options.compactionOff ? EMPTY_PI_HISTORIAN_STATE_SNAPSHOT : (() => {
48894
- try {
48895
- return loadPiHistorianStateSnapshot(options.db, sessionId);
48896
- } catch (error) {
48897
- sessionLog2(sessionId, `historian state snapshot failed; using safe defaults: ${error instanceof Error ? error.message : String(error)}`);
48898
- return EMPTY_PI_HISTORIAN_STATE_SNAPSHOT;
48899
- }
48900
- })();
48901
49834
  let piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
48902
49835
  db: options.db,
48903
49836
  sessionId,
@@ -49019,6 +49952,14 @@ function registerPiContextHandler(pi, baseOptions) {
49019
49952
  sessionMetaForUsage.lastContextPercentage = 0;
49020
49953
  sessionMetaForUsage.lastInputTokens = 0;
49021
49954
  }
49955
+ const historianStateForPass = options.compactionOff ? EMPTY_PI_HISTORIAN_STATE_SNAPSHOT : (() => {
49956
+ try {
49957
+ return loadPiHistorianStateSnapshot(options.db, sessionId);
49958
+ } catch (error) {
49959
+ sessionLog2(sessionId, `historian state snapshot failed; using safe defaults: ${error instanceof Error ? error.message : String(error)}`);
49960
+ return EMPTY_PI_HISTORIAN_STATE_SNAPSHOT;
49961
+ }
49962
+ })();
49022
49963
  let usagePercentage = 0;
49023
49964
  let usageInputTokens = 0;
49024
49965
  let usedPersistedUsage = false;
@@ -49171,7 +50112,19 @@ function registerPiContextHandler(pi, baseOptions) {
49171
50112
  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))));
49172
50113
  if (historian && !hasToolReclaim && getPendingOps(options.db, sessionId).length === 0 && !historyRefreshSessions.has(sessionId) && !deferredHistoryRefreshSessions.has(sessionId)) {
49173
50114
  budget.stage = "emergency historian";
49174
- await budget.wait(historian);
50115
+ const historianProgress = inFlightHistorianProgress.get(sessionId);
50116
+ const historianWaitMs = budget.remainingWork();
50117
+ try {
50118
+ await budget.wait(historian);
50119
+ } catch (error) {
50120
+ throw describeHistorianJoinDeadline(error, {
50121
+ db: options.db,
50122
+ sessionId,
50123
+ waitedMs: historianWaitMs,
50124
+ usagePercentage,
50125
+ run: historianProgress
50126
+ });
50127
+ }
49175
50128
  assertCurrentPass();
49176
50129
  sessionMeta = getOrCreateSessionMeta(options.db, sessionId);
49177
50130
  piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
@@ -49246,6 +50199,7 @@ function registerPiContextHandler(pi, baseOptions) {
49246
50199
  recoveryPrefix: recovery.prefix,
49247
50200
  recoveryRebuildReason: recovery.rebuildReason,
49248
50201
  assertCurrentPass,
50202
+ remainingPassMs: budget.remainingOutcome,
49249
50203
  db: options.db,
49250
50204
  tagger,
49251
50205
  sessionId,
@@ -50177,6 +51131,12 @@ function registerPiContextHandler(pi, baseOptions) {
50177
51131
  if (err instanceof PiDegradedPassError && err.site === "outgoing-over-window")
50178
51132
  throw contextRefusalError("The request exceeds the model's context window after reclaim, and no fitting saved request is available; this turn was not sent.");
50179
51133
  if (!lkgCompactionOff && sessionIdForError) {
51134
+ const historianJoin = findPiHistorianJoinDeadline(err);
51135
+ if (historianJoin)
51136
+ throw new PiDegradedPassError("emergency-historian-join", {
51137
+ cause: err,
51138
+ message: `${historianJoin.refusal} (${historianJoin.message})`
51139
+ });
50180
51140
  throw piFallbackRefusal("context-handler-failed", err);
50181
51141
  }
50182
51142
  log2(`[magic-context][pi] context handler failed (continuing without mutation): ${message}`, stack);
@@ -50206,6 +51166,7 @@ function registerPiContextHandler(pi, baseOptions) {
50206
51166
  log2("[magic-context][pi] registered context handler (tagging + drops + nudges)");
50207
51167
  }
50208
51168
  var inFlightHistorian = new Map;
51169
+ var inFlightHistorianProgress = new Map;
50209
51170
  var historianAbortControllers = new Map;
50210
51171
  function abortInFlightHistorians(sessionId) {
50211
51172
  historianAbortControllers.get(sessionId)?.abort();
@@ -50295,6 +51256,32 @@ function hasEligiblePiCompartmentHistory(db, sessionId, boundarySnapshot) {
50295
51256
  return false;
50296
51257
  }
50297
51258
  }
51259
+ function describeHistorianJoinDeadline(error, facts) {
51260
+ if (!(error instanceof PiContextDeadlineError))
51261
+ return error;
51262
+ try {
51263
+ return new PiHistorianJoinDeadlineError(error.message, describeHistorianJoinRefusal({
51264
+ waitedMs: facts.waitedMs,
51265
+ usagePercentage: facts.usagePercentage,
51266
+ run: facts.run,
51267
+ failures: readHistorianFailureStreak(facts.db, facts.sessionId)
51268
+ }));
51269
+ } catch (readError) {
51270
+ sessionLog2(facts.sessionId, `historian join refusal could not read the failure record: ${readError instanceof Error ? readError.message : String(readError)}`);
51271
+ return error;
51272
+ }
51273
+ }
51274
+ function findPiHistorianJoinDeadline(error) {
51275
+ const seen = new Set;
51276
+ let current = error;
51277
+ while (current && typeof current === "object" && !seen.has(current)) {
51278
+ if (current instanceof PiHistorianJoinDeadlineError)
51279
+ return current;
51280
+ seen.add(current);
51281
+ current = current.cause;
51282
+ }
51283
+ return;
51284
+ }
50298
51285
  function sendPiIgnoredNotification(ctx, message) {
50299
51286
  const uiNotify = ctx.ui?.notify;
50300
51287
  if (typeof uiNotify === "function") {
@@ -50326,6 +51313,7 @@ function spawnPiHistorianRun(args) {
50326
51313
  const holderId = crypto3.randomUUID();
50327
51314
  const controller = new AbortController;
50328
51315
  historianAbortControllers.set(sessionId, controller);
51316
+ const progress = { startedAt: Date.now() };
50329
51317
  const runPromise = inPiHistorianRootContext(sessionId, () => (async () => {
50330
51318
  await new Promise((resolve) => setTimeout(resolve, 0));
50331
51319
  if (controller.signal.aborted)
@@ -50390,6 +51378,9 @@ function spawnPiHistorianRun(args) {
50390
51378
  userObservationsRequested: historian.userObservationsRequested,
50391
51379
  language: historian.language,
50392
51380
  compartmentLeaseHolderId: holderId,
51381
+ onChunkSelected: (chunk) => {
51382
+ progress.chunk = chunk;
51383
+ },
50393
51384
  notifyIssue: (text) => {
50394
51385
  if (!isContextHandlerSessionActive(sessionId)) {
50395
51386
  sessionLog2(sessionId, "historian failure notice skipped after session context cleared");
@@ -50424,8 +51415,11 @@ function spawnPiHistorianRun(args) {
50424
51415
  })().catch((error) => {
50425
51416
  sessionLog2(sessionId, `pi historian run failed: ${error instanceof Error ? error.message : String(error)}`);
50426
51417
  }).finally(() => {
51418
+ progress.endedAt = Date.now();
50427
51419
  try {
50428
51420
  inFlightHistorian.delete(sessionId);
51421
+ if (inFlightHistorianProgress.get(sessionId) === progress)
51422
+ inFlightHistorianProgress.delete(sessionId);
50429
51423
  if (historianAbortControllers.get(sessionId) === controller)
50430
51424
  historianAbortControllers.delete(sessionId);
50431
51425
  unregister();
@@ -50437,6 +51431,7 @@ function spawnPiHistorianRun(args) {
50437
51431
  }
50438
51432
  }));
50439
51433
  inFlightHistorian.set(sessionId, runPromise);
51434
+ inFlightHistorianProgress.set(sessionId, progress);
50440
51435
  historian.onStatusChange?.(ctx, sessionId);
50441
51436
  }
50442
51437
  function resolvePiAppendCompaction(ctx) {
@@ -51346,6 +52341,7 @@ async function runPipeline(args) {
51346
52341
  realIdPositions: fallbackIndex.positions,
51347
52342
  hasFallbackMessageTags,
51348
52343
  preflightRevision,
52344
+ remainingMs: args.remainingPassMs,
51349
52345
  rebuildFingerprints: args.reusableMessageIds?.size ? () => {
51350
52346
  args.assertCurrentPass?.();
51351
52347
  const full = fallbackIndex.fingerprints(readPiFallbackFingerprintHeaders(args.db, args.sessionId));
@@ -56479,6 +57475,27 @@ async function persistPiPressureFromMessageEnd(args) {
56479
57475
  const activeModel = args.piModel ?? { provider, id: model };
56480
57476
  const modelKey = activeModel.provider && activeModel.id ? piModelRefToCanonical(`${activeModel.provider}/${activeModel.id}`) : undefined;
56481
57477
  const usage = extractAssistantUsage(args.message);
57478
+ const msg = args.message && typeof args.message === "object" ? args.message : undefined;
57479
+ const messageHadOverflowError = typeof msg?.errorMessage === "string" && detectOverflow(msg.errorMessage).isOverflow;
57480
+ const requestAccepted = !messageHadOverflowError && !providerResponseFailed({
57481
+ finish: args.message?.stopReason,
57482
+ error: msg?.errorMessage
57483
+ });
57484
+ if (requestAccepted) {
57485
+ const rawOverflow = getOverflowState(args.db, args.sessionId);
57486
+ const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
57487
+ if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel) {
57488
+ const uncappedPressure = computePiPressure(usage, args.piContextWindow, piPressureEvidenceLimit(resolvePiWindowGeometry({
57489
+ rawContextWindow: args.piContextWindow,
57490
+ rawContextWindowSource: args.piContextWindowSource,
57491
+ model: activeModel
57492
+ })));
57493
+ if (uncappedPressure && uncappedPressure.inputTokens > rawOverflow.detectedContextLimit) {
57494
+ clearDetectedContextLimit(args.db, args.sessionId);
57495
+ info(`message_end: detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${uncappedPressure.inputTokens}-token request; using Pi contextWindow`);
57496
+ }
57497
+ }
57498
+ }
56482
57499
  const detectedContextLimit = getOverflowState(args.db, args.sessionId, modelKey).detectedContextLimit;
56483
57500
  const reportedGeometry = resolvePiWindowGeometry({
56484
57501
  rawContextWindow: args.piContextWindow,
@@ -56495,21 +57512,7 @@ async function persistPiPressureFromMessageEnd(args) {
56495
57512
  if (rejectedUsage) {
56496
57513
  noteRejectedPiUsage(args.sessionId, reportedInput, providerInputLimit, "message_end");
56497
57514
  }
56498
- const msg = args.message && typeof args.message === "object" ? args.message : undefined;
56499
- const messageHadOverflowError = typeof msg?.errorMessage === "string" && detectOverflow(msg.errorMessage).isOverflow;
56500
- const requestAccepted = !messageHadOverflowError && !providerResponseFailed({
56501
- finish: args.message?.stopReason,
56502
- error: msg?.errorMessage
56503
- });
56504
57515
  const requestSucceeded = requestAccepted && !rejectedUsage;
56505
- if (requestAccepted && unboundedPressure) {
56506
- const rawOverflow = getOverflowState(args.db, args.sessionId);
56507
- const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
56508
- if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel && unboundedPressure.inputTokens > rawOverflow.detectedContextLimit) {
56509
- clearDetectedContextLimit(args.db, args.sessionId);
56510
- info(`message_end: detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${unboundedPressure.inputTokens}-token request; using Pi contextWindow`);
56511
- }
56512
- }
56513
57516
  const floorModelKey = piProvenFloorModelKey(activeModel);
56514
57517
  const observedSafeInputTokens = resolvePiProvenInputFloor({
56515
57518
  db: args.db,