@cortexkit/pi-magic-context 0.49.56 → 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-b1q0h16h.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-ywmt8sdr.js → index-mbzqrp0s.js} +19 -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-9x1jpjeb.js → index-tz8431zx.js} +88 -14
  12. package/dist/{index-5n3e2gq5.js → index-xgkq843e.js} +23 -1
  13. package/dist/index.js +842 -153
  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-gj0nzrg0.js → render-nejsk0az.js} +5 -5
  19. package/dist/{search-archive-vpxem4pj.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-r96gp6nc.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-9x1jpjeb.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,
@@ -564,6 +565,7 @@ import {
564
565
  externalHistorianFailureReason,
565
566
  subprocessExitHistorianFailureReason,
566
567
  countHistorianRuns,
568
+ getRecentFailedHistorianRunTimes,
567
569
  recordHistorianRun,
568
570
  summarizeImportance,
569
571
  tallyFactsByCategory,
@@ -579,7 +581,7 @@ import {
579
581
  getSourceContents,
580
582
  recordSubagentInvocation,
581
583
  getLatestHistorianInvocationId
582
- } from "./index-ywmt8sdr.js";
584
+ } from "./index-mbzqrp0s.js";
583
585
  import {
584
586
  resolveOpenCodeDbPath,
585
587
  assertOpenCodeStoreGeneration,
@@ -645,7 +647,7 @@ import {
645
647
  getRawSessionTagKeysThrough2,
646
648
  getLegacyProtectedTailStartOrdinal2,
647
649
  readSessionChunk2
648
- } from "./index-rekymyxd.js";
650
+ } from "./index-7mvsg371.js";
649
651
  import"./index-nvh6d3bz.js";
650
652
  import {
651
653
  formatSynapseLaneDescriptor
@@ -685,7 +687,7 @@ import {
685
687
  clearCompressionDepthRange,
686
688
  cleanSearchText,
687
689
  matchedSearchSnippet
688
- } from "./index-2pptpxq8.js";
690
+ } from "./index-15rx61th.js";
689
691
  import {
690
692
  rememberV1HiddenRun
691
693
  } from "./index-6x556c2q.js";
@@ -814,7 +816,7 @@ import {
814
816
  scheduleClearAndReindex,
815
817
  clearSessionTracking,
816
818
  createAutoSearchDiagnostics
817
- } from "./index-c3mms4dp.js";
819
+ } from "./index-8ej7crnf.js";
818
820
  import"./index-xssjy4z9.js";
819
821
  import {
820
822
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -831,6 +833,7 @@ import {
831
833
  import {
832
834
  PI_CONTEXT_BUDGET,
833
835
  PiContextDeadlineError,
836
+ PiHistorianJoinDeadlineError,
834
837
  PiContextSupersededError,
835
838
  PiContextBudget,
836
839
  PiTagHydrationError,
@@ -842,11 +845,11 @@ import {
842
845
  drainPiTagSnapshotSession,
843
846
  assertPiTagSnapshotReady,
844
847
  ensurePiTagSnapshotReady
845
- } from "./index-nhpvvdhw.js";
848
+ } from "./index-mmwgmz8f.js";
846
849
  import"./index-yjgkjkjs.js";
847
850
  import"./index-8d2z6503.js";
848
- import"./index-b1q0h16h.js";
849
- import"./index-9kaj9ty1.js";
851
+ import"./index-15eq9z3a.js";
852
+ import"./index-prhdb9c5.js";
850
853
  import {
851
854
  __toESM
852
855
  } from "./index-22jkk6wg.js";
@@ -3598,7 +3601,7 @@ function startHostStallProfilerSwitch() {
3598
3601
  // package.json
3599
3602
  var package_default = {
3600
3603
  name: "@cortexkit/pi-magic-context",
3601
- version: "0.49.56",
3604
+ version: "0.49.57",
3602
3605
  type: "module",
3603
3606
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3604
3607
  main: "dist/index.js",
@@ -3678,6 +3681,8 @@ var package_default = {
3678
3681
  "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
3679
3682
  "omp-pi-ai-18186": "npm:@oh-my-pi/pi-ai@18.18.6",
3680
3683
  "omp-pi-ai-18190": "npm:@oh-my-pi/pi-ai@18.19.0",
3684
+ "omp-pi-ai-18200": "npm:@oh-my-pi/pi-ai@18.20.0",
3685
+ "omp-pi-ai-18203": "npm:@oh-my-pi/pi-ai@18.20.3",
3681
3686
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3682
3687
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3683
3688
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -27183,6 +27188,140 @@ function foldExecutesThisPass(foldDue, materialized) {
27183
27188
  return foldDue && materialized;
27184
27189
  }
27185
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
+
27186
27325
  // ../plugin/src/hooks/magic-context/reasoning-removal.ts
27187
27326
  var REMOVABLE_REASONING_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
27188
27327
 
@@ -30853,6 +30992,37 @@ async function runPiHistorian(deps) {
30853
30992
  });
30854
30993
  }
30855
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
+ };
30856
31026
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
30857
31027
  const invocationBaseline = getLatestHistorianInvocationId(db, sessionId);
30858
31028
  const telemetry = {
@@ -30878,7 +31048,7 @@ async function runPiHistorian(deps) {
30878
31048
  sessionLog2(sessionId, `historian failure: source=existing-validation reason="${existingValidationError}"`);
30879
31049
  {
30880
31050
  const failCount = incrementHistorianFailure(db, sessionId, existingValidationError);
30881
- await notify(buildHistorianFailureNotice(failCount, existingValidationError));
31051
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, existingValidationError));
30882
31052
  }
30883
31053
  return;
30884
31054
  }
@@ -30979,9 +31149,9 @@ async function runPiHistorian(deps) {
30979
31149
  return;
30980
31150
  }
30981
31151
  sessionLog2(sessionId, `historian failure: source=prompt-fit reason="${promptFit.reason}"`);
30982
- incrementHistorianFailure(db, sessionId, promptFit.reason);
31152
+ const failCount = incrementHistorianFailure(db, sessionId, promptFit.reason);
30983
31153
  retainDrainReservationForRetryThrottle = true;
30984
- await notify(buildHistorianWindowTooSmallNotice());
31154
+ await notifyCountedFailure(failCount, buildHistorianWindowTooSmallNotice());
30985
31155
  return;
30986
31156
  }
30987
31157
  const chunkTokens = promptFit.chunkTokens;
