@cortexkit/pi-magic-context 0.49.22 → 0.49.24

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 (32) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +4 -4
  3. package/dist/{compartment-chunk-embedding-y01m95c2.js → compartment-chunk-embedding-g9a977b8.js} +3 -3
  4. package/dist/{embedding-backfill-2vh6m3bg.js → embedding-backfill-qxzjy5v2.js} +5 -5
  5. package/dist/historian-calibration-extension.js +1 -1
  6. package/dist/{index-w1twp2kp.js → index-00c5a49f.js} +1 -1
  7. package/dist/{index-fa485mqs.js → index-0b5kqg7n.js} +37 -1
  8. package/dist/{index-dbgg6hsf.js → index-3jde7hdr.js} +2 -2
  9. package/dist/{index-579m1751.js → index-8a2wvrda.js} +1 -1
  10. package/dist/{index-at6py2k3.js → index-8hmqdav2.js} +5 -1
  11. package/dist/{index-gqjxy2p7.js → index-byh4rfe7.js} +77 -5
  12. package/dist/{index-st4gwt64.js → index-faz8bw8b.js} +1 -1
  13. package/dist/{index-2bx7ge3x.js → index-fbrxezw0.js} +32 -32
  14. package/dist/{index-wgmhk91m.js → index-hf01gtz7.js} +3 -3
  15. package/dist/{index-pe5gz5c4.js → index-nxq2srg9.js} +1 -1
  16. package/dist/{index-ftvm2acc.js → index-rk8xef10.js} +4 -4
  17. package/dist/{index-vx6f7wff.js → index-wb2t932e.js} +1 -1
  18. package/dist/{index-5j6vwg4z.js → index-ygzh9xdg.js} +32 -22
  19. package/dist/index.js +550 -150
  20. package/dist/{message-fts-rowid-map-59y476bk.js → message-fts-rowid-map-1tb3qjtc.js} +2 -2
  21. package/dist/{message-index-bounded-4ngt600v.js → message-index-bounded-hjat9176.js} +5 -5
  22. package/dist/{message-index-3snxf11x.js → message-index-esykp965.js} +5 -5
  23. package/dist/migration-worker.js +3 -3
  24. package/dist/{project-embedding-registry-hfyzs654.js → project-embedding-registry-9e82qsb6.js} +4 -4
  25. package/dist/raw-ordinal-warmup-worker.js +6 -6
  26. package/dist/{read-session-chunk-5dmc77q2.js → read-session-chunk-tzvv1kph.js} +2 -2
  27. package/dist/{read-session-raw-yxv2fv34.js → read-session-raw-napqv76k.js} +3 -1
  28. package/dist/{search-archive-3daj5ttc.js → search-archive-enx1vd9n.js} +3 -3
  29. package/dist/{search-jhfh3tsj.js → search-n3yqng95.js} +8 -8
  30. package/dist/subagent-entry.js +11 -11
  31. package/dist/tag-snapshot-worker-pi.js +4 -4
  32. package/package.json +4 -3
package/dist/index.js CHANGED
@@ -251,7 +251,7 @@ import {
251
251
  registerTodoStateLifecycle,
252
252
  syncCtxMemoryToolEnabled,
253
253
  registerMagicContextTools
254
- } from "./index-2bx7ge3x.js";
254
+ } from "./index-fbrxezw0.js";
255
255
  import"./index-4knyh1kt.js";