@@ -31009,6 +31179,8 @@ async function runPiHistorian(deps) {
31009
31179
  drainReservation = reserve.reservation;
31010
31180
  const chunk = readSessionChunk2(sessionId, chunkTokens, offset, eligibleEndOrdinal, { expandTools: deps.expandTools });
31011
31181
  const forceKeepLastCompartmentForChunk = forceKeepLastCompartment === true && !chunk.hasMore;
31182
+ selectedChunk = { start: chunk.startIndex, end: chunk.endIndex };
31183
+ deps.onChunkSelected?.(selectedChunk);
31012
31184
  if (!chunk.text || chunk.messageCount === 0) {
31013
31185
  if (persistFilteredNoise(db, sessionId, chunk, eligibleEndOrdinal)) {
31014
31186
  telemetry.status = "noop";
@@ -31037,7 +31209,7 @@ async function runPiHistorian(deps) {
31037
31209
  sessionLog2(sessionId, `historian failure: source=chunk-coverage reason="${chunkCoverageError}" chunkRange=${chunk.startIndex}-${chunk.endIndex}`);
31038
31210
  {
31039
31211
  const failCount = incrementHistorianFailure(db, sessionId, chunkCoverageError);
31040
- await notify(buildHistorianFailureNotice(failCount, chunkCoverageError));
31212
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, chunkCoverageError));
31041
31213
  }
31042
31214
  rollbackDrainReservation();
31043
31215
  return;
@@ -31236,7 +31408,7 @@ ${chunkText}`,
31236
31408
  sessionLog2(sessionId, `historian failure: ${errorMsg}`);
31237
31409
  {
31238
31410
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31239
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31411
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31240
31412
  }
31241
31413
  return;
31242
31414
  }
@@ -31293,7 +31465,7 @@ ${chunkText}`,
31293
31465
  sessionLog2(sessionId, `historian failure: source=no-progress newCompartmentCount=${newCompartments.length} lastNewEnd=${lastNewEnd} priorEnd=${offset - 1}`);
31294
31466
  {
31295
31467
  const failCount = incrementHistorianFailure(db, sessionId, errorMsg);
31296
- await notify(buildHistorianFailureNotice(failCount, errorMsg));
31468
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, errorMsg));
31297
31469
  }
31298
31470
  recordHistorianNoProgress(boundarySnapshot, inEmergency);
31299
31471
  rollbackDrainReservation();
@@ -31508,7 +31680,7 @@ ${chunkText}`,
31508
31680
  sessionLog2(sessionId, `historian failure: source=exception ${desc.brief}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
31509
31681
  if (!issueNotified) {
31510
31682
  const failCount = incrementHistorianFailure(db, sessionId, desc.brief);
31511
- await notify(buildHistorianFailureNotice(failCount, desc.brief));
31683
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, desc.brief));
31512
31684
  }
31513
31685
  } finally {
31514
31686
  if (!completedSuccessfully) {
@@ -37039,12 +37211,93 @@ function isOmpAdvisorRequest(payload) {
37039
37211
  `) === true;
37040
37212
  }
37041
37213
  function isOmpUnmanagedCaptureRequest(payload) {
37214
+ return isOmpLegacyCaptureRequest(payload) || isOmpAutolearnCapture(payload);
37215
+ }
37216
+ function isOmpLegacyCaptureRequest(payload) {
37042
37217
  const request = providerRequest(payload);
37043
37218
  if (!request?.tools.length || !request.tools.every((name) => name === "manage_skill" || name === "learn"))
37044
37219
  return false;
37045
37220
  const last = record3(request.messages.at(-1));
37046
37221
  return last?.role === "user" && firstText(last.content, request.textType)?.startsWith(CAPTURE_PREFIX) === true;
37047
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
+ }
37048
37301
 
37049
37302
  // src/pi-dispatch-date-reminder.ts
37050
37303
  function object(value) {
@@ -37857,7 +38110,7 @@ ${wellFormed2(text)}
37857
38110
  </think>`;
37858
38111
  return;
37859
38112
  }
37860
- function coldReplayable(items) {
38113
+ function piResponsesColdReplayable(items) {
37861
38114
  let reasoning = false;
37862
38115
  for (const value of items) {
37863
38116
  const item = object8(value);
@@ -37979,7 +38232,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
37979
38232
  return texts;
37980
38233
  if (unsigned && alternatives) {
37981
38234
  alternatives.fallback = texts;
37982
- alternatives.cold = coldReplayable(payload.items) ? replay : texts;
38235
+ alternatives.cold = piResponsesColdReplayable(payload.items) ? replay : texts;
37983
38236
  }
37984
38237
  return replay;
37985
38238
  }
@@ -38004,15 +38257,270 @@ function piResponsesWireTexts(value, phase) {
38004
38257
  return texts;
38005
38258
  }
38006
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
+
38007
38515
  // src/pi-dispatch-row-diagnostic.ts
38008
- 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;
38009
38517
  function piDispatchRowDiagnostic(role, content) {
38010
38518
  const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : [];
38011
38519
  let kinds = 0;
38012
38520
  let chars = 0;
38013
38521
  let onlyText;
38014
38522
  for (const part of parts) {
38015
- const block = object9(part);
38523
+ const block = object10(part);
38016
38524
  const text = typeof part === "string" ? part : block?.text;
38017
38525
  if (typeof text === "string") {
38018
38526
  kinds |= block?.thought === true ? 16 : 1;
@@ -38143,11 +38651,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
38143
38651
  "devin-agent",
38144
38652
  "apple-foundation-models"
38145
38653
  ]);
38146
- function object10(value) {
38654
+ function object11(value) {
38147
38655
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
38148
38656
  }
38149
38657
  function messageStructure(value) {
38150
- const message = object10(value);
38658
+ const message = object11(value);
38151
38659
  if (!message)
38152
38660
  return;
38153
38661
  const role = [
@@ -38177,7 +38685,7 @@ function messageStructure(value) {
38177
38685
  }
38178
38686
  if (role === "assistant" && Array.isArray(message.content)) {
38179
38687
  for (const value of message.content) {
38180
- const block = object10(value);
38688
+ const block = object11(value);
38181
38689
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
38182
38690
  continue;
38183
38691
  if (typeof block.id !== "string")
@@ -38193,7 +38701,7 @@ function windowCalls(message) {
38193
38701
  if (!Array.isArray(message.content))
38194
38702
  return [];
38195
38703
  return message.content.flatMap((value) => {
38196
- const block = object10(value);
38704
+ const block = object11(value);
38197
38705
  return block?.type === "toolCall" && typeof block.id === "string" ? [
38198
38706
  {
38199
38707
  id: block.id,
@@ -38203,7 +38711,7 @@ function windowCalls(message) {
38203
38711
  });
38204
38712
  }
38205
38713
  function duplicateSuffix(model) {
38206
- const compat = object10(model?.compat);
38714
+ const compat = object11(model?.compat);
38207
38715
  if (model?.api === "openai-completions") {
38208
38716
  if (compat?.requiresMistralToolIds === true)
38209
38717
  return { prefix: "dup", max: 9 };
@@ -38218,24 +38726,14 @@ function appendDuplicateSuffix(id, suffix, max) {
38218
38726
  const segment = (part) => part.length + suffix.length <= max ? `${part}${suffix}` : `${part.slice(0, Math.max(0, max - suffix.length))}${suffix}`;
38219
38727
  return id.includes("|") ? id.split("|").map(segment).join("|") : segment(id);
38220
38728
  }
38221
- function projectMissingToolResults(messages, model, host = "omp") {
38222
- const input = messages.filter((value) => {
38223
- const message = object10(value);
38224
- return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
38225
- });
38226
- if (host === "pi")
38227
- return projectPiToolResults(input);
38228
- const api = model?.api;
38229
- if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
38230
- return projectUnmodeledToolResults(messages);
38231
- const pairingId = piToolCallPairing(input);
38729
+ function deduplicateToolCallIds(input, pairingId, model) {
38232
38730
  const { prefix, max } = duplicateSuffix(model);
38233
38731
  const seen = new Map;
38234
38732
  const renames = new Map;
38235
38733
  const realResults = new Map;
38236
38734
  const validToolUseIds = new Set;
38237
38735
  const deduplicated = input.map((value, index) => {
38238
- const message = object10(value);
38736
+ const message = object11(value);
38239
38737
  if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
38240
38738
  let key = pairingId(message.toolCallId);
38241
38739
  let output = value;
@@ -38262,7 +38760,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38262
38760
  const touched = new Set;
38263
38761
  let changed = false;
38264
38762
  const content = message.content.map((part) => {
38265
- const block = object10(part);
38763
+ const block = object11(part);
38266
38764
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38267
38765
  return part;
38268
38766
  const key = pairingId(block.id);
@@ -38294,6 +38792,25 @@ function projectMissingToolResults(messages, model, host = "omp") {
38294
38792
  validToolUseIds.add(pairingId(call.id));
38295
38793
  return changed ? { ...message, content } : value;
38296
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);
38297
38814
  const takeRealResult = (id, afterIndex) => {
38298
38815
  for (const entry of realResults.get(pairingId(id)) ?? []) {
38299
38816
  if (entry.consumed || entry.index <= afterIndex)
@@ -38341,7 +38858,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38341
38858
  };
38342
38859
  for (let index = 0;index < deduplicated.length; index++) {
38343
38860
  const value = deduplicated[index];
38344
- const message = object10(value);
38861
+ const message = object11(value);
38345
38862
  if (message?.role === "assistant") {
38346
38863
  flush(message.timestamp);
38347
38864
  if (piOmitsTruncatedAssistant(message))
@@ -38382,7 +38899,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
38382
38899
  if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
38383
38900
  continue;
38384
38901
  const parts = message.content.flatMap((value) => {
38385
- const part = object10(value);
38902
+ const part = object11(value);
38386
38903
  return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
38387
38904
  });
38388
38905
  if (!parts.length)
@@ -38410,11 +38927,11 @@ function projectUnmodeledToolResults(messages) {
38410
38927
  return pipe > 0 ? id.slice(0, pipe) : id;
38411
38928
  };
38412
38929
  for (const value of messages) {
38413
- const message = object10(value);
38930
+ const message = object11(value);
38414
38931
  if (message?.role !== "assistant" || !Array.isArray(message.content))
38415
38932
  continue;
38416
38933
  for (const value of message.content) {
38417
- const block = object10(value);
38934
+ const block = object11(value);
38418
38935
  if (block?.type !== "toolCall" || typeof block.id !== "string")
38419
38936
  continue;
38420
38937
  if ([
@@ -38430,7 +38947,7 @@ function projectUnmodeledToolResults(messages) {
38430
38947
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
38431
38948
  const lastResult = new Map;
38432
38949
  messages.forEach((value, index) => {
38433
- const message = object10(value);
38950
+ const message = object11(value);
38434
38951
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
38435
38952
  lastResult.set(pairingId(message.toolCallId), index);
38436
38953
  });
@@ -38461,7 +38978,7 @@ function projectUnmodeledToolResults(messages) {
38461
38978
  };
38462
38979
  for (let index = 0;index < messages.length; index++) {
38463
38980
  const value = messages[index];
38464
- const message = object10(value);
38981
+ const message = object11(value);
38465
38982
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
38466
38983
  continue;
38467
38984
  if (message?.role !== "toolResult")
@@ -38503,7 +39020,7 @@ function projectPiToolResults(messages) {
38503
39020
  held.length = 0;
38504
39021
  };
38505
39022
  for (const value of messages) {
38506
- const message = object10(value);
39023
+ const message = object11(value);
38507
39024
  const role = message?.role;
38508
39025
  if (role === "assistant") {
38509
39026
  close(message?.timestamp);
@@ -38534,7 +39051,7 @@ function projectPiToolResults(messages) {
38534
39051
  function preparePiDispatch(messages, model, omp, cwd) {
38535
39052
  let output = messages;
38536
39053
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
38537
- if (object10(source.providerPayload)?.type !== "openaiResponsesHistory")
39054
+ if (object11(source.providerPayload)?.type !== "openaiResponsesHistory")
38538
39055
  return;
38539
39056
  if (output === messages)
38540
39057
  output = messages.slice();
@@ -38555,7 +39072,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38555
39072
  if (!messages.length || messages.length > MAX_MESSAGES)
38556
39073
  return;
38557
39074
  for (let index = 0;index < messages.length; index++) {
38558
- const source = object10(messages[index]);
39075
+ const source = object11(messages[index]);
38559
39076
  if (source?.role === "user" || source?.role === "compactionSummary")
38560
39077
  prepareUser?.(index, source);
38561
39078
  }
@@ -38572,7 +39089,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38572
39089
  let valid = true;
38573
39090
  for (let index = 0;index < projectedMessages.length; index++) {
38574
39091
  const message = projectedMessages[index];
38575
- const source = object10(message);
39092
+ const source = object11(message);
38576
39093
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
38577
39094
  continue;
38578
39095
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -38596,7 +39113,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38596
39113
  "azure-openai-responses",
38597
39114
  "openai-codex-responses"
38598
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) => {
38599
- const block = object10(value);
39116
+ const block = object11(value);
38600
39117
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
38601
39118
  })))
38602
39119
  continue;
@@ -38640,12 +39157,12 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38640
39157
  const positionedRows = [...byIndex];
38641
39158
  for (let position = positionedRows.length - 1;position >= 0; position--) {
38642
39159
  const [index, row] = positionedRows[position];
38643
- const source = object10(projectedMessages[index]);
39160
+ const source = object11(projectedMessages[index]);
38644
39161
  if (!source)
38645
39162
  return;
38646
39163
  const content = source.content;
38647
39164
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
38648
- const textOnly = Array.isArray(parts) && parts.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string");
39165
+ const textOnly = Array.isArray(parts) && parts.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string");
38649
39166
  const systemTexts = () => {
38650
39167
  const texts = parts.map((part) => part.text);
38651
39168
  return model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
@@ -38653,7 +39170,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38653
39170
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
38654
39171
  const previous = rows[position - 1];
38655
39172
  const next = rows[position + 1];
38656
- 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;
38657
39174
  if (anthropicPromotable)
38658
39175
  promotable.set(row, systemTexts());
38659
39176
  if (model?.api === "ollama-chat" || anthropicPromotable && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
@@ -38682,6 +39199,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38682
39199
  const fallbackMessages = [];
38683
39200
  const coldMessages = [];
38684
39201
  let unsignedAlternatives = false;
39202
+ const planRows = [];
38685
39203
  const appendResponse = (output, row, texts) => {
38686
39204
  if (!texts.length && !row.calls.length)
38687
39205
  return;
@@ -38704,6 +39222,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38704
39222
  responsesMessages.push(row);
38705
39223
  fallbackMessages.push(row);
38706
39224
  coldMessages.push(row);
39225
+ planRows.push({ row });
38707
39226
  continue;
38708
39227
  }
38709
39228
  const alternatives = {};
@@ -38716,8 +39235,42 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38716
39235
  appendResponse(responsesMessages, row, texts);
38717
39236
  appendResponse(fallbackMessages, row, alternatives.fallback ?? texts);
38718
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
+ });
38719
39247
  }
38720
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");
38721
39274
  const plan = piChatHistoryPlan(projectedMessages, model);
38722
39275
  let pendingToolImages = [];
38723
39276
  const chatMessages = plan?.flatMap((step) => {
@@ -38750,12 +39303,17 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38750
39303
  ...responsesApi && !responsesMessages ? { structuralSkipReason: "Responses history transform is not modeled" } : model?.api === "openai-completions" && !chatMessages ? { structuralSkipReason: "Chat history transform is not modeled" } : {},
38751
39304
  ...chatMessages ? { chatMessages } : {},
38752
39305
  ...responsesMessages ? { responsesMessages } : {},
38753
- ...responsesMessages && unsignedAlternatives ? { responsesAlternatives: [fallbackMessages, coldMessages] } : {},
39306
+ ...responsesMessages && (unsignedAlternatives || replays) ? {
39307
+ responsesAlternatives: [
39308
+ replayPlan(fallbackMessages, "fallback"),
39309
+ replayPlan(coldMessages, "cold")
39310
+ ]
39311
+ } : {},
38754
39312
  ...model?.api ? { api: model.api } : {},
38755
39313
  ...modelsContinuePad ? { anthropicContinuePad: true } : {},
38756
39314
  ...modelsContinuePad && baseRows.some((row) => row.optionalThinking) ? { anthropicOptional: { rows: baseRows, promotable } } : {},
38757
39315
  ...model?.api?.startsWith("google-") ? {
38758
- googleFunctionIds: object10(model.compat)?.supportsFunctionPartId === true
39316
+ googleFunctionIds: object11(model.compat)?.supportsFunctionPartId === true
38759
39317
  } : {}
38760
39318
  };
38761
39319
  preparedSources.set(prepared, { messages: projectedMessages, rows: byIndex });
@@ -38763,8 +39321,8 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38763
39321
  dateReminderPlans.set(prepared, {
38764
39322
  ...modelsContinuePad ? { plan: { rows: baseRows, promotable } } : {},
38765
39323
  firstUser: firstUserRow ? baseRows.indexOf(firstUserRow) : -1,
38766
- midConversationSystem: object10(model?.compat)?.supportsMidConversationSystem === true,
38767
- developerRole: object10(model?.compat)?.supportsDeveloperRole === true
39324
+ midConversationSystem: object11(model?.compat)?.supportsMidConversationSystem === true,
39325
+ developerRole: object11(model?.compat)?.supportsDeveloperRole === true
38768
39326
  });
38769
39327
  return prepared;
38770
39328
  }
@@ -38784,7 +39342,7 @@ function responsesLane(api) {
38784
39342
  ].includes(api ?? "");
38785
39343
  }
38786
39344
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false, trackRows = false) {
38787
- const body = object10(payload);
39345
+ const body = object11(payload);
38788
39346
  if (!body)
38789
39347
  return;
38790
39348
  const google = piGoogleConversation(payload);
@@ -38799,12 +39357,12 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38799
39357
  return;
38800
39358
  const rows = [];
38801
39359
  for (const value of messages) {
38802
- const message = object10(value);
39360
+ const message = object11(value);
38803
39361
  if (!message)
38804
39362
  return;
38805
39363
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
38806
39364
  continue;
38807
- 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))))
38808
39366
  continue;
38809
39367
  if (responses && message.type === "reasoning")
38810
39368
  continue;
@@ -38881,7 +39439,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38881
39439
  continue;
38882
39440
  }
38883
39441
  if (message.role === "user" && Array.isArray(message.content)) {
38884
- 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);
38885
39443
  if (results.length) {
38886
39444
  for (const block of results) {
38887
39445
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -38938,11 +39496,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38938
39496
  }
38939
39497
  if (Array.isArray(message.tool_calls)) {
38940
39498
  for (const call of message.tool_calls) {
38941
- const source = object10(call);
39499
+ const source = object11(call);
38942
39500
  if (!source)
38943
39501
  return;
38944
39502
  if (source.id === undefined && ollama) {
38945
- const fn = object10(source.function);
39503
+ const fn = object11(source.function);
38946
39504
  if (typeof fn?.name !== "string")
38947
39505
  return;
38948
39506
  row.calls.push("");
@@ -38982,7 +39540,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38982
39540
  return;
38983
39541
  const rows = [];
38984
39542
  for (const value of contents) {
38985
- const message = object10(value);
39543
+ const message = object11(value);
38986
39544
  if (!message || !Array.isArray(message.parts))
38987
39545
  return;
38988
39546
  if (message.role !== "user" && message.role !== "model")
@@ -38998,11 +39556,11 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
38998
39556
  };
38999
39557
  const results = [];
39000
39558
  for (const value of message.parts) {
39001
- const part = object10(value);
39559
+ const part = object11(value);
39002
39560
  if (!part)
39003
39561
  return;
39004
39562
  if (part.functionCall) {
39005
- const call = object10(part.functionCall);
39563
+ const call = object11(part.functionCall);
39006
39564
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
39007
39565
  return;
39008
39566
  row.calls.push(call.id ?? "");
@@ -39010,7 +39568,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39010
39568
  row.callNames.push(call.name);
39011
39569
  }
39012
39570
  if (part.functionResponse) {
39013
- const result = object10(part.functionResponse);
39571
+ const result = object11(part.functionResponse);
39014
39572
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
39015
39573
  return;
39016
39574
  results.push({
@@ -39025,7 +39583,7 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39025
39583
  role: "tool-result",
39026
39584
  parts: 1,
39027
39585
  kinds: 8,
39028
- chars: typeof result.response === "string" ? result.response.length : Object.values(object10(result.response) ?? {}).reduce((count, value) => count + (typeof value === "string" ? value.length : 0), 0),
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),
39029
39587
  injector: "none"
39030
39588
  });
39031
39589
  }
@@ -39045,6 +39603,10 @@ function googleStructure(contents, imageProjection = false, trackRows = false) {
39045
39603
  }
39046
39604
  return rows;
39047
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
+ }
39048
39610
  function wireId(id, anthropic, responses) {
39049
39611
  if (anthropic)
39050
39612
  return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
@@ -39058,11 +39620,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
39058
39620
  if (responses || googleOrBedrock) {
39059
39621
  if (!Array.isArray(content) || content.length !== 1)
39060
39622
  return false;
39061
- const block = object10(content[0]);
39623
+ const block = object11(content[0]);
39062
39624
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
39063
39625
  }
39064
39626
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
39065
- const block = content.length === 1 ? object10(content[0]) : undefined;
39627
+ const block = content.length === 1 ? object11(content[0]) : undefined;
39066
39628
  return block?.type === "text" && block.text === text;
39067
39629
  }
39068
39630
  return content === text;
@@ -39248,15 +39810,15 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39248
39810
  }))) : undefined;
39249
39811
  const plan = prepared && dateReminderPlans.get(prepared);
39250
39812
  try {
39251
- const body = plan ? object10(payload) : undefined;
39813
+ const body = plan ? object11(payload) : undefined;
39252
39814
  const messages = body?.messages ?? body?.input;
39253
39815
  if (Array.isArray(messages)) {
39254
39816
  for (const value of messages) {
39255
- const message = object10(value);
39817
+ const message = object11(value);
39256
39818
  if (message?.role !== "system" && message?.role !== "developer")
39257
39819
  break;
39258
39820
  const content = message.content;
39259
- 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;
39260
39822
  if (piDateReminderWireText(content, plan?.cwd) !== undefined || piDateReminderText(inputText, plan?.cwd))
39261
39823
  return "comparison=role";
39262
39824
  }
@@ -39272,7 +39834,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39272
39834
  if (plan.firstUser < 0)
39273
39835
  return mismatch;
39274
39836
  const root = prepared.messages[plan.firstUser];
39275
- const body = object10(payload);
39837
+ const body = object11(payload);
39276
39838
  const routeRows = Array.isArray(body?.input) ? prepared.responsesMessages ?? prepared.messages : prepared.api === "openai-completions" ? prepared.chatMessages ?? prepared.messages : prepared.messages;
39277
39839
  const firstUser = routeRows.indexOf(root);
39278
39840
  if (firstUser < 0)
@@ -39283,11 +39845,11 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim, onAlignment
39283
39845
  });
39284
39846
  return filtered === undefined ? mismatch : preparedStructureMismatch(filtered, prepared, onImageTrim, undefined, undefined, undefined, aligned);
39285
39847
  }
39286
- const messages = object10(payload)?.messages;
39848
+ const messages = object11(payload)?.messages;
39287
39849
  if (!Array.isArray(messages))
39288
39850
  return mismatch;
39289
39851
  for (const value of messages) {
39290
- const message = object10(value);
39852
+ const message = object11(value);
39291
39853
  if (piDateReminderWireText(message?.content, plan.cwd) !== undefined && Object.keys(message ?? {}).some((key) => !["role", "content"].includes(key)))
39292
39854
  return mismatch;
39293
39855
  }
@@ -39327,7 +39889,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39327
39889
  return "comparison=image count";
39328
39890
  const imageProjection = trimmed > 0;
39329
39891
  stage = "wire rows";
39330
- const body = object10(payload);
39892
+ const body = object11(payload);
39331
39893
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
39332
39894
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39333
39895
  rows = reminderWire ?? payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection, !!onAlignment);
@@ -39336,7 +39898,12 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39336
39898
  expectedRows = responses && prepared?.responsesMessages ? prepared.responsesMessages : chat && prepared?.chatMessages ? prepared.chatMessages : prepared?.messages;
39337
39899
  if (responses && rows && prepared?.responsesAlternatives) {
39338
39900
  const actual = rows;
39339
- expectedRows = [prepared.responsesMessages, ...prepared.responsesAlternatives].find((candidate) => candidate?.length === actual.length && candidate.every((expected, index) => JSON.stringify(expected.responseTexts) === JSON.stringify(actual[index].responseTexts))) ?? expectedRows;
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;
39340
39907
  }
39341
39908
  const optionalPlan = expectedRows === prepared?.messages ? prepared?.anthropicOptional : undefined;
39342
39909
  if (expectedRows && imageProjection && imageBudget)
@@ -39354,7 +39921,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39354
39921
  if (expected.systemText !== undefined) {
39355
39922
  const texts = expected.systemText;
39356
39923
  const content = actual.wireContent;
39357
- const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string") ? content.map((part) => part.text) : undefined;
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;
39358
39925
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
39359
39926
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
39360
39927
  return "content";
@@ -39451,7 +40018,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
39451
40018
  }
39452
40019
  function piDispatchRowCount(payload, prepared) {
39453
40020
  try {
39454
- const body = object10(payload);
40021
+ const body = object11(payload);
39455
40022
  return payloadStructure(payload, prepared?.api === "ollama-chat", body?.messages === undefined && Array.isArray(body?.input) && !!prepared?.responsesMessages)?.length;
39456
40023
  } catch {
39457
40024
  return;
@@ -39473,7 +40040,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
39473
40040
  let expected = prepared?.messages;
39474
40041
  let actual;
39475
40042
  try {
39476
- const body = object10(payload);
40043
+ const body = object11(payload);
39477
40044
  const responses = body?.messages === undefined && Array.isArray(body?.input);
39478
40045
  if (responses)
39479
40046
  expected = prepared?.responsesMessages ?? expected;
@@ -40949,20 +41516,59 @@ function piCheckPreparedDispatch(payload, prepared, evidence, onImageTrim, onCom
40949
41516
  import { isDeepStrictEqual } from "node:util";
40950
41517
 
40951
41518
  // src/pi-dispatch-chain-tail.ts
40952
- function object11(value) {
41519
+ function object12(value) {
40953
41520
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
40954
41521
  }
40955
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
+ }
40956
41562
  function piEncodeChainTail(messages, assistant, responseItems, model) {
40957
- const harmony = object11(model.identity)?.class === "gpt-oss";
41563
+ const harmony = object12(model.identity)?.class === "gpt-oss";
40958
41564
  const text = (value) => {
40959
41565
  const wellFormed = value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
40960
41566
  return harmony ? wellFormed.replace(/<\|(start|end|message|channel|constrain|return|call)\|>/g, "<\\|$1\\|>") : wellFormed;
40961
41567
  };
40962
41568
  const supportsImages = model.input?.includes("image") === true;
40963
41569
  const image = (block) => {
40964
- const detail = block.detail === "original" && object11(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
40965
- 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);
40966
41572
  if (file?.provider === "openai" && typeof file.id === "string" && file.id)
40967
41573
  return { type: "input_image", detail, file_id: file.id };
40968
41574
  if (typeof block.url !== "string" && (typeof block.mimeType !== "string" || typeof block.data !== "string"))
@@ -40973,9 +41579,21 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40973
41579
  image_url: block.url ?? `data:${block.mimeType};base64,${block.data}`
40974
41580
  };
40975
41581
  };
40976
- const items = [];
41582
+ const outputs = new Set;
40977
41583
  for (const value of messages) {
40978
- let message = object11(value);
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];
41595
+ for (const value of messages) {
41596
+ let message = object12(value);
40979
41597
  if (!message || message.providerPayload !== undefined)
40980
41598
  return;
40981
41599
  message = piOmpUserHistory(message);
@@ -40983,7 +41601,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
40983
41601
  if (typeof message.customType !== "string" || message.attribution === "user")
40984
41602
  return;
40985
41603
  const converted = piAgentHistory([message], model.api);
40986
- const developer = object11(converted[0]);
41604
+ const developer = object12(converted[0]);
40987
41605
  if (converted.length !== 1 || !developer || !piIsDeveloperHistory(developer))
40988
41606
  return;
40989
41607
  message = {
@@ -41001,7 +41619,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
41001
41619
  const images = [];
41002
41620
  const ordered = [];
41003
41621
  for (const value of content) {
41004
- const block = object11(value);
41622
+ const block = object12(value);
41005
41623
  if (block?.type === "text" && typeof block.text === "string") {
41006
41624
  texts.push(block.text);
41007
41625
  if (!user || block.text.trim())
@@ -41029,15 +41647,15 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
41029
41647
  if (typeof message.toolCallId !== "string" || message.providerMetadata !== undefined)
41030
41648
  return;
41031
41649
  const id = piToolCallWireId(message.toolCallId, model, assistant);
41032
- const call = responseItems.map(object11).find((item) => item?.call_id === id);
41033
- if (!id || call?.type !== "function_call" && call?.type !== "custom_tool_call")
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")
41034
41652
  return;
41035
41653
  const joined = texts.join(`
41036
41654
  `);
41037
41655
  const output = images.length && supportsImages ? ordered : text(images.length && !supportsImages ? joined ? `${joined}
41038
41656
  ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41039
41657
  items.push({
41040
- 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",
41041
41659
  call_id: id,
41042
41660
  output
41043
41661
  });
@@ -41046,7 +41664,7 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41046
41664
  }
41047
41665
 
41048
41666
  // src/pi-dispatch-chain.ts
41049
- function object12(value) {
41667
+ function object13(value) {
41050
41668
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41051
41669
  }
41052
41670
  function piChainCapableApi(api) {
@@ -41054,10 +41672,10 @@ function piChainCapableApi(api) {
41054
41672
  }
41055
41673
  function injectedHeadIndex(messages) {
41056
41674
  let index = 0;
41057
- while (object12(messages[index])?.role === "system")
41675
+ while (object13(messages[index])?.role === "system")
41058
41676
  index++;
41059
- const m0 = object12(messages[index]);
41060
- const m1 = object12(messages[index + 1]);
41677
+ const m0 = object13(messages[index]);
41678
+ const m1 = object13(messages[index + 1]);
41061
41679
  const syntheticUser = (message) => message?.role === "user" && Object.keys(message).every((key) => ["role", "content", "timestamp"].includes(key));
41062
41680
  if (!syntheticUser(m0) || !syntheticUser(m1))
41063
41681
  return -1;
@@ -41065,16 +41683,16 @@ function injectedHeadIndex(messages) {
41065
41683
  const m1Content = m1?.content;
41066
41684
  if (!Array.isArray(m0Content) || !Array.isArray(m1Content))
41067
41685
  return -1;
41068
- const m0Text = object12(m0Content[0]);
41069
- const m1Text = object12(m1Content[0]);
41070
- return m0Content.length >= 1 && m0Content.length <= 2 && (m0Content.length === 1 || object12(m0Content[1])?.type === "image") && m1Content.length === 1 && m0Text?.type === "text" && typeof m0Text.text === "string" && /^(<project-docs>|<user-profile>|<covered-system-messages>|<session-history>)/.test(m0Text.text) && m0Text.text.includes("</session-history>") && m1Text?.type === "text" && typeof m1Text.text === "string" && /^(<session-history-since>|<knowledge-updates>)/.test(m1Text.text) ? index : -1;
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;
41071
41689
  }
41072
41690
  function piPreparedHistory(messages, model) {
41073
41691
  const snapshots = [];
41074
41692
  const responseIds = [];
41075
41693
  const head = injectedHeadIndex(messages);
41076
41694
  for (const [index, message] of messages.entries()) {
41077
- const source = object12(message);
41695
+ const source = object13(message);
41078
41696
  const identity = head >= 0 && (index === head || index === head + 1) ? Object.fromEntries(Object.entries(source ?? {}).filter(([key]) => key !== "timestamp")) : message;
41079
41697
  const fields = lkgContentFields(identity);
41080
41698
  if (!fields)
@@ -41086,17 +41704,18 @@ function piPreparedHistory(messages, model) {
41086
41704
  let index = responseIds.length - 1;
41087
41705
  while (index >= 0 && responseIds[index] === undefined)
41088
41706
  index--;
41089
- const assistant = object12(messages[index]);
41707
+ const assistant = object13(messages[index]);
41090
41708
  const response = piChainResponse(assistant);
41091
41709
  if (model && assistant && response) {
41092
- 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);
41093
41712
  if (delta)
41094
41713
  prepared.continuation = { index, ...response, delta };
41095
41714
  }
41096
41715
  return prepared;
41097
41716
  }
41098
41717
  function piChainedRequest(payload) {
41099
- const body = object12(payload);
41718
+ const body = object13(payload);
41100
41719
  if (!body || body.previous_response_id === undefined)
41101
41720
  return;
41102
41721
  const id = body.previous_response_id;
@@ -41105,14 +41724,14 @@ function piChainedRequest(payload) {
41105
41724
  return { previousResponseId: id, delta: body.input };
41106
41725
  }
41107
41726
  function piChainResponse(message) {
41108
- const source = object12(message);
41727
+ const source = object13(message);
41109
41728
  if (source?.role !== "assistant")
41110
41729
  return;
41111
41730
  if (source.stopReason !== "stop" && source.stopReason !== "toolUse")
41112
41731
  return;
41113
41732
  if (typeof source.responseId !== "string" || !source.responseId)
41114
41733
  return;
41115
- const payload = object12(source.providerPayload);
41734
+ const payload = object13(source.providerPayload);
41116
41735
  if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
41117
41736
  return;
41118
41737
  return {
@@ -41160,14 +41779,14 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
41160
41779
  import { createHash as createHash16 } from "node:crypto";
41161
41780
  var MAX_BYTES = 32 * 1024 * 1024;
41162
41781
  var MAX_ENTRIES = 1e5;
41163
- function object13(value) {
41782
+ function object14(value) {
41164
41783
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
41165
41784
  }
41166
41785
  function piCursorConversation(payload) {
41167
- const body = object13(payload);
41786
+ const body = object14(payload);
41168
41787
  if (body?.messages !== undefined || body?.input !== undefined || body?.contents !== undefined || body?.request !== undefined)
41169
41788
  return;
41170
- const state = object13(body?.conversationState);
41789
+ const state = object14(body?.conversationState);
41171
41790
  if (!state || !Array.isArray(state.rootPromptMessagesJson) || !Array.isArray(state.turns))
41172
41791
  return;
41173
41792
  let bytes = 0;
@@ -41187,7 +41806,7 @@ function piCursorConversation(payload) {
41187
41806
  }
41188
41807
  if (Array.isArray(value))
41189
41808
  return value.map((entry) => decode(entry, depth + 1));
41190
- const record = object13(value);
41809
+ const record = object14(value);
41191
41810
  if (record)
41192
41811
  return Object.fromEntries(Object.entries(record).map(([key, child]) => [
41193
41812
  key,
@@ -41198,7 +41817,7 @@ function piCursorConversation(payload) {
41198
41817
  try {
41199
41818
  const decoded = decode(state);
41200
41819
  for (const root of decoded.rootPromptMessagesJson) {
41201
- const record = object13(root);
41820
+ const record = object14(root);
41202
41821
  if (typeof record?.blobId === "string")
41203
41822
  rootIds.push(record.blobId);
41204
41823
  else if (record && typeof record.role === "string")
@@ -41207,19 +41826,19 @@ function piCursorConversation(payload) {
41207
41826
  return;
41208
41827
  }
41209
41828
  for (const value of decoded.turns.slice(0, 8)) {
41210
- const turn = object13(value);
41211
- const agent = object13(object13(turn?.turn)?.value) ?? turn;
41212
- const user = object13(agent?.userMessage);
41829
+ const turn = object14(value);
41830
+ const agent = object14(object14(turn?.turn)?.value) ?? turn;
41831
+ const user = object14(agent?.userMessage);
41213
41832
  if (typeof user?.text === "string")
41214
41833
  messages.push({ role: "user", content: user.text });
41215
41834
  }
41216
- const action = object13(object13(body?.action)?.action);
41835
+ const action = object14(object14(body?.action)?.action);
41217
41836
  if (!action || !["userMessageAction", "resumeAction"].includes(String(action.case)))
41218
41837
  return;
41219
41838
  let active = decode(body?.action);
41220
41839
  let activeText;
41221
41840
  if (action.case === "userMessageAction") {
41222
- const user = object13(object13(action.value)?.userMessage);
41841
+ const user = object14(object14(action.value)?.userMessage);
41223
41842
  if (!user || typeof user.text !== "string")
41224
41843
  return;
41225
41844
  messages.push({ role: "user", content: user.text });
@@ -41228,7 +41847,7 @@ function piCursorConversation(payload) {
41228
41847
  active = decode({
41229
41848
  action: {
41230
41849
  case: action.case,
41231
- value: { ...object13(action.value), userMessage: content }
41850
+ value: { ...object14(action.value), userMessage: content }
41232
41851
  }
41233
41852
  });
41234
41853
  }
@@ -41256,7 +41875,7 @@ function piCursorManagedRoots(messages, signature, cwd) {
41256
41875
  Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not repeat this information in your reply.
41257
41876
  </system-reminder>`;
41258
41877
  for (const value of messages.slice(0, 8)) {
41259
- const source = object13(value);
41878
+ const source = object14(value);
41260
41879
  if (!source || !["user", "developer"].includes(String(source.role)))
41261
41880
  continue;
41262
41881
  const message = piOmpUserHistory(source);
@@ -42585,7 +43204,7 @@ class PiDegradedPassError extends Error {
42585
43204
  code = "PI_DEGRADED_PASS";
42586
43205
  recoverable = true;
42587
43206
  constructor(site, options) {
42588
- super(describeDegradedPassFailure(site, options?.cause), options);
43207
+ super(options?.message ?? describeDegradedPassFailure(site, options?.cause), options);
42589
43208
  this.site = site;
42590
43209
  this.name = "PiDegradedPassError";
42591
43210
  }
@@ -42787,6 +43406,7 @@ function classifyPiOutgoingFit(estimate, limit) {
42787
43406
  // src/pi-context-refusal.ts
42788
43407
  var ENTRY_TYPE = "magic-context-turn-refused";
42789
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.";
42790
43410
  var MAX_UNSENDABLE_NONCES_PER_SESSION = 32;
42791
43411
  var receiptMaps = new Set;
42792
43412
  function clearPiContextReceipt(sessionId) {
@@ -42989,6 +43609,8 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42989
43609
  receiptMaps.add(imageTrimNotices);
42990
43610
  const foreignNotices = new Map;
42991
43611
  receiptMaps.add(foreignNotices);
43612
+ const captureNotices = new Map;
43613
+ receiptMaps.add(captureNotices);
42992
43614
  const foreignIndexes = new Map;
42993
43615
  receiptMaps.add(foreignIndexes);
42994
43616
  const chains = new Map;
@@ -43068,7 +43690,18 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43068
43690
  }
43069
43691
  });
43070
43692
  pi.on("before_provider_request", (event, ctx) => {
43071
- 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);
43072
43705
  const signal = ctx.signal;
43073
43706
  if (signal ? signal.aborted : cancelledOperation?.pass?.isCancelled()) {
43074
43707
  cancelledOperation?.pass?.cancel();
@@ -43077,11 +43710,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43077
43710
  return piRefusedPayload("Magic Context request cancelled before provider dispatch.");
43078
43711
  }
43079
43712
  if (options.compactionOff?.(ctx)) {
43080
- chains.delete(operationKey(ctx));
43713
+ chains.delete(key);
43081
43714
  return;
43082
43715
  }
43083
- const payload = event.payload;
43084
- const key = operationKey(ctx);
43085
43716
  if (sideSessions.get(key)?.sides)
43086
43717
  return;
43087
43718
  const nonces = unsendableNonces.get(key);
@@ -43110,15 +43741,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43110
43741
  }
43111
43742
  const active = operation;
43112
43743
  const isCurrent = () => operations.get(key) === active;
43113
- const capture = isOmpUnmanagedCaptureRequest(payload);
43114
- const budget = (capture ? undefined : active.pass) ?? new PiContextBudget;
43744
+ const budget = active.pass ?? new PiContextBudget;
43115
43745
  if (active.refused && active.pass === budget) {
43116
43746
  return piRefusedPayload(active.refusalMessage ?? RETRY_MESSAGE);
43117
43747
  }
43118
43748
  let refusalOrigin;
43119
43749
  try {
43120
- if (capture)
43121
- throw new Error("no context pass ran for OMP auto-learn capture; raw conversation refused");
43122
43750
  if (!active.pass)
43123
43751
  throw new Error("no context pass ran for this operation");
43124
43752
  if (!budget.completed && (budget.abandoned || budget.elapsed() >= PI_CONTEXT_BUDGET.outcomeMs))
@@ -43129,11 +43757,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
43129
43757
  }
43130
43758
  if (!budget.completed || !active.ready || active.refused || budget.abandoned)
43131
43759
  throw new Error("context pass ran without a managed context receipt");
43132
- const chained = piChainedRequest(payload);
43133
- let checked = payload;
43760
+ const managed = piWithoutOmpJuice(payload, ctx.model);
43761
+ const chained = piChainedRequest(managed);
43762
+ let checked = managed;
43134
43763
  let chainInput;
43135
43764
  if (chained) {
43136
- const expanded = piExpandChainedRequest(payload, chained, chains.get(key)?.anchor, active.preparedHistory, {
43765
+ const expanded = piExpandChainedRequest(managed, chained, chains.get(key)?.anchor, active.preparedHistory, {
43137
43766
  current: active.pass,
43138
43767
  resend: active.chainDispatchFields !== undefined
43139
43768
  });
@@ -49202,14 +49831,6 @@ function registerPiContextHandler(pi, baseOptions) {
49202
49831
  }
49203
49832
  }
49204
49833
  const tMeta = performance.now();
49205
- const historianStateForPass = options.compactionOff ? EMPTY_PI_HISTORIAN_STATE_SNAPSHOT : (() => {
49206
- try {
49207
- return loadPiHistorianStateSnapshot(options.db, sessionId);
49208
- } catch (error) {
49209
- sessionLog2(sessionId, `historian state snapshot failed; using safe defaults: ${error instanceof Error ? error.message : String(error)}`);
49210
- return EMPTY_PI_HISTORIAN_STATE_SNAPSHOT;
49211
- }
49212
- })();
49213
49834
  let piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
49214
49835
  db: options.db,
49215
49836
  sessionId,
@@ -49331,6 +49952,14 @@ function registerPiContextHandler(pi, baseOptions) {
49331
49952
  sessionMetaForUsage.lastContextPercentage = 0;
49332
49953
  sessionMetaForUsage.lastInputTokens = 0;
49333
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
+ })();
49334
49963
  let usagePercentage = 0;
49335
49964
  let usageInputTokens = 0;
49336
49965
  let usedPersistedUsage = false;
@@ -49483,7 +50112,19 @@ function registerPiContextHandler(pi, baseOptions) {
49483
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))));
49484
50113
  if (historian && !hasToolReclaim && getPendingOps(options.db, sessionId).length === 0 && !historyRefreshSessions.has(sessionId) && !deferredHistoryRefreshSessions.has(sessionId)) {
49485
50114
  budget.stage = "emergency historian";
49486
- 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
+ }
49487
50128
  assertCurrentPass();
49488
50129
  sessionMeta = getOrCreateSessionMeta(options.db, sessionId);
49489
50130
  piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
@@ -50490,6 +51131,12 @@ function registerPiContextHandler(pi, baseOptions) {
50490
51131
  if (err instanceof PiDegradedPassError && err.site === "outgoing-over-window")
50491
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.");
50492
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
+ });
50493
51140
  throw piFallbackRefusal("context-handler-failed", err);
50494
51141
  }
50495
51142
  log2(`[magic-context][pi] context handler failed (continuing without mutation): ${message}`, stack);
@@ -50519,6 +51166,7 @@ function registerPiContextHandler(pi, baseOptions) {
50519
51166
  log2("[magic-context][pi] registered context handler (tagging + drops + nudges)");
50520
51167
  }
50521
51168
  var inFlightHistorian = new Map;
51169
+ var inFlightHistorianProgress = new Map;
50522
51170
  var historianAbortControllers = new Map;
50523
51171
  function abortInFlightHistorians(sessionId) {
50524
51172
  historianAbortControllers.get(sessionId)?.abort();
@@ -50608,6 +51256,32 @@ function hasEligiblePiCompartmentHistory(db, sessionId, boundarySnapshot) {
50608
51256
  return false;
50609
51257
  }
50610
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
+ }
50611
51285
  function sendPiIgnoredNotification(ctx, message) {
50612
51286
  const uiNotify = ctx.ui?.notify;
50613
51287
  if (typeof uiNotify === "function") {
@@ -50639,6 +51313,7 @@ function spawnPiHistorianRun(args) {
50639
51313
  const holderId = crypto3.randomUUID();
50640
51314
  const controller = new AbortController;
50641
51315
  historianAbortControllers.set(sessionId, controller);
51316
+ const progress = { startedAt: Date.now() };
50642
51317
  const runPromise = inPiHistorianRootContext(sessionId, () => (async () => {
50643
51318
  await new Promise((resolve) => setTimeout(resolve, 0));
50644
51319
  if (controller.signal.aborted)
@@ -50703,6 +51378,9 @@ function spawnPiHistorianRun(args) {
50703
51378
  userObservationsRequested: historian.userObservationsRequested,
50704
51379
  language: historian.language,
50705
51380
  compartmentLeaseHolderId: holderId,
51381
+ onChunkSelected: (chunk) => {
51382
+ progress.chunk = chunk;
51383
+ },
50706
51384
  notifyIssue: (text) => {
50707
51385
  if (!isContextHandlerSessionActive(sessionId)) {
50708
51386
  sessionLog2(sessionId, "historian failure notice skipped after session context cleared");
@@ -50737,8 +51415,11 @@ function spawnPiHistorianRun(args) {
50737
51415
  })().catch((error) => {
50738
51416
  sessionLog2(sessionId, `pi historian run failed: ${error instanceof Error ? error.message : String(error)}`);
50739
51417
  }).finally(() => {
51418
+ progress.endedAt = Date.now();
50740
51419
  try {
50741
51420
  inFlightHistorian.delete(sessionId);
51421
+ if (inFlightHistorianProgress.get(sessionId) === progress)
51422
+ inFlightHistorianProgress.delete(sessionId);
50742
51423
  if (historianAbortControllers.get(sessionId) === controller)
50743
51424
  historianAbortControllers.delete(sessionId);
50744
51425
  unregister();
@@ -50750,6 +51431,7 @@ function spawnPiHistorianRun(args) {
50750
51431
  }
50751
51432
  }));
50752
51433
  inFlightHistorian.set(sessionId, runPromise);
51434
+ inFlightHistorianProgress.set(sessionId, progress);
50753
51435
  historian.onStatusChange?.(ctx, sessionId);
50754
51436
  }
50755
51437
  function resolvePiAppendCompaction(ctx) {
@@ -56793,6 +57475,27 @@ async function persistPiPressureFromMessageEnd(args) {
56793
57475
  const activeModel = args.piModel ?? { provider, id: model };
56794
57476
  const modelKey = activeModel.provider && activeModel.id ? piModelRefToCanonical(`${activeModel.provider}/${activeModel.id}`) : undefined;
56795
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
+ }
56796
57499
  const detectedContextLimit = getOverflowState(args.db, args.sessionId, modelKey).detectedContextLimit;
56797
57500
  const reportedGeometry = resolvePiWindowGeometry({
56798
57501
  rawContextWindow: args.piContextWindow,
@@ -56809,21 +57512,7 @@ async function persistPiPressureFromMessageEnd(args) {
56809
57512
  if (rejectedUsage) {
56810
57513
  noteRejectedPiUsage(args.sessionId, reportedInput, providerInputLimit, "message_end");
56811
57514
  }
56812
- const msg = args.message && typeof args.message === "object" ? args.message : undefined;
56813
- const messageHadOverflowError = typeof msg?.errorMessage === "string" && detectOverflow(msg.errorMessage).isOverflow;
56814
- const requestAccepted = !messageHadOverflowError && !providerResponseFailed({
56815
- finish: args.message?.stopReason,
56816
- error: msg?.errorMessage
56817
- });
56818
57515
  const requestSucceeded = requestAccepted && !rejectedUsage;
56819
- if (requestAccepted && unboundedPressure) {
56820
- const rawOverflow = getOverflowState(args.db, args.sessionId);
56821
- const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
56822
- if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel && unboundedPressure.inputTokens > rawOverflow.detectedContextLimit) {
56823
- clearDetectedContextLimit(args.db, args.sessionId);
56824
- info(`message_end: detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${unboundedPressure.inputTokens}-token request; using Pi contextWindow`);
56825
- }
56826
- }
56827
57516
  const floorModelKey = piProvenFloorModelKey(activeModel);
56828
57517
  const observedSafeInputTokens = resolvePiProvenInputFloor({
56829
57518
  db: args.db,