256
256
  import {
257
257
  canonicalModelIdentity,
@@ -292,7 +292,7 @@ import {
292
292
  openCurrentDatabase,
293
293
  openDatabaseAsync,
294
294
  closeDatabase
295
- } from "./index-dbgg6hsf.js";
295
+ } from "./index-3jde7hdr.js";
296
296
  import {
297
297
  pruneMissingProjectIdentities,
298
298
  setHomeProjectPermission,
@@ -408,6 +408,7 @@ import {
408
408
  setSessionWorkMetrics,
409
409
  getSessionWorkMetrics,
410
410
  resolveEpochFloorForPass,
411
+ askAnswerLines,
411
412
  retreatPastHostUnservedRows,
412
413
  completedToolArcCrossesBoundary,
413
414
  estimateTrueRawMessageTokens,
@@ -465,7 +466,7 @@ import {
465
466
  getRawSessionTagKeysThrough2,
466
467
  getLegacyProtectedTailStartOrdinal2,
467
468
  readSessionChunk2
468
- } from "./index-gqjxy2p7.js";
469
+ } from "./index-byh4rfe7.js";
469
470
  import {
470
471
  UNKNOWN_FIT_RATIO,
471
472
  hasMeasuredDecisionCalibration,
@@ -616,7 +617,7 @@ import {
616
617
  indexSingleMessage2,
617
618
  indexMessagesAfterOrdinal2,
618
619
  sweepOrphanedOpenCodeMessageIndexesCooperatively2
619
- } from "./index-wgmhk91m.js";
620
+ } from "./index-hf01gtz7.js";
620
621
  import {
621
622
  resolveOpenCodeDbPath,
622
623
  assertOpenCodeStoreGeneration,
@@ -632,11 +633,11 @@ import {
632
633
  import {
633
634
  runSessionWarmupWorker,
634
635
  RAW_SUMMARY_TEXT_MAX_CHARS2
635
- } from "./index-at6py2k3.js";
636
+ } from "./index-8hmqdav2.js";
636
637
  import {
637
638
  formatSynapseLaneDescriptor
638
639
  } from "./index-gwxaz0z5.js";
639
- import"./index-579m1751.js";
640
+ import"./index-8a2wvrda.js";
640
641
  import {
641
642
  buildCanonicalChunkTextFromFts2,
642
643
  buildCompartmentSummaryFallbackText2,
@@ -646,7 +647,7 @@ import {
646
647
  replaceCompartmentChunkEmbeddings2,
647
648
  deleteChunkEmbedBackoffForSession2,
648
649
  chunkWindowSourceKey2
649
- } from "./index-vx6f7wff.js";
650
+ } from "./index-wb2t932e.js";
650
651
  import {
651
652
  recordSessionProjectIdentity,
652
653
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -681,7 +682,7 @@ import {
681
682
  embedSessionCompartmentChunks2,
682
683
  getEmbeddingCoverageStatus2,
683
684
  getAutoEmbeddingSessionCoverage2
684
- } from "./index-w1twp2kp.js";
685
+ } from "./index-00c5a49f.js";
685
686
  import {
686
687
  rememberV1HiddenRun
687
688
  } from "./index-6x556c2q.js";
@@ -746,7 +747,7 @@ import {
746
747
  normalizeVerificationFiles,
747
748
  indexCommitsForProject,
748
749
  embedUnembeddedCommits
749
- } from "./index-ftvm2acc.js";
750
+ } from "./index-rk8xef10.js";
750
751
  import {
751
752
  setEmbeddingSessionBusy2,
752
753
  isEmbeddingHostBusy2
@@ -782,7 +783,7 @@ import {
782
783
  } from "./index-wqpjhx1p.js";
783
784
  import {
784
785
  cosineSimilarity
785
- } from "./index-pe5gz5c4.js";
786
+ } from "./index-nxq2srg9.js";
786
787
  import"./index-6wdwv3a6.js";
787
788
  import {
788
789
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -791,10 +792,11 @@ import {
791
792
  readHostSystemPrompt,
792
793
  subagentStepCap,
793
794
  SubagentTelemetry,
795
+ OMP_CHILD_TOOL_CONFIG,
794
796
  HISTORIAN_CACHE_TAIL_ENV2,
795
797
  HISTORIAN_MAX_OUTPUT_TOKENS_ENV2,
796
798
  SUBAGENT_OUTPUT_CEILING_ENV2
797
- } from "./index-fa485mqs.js";
799
+ } from "./index-0b5kqg7n.js";
798
800
  import {
799
801
  PI_CONTEXT_BUDGET,
800
802
  PiContextDeadlineError,
@@ -809,10 +811,10 @@ import {
809
811
  drainPiTagSnapshotSession,
810
812
  assertPiTagSnapshotReady,
811
813
  ensurePiTagSnapshotReady
812
- } from "./index-5j6vwg4z.js";
814
+ } from "./index-ygzh9xdg.js";
813
815
  import"./index-jn44h81p.js";
814
816
  import"./index-1cvyaw9a.js";
815
- import"./index-st4gwt64.js";
817
+ import"./index-faz8bw8b.js";
816
818
  import {
817
819
  __toESM
818
820
  } from "./index-22jkk6wg.js";
@@ -3554,7 +3556,7 @@ function startHostStallProfilerSwitch() {
3554
3556
  // package.json
3555
3557
  var package_default = {
3556
3558
  name: "@cortexkit/pi-magic-context",
3557
- version: "0.49.22",
3559
+ version: "0.49.24",
3558
3560
  type: "module",
3559
3561
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3560
3562
  main: "dist/index.js",
@@ -3586,8 +3588,8 @@ var package_default = {
3586
3588
  build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3587
3589
  "build:e2e-argv": `bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import("../../tests/docker/.generated/subagent-runner-e2e.mjs"); if (typeof __test.buildArgs !== "function" || typeof __test.resolvePiInvocation !== "function") throw new Error("argv renderer exports missing"); console.log("Node argv renderer: 2 exports loaded")'`,
3588
3590
  typecheck: "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
3589
- test: "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",
3590
- "test:serial": "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && BUN_JSC_useOMGJIT=0 bun test --parallel=1 --timeout 30000",
3591
+ test: "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",
3592
+ "test:serial": "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=1 --timeout 30000",
3591
3593
  lint: "bun ../../scripts/check-bun.mjs && biome check src",
3592
3594
  "lint:fix": "biome check --write src",
3593
3595
  format: "biome format --write src",
@@ -3625,6 +3627,7 @@ var package_default = {
3625
3627
  "omp-pi-ai-1811": "npm:@oh-my-pi/pi-ai@18.11.3",
3626
3628
  "omp-pi-ai-1812": "npm:@oh-my-pi/pi-ai@18.12.3",
3627
3629
  "omp-pi-ai-18126": "npm:@oh-my-pi/pi-ai@18.12.6",
3630
+ "omp-pi-ai-1813": "npm:@oh-my-pi/pi-ai@18.13.0",
3628
3631
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3629
3632
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3630
3633
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -15543,7 +15546,10 @@ function orientationRenderer(capTokens) {
15543
15546
  sawMessage = true;
15544
15547
  const out = [];
15545
15548
  if (msg.role === "user" && hasMeaningfulUserText2(msg.parts)) {
15546
- const text = extractTexts2(msg.parts).map((t) => cleanUserText2(t)).map(normalizeText).filter((t) => t.length > 0).join(" / ");
15549
+ const rawTexts = extractTexts2(msg.parts);
15550
+ const parts = rawTexts.map((t) => cleanUserText2(t)).map(normalizeText).filter((t) => t.length > 0);
15551
+ parts.push(...rawTexts.flatMap((t) => askAnswerLines(t)).map(normalizeText));
15552
+ const text = parts.filter((t) => t.length > 0).join(" / ");
15547
15553
  if (text)
15548
15554
  out.push(`U: ${text}`);
15549
15555
  }
@@ -21077,6 +21083,7 @@ class PiSubagentRunner {
21077
21083
  const deliverViaStdin = !rpcBudget && (promptBytes > PROMPT_ARGV_MAX_BYTES || this.platform === "win32");
21078
21084
  let systemPromptTempDir;
21079
21085
  let systemPromptPath;
21086
+ let ompToolConfigPath;
21080
21087
  const cleanupSystemPromptFile = () => {
21081
21088
  if (!systemPromptTempDir)
21082
21089
  return;
@@ -21097,13 +21104,24 @@ class PiSubagentRunner {
21097
21104
  return failBeforeSpawn("spawn_failed", `failed to prepare pi system prompt file: ${error instanceof Error ? error.message : String(error)}`);
21098
21105
  }
21099
21106
  }
21100
- if (rpcBudget && !systemPromptTempDir) {
21107
+ if ((rpcBudget || this.invocation.targetHarness === "omp") && !systemPromptTempDir) {
21101
21108
  try {
21102
21109
  systemPromptTempDir = mkdtempSync2(join10(tmpdir2(), "mc-pi-prompt-"));
21103
21110
  } catch (error) {
21104
21111
  return failBeforeSpawn("spawn_failed", `failed to prepare pi budget guard: ${error instanceof Error ? error.message : String(error)}`);
21105
21112
  }
21106
21113
  }
21114
+ if (this.invocation.targetHarness === "omp") {
21115
+ try {
21116
+ if (!systemPromptTempDir)
21117
+ throw new Error("child temp directory is unavailable");
21118
+ ompToolConfigPath = join10(systemPromptTempDir, "tool-boundary.yml");
21119
+ writeFileSync4(ompToolConfigPath, OMP_CHILD_TOOL_CONFIG, "utf8");
21120
+ } catch (error) {
21121
+ cleanupSystemPromptFile();
21122
+ return failBeforeSpawn("spawn_failed", `failed to prepare OMP child tool config: ${String(error)}`);
21123
+ }
21124
+ }
21107
21125
  const budgetGuardFile = rpcBudget && systemPromptTempDir ? join10(systemPromptTempDir, "budget-guard") : undefined;
21108
21126
  if (budgetGuardFile) {
21109
21127
  try {
@@ -21120,6 +21138,7 @@ class PiSubagentRunner {
21120
21138
  hostToolNames: this.readHostToolNames(),
21121
21139
  omitPositionalMessage: deliverViaStdin || rpcBudget,
21122
21140
  systemPromptPath,
21141
+ ompToolConfigPath,
21123
21142
  modelRef: modelRefOverride,
21124
21143
  rpc: rpcBudget
21125
21144
  });
@@ -21812,6 +21831,10 @@ var PROMPT_ARGV_MAX_BYTES = 96 * 1024;
21812
21831
  function buildArgs(options, opts) {
21813
21832
  const targetHarness = opts?.targetHarness ?? resolvePiHarnessKind();
21814
21833
  const ompTarget = targetHarness === "omp";
21834
+ const ompToolConfigPath = opts?.ompToolConfigPath;
21835
+ if (ompTarget && !ompToolConfigPath) {
21836
+ throw new Error("OMP child requires a tool-boundary config overlay");
21837
+ }
21815
21838
  const args = [
21816
21839
  ...opts?.rpc ? [] : ["--print"],
21817
21840
  "--mode",
@@ -21820,6 +21843,9 @@ function buildArgs(options, opts) {
21820
21843
  "--no-skills",
21821
21844
  ...ompTarget ? ["--no-rules"] : ["--no-prompt-templates", "--no-context-files"]
21822
21845
  ];
21846
+ if (ompTarget && ompToolConfigPath) {
21847
+ args.push("--config", ompToolConfigPath);
21848
+ }
21823
21849
  if (opts?.disableDiscoveredExtensions || opts?.subagentExtensions !== undefined) {
21824
21850
  args.push("--no-extensions");
21825
21851
  }
@@ -21836,17 +21862,24 @@ function buildArgs(options, opts) {
21836
21862
  args.push("--magic-context-dreamer-actions");
21837
21863
  }
21838
21864
  }
21839
- const historianCalibrationEntryPath = opts?.historianCalibrationEntryPath === undefined ? HISTORIAN_CALIBRATION_ENTRY_PATH : opts.historianCalibrationEntryPath;
21840
- if (subagentStepCap(options.agent) !== undefined && historianCalibrationEntryPath) {
21865
+ const historianCalibrationEntryPath = opts?.historianCalibrationEntryPath === undefined ? HISTORIAN_CALIBRATION_ENTRY_PATH ?? (ompTarget ? resolveSiblingEntryPath("historian-calibration-extension.ts") : undefined) : opts.historianCalibrationEntryPath;
21866
+ if (ompTarget && !historianCalibrationEntryPath) {
21867
+ throw new Error("OMP child requires the tool-boundary startup extension");
21868
+ }
21869
+ if ((ompTarget || subagentStepCap(options.agent) !== undefined) && historianCalibrationEntryPath) {
21841
21870
  args.push("--extension", historianCalibrationEntryPath);
21842
21871
  }
21843
21872
  const strictTools = STRICT_TOOL_ALLOWLIST.get(options.agent);
21873
+ let activeToolNames = [];
21844
21874
  if (strictTools === undefined) {
21845
21875
  sessionLog2(options.accountingSessionId ?? "pi-subagent", `Pi subagent agent "${options.agent}" has no strict tool allow-list; forcing --no-tools`);
21846
21876
  args.push("--no-tools");
21847
21877
  } else {
21848
21878
  const resolution = resolveHostToolAllowlistDetails(strictTools, ompTarget, ompTarget ? opts?.hostToolNames : undefined);
21849
21879
  const hostTools = resolution.tools;
21880
+ activeToolNames = [
21881
+ ...new Set(strictTools.map((tool) => ompTarget ? OMP_TOOL_ALIASES[tool] ?? tool : tool).filter((tool) => !resolution.dropped.includes(tool)))
21882
+ ];
21850
21883
  for (const tool of resolution.dropped) {
21851
21884
  const warningKey = `${options.agent}\x00${tool}`;
21852
21885
  if (loggedUnavailableBuiltinTools.has(warningKey))
@@ -21861,6 +21894,9 @@ function buildArgs(options, opts) {
21861
21894
  args.push("--no-tools");
21862
21895
  }
21863
21896
  }
21897
+ if (ompTarget) {
21898
+ args.push("--magic-context-tool-allowlist", JSON.stringify(activeToolNames));
21899
+ }
21864
21900
  if (opts?.systemPromptPath) {
21865
21901
  args.push("--system-prompt", opts.systemPromptPath);
21866
21902
  }
@@ -25998,6 +26034,7 @@ function resolveProtectedTailBoundary(ctx) {
25998
26034
  priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
25999
26035
  migrationFloorActive: ctx.migrationFloorActive,
26000
26036
  emergencyTailScale: ctx.emergencyTailScale,
26037
+ liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
26001
26038
  providerShapeVersion: ctx.providerShapeVersion,
26002
26039
  cacheNamespace: ctx.cacheNamespace,
26003
26040
  createdAt,
@@ -29975,7 +30012,7 @@ async function runPiHistorian(deps) {
29975
30012
  }) : { ok: true };
29976
30013
  if (!validation.ok && validation.reason === "stale_snapshot" && refreshBoundarySnapshot) {
29977
30014
  try {
29978
- const refreshed = refreshBoundarySnapshot();
30015
+ const refreshed = refreshBoundarySnapshot(boundarySnapshot);
29979
30016
  if (hasRunnableCompartmentWindow(refreshed)) {
29980
30017
  sessionLog2(sessionId, `historian: refreshed stale protected-tail snapshot at run time (was: ${validation.detail ?? "stale"}) — eligible head ${refreshed.offset}-${refreshed.eligibleEndOrdinal - 1}`);
29981
30018
  boundarySnapshot = refreshed;
@@ -32353,6 +32390,7 @@ async function sendStatusNotification(_client, sessionId, text, params) {
32353
32390
  var inconsistentProducerWindows = new Set;
32354
32391
  var HISTORIAN_ALERT_COOLDOWN_MS2 = 60 * 1000;
32355
32392
  var lastHistorianAlertBySession2 = new Map;
32393
+ var loggedStoredValidationFailures = new Map;
32356
32394
  var STORED_COMPARTMENT_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
32357
32395
 
32358
32396
  // ../plugin/src/hooks/magic-context/compartment-runner-recomp.ts
@@ -35499,19 +35537,103 @@ function isOmpUnmanagedCaptureRequest(payload) {
35499
35537
  // src/pi-dispatch-chain.ts
35500
35538
  import { isDeepStrictEqual } from "node:util";
35501
35539
 
35502
- // src/pi-dispatch-agent-history.ts
35540
+ // src/pi-dispatch-omp-user.ts
35541
+ var PI_OMP_STEERING_TEMPLATE = `<system-notice>
35542
+ User interjection during work: priority; supersedes conflicting prior instructions. Re-read; ensure current work reflects user intent.
35543
+ </system-notice>
35544
+ {{message}}
35545
+ `;
35503
35546
  function object(value) {
35504
35547
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35505
35548
  }
35549
+ function renderSteering(text) {
35550
+ const lines = PI_OMP_STEERING_TEMPLATE.replace("{{message}}", () => text).split(`
35551
+ `);
35552
+ const result = [];
35553
+ let code = false;
35554
+ for (let index = 0;index < lines.length; index++) {
35555
+ let line = lines[index].trimEnd();
35556
+ let indent = 0;
35557
+ while (line.charCodeAt(indent) === 32 || line.charCodeAt(indent) === 9)
35558
+ indent++;
35559
+ if (line.charCodeAt(indent) >= 128)
35560
+ indent = line.length - line.trimStart().length;
35561
+ const start = line.slice(indent);
35562
+ if (start.startsWith("```") || start.startsWith("~~~")) {
35563
+ code = !code;
35564
+ result.push(line);
35565
+ continue;
35566
+ }
35567
+ if (code) {
35568
+ result.push(line);
35569
+ continue;
35570
+ }
35571
+ if (/^\|[-:\s|]+\|$/.test(start)) {
35572
+ const cells = start.split("|").filter((cell) => cell.trim());
35573
+ line = line.slice(0, line.length - start.length) + "|" + cells.map((cell) => {
35574
+ const value = cell.trim();
35575
+ return `${value.startsWith(":") ? ":" : ""}---${value.endsWith(":") ? ":" : ""}`;
35576
+ }).join("|") + "|";
35577
+ } else if (/^\|.*\|$/.test(start)) {
35578
+ line = line.slice(0, line.length - start.length) + start.split("|").map((cell) => cell.trim()).join("|");
35579
+ }
35580
+ if (!line.trim()) {
35581
+ const next = lines[index + 1];
35582
+ if (next === undefined || !next.trim()) {
35583
+ while (result.at(-1) === "")
35584
+ result.pop();
35585
+ while (index + 1 < lines.length && !lines[index + 1].trim())
35586
+ index++;
35587
+ continue;
35588
+ }
35589
+ if (!result.length || result.at(-1) === "")
35590
+ continue;
35591
+ }
35592
+ if (/^<\/[a-z_-]+>$/.test(start)) {
35593
+ while (result.at(-1) === "")
35594
+ result.pop();
35595
+ }
35596
+ result.push(line);
35597
+ }
35598
+ while (result.at(-1) === "")
35599
+ result.pop();
35600
+ return result.join(`
35601
+ `);
35602
+ }
35603
+ function piOmpUserHistory(message) {
35604
+ if (message.role !== "user" || message.steering !== true)
35605
+ return message;
35606
+ const content = message.content;
35607
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.filter((part) => object(part)?.type === "text").map((part) => object(part)?.text).join(`
35608
+ `) : "";
35609
+ if (!text.length)
35610
+ return message;
35611
+ const { steering: _steering, ...rest } = message;
35612
+ const wrapped = renderSteering(text);
35613
+ return {
35614
+ ...rest,
35615
+ content: typeof content === "string" ? wrapped : [
35616
+ { type: "text", text: wrapped },
35617
+ ...Array.isArray(content) ? content.filter((part) => object(part)?.type === "image") : []
35618
+ ]
35619
+ };
35620
+ }
35621
+
35622
+ // src/pi-dispatch-agent-history.ts
35623
+ function object2(value) {
35624
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35625
+ }
35506
35626
  var DEVELOPER_ORIGIN = Symbol("custom developer history");
35507
35627
  function piIsDeveloperHistory(message) {
35508
35628
  return message.role === "developer" || Reflect.get(message, DEVELOPER_ORIGIN) === true;
35509
35629
  }
35510
35630
  function piAgentHistory(messages, api) {
35511
35631
  return messages.flatMap((value) => {
35512
- const message = object(value);
35632
+ const message = object2(value);
35513
35633
  if (!message)
35514
35634
  return [value];
35635
+ if (message.role === "user")
35636
+ return [piOmpUserHistory(message)];
35515
35637
  if (message.role === "compactionSummary") {
35516
35638
  return [
35517
35639
  {
@@ -35534,7 +35656,7 @@ function piAgentHistory(messages, api) {
35534
35656
  const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
35535
35657
  const userInvoked = message.role === "custom" && message.attribution === "user";
35536
35658
  if (userInvoked && message.customType === "collab-prompt") {
35537
- const text = content.filter((part) => object(part)?.type === "text").map((part) => object(part)?.text).join(`
35659
+ const text = content.filter((part) => object2(part)?.type === "text").map((part) => object2(part)?.text).join(`
35538
35660
  `);
35539
35661
  return [
35540
35662
  {
@@ -35545,20 +35667,20 @@ function piAgentHistory(messages, api) {
35545
35667
  type: "text",
35546
35668
  text: text.length ? "User interjection envelope" : ""
35547
35669
  },
35548
- ...content.filter((part) => object(part)?.type === "image")
35670
+ ...content.filter((part) => object2(part)?.type === "image")
35549
35671
  ]
35550
35672
  }
35551
35673
  ];
35552
35674
  }
35553
35675
  if (userInvoked && message.customType === "skill-prompt")
35554
35676
  return [{ ...message, role: "user", content }];
35555
- const images = content.filter((part) => object(part)?.type === "image");
35677
+ const images = content.filter((part) => object2(part)?.type === "image");
35556
35678
  const developerRole = api === "ollama-chat" && message.attribution !== "user" ? "developer" : "user";
35557
35679
  if (!images.length)
35558
35680
  return [
35559
35681
  { ...message, role: developerRole, content, [DEVELOPER_ORIGIN]: true }
35560
35682
  ];
35561
- const texts = content.filter((part) => object(part)?.type === "text");
35683
+ const texts = content.filter((part) => object2(part)?.type === "text");
35562
35684
  return [
35563
35685
  ...texts.length ? [
35564
35686
  {
@@ -35651,20 +35773,20 @@ function piToolCallWireId(id, model, source) {
35651
35773
  }
35652
35774
 
35653
35775
  // src/pi-dispatch-chain-tail.ts
35654
- function object2(value) {
35776
+ function object3(value) {
35655
35777
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35656
35778
  }
35657
35779
  var OMITTED_IMAGE = "[image omitted: model does not support vision]";
35658
35780
  function piEncodeChainTail(messages, assistant, responseItems, model) {
35659
- const harmony = object2(model.identity)?.class === "gpt-oss";
35781
+ const harmony = object3(model.identity)?.class === "gpt-oss";
35660
35782
  const text = (value) => {
35661
35783
  const wellFormed = value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
35662
35784
  return harmony ? wellFormed.replace(/<\|(start|end|message|channel|constrain|return|call)\|>/g, "<\\|$1\\|>") : wellFormed;
35663
35785
  };
35664
35786
  const supportsImages = model.input?.includes("image") === true;
35665
35787
  const image = (block) => {
35666
- const detail = block.detail === "original" && object2(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
35667
- const file = object2(block.providerFile);
35788
+ const detail = block.detail === "original" && object3(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
35789
+ const file = object3(block.providerFile);
35668
35790
  if (file?.provider === "openai" && typeof file.id === "string" && file.id)
35669
35791
  return { type: "input_image", detail, file_id: file.id };
35670
35792
  if (typeof block.url !== "string" && (typeof block.mimeType !== "string" || typeof block.data !== "string"))
@@ -35677,14 +35799,15 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
35677
35799
  };
35678
35800
  const items = [];
35679
35801
  for (const value of messages) {
35680
- let message = object2(value);
35802
+ let message = object3(value);
35681
35803
  if (!message || message.providerPayload !== undefined)
35682
35804
  return;
35805
+ message = piOmpUserHistory(message);
35683
35806
  if (message.role === "custom" || message.role === "hookMessage") {
35684
35807
  if (typeof message.customType !== "string" || message.attribution === "user")
35685
35808
  return;
35686
35809
  const converted = piAgentHistory([message], model.api);
35687
- const developer = object2(converted[0]);
35810
+ const developer = object3(converted[0]);
35688
35811
  if (converted.length !== 1 || !developer || !piIsDeveloperHistory(developer))
35689
35812
  return;
35690
35813
  message = {
@@ -35702,7 +35825,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
35702
35825
  const images = [];
35703
35826
  const ordered = [];
35704
35827
  for (const value of content) {
35705
- const block = object2(value);
35828
+ const block = object3(value);
35706
35829
  if (block?.type === "text" && typeof block.text === "string") {
35707
35830
  texts.push(block.text);
35708
35831
  if (!user || block.text.trim())
@@ -35730,7 +35853,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
35730
35853
  if (typeof message.toolCallId !== "string" || message.providerMetadata !== undefined)
35731
35854
  return;
35732
35855
  const id = piToolCallWireId(message.toolCallId, model, assistant);
35733
- const call = responseItems.map(object2).find((item) => item?.call_id === id);
35856
+ const call = responseItems.map(object3).find((item) => item?.call_id === id);
35734
35857
  if (!id || call?.type !== "function_call" && call?.type !== "custom_tool_call")
35735
35858
  return;
35736
35859
  const joined = texts.join(`
@@ -35747,28 +35870,47 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
35747
35870
  }
35748
35871
 
35749
35872
  // src/pi-dispatch-chain.ts
35750
- function object3(value) {
35873
+ function object4(value) {
35751
35874
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35752
35875
  }
35753
35876
  function piChainCapableApi(api) {
35754
35877
  return api === "openai-codex-responses" || api === "openai-responses" || api === "azure-openai-responses";
35755
35878
  }
35879
+ function injectedHeadIndex(messages) {
35880
+ let index = 0;
35881
+ while (object4(messages[index])?.role === "system")
35882
+ index++;
35883
+ const m0 = object4(messages[index]);
35884
+ const m1 = object4(messages[index + 1]);
35885
+ const syntheticUser = (message) => message?.role === "user" && Object.keys(message).every((key) => ["role", "content", "timestamp"].includes(key));
35886
+ if (!syntheticUser(m0) || !syntheticUser(m1))
35887
+ return -1;
35888
+ const m0Content = m0?.content;
35889
+ const m1Content = m1?.content;
35890
+ if (!Array.isArray(m0Content) || !Array.isArray(m1Content))
35891
+ return -1;
35892
+ const m0Text = object4(m0Content[0]);
35893
+ const m1Text = object4(m1Content[0]);
35894
+ return m0Content.length >= 1 && m0Content.length <= 2 && (m0Content.length === 1 || object4(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;
35895
+ }
35756
35896
  function piPreparedHistory(messages, model) {
35757
35897
  const snapshots = [];
35758
35898
  const responseIds = [];
35759
- for (const message of messages) {
35760
- const fields = lkgContentFields(message);
35899
+ const head = injectedHeadIndex(messages);
35900
+ for (const [index, message] of messages.entries()) {
35901
+ const source = object4(message);
35902
+ const identity = head >= 0 && (index === head || index === head + 1) ? Object.fromEntries(Object.entries(source ?? {}).filter(([key]) => key !== "timestamp")) : message;
35903
+ const fields = lkgContentFields(identity);
35761
35904
  if (!fields)
35762
35905
  return;
35763
35906
  snapshots.push({ id: "", fields });
35764
- const source = object3(message);
35765
35907
  responseIds.push(source?.role === "assistant" && typeof source.responseId === "string" && source.responseId.length > 0 ? source.responseId : undefined);
35766
35908
  }
35767
35909
  const prepared = { snapshots, responseIds };
35768
35910
  let index = responseIds.length - 1;
35769
35911
  while (index >= 0 && responseIds[index] === undefined)
35770
35912
  index--;
35771
- const assistant = object3(messages[index]);
35913
+ const assistant = object4(messages[index]);
35772
35914
  const response = piChainResponse(assistant);
35773
35915
  if (model && assistant && response) {
35774
35916
  const delta = piEncodeChainTail(messages.slice(index + 1), assistant, response.responseItems, model);
@@ -35778,7 +35920,7 @@ function piPreparedHistory(messages, model) {
35778
35920
  return prepared;
35779
35921
  }
35780
35922
  function piChainedRequest(payload) {
35781
- const body = object3(payload);
35923
+ const body = object4(payload);
35782
35924
  if (!body || body.previous_response_id === undefined)
35783
35925
  return;
35784
35926
  const id = body.previous_response_id;
@@ -35787,14 +35929,14 @@ function piChainedRequest(payload) {
35787
35929
  return { previousResponseId: id, delta: body.input };
35788
35930
  }
35789
35931
  function piChainResponse(message) {
35790
- const source = object3(message);
35932
+ const source = object4(message);
35791
35933
  if (source?.role !== "assistant")
35792
35934
  return;
35793
35935
  if (source.stopReason !== "stop" && source.stopReason !== "toolUse")
35794
35936
  return;
35795
35937
  if (typeof source.responseId !== "string" || !source.responseId)
35796
35938
  return;
35797
- const payload = object3(source.providerPayload);
35939
+ const payload = object4(source.providerPayload);
35798
35940
  if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
35799
35941
  return;
35800
35942
  return {
@@ -35988,6 +36130,121 @@ function piHasManagedSignature(payload, signature) {
35988
36130
  function piOmitsTruncatedAssistant(message) {
35989
36131
  return (message.stopReason === "length" || message.stopReason === "error" || message.stopReason === "aborted") && Array.isArray(message.content) && !message.content.some((block) => block?.type === "text" || block?.type === "toolCall");
35990
36132
  }
36133
+ function object5(value) {
36134
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36135
+ }
36136
+ function nonblank(value) {
36137
+ return typeof value === "string" && value.trim().length > 0;
36138
+ }
36139
+ function wellFormed(text) {
36140
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
36141
+ }
36142
+ function piAnthropicAssistantReplay(message, model, host) {
36143
+ if (model?.api !== "anthropic-messages" || !Array.isArray(message.content))
36144
+ return "kept";
36145
+ const sameModel = message.provider === model.provider && message.api === model.api && message.model === model.id;
36146
+ let thinking = false;
36147
+ let fallback = false;
36148
+ for (const value of message.content) {
36149
+ const block = object5(value);
36150
+ if (!block)
36151
+ return "kept";
36152
+ if (block.type === "toolCall")
36153
+ return "kept";
36154
+ if (block.type === "text") {
36155
+ if (typeof block.text !== "string" || block.text.trim())
36156
+ return "kept";
36157
+ continue;
36158
+ }
36159
+ if (block.type === "thinking") {
36160
+ if (host === "pi") {
36161
+ if (block.redacted === true) {
36162
+ if (sameModel)
36163
+ return "kept";
36164
+ continue;
36165
+ }
36166
+ if (typeof block.thinking !== "string")
36167
+ return "kept";
36168
+ if (nonblank(block.thinking))
36169
+ return "kept";
36170
+ if (sameModel && nonblank(block.thinkingSignature))
36171
+ return "kept";
36172
+ continue;
36173
+ }
36174
+ if (typeof block.thinking !== "string")
36175
+ return "kept";
36176
+ if (message.api !== model.api) {
36177
+ if (nonblank(block.thinking))
36178
+ return "kept";
36179
+ continue;
36180
+ }
36181
+ if (message.provider !== model.provider && (nonblank(block.thinking) || nonblank(block.thinkingSignature)))
36182
+ return "kept";
36183
+ if (nonblank(block.thinking) || nonblank(block.thinkingSignature))
36184
+ thinking = true;
36185
+ continue;
36186
+ }
36187
+ if (host === "omp" && block.type === "redactedThinking") {
36188
+ if (typeof block.data !== "string")
36189
+ return "kept";
36190
+ if (message.api !== model.api)
36191
+ continue;
36192
+ if (message.provider !== model.provider && nonblank(block.data))
36193
+ return "kept";
36194
+ if (nonblank(block.data))
36195
+ thinking = true;
36196
+ continue;
36197
+ }
36198
+ if (host === "omp" && block.type === "anthropicServerTool") {
36199
+ if (message.api === "anthropic-messages" && message.provider === model.provider)
36200
+ return "kept";
36201
+ continue;
36202
+ }
36203
+ if (host === "omp" && block.type === "fallback")
36204
+ fallback = true;
36205
+ }
36206
+ if (thinking)
36207
+ return "optional";
36208
+ return fallback ? "kept" : "dropped";
36209
+ }
36210
+ function piAnthropicOptionalThinking(message) {
36211
+ const signatures = [];
36212
+ const redacted = [];
36213
+ const texts = [];
36214
+ let fallback = false;
36215
+ for (const value of Array.isArray(message.content) ? message.content : []) {
36216
+ const block = object5(value);
36217
+ if (block?.type === "thinking") {
36218
+ if (nonblank(block.thinkingSignature))
36219
+ signatures.push(block.thinkingSignature);
36220
+ if (nonblank(block.thinking))
36221
+ texts.push(wellFormed(block.thinking).trim());
36222
+ } else if (block?.type === "redactedThinking" && nonblank(block.data))
36223
+ redacted.push(block.data);
36224
+ else if (block?.type === "fallback")
36225
+ fallback = true;
36226
+ }
36227
+ return { signatures, redacted, texts, fallback };
36228
+ }
36229
+ var THINKING_PRESENCE_PLACEHOLDER = "(no reasoning was returned for this turn)";
36230
+ function piExplainsOptionalAssistant(thinking, content) {
36231
+ const fromThinking = (text) => typeof text === "string" && thinking.texts.some((prepared) => text.includes(prepared));
36232
+ return Array.isArray(content) && content.length > 0 && content.every((value) => {
36233
+ const block = object5(value);
36234
+ if (block?.type === "thinking") {
36235
+ if (nonblank(block.signature))
36236
+ return thinking.signatures.includes(block.signature);
36237
+ return block.thinking === THINKING_PRESENCE_PLACEHOLDER || fromThinking(block.thinking);
36238
+ }
36239
+ if (block?.type === "redacted_thinking")
36240
+ return typeof block.data === "string" && thinking.redacted.includes(block.data);
36241
+ if (block?.type === "text")
36242
+ return fromThinking(block.text);
36243
+ if (block?.type === "fallback")
36244
+ return thinking.fallback;
36245
+ return false;
36246
+ });
36247
+ }
35991
36248
 
35992
36249
  // src/pi-dispatch-tool-pairing.ts
35993
36250
  var RESPONSES_APIS = new Set([
@@ -35995,7 +36252,7 @@ var RESPONSES_APIS = new Set([
35995
36252
  "openai-codex-responses",
35996
36253
  "azure-openai-responses"
35997
36254
  ]);
35998
- function object4(value) {
36255
+ function object6(value) {
35999
36256
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36000
36257
  }
36001
36258
  function piResponsesCallComponent(id) {
@@ -36006,12 +36263,12 @@ function piToolCallPairing(messages) {
36006
36263
  const responsesComponents = new Set;
36007
36264
  const opaqueCompositeIds = new Set;
36008
36265
  for (const value of messages) {
36009
- const message = object4(value);
36266
+ const message = object6(value);
36010
36267
  if (message?.role !== "assistant" || !Array.isArray(message.content))
36011
36268
  continue;
36012
36269
  const responses = RESPONSES_APIS.has(String(message.api));
36013
36270
  for (const part of message.content) {
36014
- const block = object4(part);
36271
+ const block = object6(part);
36015
36272
  if (block?.type !== "toolCall" || typeof block.id !== "string")
36016
36273
  continue;
36017
36274
  if (responses)
@@ -36032,7 +36289,7 @@ function piToolCallPairing(messages) {
36032
36289
  // src/pi-dispatch-chat-history.ts
36033
36290
  var MAX_EXACT_UNITS = 32 * 1024 * 1024;
36034
36291
  var IMAGE_CAPTION = "Attached image(s) from tool result:";
36035
- function object5(value) {
36292
+ function object7(value) {
36036
36293
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36037
36294
  }
36038
36295
  function omitsAssistant(message, model, compat) {
@@ -36042,7 +36299,7 @@ function omitsAssistant(message, model, compat) {
36042
36299
  return true;
36043
36300
  let thinking = false;
36044
36301
  for (const value of message.content) {
36045
- const block = object5(value);
36302
+ const block = object7(value);
36046
36303
  if (!block)
36047
36304
  return false;
36048
36305
  if (block.type === "text") {
@@ -36064,15 +36321,15 @@ function omitsAssistant(message, model, compat) {
36064
36321
  function piChatHistoryPlan(messages, model) {
36065
36322
  if (model?.api !== "openai-completions")
36066
36323
  return;
36067
- const compat = object5(model.compat) ?? {};
36324
+ const compat = object7(model.compat) ?? {};
36068
36325
  const pairingId = piToolCallPairing(messages);
36069
36326
  const calls = new Set;
36070
36327
  for (const value of messages) {
36071
- const message = object5(value);
36328
+ const message = object7(value);
36072
36329
  if (message?.role !== "assistant" || !Array.isArray(message.content))
36073
36330
  continue;
36074
36331
  for (const value of message.content) {
36075
- const block = object5(value);
36332
+ const block = object7(value);
36076
36333
  if (block?.type === "toolCall" && typeof block.id === "string")
36077
36334
  calls.add(pairingId(block.id));
36078
36335
  }
@@ -36081,7 +36338,7 @@ function piChatHistoryPlan(messages, model) {
36081
36338
  let pending = new Set;
36082
36339
  let exactUnits = 0;
36083
36340
  for (let index = 0;index < messages.length; index++) {
36084
- const message = object5(messages[index]);
36341
+ const message = object7(messages[index]);
36085
36342
  if (!message)
36086
36343
  return;
36087
36344
  if ((message.role === "bashExecution" || message.role === "pythonExecution") && message.excludeFromContext === true)
@@ -36093,7 +36350,7 @@ function piChatHistoryPlan(messages, model) {
36093
36350
  continue;
36094
36351
  if (Array.isArray(message.content))
36095
36352
  for (const value of message.content) {
36096
- const block = object5(value);
36353
+ const block = object7(value);
36097
36354
  if (block?.type === "toolCall" && typeof block.id === "string")
36098
36355
  pending.add(pairingId(block.id));
36099
36356
  }
@@ -36105,7 +36362,7 @@ function piChatHistoryPlan(messages, model) {
36105
36362
  return;
36106
36363
  const parts = [];
36107
36364
  for (const value of message.content) {
36108
- const part = object5(value);
36365
+ const part = object7(value);
36109
36366
  if (part?.type === "text" && typeof part.text === "string" && part.text.trim())
36110
36367
  parts.push(part.text);
36111
36368
  }
@@ -36138,14 +36395,14 @@ ${parts.join(`
36138
36395
  };
36139
36396
  const vision = model.input?.includes("image") === true && compat.stripImageInput !== true;
36140
36397
  for (const step of transformed) {
36141
- const message = step.kind === "source" ? object5(messages[step.index]) : undefined;
36398
+ const message = step.kind === "source" ? object7(messages[step.index]) : undefined;
36142
36399
  if (message?.role !== "toolResult")
36143
36400
  flushImages();
36144
36401
  steps.push(step);
36145
36402
  if (message?.role !== "toolResult" || !vision || !Array.isArray(message.content))
36146
36403
  continue;
36147
36404
  for (const value of message.content) {
36148
- const block = object5(value);
36405
+ const block = object7(value);
36149
36406
  if (block?.type !== "image")
36150
36407
  continue;
36151
36408
  if (compat.requiresAssistantAfterToolResult === true)
@@ -36169,12 +36426,12 @@ ${parts.join(`
36169
36426
  function piMatchesChatImages(content, urls) {
36170
36427
  if (!Array.isArray(content) || content.length !== urls.length + 1)
36171
36428
  return false;
36172
- const caption = object5(content[0]);
36429
+ const caption = object7(content[0]);
36173
36430
  if (caption?.type !== "text" || caption.text !== IMAGE_CAPTION || Object.keys(caption).length !== 2)
36174
36431
  return false;
36175
36432
  for (let i = 0;i < urls.length; i++) {
36176
- const block = object5(content[i + 1]);
36177
- const image = object5(block?.image_url);
36433
+ const block = object7(content[i + 1]);
36434
+ const image = object7(block?.image_url);
36178
36435
  if (block?.type !== "image_url" || Object.keys(block).length !== 2 || !image || Object.keys(image).length !== 1 || image.url !== urls[i])
36179
36436
  return false;
36180
36437
  }
@@ -36182,22 +36439,22 @@ function piMatchesChatImages(content, urls) {
36182
36439
  }
36183
36440
 
36184
36441
  // src/pi-dispatch-image-budget.ts
36185
- function object6(value) {
36442
+ function object8(value) {
36186
36443
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36187
36444
  }
36188
36445
  function piImageBudgetPlan(model) {
36189
- if (!model?.input?.includes("image") || object6(model.compat)?.stripImageInput === true)
36446
+ if (!model?.input?.includes("image") || object8(model.compat)?.stripImageInput === true)
36190
36447
  return;
36191
36448
  return {
36192
36449
  count: 0,
36193
36450
  api: model.api,
36194
36451
  rows: new Map,
36195
- hoistToolImages: model.api?.startsWith("google-") === true && object6(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
36452
+ hoistToolImages: model.api?.startsWith("google-") === true && object8(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
36196
36453
  hoistErrorImages: model.api === "anthropic-messages" || model.api === "bedrock-converse-stream"
36197
36454
  };
36198
36455
  }
36199
36456
  function inputImage(block, api) {
36200
- const file = object6(block.providerFile);
36457
+ const file = object8(block.providerFile);
36201
36458
  if (api === "ollama-chat")
36202
36459
  return { kind: "bytes", value: String(block.data ?? "") };
36203
36460
  if ((api?.endsWith("responses") && file?.provider === "openai" || api === "anthropic-messages" && file?.provider === "anthropic") && typeof file?.id === "string")
@@ -36217,7 +36474,7 @@ function piRecordImages(plan, row, source) {
36217
36474
  return;
36218
36475
  const images = [];
36219
36476
  for (const value of source.content) {
36220
- const block = object6(value);
36477
+ const block = object8(value);
36221
36478
  if (block?.type === "image")
36222
36479
  images.push(inputImage(block, plan.api));
36223
36480
  }
@@ -36243,20 +36500,20 @@ function piWireImages(content, ollamaImages) {
36243
36500
  return [];
36244
36501
  const images = [];
36245
36502
  for (const value of content) {
36246
- const block = object6(value);
36503
+ const block = object8(value);
36247
36504
  if (!block)
36248
36505
  continue;
36249
- const source = object6(block.source);
36250
- const inline = object6(block.inlineData);
36251
- const file = object6(block.fileData);
36252
- const bedrock = object6(block.image);
36506
+ const source = object8(block.source);
36507
+ const inline = object8(block.inlineData);
36508
+ const file = object8(block.fileData);
36509
+ const bedrock = object8(block.image);
36253
36510
  if (block.type === "image_url" || block.type === "input_image") {
36254
36511
  if (typeof block.file_id === "string")
36255
36512
  images.push({ kind: "file", value: block.file_id });
36256
36513
  else
36257
36514
  images.push({
36258
36515
  kind: "url",
36259
- value: String(typeof block.image_url === "string" ? block.image_url : object6(block.image_url)?.url)
36516
+ value: String(typeof block.image_url === "string" ? block.image_url : object8(block.image_url)?.url)
36260
36517
  });
36261
36518
  } else if (block.type === "image") {
36262
36519
  if (source?.type === "file")
@@ -36280,7 +36537,7 @@ function piWireImages(content, ollamaImages) {
36280
36537
  else if (bedrock)
36281
36538
  images.push({
36282
36539
  kind: "data",
36283
- value: String(object6(bedrock.source)?.bytes),
36540
+ value: String(object8(bedrock.source)?.bytes),
36284
36541
  mime: `image/${bedrock.format}`
36285
36542
  });
36286
36543
  }
@@ -36302,11 +36559,11 @@ function piMatchesImages(actual, expected) {
36302
36559
  return true;
36303
36560
  }
36304
36561
  function piWireImageCount(payload) {
36305
- const body = object6(payload);
36562
+ const body = object8(payload);
36306
36563
  const visit = (value) => {
36307
36564
  if (Array.isArray(value))
36308
36565
  return value.reduce((n, item) => n + visit(item), 0);
36309
- const block = object6(value);
36566
+ const block = object8(value);
36310
36567
  if (!block)
36311
36568
  return 0;
36312
36569
  if (["image", "image_url", "input_image"].includes(String(block.type)) || block.inlineData || block.fileData || block.image)
@@ -36320,15 +36577,15 @@ function piWireImageCount(payload) {
36320
36577
  block.response
36321
36578
  ].reduce((n, item) => n + visit(item), Array.isArray(block.images) ? block.images.length : 0);
36322
36579
  };
36323
- return visit(body?.messages ?? body?.input ?? body?.contents ?? object6(body?.request)?.contents);
36580
+ return visit(body?.messages ?? body?.input ?? body?.contents ?? object8(body?.request)?.contents);
36324
36581
  }
36325
36582
 
36326
36583
  // src/pi-dispatch-responses-history.ts
36327
36584
  var MAX_TEXT_UNITS = 32 * 1024 * 1024;
36328
- function object7(value) {
36585
+ function object9(value) {
36329
36586
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36330
36587
  }
36331
- function wellFormed(text) {
36588
+ function wellFormed2(text) {
36332
36589
  return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
36333
36590
  }
36334
36591
  function textIdentity2(text, phase) {
@@ -36340,7 +36597,7 @@ function textIdentity2(text, phase) {
36340
36597
  function signaturePhase(block) {
36341
36598
  try {
36342
36599
  if (typeof block.textSignature === "string") {
36343
- const signature = object7(JSON.parse(block.textSignature));
36600
+ const signature = object9(JSON.parse(block.textSignature));
36344
36601
  if (signature?.v === 1 && typeof signature.id === "string")
36345
36602
  return signature.phase;
36346
36603
  }
@@ -36351,30 +36608,30 @@ function demotedThinking(text, model) {
36351
36608
  const id = model.id?.toLowerCase() ?? "";
36352
36609
  if (/^(?:[^/]+\/)?muse-spark-1\.3(?:-|$)/u.test(id))
36353
36610
  return `<thinking>
36354
- ${wellFormed(text)}
36611
+ ${wellFormed2(text)}
36355
36612
  </thinking>`;
36356
36613
  if (/^(?:[^/]+\/)?(?:gpt-|o[134](?:-|$)|chatgpt-|codex-)/u.test(id))
36357
36614
  return `<think>
36358
- ${wellFormed(text)}
36615
+ ${wellFormed2(text)}
36359
36616
  </think>`;
36360
36617
  return;
36361
36618
  }
36362
36619
  function coldReplayable(items) {
36363
36620
  let reasoning = false;
36364
36621
  for (const value of items) {
36365
- const item = object7(value);
36622
+ const item = object9(value);
36366
36623
  if (typeof item?.encrypted_content === "string")
36367
36624
  return false;
36368
36625
  if (item?.type !== "reasoning")
36369
36626
  continue;
36370
- if (!Array.isArray(item.content) || !item.content.some((part) => object7(part)?.type === "reasoning_text"))
36627
+ if (!Array.isArray(item.content) || !item.content.some((part) => object9(part)?.type === "reasoning_text"))
36371
36628
  return false;
36372
36629
  reasoning = true;
36373
36630
  }
36374
36631
  return reasoning;
36375
36632
  }
36376
36633
  function piResponsesAssistantTexts(value, model, host, alternatives) {
36377
- const message = object7(value);
36634
+ const message = object9(value);
36378
36635
  if (!message || !Array.isArray(message.content))
36379
36636
  return;
36380
36637
  if (piOmitsTruncatedAssistant(message))
@@ -36384,7 +36641,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36384
36641
  const sameModel = model !== undefined && typeof model.api === "string" && typeof model.id === "string" && typeof model.provider === "string" && message.api === model.api && message.model === model.id && message.provider === model.provider;
36385
36642
  let units = 0;
36386
36643
  for (const value of message.content) {
36387
- const block = object7(value);
36644
+ const block = object9(value);
36388
36645
  if (block?.type === "toolCall")
36389
36646
  continue;
36390
36647
  if (block?.type === "thinking") {
@@ -36394,7 +36651,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36394
36651
  return;
36395
36652
  if (!block.thinking.trim())
36396
36653
  continue;
36397
- const compat = object7(model.compat);
36654
+ const compat = object9(model.compat);
36398
36655
  if (block.summary === false && (compat?.requiresReasoningContentForToolCalls === true || compat?.requiresReasoningContentForAllAssistantTurns === true))
36399
36656
  return;
36400
36657
  const text = demotedThinking(block.thinking, model);
@@ -36411,10 +36668,10 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36411
36668
  units += block.text.length;
36412
36669
  if (units > MAX_TEXT_UNITS)
36413
36670
  return;
36414
- texts.push(textIdentity2(wellFormed(block.text), sameModel ? signaturePhase(block) : undefined));
36671
+ texts.push(textIdentity2(wellFormed2(block.text), sameModel ? signaturePhase(block) : undefined));
36415
36672
  blocks.push(block);
36416
36673
  }
36417
- const payload = object7(message.providerPayload);
36674
+ const payload = object9(message.providerPayload);
36418
36675
  if (message.api !== model?.api || typeof model?.id !== "string" || typeof model?.provider !== "string" || message.model !== model?.id || (payload?.provider ?? message.provider) !== model?.provider || payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
36419
36676
  return texts;
36420
36677
  const replay = [];
@@ -36428,7 +36685,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36428
36685
  let unsigned = false;
36429
36686
  let rewrittenText = false;
36430
36687
  for (const value of payload.items) {
36431
- const item = object7(value);
36688
+ const item = object9(value);
36432
36689
  if (item?.type === "reasoning")
36433
36690
  continue;
36434
36691
  if (item?.type === "function_call" || item?.type === "custom_tool_call") {
@@ -36439,14 +36696,14 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36439
36696
  return texts;
36440
36697
  const itemTexts = [];
36441
36698
  for (const value of item.content) {
36442
- const part = object7(value);
36699
+ const part = object9(value);
36443
36700
  const block = blocks[bound];
36444
36701
  if (!block || part?.type !== "output_text" || typeof part.text !== "string")
36445
36702
  return texts;
36446
36703
  let signature;
36447
36704
  try {
36448
36705
  if (typeof block.textSignature === "string")
36449
- signature = object7(JSON.parse(block.textSignature));
36706
+ signature = object9(JSON.parse(block.textSignature));
36450
36707
  } catch {
36451
36708
  return texts;
36452
36709
  }
@@ -36465,7 +36722,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36465
36722
  continue;
36466
36723
  output = true;
36467
36724
  for (const text of itemTexts)
36468
- replay.push(textIdentity2(wellFormed(text), item.phase));
36725
+ replay.push(textIdentity2(wellFormed2(text), item.phase));
36469
36726
  }
36470
36727
  if (!output || bound !== blocks.length || unsigned && !rewrittenText)
36471
36728
  return texts;
@@ -36485,7 +36742,7 @@ function piResponsesWireTexts(value, phase) {
36485
36742
  const texts = [];
36486
36743
  let units = 0;
36487
36744
  for (const partValue of value) {
36488
- const part = object7(partValue);
36745
+ const part = object9(partValue);
36489
36746
  if (part?.type !== "output_text" || typeof part.text !== "string")
36490
36747
  return;
36491
36748
  units += part.text.length;
@@ -36499,6 +36756,14 @@ function piResponsesWireTexts(value, phase) {
36499
36756
  // src/pi-dispatch-structure.ts
36500
36757
  var MAX_MESSAGES = 1e5;
36501
36758
  var ORPHAN_NOTE = Symbol("prepared orphan tool result");
36759
+ var ANTHROPIC_CONTINUE_PAD_TEXT = "Continue.";
36760
+ var ANTHROPIC_CONTINUE_PAD_APIS = new Set(["anthropic-messages"]);
36761
+ function piModelsAnthropicContinuePad(api, host) {
36762
+ return host === "omp" && api !== undefined && ANTHROPIC_CONTINUE_PAD_APIS.has(api);
36763
+ }
36764
+ function isAnthropicContinuePadRow(row) {
36765
+ return row.role === "user" && row.wireContent === ANTHROPIC_CONTINUE_PAD_TEXT;
36766
+ }
36502
36767
  var TRANSFORM_MESSAGES_APIS = new Set([
36503
36768
  "openai-completions",
36504
36769
  "openai-responses",
@@ -36515,11 +36780,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
36515
36780
  "devin-agent",
36516
36781
  "apple-foundation-models"
36517
36782
  ]);
36518
- function object8(value) {
36783
+ function object10(value) {
36519
36784
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36520
36785
  }
36521
36786
  function messageStructure(value) {
36522
- const message = object8(value);
36787
+ const message = object10(value);
36523
36788
  if (!message)
36524
36789
  return;
36525
36790
  const role = [
@@ -36548,7 +36813,7 @@ function messageStructure(value) {
36548
36813
  }
36549
36814
  if (role === "assistant" && Array.isArray(message.content)) {
36550
36815
  for (const value of message.content) {
36551
- const block = object8(value);
36816
+ const block = object10(value);
36552
36817
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
36553
36818
  continue;
36554
36819
  if (typeof block.id !== "string")
@@ -36564,7 +36829,7 @@ function windowCalls(message) {
36564
36829
  if (!Array.isArray(message.content))
36565
36830
  return [];
36566
36831
  return message.content.flatMap((value) => {
36567
- const block = object8(value);
36832
+ const block = object10(value);
36568
36833
  return block?.type === "toolCall" && typeof block.id === "string" ? [
36569
36834
  {
36570
36835
  id: block.id,
@@ -36574,7 +36839,7 @@ function windowCalls(message) {
36574
36839
  });
36575
36840
  }
36576
36841
  function duplicateSuffix(model) {
36577
- const compat = object8(model?.compat);
36842
+ const compat = object10(model?.compat);
36578
36843
  if (model?.api === "openai-completions") {
36579
36844
  if (compat?.requiresMistralToolIds === true)
36580
36845
  return { prefix: "dup", max: 9 };
@@ -36591,7 +36856,7 @@ function appendDuplicateSuffix(id, suffix, max) {
36591
36856
  }
36592
36857
  function projectMissingToolResults(messages, model, host = "omp") {
36593
36858
  const input = messages.filter((value) => {
36594
- const message = object8(value);
36859
+ const message = object10(value);
36595
36860
  return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
36596
36861
  });
36597
36862
  if (host === "pi")
@@ -36606,7 +36871,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
36606
36871
  const realResults = new Map;
36607
36872
  const validToolUseIds = new Set;
36608
36873
  const deduplicated = input.map((value, index) => {
36609
- const message = object8(value);
36874
+ const message = object10(value);
36610
36875
  if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
36611
36876
  let key = pairingId(message.toolCallId);
36612
36877
  let output = value;
@@ -36633,7 +36898,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
36633
36898
  const touched = new Set;
36634
36899
  let changed = false;
36635
36900
  const content = message.content.map((part) => {
36636
- const block = object8(part);
36901
+ const block = object10(part);
36637
36902
  if (block?.type !== "toolCall" || typeof block.id !== "string")
36638
36903
  return part;
36639
36904
  const key = pairingId(block.id);
@@ -36712,7 +36977,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
36712
36977
  };
36713
36978
  for (let index = 0;index < deduplicated.length; index++) {
36714
36979
  const value = deduplicated[index];
36715
- const message = object8(value);
36980
+ const message = object10(value);
36716
36981
  if (message?.role === "assistant") {
36717
36982
  flush(message.timestamp);
36718
36983
  if (piOmitsTruncatedAssistant(message))
@@ -36753,7 +37018,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
36753
37018
  if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
36754
37019
  continue;
36755
37020
  const parts = message.content.flatMap((value) => {
36756
- const part = object8(value);
37021
+ const part = object10(value);
36757
37022
  return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
36758
37023
  });
36759
37024
  if (!parts.length)
@@ -36781,11 +37046,11 @@ function projectUnmodeledToolResults(messages) {
36781
37046
  return pipe > 0 ? id.slice(0, pipe) : id;
36782
37047
  };
36783
37048
  for (const value of messages) {
36784
- const message = object8(value);
37049
+ const message = object10(value);
36785
37050
  if (message?.role !== "assistant" || !Array.isArray(message.content))
36786
37051
  continue;
36787
37052
  for (const value of message.content) {
36788
- const block = object8(value);
37053
+ const block = object10(value);
36789
37054
  if (block?.type !== "toolCall" || typeof block.id !== "string")
36790
37055
  continue;
36791
37056
  if ([
@@ -36801,7 +37066,7 @@ function projectUnmodeledToolResults(messages) {
36801
37066
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
36802
37067
  const lastResult = new Map;
36803
37068
  messages.forEach((value, index) => {
36804
- const message = object8(value);
37069
+ const message = object10(value);
36805
37070
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
36806
37071
  lastResult.set(pairingId(message.toolCallId), index);
36807
37072
  });
@@ -36832,7 +37097,7 @@ function projectUnmodeledToolResults(messages) {
36832
37097
  };
36833
37098
  for (let index = 0;index < messages.length; index++) {
36834
37099
  const value = messages[index];
36835
- const message = object8(value);
37100
+ const message = object10(value);
36836
37101
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
36837
37102
  continue;
36838
37103
  if (message?.role !== "toolResult")
@@ -36874,7 +37139,7 @@ function projectPiToolResults(messages) {
36874
37139
  held.length = 0;
36875
37140
  };
36876
37141
  for (const value of messages) {
36877
- const message = object8(value);
37142
+ const message = object10(value);
36878
37143
  const role = message?.role;
36879
37144
  if (role === "assistant") {
36880
37145
  close(message?.timestamp);
@@ -36905,7 +37170,7 @@ function projectPiToolResults(messages) {
36905
37170
  function preparePiDispatch(messages, model, omp) {
36906
37171
  let output = messages;
36907
37172
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
36908
- if (object8(source.providerPayload)?.type !== "openaiResponsesHistory")
37173
+ if (object10(source.providerPayload)?.type !== "openaiResponsesHistory")
36909
37174
  return;
36910
37175
  if (output === messages)
36911
37176
  output = messages.slice();
@@ -36918,7 +37183,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
36918
37183
  if (!messages.length || messages.length > MAX_MESSAGES)
36919
37184
  return;
36920
37185
  for (let index = 0;index < messages.length; index++) {
36921
- const source = object8(messages[index]);
37186
+ const source = object10(messages[index]);
36922
37187
  if (source?.role === "user" || source?.role === "compactionSummary")
36923
37188
  prepareUser?.(index, source);
36924
37189
  }
@@ -36934,7 +37199,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
36934
37199
  let valid = true;
36935
37200
  for (let index = 0;index < projectedMessages.length; index++) {
36936
37201
  const message = projectedMessages[index];
36937
- const source = object8(message);
37202
+ const source = object10(message);
36938
37203
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
36939
37204
  continue;
36940
37205
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -36958,10 +37223,17 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
36958
37223
  "azure-openai-responses",
36959
37224
  "openai-codex-responses"
36960
37225
  ].includes(model?.api ?? "") && (source?.role === "user" || source?.role === "developer") && (typeof source.content === "string" ? !source.content.trim() : Array.isArray(source.content) && !source.content.some((value) => {
36961
- const block = object8(value);
37226
+ const block = object10(value);
36962
37227
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
36963
37228
  })))
36964
37229
  continue;
37230
+ if (source?.role === "assistant") {
37231
+ const replay = piAnthropicAssistantReplay(source, model, host);
37232
+ if (replay === "dropped")
37233
+ continue;
37234
+ if (replay === "optional")
37235
+ row.optionalThinking = piAnthropicOptionalThinking(source);
37236
+ }
36965
37237
  row.calls.forEach((id, index) => {
36966
37238
  toolNames.set(id, row.callNames?.[index] ?? "");
36967
37239
  if (model?.api) {
@@ -36988,26 +37260,46 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
36988
37260
  }
36989
37261
  if (!valid)
36990
37262
  return;
37263
+ const baseRows = [...rows];
37264
+ const promotable = new Map;
36991
37265
  const positionedRows = [...byIndex];
36992
37266
  for (let position = positionedRows.length - 1;position >= 0; position--) {
36993
37267
  const [index, row] = positionedRows[position];
36994
- const source = object8(projectedMessages[index]);
37268
+ const source = object10(projectedMessages[index]);
36995
37269
  if (!source)
36996
37270
  return;
36997
37271
  const content = source.content;
36998
37272
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
36999
- const textOnly = Array.isArray(parts) && parts.every((part) => object8(part)?.type === "text" && typeof object8(part)?.text === "string");
37273
+ const textOnly = Array.isArray(parts) && parts.every((part) => object10(part)?.type === "text" && typeof object10(part)?.text === "string");
37274
+ const systemTexts = () => {
37275
+ const texts = parts.map((part) => part.text);
37276
+ return model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
37277
+ };
37000
37278
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
37001
37279
  const previous = rows[position - 1];
37002
37280
  const next = rows[position + 1];
37003
- if (model?.api === "ollama-chat" || model?.api === "anthropic-messages" && object8(model.compat)?.supportsMidConversationSystem === true && textOnly && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
37281
+ const anthropicPromotable = model?.api === "anthropic-messages" && object10(model.compat)?.supportsMidConversationSystem === true && textOnly;
37282
+ if (anthropicPromotable)
37283
+ promotable.set(row, systemTexts());
37284
+ if (model?.api === "ollama-chat" || anthropicPromotable && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
37004
37285
  row.role = "system";
37005
37286
  }
37006
37287
  if (row.role === "system") {
37007
37288
  if (!textOnly)
37008
37289
  return;
37009
- const texts = parts.map((part) => part.text);
37010
- row.systemText = model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
37290
+ row.systemText = systemTexts();
37291
+ }
37292
+ }
37293
+ const modelsContinuePad = piModelsAnthropicContinuePad(model?.api, host);
37294
+ if (modelsContinuePad) {
37295
+ for (let position = rows.length - 1;position > 0; position--) {
37296
+ if (rows[position]?.role === "assistant" && rows[position - 1]?.role === "assistant")
37297
+ rows.splice(position, 0, {
37298
+ role: "user",
37299
+ calls: [],
37300
+ results: [],
37301
+ exactText: ANTHROPIC_CONTINUE_PAD_TEXT
37302
+ });
37011
37303
  }
37012
37304
  }
37013
37305
  const responsesApi = responsesLane(model?.api);
@@ -37085,8 +37377,10 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
37085
37377
  ...responsesMessages ? { responsesMessages } : {},
37086
37378
  ...responsesMessages && unsignedAlternatives ? { responsesAlternatives: [fallbackMessages, coldMessages] } : {},
37087
37379
  ...model?.api ? { api: model.api } : {},
37380
+ ...modelsContinuePad ? { anthropicContinuePad: true } : {},
37381
+ ...modelsContinuePad && baseRows.some((row) => row.optionalThinking) ? { anthropicOptional: { rows: baseRows, promotable } } : {},
37088
37382
  ...model?.api?.startsWith("google-") ? {
37089
- googleFunctionIds: object8(model.compat)?.supportsFunctionPartId === true
37383
+ googleFunctionIds: object10(model.compat)?.supportsFunctionPartId === true
37090
37384
  } : {}
37091
37385
  };
37092
37386
  }
@@ -37098,7 +37392,7 @@ function responsesLane(api) {
37098
37392
  ].includes(api ?? "");
37099
37393
  }
37100
37394
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false) {
37101
- const body = object8(payload);
37395
+ const body = object10(payload);
37102
37396
  if (!body)
37103
37397
  return;
37104
37398
  const google = piGoogleConversation(payload);
@@ -37113,11 +37407,13 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
37113
37407
  return;
37114
37408
  const rows = [];
37115
37409
  for (const value of messages) {
37116
- const message = object8(value);
37410
+ const message = object10(value);
37117
37411
  if (!message)
37118
37412
  return;
37119
37413
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
37120
37414
  continue;
37415
+ if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object10(block)?.type))))
37416
+ continue;
37121
37417
  if (responses && message.type === "reasoning")
37122
37418
  continue;
37123
37419
  if (responses && ["function_call", "custom_tool_call", "computer_call"].includes(String(message.type))) {
@@ -37173,7 +37469,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
37173
37469
  continue;
37174
37470
  }
37175
37471
  if (message.role === "user" && Array.isArray(message.content)) {
37176
- const results = message.content.filter((block) => object8(block)?.type === "tool_result" || bedrock && object8(block)?.toolResult);
37472
+ const results = message.content.filter((block) => object10(block)?.type === "tool_result" || bedrock && object10(block)?.toolResult);
37177
37473
  if (results.length) {
37178
37474
  for (const block of results) {
37179
37475
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -37220,11 +37516,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
37220
37516
  }
37221
37517
  if (Array.isArray(message.tool_calls)) {
37222
37518
  for (const call of message.tool_calls) {
37223
- const source = object8(call);
37519
+ const source = object10(call);
37224
37520
  if (!source)
37225
37521
  return;
37226
37522
  if (source.id === undefined && ollama) {
37227
- const fn = object8(source.function);
37523
+ const fn = object10(source.function);
37228
37524
  if (typeof fn?.name !== "string")
37229
37525
  return;
37230
37526
  row.calls.push("");
@@ -37260,7 +37556,7 @@ function googleStructure(contents, imageProjection = false) {
37260
37556
  return;
37261
37557
  const rows = [];
37262
37558
  for (const value of contents) {
37263
- const message = object8(value);
37559
+ const message = object10(value);
37264
37560
  if (!message || !Array.isArray(message.parts))
37265
37561
  return;
37266
37562
  if (message.role !== "user" && message.role !== "model")
@@ -37275,11 +37571,11 @@ function googleStructure(contents, imageProjection = false) {
37275
37571
  };
37276
37572
  const results = [];
37277
37573
  for (const value of message.parts) {
37278
- const part = object8(value);
37574
+ const part = object10(value);
37279
37575
  if (!part)
37280
37576
  return;
37281
37577
  if (part.functionCall) {
37282
- const call = object8(part.functionCall);
37578
+ const call = object10(part.functionCall);
37283
37579
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
37284
37580
  return;
37285
37581
  row.calls.push(call.id ?? "");
@@ -37287,7 +37583,7 @@ function googleStructure(contents, imageProjection = false) {
37287
37583
  row.callNames.push(call.name);
37288
37584
  }
37289
37585
  if (part.functionResponse) {
37290
- const result = object8(part.functionResponse);
37586
+ const result = object10(part.functionResponse);
37291
37587
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
37292
37588
  return;
37293
37589
  results.push({
@@ -37321,11 +37617,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
37321
37617
  if (responses || googleOrBedrock) {
37322
37618
  if (!Array.isArray(content) || content.length !== 1)
37323
37619
  return false;
37324
- const block = object8(content[0]);
37620
+ const block = object10(content[0]);
37325
37621
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
37326
37622
  }
37327
37623
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
37328
- const block = content.length === 1 ? object8(content[0]) : undefined;
37624
+ const block = content.length === 1 ? object10(content[0]) : undefined;
37329
37625
  return block?.type === "text" && block.text === text;
37330
37626
  }
37331
37627
  return content === text;
@@ -37378,6 +37674,79 @@ function trimPreparedImageRows(rows, budget, drops) {
37378
37674
  flush();
37379
37675
  return projected;
37380
37676
  }
37677
+ function countAnthropicOptionalAlignments(plan, base, wire, compare) {
37678
+ const pad = {
37679
+ role: "user",
37680
+ calls: [],
37681
+ results: [],
37682
+ exactText: ANTHROPIC_CONTINUE_PAD_TEXT
37683
+ };
37684
+ const role = (index) => plan.promotable.has(base[index]) ? "user" : base[index].role;
37685
+ const final = (index, previous, next) => {
37686
+ const row = base[index];
37687
+ const systemText = plan.promotable.get(row);
37688
+ if (!systemText)
37689
+ return row;
37690
+ const promoted = (previous === "user" || previous === "toolResult") && (next === undefined || next === "assistant");
37691
+ return promoted ? { ...row, role: "system", systemText } : { ...row, role: "user", systemText: undefined };
37692
+ };
37693
+ const matches = (expected, at) => at < wire.length && compare(expected, wire[at]) === undefined;
37694
+ const states = new Map;
37695
+ const add = (index, previous, at, count) => {
37696
+ let bucket = states.get(index);
37697
+ if (!bucket) {
37698
+ bucket = new Map;
37699
+ states.set(index, bucket);
37700
+ }
37701
+ const key = `${previous ?? ""}|${at}`;
37702
+ bucket.set(key, Math.min(2, (bucket.get(key) ?? 0) + count));
37703
+ };
37704
+ let complete = 0;
37705
+ const advance = (current, previous, at, count) => {
37706
+ const place = (next) => {
37707
+ if (current < 0)
37708
+ return at;
37709
+ const nextRole = next === undefined ? undefined : role(next);
37710
+ if (!matches(final(current, previous, nextRole), at))
37711
+ return;
37712
+ let after = at + 1;
37713
+ if (role(current) === "assistant" && nextRole === "assistant") {
37714
+ if (!matches(pad, after))
37715
+ return;
37716
+ after++;
37717
+ }
37718
+ return after;
37719
+ };
37720
+ for (let next = current + 1;next < base.length; next++) {
37721
+ const after = place(next);
37722
+ if (after !== undefined)
37723
+ add(next, current < 0 ? undefined : role(current), after, count);
37724
+ if (!base[next].optionalThinking)
37725
+ return;
37726
+ }
37727
+ if (current < 0) {
37728
+ if (wire.length === 0)
37729
+ complete = Math.min(2, complete + count);
37730
+ return;
37731
+ }
37732
+ const after = place(undefined);
37733
+ if (after === wire.length || after === wire.length - 1 && role(current) === "assistant" && isAnthropicContinuePadRow(wire[after]))
37734
+ complete = Math.min(2, complete + count);
37735
+ };
37736
+ advance(-1, undefined, 0, 1);
37737
+ for (let index = 0;index < base.length && complete < 2; index++) {
37738
+ const bucket = states.get(index);
37739
+ if (!bucket)
37740
+ continue;
37741
+ states.delete(index);
37742
+ for (const [key, count] of bucket) {
37743
+ const split = key.lastIndexOf("|");
37744
+ const previous = key.slice(0, split) || undefined;
37745
+ advance(index, previous, Number(key.slice(split + 1)), count);
37746
+ }
37747
+ }
37748
+ return complete;
37749
+ }
37381
37750
  function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
37382
37751
  let stage = "image count";
37383
37752
  let row = 0;
@@ -37393,7 +37762,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
37393
37762
  return "comparison=image count";
37394
37763
  const imageProjection = trimmed > 0;
37395
37764
  stage = "wire rows";
37396
- const body = object8(payload);
37765
+ const body = object10(payload);
37397
37766
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
37398
37767
  const responses = body?.messages === undefined && Array.isArray(body?.input);
37399
37768
  rows = payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection);
@@ -37404,6 +37773,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
37404
37773
  const actual = rows;
37405
37774
  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;
37406
37775
  }
37776
+ const optionalPlan = expectedRows === prepared?.messages ? prepared?.anthropicOptional : undefined;
37407
37777
  if (expectedRows && imageProjection && imageBudget)
37408
37778
  expectedRows = trimPreparedImageRows(expectedRows, imageBudget, trimmed);
37409
37779
  if (!rows || !expectedRows)
@@ -37413,43 +37783,71 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
37413
37783
  stage = "row comparison";
37414
37784
  const google = !!piGoogleConversation(payload);
37415
37785
  const anthropic = google || body.inferenceConfig !== undefined || prepared?.api === "anthropic-messages" || !prepared?.api && body.max_tokens !== undefined && Array.isArray(body.system);
37416
- for (let i = 0;i < Math.min(rows.length, expectedRows.length); i++) {
37417
- row = i;
37418
- const expected = expectedRows[i];
37419
- const actual = rows[i];
37786
+ const compareRow = (expected, actual) => {
37420
37787
  if (actual.role !== expected.role)
37421
- return structureDetail(i, expectedRows, rows, "role");
37788
+ return "role";
37422
37789
  if (expected.systemText !== undefined) {
37423
37790
  const texts = expected.systemText;
37424
37791
  const content = actual.wireContent;
37425
- const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object8(part)?.type === "text" && typeof object8(part)?.text === "string") ? content.map((part) => part.text) : undefined;
37792
+ 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;
37426
37793
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
37427
37794
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
37428
- return structureDetail(i, expectedRows, rows, "content");
37795
+ return "content";
37429
37796
  }
37430
37797
  if (imageProjection && !piMatchesImages(actual.images ?? [], expected.images ?? []))
37431
- return structureDetail(i, expectedRows, rows, "content");
37798
+ return "content";
37432
37799
  if (expected.responseTexts !== undefined && (expected.responseTexts.length !== actual.responseTexts?.length || expected.responseTexts.some((text, index) => text !== actual.responseTexts?.[index])))
37433
- return structureDetail(i, expectedRows, rows, "content");
37800
+ return "content";
37434
37801
  if (expected.exactText !== undefined || expected.exactImages !== undefined) {
37435
37802
  if (actual.wireRole !== "user")
37436
- return structureDetail(i, expectedRows, rows, "role");
37803
+ return "role";
37437
37804
  if (expected.exactText !== undefined && !matchesUserText(actual.wireContent, expected.exactText, prepared?.api, responses, google || body.inferenceConfig !== undefined) || expected.exactImages !== undefined && !piMatchesChatImages(actual.wireContent, expected.exactImages))
37438
- return structureDetail(i, expectedRows, rows, "content");
37805
+ return "content";
37439
37806
  }
37440
37807
  if (actual.calls.length !== expected.calls.length || actual.results.length !== expected.results.length)
37441
- return structureDetail(i, expectedRows, rows, "count");
37808
+ return "count";
37442
37809
  if (actual.timestamp !== undefined && actual.timestamp !== expected.timestamp)
37443
- return structureDetail(i, expectedRows, rows, "timestamp");
37810
+ return "timestamp";
37444
37811
  for (let j = 0;j < actual.calls.length; j++)
37445
37812
  if (google && actual.calls[j] === "" && prepared?.googleFunctionIds !== true || ollama && actual.idlessCalls?.[j] === true ? !expected.callNames?.[j] || actual.callNames?.[j] !== expected.callNames[j] : google && prepared?.googleFunctionIds === false || actual.calls[j] !== (expected.wireCalls ? expected.wireCalls[j] : wireId(expected.calls[j], anthropic, responses)))
37446
- return structureDetail(i, expectedRows, rows, google && actual.calls[j] === "" || ollama && actual.idlessCalls?.[j] === true ? "name" : "call id");
37813
+ return google && actual.calls[j] === "" || ollama && actual.idlessCalls?.[j] === true ? "name" : "call id";
37447
37814
  for (let j = 0;j < actual.results.length; j++)
37448
37815
  if (google && actual.results[j] === "" && prepared?.googleFunctionIds !== true || ollama && actual.idlessResults?.[j] === true ? !expected.resultNames?.[j] || actual.resultNames?.[j] !== expected.resultNames[j] : google && prepared?.googleFunctionIds === false || actual.results[j] !== (expected.wireResults ? expected.wireResults[j] : wireId(expected.results[j], anthropic, responses)))
37449
- return structureDetail(i, expectedRows, rows, google && actual.results[j] === "" || ollama && actual.idlessResults?.[j] === true ? "name" : "result id");
37816
+ return google && actual.results[j] === "" || ollama && actual.idlessResults?.[j] === true ? "name" : "result id";
37817
+ if (expected.optionalThinking && !piExplainsOptionalAssistant(expected.optionalThinking, actual.wireContent))
37818
+ return "content";
37819
+ return;
37820
+ };
37821
+ if (optionalPlan) {
37822
+ stage = "optional assistants";
37823
+ const alignments = countAnthropicOptionalAlignments(optionalPlan, imageProjection && imageBudget ? trimPreparedImageRows(optionalPlan.rows, imageBudget, trimmed) : optionalPlan.rows, rows, compareRow);
37824
+ if (alignments > 1)
37825
+ return structureDetail(0, expectedRows, rows, "alignment");
37826
+ if (alignments === 1) {
37827
+ if (imageProjection && imageBudget)
37828
+ onImageTrim?.({
37829
+ planned: imageBudget.count,
37830
+ actual: actualImages,
37831
+ trimmed
37832
+ });
37833
+ return;
37834
+ }
37835
+ stage = "row comparison";
37450
37836
  }
37451
- if (rows.length !== expectedRows.length)
37452
- return structureDetail(Math.min(rows.length, expectedRows.length), expectedRows, rows, "count");
37837
+ for (let i = 0;i < Math.min(rows.length, expectedRows.length); i++) {
37838
+ row = i;
37839
+ const comparison = compareRow(expectedRows[i], rows[i]);
37840
+ if (comparison)
37841
+ return structureDetail(i, expectedRows, rows, comparison);
37842
+ }
37843
+ if (rows.length !== expectedRows.length) {
37844
+ const lastActual = rows[rows.length - 1];
37845
+ const allowsTrailingPad = prepared?.anthropicContinuePad === true && expectedRows.length > 0 && expectedRows[expectedRows.length - 1]?.role === "assistant" && rows.length === expectedRows.length + 1 && !!lastActual && isAnthropicContinuePadRow(lastActual);
37846
+ if (!allowsTrailingPad)
37847
+ return structureDetail(Math.min(rows.length, expectedRows.length), expectedRows, rows, "count");
37848
+ }
37849
+ if (optionalPlan)
37850
+ return structureDetail(0, expectedRows, rows, "alignment");
37453
37851
  if (imageProjection && imageBudget)
37454
37852
  onImageTrim?.({
37455
37853
  planned: imageBudget.count,
@@ -46064,7 +46462,7 @@ function maybeFireHistorian(args) {
46064
46462
  return;
46065
46463
  }
46066
46464
  const unregister = setRawMessageProvider2(sessionId, provider);
46067
- const resolvePiBoundarySnapshot = (emergencyTailScale) => resolveProtectedTailBoundary(resolveBoundaryContext({
46465
+ const resolvePiBoundarySnapshot = (emergencyTailScale, liftLivePromptFloor = false) => resolveProtectedTailBoundary(resolveBoundaryContext({
46068
46466
  db,
46069
46467
  sessionId,
46070
46468
  mode: "pi-trigger",
@@ -46074,12 +46472,14 @@ function maybeFireHistorian(args) {
46074
46472
  usageSource: "live",
46075
46473
  providerShapeVersion: "pi-folded-v1",
46076
46474
  cacheNamespace: `pi:${sessionId}`,
46077
- emergencyTailScale
46475
+ emergencyTailScale,
46476
+ liftLivePromptFloor
46078
46477
  }));
46079
- const resolveRunnablePiBoundarySnapshot = () => {
46080
- let snapshot = ensureRunnablePiBoundaryForTests(resolvePiBoundarySnapshot());
46478
+ const resolveRunnablePiBoundarySnapshot = (stale) => {
46479
+ const liftLivePromptFloor = stale?.liftLivePromptFloor === true;
46480
+ let snapshot = ensureRunnablePiBoundaryForTests(resolvePiBoundarySnapshot(undefined, liftLivePromptFloor));
46081
46481
  if (!hasRunnableCompartmentWindow(snapshot) && usage.percentage >= historianForceMaterializationPercentage) {
46082
- snapshot = ensureRunnablePiBoundaryForTests(resolvePiBoundarySnapshot(usage.percentage >= 95 ? 0.25 : 0.5));
46482
+ snapshot = ensureRunnablePiBoundaryForTests(resolvePiBoundarySnapshot(usage.percentage >= 95 ? 0.25 : 0.5, liftLivePromptFloor));
46083
46483
  }
46084
46484
  return snapshot;
46085
46485
  };