@cortexkit/pi-magic-context 0.49.15 → 0.49.16

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 (40) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +8 -6
  3. package/dist/{embedding-backfill-7kj16fh9.js → embedding-backfill-c4bdw8pp.js} +10 -8
  4. package/dist/embedding-worker.js +2 -2
  5. package/dist/index-1cvyaw9a.js +58 -0
  6. package/dist/{index-hshd96pt.js → index-4178cbfw.js} +19 -68
  7. package/dist/{index-75ah9413.js → index-44h64qza.js} +3 -3
  8. package/dist/{index-9jvktm7k.js → index-657xh9w4.js} +1 -1
  9. package/dist/{index-7qc73yk5.js → index-afy3dzf9.js} +3 -3
  10. package/dist/{index-1k729e4f.js → index-bxmf4dhr.js} +6 -6
  11. package/dist/{index-j0n09wtp.js → index-dne4ja7a.js} +7 -5
  12. package/dist/{index-a4pk5yv9.js → index-fhyy4ave.js} +14 -14
  13. package/dist/index-ja1c33qa.js +62 -0
  14. package/dist/{index-1mrvw9en.js → index-mx59cve4.js} +1 -1
  15. package/dist/{index-nwbhe6qv.js → index-n3r2d2pr.js} +5 -5
  16. package/dist/{index-7wagp5jp.js → index-p3evwech.js} +3 -3
  17. package/dist/{index-he9s4qsj.js → index-qqxqwqhp.js} +22 -2
  18. package/dist/{index-djxc8w8c.js → index-s1xn8qfw.js} +21 -25
  19. package/dist/{index-bet4sd3e.js → index-tympym62.js} +1 -1
  20. package/dist/{index-ccsscaap.js → index-v8d4vgam.js} +37 -16
  21. package/dist/index-wrr9rp9a.js +16 -0
  22. package/dist/{index-1vw4f2pe.js → index-x3k1530z.js} +5 -7
  23. package/dist/{index-0awvkeb5.js → index-xmzhrht0.js} +10 -61
  24. package/dist/{index-6ex901g3.js → index-y5c73caa.js} +2 -2
  25. package/dist/index.js +183 -130
  26. package/dist/message-fts-rowid-map-mbanfkt1.js +22 -0
  27. package/dist/{message-index-bounded-z4d3x9ty.js → message-index-bounded-xzerjxmp.js} +7 -7
  28. package/dist/{message-index-dw4z9efj.js → message-index-easvmz22.js} +8 -8
  29. package/dist/{message-time-backfill-r2ar1qvk.js → message-time-backfill-3q4kemfc.js} +4 -4
  30. package/dist/migration-worker.js +6 -4
  31. package/dist/{project-embedding-registry-52zwmtbn.js → project-embedding-registry-xwnmqmx8.js} +9 -7
  32. package/dist/raw-ordinal-warmup-worker.js +37 -7
  33. package/dist/{read-session-chunk-0fsgg2k1.js → read-session-chunk-1sb5n7zs.js} +5 -5
  34. package/dist/{read-session-raw-azkqjgzg.js → read-session-raw-jz5e9jz0.js} +1 -1
  35. package/dist/search-archive-3ma5n0wr.js +20 -0
  36. package/dist/{search-ddbz6v60.js → search-x3fa0561.js} +16 -15
  37. package/dist/{storage-tags-3kb5tvgg.js → storage-tags-jtessrec.js} +1 -1
  38. package/dist/subagent-entry.js +19 -17
  39. package/dist/tag-snapshot-worker-pi.js +15 -18
  40. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -248,7 +248,7 @@ import {
248
248
  registerTodoStateLifecycle,
249
249
  syncCtxMemoryToolEnabled,
250
250
  registerMagicContextTools
251
- } from "./index-hshd96pt.js";
251
+ } from "./index-4178cbfw.js";
252
252
  import {
253
253
  canonicalModelIdentity,
254
254
  piModelRefToCanonical,
@@ -265,7 +265,7 @@ import {
265
265
  DEFAULT_HISTORIAN_TIMEOUT_MS,
266
266
  DREAM_TASK_PROMOTION_DEFAULTS,
267
267
  LIVE_RELOAD_CONFIG_PATHS
268
- } from "./index-1k729e4f.js";
268
+ } from "./index-bxmf4dhr.js";
269
269
  import {
270
270
  FAIL_CLOSED_DOCTOR_COMMAND,
271
271
  formatFailClosedBlockingMessage,
@@ -288,7 +288,7 @@ import {
288
288
  openCurrentDatabase,
289
289
  openDatabaseAsync,
290
290
  closeDatabase
291
- } from "./index-ccsscaap.js";
291
+ } from "./index-v8d4vgam.js";
292
292
  import {
293
293
  setHomeProjectPermission,
294
294
  ProjectIdentityError,
@@ -299,7 +299,7 @@ import {
299
299
  resolveProjectIdentityForSession,
300
300
  beginBootQuietPeriod,
301
301
  scheduleAfterBootQuiet
302
- } from "./index-6ex901g3.js";
302
+ } from "./index-y5c73caa.js";
303
303
  import {
304
304
  detectThinkingBindingMismatch,
305
305
  detectLatestTurnThinkingMismatch,
@@ -458,7 +458,7 @@ import {
458
458
  getRawSessionTagKeysThrough2,
459
459
  getLegacyProtectedTailStartOrdinal2,
460
460
  readSessionChunk2
461
- } from "./index-75ah9413.js";
461
+ } from "./index-44h64qza.js";
462
462
  import {
463
463
  UNKNOWN_FIT_RATIO,
464
464
  hasMeasuredDecisionCalibration,
@@ -545,7 +545,7 @@ import {
545
545
  getToolTagNumberByOwner2,
546
546
  getNullOwnerToolTag2,
547
547
  adoptNullOwnerToolTag2
548
- } from "./index-j0n09wtp.js";
548
+ } from "./index-dne4ja7a.js";
549
549
  import {
550
550
  textMentionsRecentCommit,
551
551
  hasMeaningfulUserText2,
@@ -591,7 +591,7 @@ import"./index-399p688g.js";
591
591
  import {
592
592
  runSessionWarmupWorker,
593
593
  RAW_SUMMARY_TEXT_MAX_CHARS2
594
- } from "./index-he9s4qsj.js";
594
+ } from "./index-qqxqwqhp.js";
595
595
  import {
596
596
  piHarnessKindFromExecutable
597
597
  } from "./index-apgwdby5.js";
@@ -617,13 +617,11 @@ import {
617
617
  indexSingleMessage2,
618
618
  indexMessagesAfterOrdinal2,
619
619
  sweepOrphanedOpenCodeMessageIndexes2
620
- } from "./index-a4pk5yv9.js";
620
+ } from "./index-fhyy4ave.js";
621
621
  import {
622
622
  formatSynapseLaneDescriptor
623
623
  } from "./index-6dz2ed1v.js";
624
- import {
625
- sameProjectDirectory
626
- } from "./index-djxc8w8c.js";
624
+ import"./index-s1xn8qfw.js";
627
625
  import {
628
626
  buildCanonicalChunkTextFromFts,
629
627
  buildCompartmentSummaryFallbackText,
@@ -633,7 +631,7 @@ import {
633
631
  replaceCompartmentChunkEmbeddings,
634
632
  deleteChunkEmbedBackoffForSession,
635
633
  chunkWindowSourceKey
636
- } from "./index-7qc73yk5.js";
634
+ } from "./index-afy3dzf9.js";
637
635
  import {
638
636
  recordSessionProjectIdentity,
639
637
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -642,7 +640,7 @@ import {
642
640
  markGitSweepSuccessAndRelease,
643
641
  parkGitSweepNonIndexable,
644
642
  releaseGitSweepLease
645
- } from "./index-1mrvw9en.js";
643
+ } from "./index-mx59cve4.js";
646
644
  import {
647
645
  embedPauseBySession,
648
646
  embedRunStateBySession,
@@ -668,7 +666,7 @@ import {
668
666
  embedSessionCompartmentChunks2,
669
667
  getEmbeddingCoverageStatus2,
670
668
  getAutoEmbeddingSessionCoverage2
671
- } from "./index-nwbhe6qv.js";
669
+ } from "./index-n3r2d2pr.js";
672
670
  import {
673
671
  rememberV1HiddenRun
674
672
  } from "./index-6x556c2q.js";
@@ -683,7 +681,7 @@ import {
683
681
  expandWorkspaceIdentitySetWithAliases,
684
682
  sourceNameForMemory,
685
683
  computeWorkspaceEpochFingerprint
686
- } from "./index-bet4sd3e.js";
684
+ } from "./index-tympym62.js";
687
685
  import {
688
686
  configureContextDatabasePragmas2
689
687
  } from "./index-fapenpch.js";
@@ -733,7 +731,7 @@ import {
733
731
  normalizeVerificationFiles,
734
732
  indexCommitsForProject,
735
733
  embedUnembeddedCommits
736
- } from "./index-0awvkeb5.js";
734
+ } from "./index-xmzhrht0.js";
737
735
  import {
738
736
  setEmbeddingSessionBusy2,
739
737
  isEmbeddingHostBusy2
@@ -764,10 +762,10 @@ import {
764
762
  import {
765
763
  pushNotification2
766
764
  } from "./index-q1yc6bs0.js";
767
- import"./index-9jvktm7k.js";
765
+ import"./index-657xh9w4.js";
768
766
  import {
769
767
  cosineSimilarity
770
- } from "./index-7wagp5jp.js";
768
+ } from "./index-p3evwech.js";
771
769
  import"./index-46q4e104.js";
772
770
  import {
773
771
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -789,8 +787,10 @@ import {
789
787
  drainPiTagSnapshotSession,
790
788
  assertPiTagSnapshotReady,
791
789
  ensurePiTagSnapshotReady
792
- } from "./index-1vw4f2pe.js";
790
+ } from "./index-x3k1530z.js";
793
791
  import"./index-f18ec69t.js";
792
+ import"./index-1cvyaw9a.js";
793
+ import"./index-ja1c33qa.js";
794
794
  import {
795
795
  __toESM
796
796
  } from "./index-22jkk6wg.js";
@@ -800,6 +800,9 @@ import {
800
800
  import {
801
801
  normalizeProtectedToolName
802
802
  } from "./index-674f6qs2.js";
803
+ import {
804
+ sameProjectDirectory
805
+ } from "./index-wrr9rp9a.js";
803
806
  import {
804
807
  logSlowWriteTransaction,
805
808
  WriteTransactionSteps
@@ -3509,7 +3512,7 @@ function startHostStallProfilerSwitch() {
3509
3512
  // package.json
3510
3513
  var package_default = {
3511
3514
  name: "@cortexkit/pi-magic-context",
3512
- version: "0.49.15",
3515
+ version: "0.49.16",
3513
3516
  type: "module",
3514
3517
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3515
3518
  main: "dist/index.js",
@@ -5036,14 +5039,14 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
5036
5039
  });
5037
5040
  throw error;
5038
5041
  }
5039
- async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport) {
5042
+ async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true) {
5040
5043
  const originalBody = { ...args.body };
5041
5044
  const attemptArgs = copyPromptArgs(args, originalBody);
5042
5045
  try {
5043
5046
  await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
5044
5047
  return;
5045
5048
  } catch (error) {
5046
- if (isNonRetryable(error, signal))
5049
+ if (isNonRetryable(error, signal) || !allowModelSuggestions)
5047
5050
  throw error;
5048
5051
  const suggestion = parseModelSuggestion(error);
5049
5052
  if (!suggestion || !originalBody.model) {
@@ -5071,7 +5074,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5071
5074
  const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
5072
5075
  let lastError = null;
5073
5076
  try {
5074
- await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport);
5077
+ await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions);
5075
5078
  return;
5076
5079
  } catch (error) {
5077
5080
  lastError = error;
@@ -5097,7 +5100,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5097
5100
  ...fallback?.qualifier ? { variant: fallback.qualifier } : {}
5098
5101
  });
5099
5102
  try {
5100
- await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport);
5103
+ await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions);
5101
5104
  log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
5102
5105
  return;
5103
5106
  } catch (error) {
@@ -5115,7 +5118,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5115
5118
  }
5116
5119
  async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
5117
5120
  try {
5118
- await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport);
5121
+ await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions);
5119
5122
  } catch (error) {
5120
5123
  throw {
5121
5124
  error,
@@ -6876,6 +6879,7 @@ function buildHistorianRepairPrompt(originalPrompt, previousOutput, validationEr
6876
6879
  "Return a corrected full XML response for the same existing state and new messages.",
6877
6880
  "Do not skip any displayed raw ordinal or displayed raw range, even if the message looks trivial.",
6878
6881
  "Every displayed message range must belong to exactly one compartment unless it is intentionally left in one trailing suffix marked by <unprocessed_from>.",
6882
+ "If every message in the chunk is covered by a compartment, nothing is unprocessed: set `<unprocessed_from>` to the chunk's last message index + 1.",
6879
6883
  "",
6880
6884
  "Previous invalid XML:",
6881
6885
  previousOutput
@@ -9437,6 +9441,7 @@ async function runHistorianPrompt(args) {
9437
9441
  return executor.attempt(opened, request);
9438
9442
  }, { childSessionId: opened.childSessionId }),
9439
9443
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
9444
+ allowModelSuggestions: false,
9440
9445
  fallbackModels: modelOverride ? undefined : fallbackModels,
9441
9446
  callContext: agentId === HISTORIAN_EDITOR_AGENT ? "historian:editor" : "historian"
9442
9447
  });
@@ -9521,7 +9526,7 @@ async function runFallbackHistorianPass(args) {
9521
9526
  const primary = toModelEntry(args.model);
9522
9527
  for (const candidateInput of [
9523
9528
  ...args.fallbackModels ?? [],
9524
- ...args.fallbackModelId ? [{ model: args.fallbackModelId }] : []
9529
+ ...!primary && args.fallbackModelId ? [{ model: args.fallbackModelId }] : []
9525
9530
  ]) {
9526
9531
  const candidate = toModelEntry(candidateInput);
9527
9532
  if (!candidate)
@@ -28585,7 +28590,7 @@ async function runHistorianSubagentWithTransientRetriesGuarded(args) {
28585
28590
  }
28586
28591
  return historianAbortResult(startedAt);
28587
28592
  }
28588
- function buildHistorianFallbackChain(primaryModel, primaryThinkingLevel, fallbackModels, fallbackModelId) {
28593
+ function buildHistorianFallbackChain(primaryModel, primaryThinkingLevel, fallbackModels) {
28589
28594
  const seen = new Set([
28590
28595
  `${primaryModel}\x00${primaryThinkingLevel ?? ""}`
28591
28596
  ]);
@@ -28596,13 +28601,7 @@ function buildHistorianFallbackChain(primaryModel, primaryThinkingLevel, fallbac
28596
28601
  if (!entry.model || seen.has(key))
28597
28602
  continue;
28598
28603
  seen.add(key);
28599
- chain.push({ entry, kind: "configured" });
28600
- }
28601
- if (fallbackModelId) {
28602
- const entry = { model: fallbackModelId };
28603
- const key = `${entry.model}\x00`;
28604
- if (!seen.has(key))
28605
- chain.push({ entry, kind: "session" });
28604
+ chain.push(entry);
28606
28605
  }
28607
28606
  return chain;
28608
28607
  }
@@ -29005,9 +29004,11 @@ ${chunkText}`,
29005
29004
  });
29006
29005
  let validatedPass = await validateHistorianResult(firstResult, sessionId, chunk, priorCompartments, sequenceOffset);
29007
29006
  let validatedDraftText = firstResult.ok ? firstResult.assistantText : null;
29007
+ let fallbackPrompt = prompt;
29008
29008
  if (validatedPass.kind === "validation-failed") {
29009
29009
  sessionLog2(sessionId, `historian: first pass validation failed, retrying with repair prompt: ${validatedPass.error}`);
29010
29010
  const repairPrompt = buildHistorianRepairPrompt(prompt, validatedPass.rawText, validatedPass.error, deps.language);
29011
+ fallbackPrompt = repairPrompt;
29011
29012
  const repairResult = await runHistorianSubagentWithTransientRetries({
29012
29013
  runner,
29013
29014
  sessionId,
@@ -29034,31 +29035,31 @@ ${chunkText}`,
29034
29035
  validatedDraftText = repairResult.assistantText;
29035
29036
  }
29036
29037
  }
29037
- const fallbackChain = buildHistorianFallbackChain(historianModel, thinkingLevel, fallbackModels, fallbackModelId);
29038
+ const fallbackChain = buildHistorianFallbackChain(historianModel, thinkingLevel, fallbackModels);
29038
29039
  if (validatedPass.kind !== "ok" && !(validatedPass.kind === "spawn-failed" && validatedPass.reason === "abort") && fallbackChain.length > 0) {
29039
29040
  for (let i = 0;i < fallbackChain.length; i += 1) {
29040
29041
  const candidate = fallbackChain[i];
29041
- sessionLog2(sessionId, `historian: escalating to ${candidate.kind === "session" ? "session-model last resort" : "configured fallback model"} ${candidate.entry.model}`);
29042
+ sessionLog2(sessionId, `historian: escalating to configured fallback model ${candidate.model}`);
29042
29043
  const fbResult = await runHistorianSubagentWithTransientRetries({
29043
29044
  runner,
29044
29045
  sessionId,
29045
- passLabel: candidate.kind === "session" ? "fallback-session" : "fallback",
29046
+ passLabel: "fallback",
29046
29047
  retryBackoffMs,
29047
29048
  options: {
29048
29049
  agent: HISTORIAN_AGENT_NAME,
29049
29050
  systemPrompt: historianSystemPrompt,
29050
- userMessage: prompt,
29051
- model: candidate.entry.model,
29051
+ userMessage: fallbackPrompt,
29052
+ model: candidate.model,
29052
29053
  timeoutMs: historianTimeoutMs,
29053
29054
  cwd: directory,
29054
29055
  signal,
29055
- thinkingLevel: candidate.entry.qualifier,
29056
+ thinkingLevel: candidate.qualifier,
29056
29057
  temperature,
29057
29058
  maxOutputTokens,
29058
29059
  onProgress: buildProgressLogger("fallback"),
29059
29060
  accountingSessionId: sessionId,
29060
29061
  accountingSubagent: "historian",
29061
- accountingTask: candidate.kind === "session" ? "fallback-session" : "fallback"
29062
+ accountingTask: "fallback"
29062
29063
  }
29063
29064
  });
29064
29065
  const fbPass = await validateHistorianResult(fbResult, sessionId, chunk, priorCompartments, sequenceOffset);
@@ -34352,6 +34353,87 @@ function isOmpUnmanagedCaptureRequest(payload) {
34352
34353
  // src/pi-dispatch-chain.ts
34353
34354
  import { isDeepStrictEqual } from "node:util";
34354
34355
 
34356
+ // src/pi-dispatch-agent-history.ts
34357
+ function object(value) {
34358
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
34359
+ }
34360
+ var DEVELOPER_ORIGIN = Symbol("custom developer history");
34361
+ function piIsDeveloperHistory(message) {
34362
+ return message.role === "developer" || Reflect.get(message, DEVELOPER_ORIGIN) === true;
34363
+ }
34364
+ function piAgentHistory(messages, api) {
34365
+ return messages.flatMap((value) => {
34366
+ const message = object(value);
34367
+ if (!message)
34368
+ return [value];
34369
+ if (message.role === "compactionSummary") {
34370
+ return [
34371
+ {
34372
+ ...message,
34373
+ role: "user",
34374
+ content: message.blocks !== undefined ? [
34375
+ { type: "text", text: message.summary },
34376
+ ...Array.isArray(message.blocks) ? message.blocks : []
34377
+ ] : [
34378
+ { type: "text", text: "Compaction context envelope" },
34379
+ ...Array.isArray(message.images) ? message.images : []
34380
+ ]
34381
+ }
34382
+ ];
34383
+ }
34384
+ if (message.role !== "custom" && message.role !== "hookMessage")
34385
+ return [value];
34386
+ if (typeof message.content !== "string" && !Array.isArray(message.content))
34387
+ return [];
34388
+ const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
34389
+ const userInvoked = message.role === "custom" && message.attribution === "user";
34390
+ if (userInvoked && message.customType === "collab-prompt") {
34391
+ const text = content.filter((part) => object(part)?.type === "text").map((part) => object(part)?.text).join(`
34392
+ `);
34393
+ return [
34394
+ {
34395
+ ...message,
34396
+ role: "user",
34397
+ content: [
34398
+ {
34399
+ type: "text",
34400
+ text: text.length ? "User interjection envelope" : ""
34401
+ },
34402
+ ...content.filter((part) => object(part)?.type === "image")
34403
+ ]
34404
+ }
34405
+ ];
34406
+ }
34407
+ if (userInvoked && message.customType === "skill-prompt")
34408
+ return [{ ...message, role: "user", content }];
34409
+ const images = content.filter((part) => object(part)?.type === "image");
34410
+ const developerRole = api === "ollama-chat" && message.attribution !== "user" ? "developer" : "user";
34411
+ if (!images.length)
34412
+ return [
34413
+ { ...message, role: developerRole, content, [DEVELOPER_ORIGIN]: true }
34414
+ ];
34415
+ const texts = content.filter((part) => object(part)?.type === "text");
34416
+ return [
34417
+ ...texts.length ? [
34418
+ {
34419
+ ...message,
34420
+ role: developerRole,
34421
+ content: texts,
34422
+ [DEVELOPER_ORIGIN]: true
34423
+ }
34424
+ ] : [],
34425
+ {
34426
+ ...message,
34427
+ role: "user",
34428
+ content: [
34429
+ { type: "text", text: `Images attached to ${message.customType}.` },
34430
+ ...images
34431
+ ]
34432
+ }
34433
+ ];
34434
+ });
34435
+ }
34436
+
34355
34437
  // src/pi-dispatch-tool-ids.ts
34356
34438
  function record4(value) {
34357
34439
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
@@ -34423,20 +34505,20 @@ function piToolCallWireId(id, model, source) {
34423
34505
  }
34424
34506
 
34425
34507
  // src/pi-dispatch-chain-tail.ts
34426
- function object(value) {
34508
+ function object2(value) {
34427
34509
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
34428
34510
  }
34429
34511
  var OMITTED_IMAGE = "[image omitted: model does not support vision]";
34430
34512
  function piEncodeChainTail(messages, assistant, responseItems, model) {
34431
- const harmony = object(model.identity)?.class === "gpt-oss";
34513
+ const harmony = object2(model.identity)?.class === "gpt-oss";
34432
34514
  const text = (value) => {
34433
34515
  const wellFormed = value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
34434
34516
  return harmony ? wellFormed.replace(/<\|(start|end|message|channel|constrain|return|call)\|>/g, "<\\|$1\\|>") : wellFormed;
34435
34517
  };
34436
34518
  const supportsImages = model.input?.includes("image") === true;
34437
34519
  const image = (block) => {
34438
- const detail = block.detail === "original" && object(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
34439
- const file = object(block.providerFile);
34520
+ const detail = block.detail === "original" && object2(model.compat)?.supportsImageDetailOriginal !== true ? "auto" : block.detail ?? "auto";
34521
+ const file = object2(block.providerFile);
34440
34522
  if (file?.provider === "openai" && typeof file.id === "string" && file.id)
34441
34523
  return { type: "input_image", detail, file_id: file.id };
34442
34524
  if (typeof block.url !== "string" && (typeof block.mimeType !== "string" || typeof block.data !== "string"))
@@ -34449,9 +34531,21 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
34449
34531
  };
34450
34532
  const items = [];
34451
34533
  for (const value of messages) {
34452
- const message = object(value);
34534
+ let message = object2(value);
34453
34535
  if (!message || message.providerPayload !== undefined)
34454
34536
  return;
34537
+ if (message.role === "custom" || message.role === "hookMessage") {
34538
+ if (typeof message.customType !== "string" || message.attribution === "user")
34539
+ return;
34540
+ const converted = piAgentHistory([message], model.api);
34541
+ const developer = object2(converted[0]);
34542
+ if (converted.length !== 1 || !developer || !piIsDeveloperHistory(developer))
34543
+ return;
34544
+ message = {
34545
+ ...developer,
34546
+ role: model.api === "openai-codex-responses" ? "developer" : "user"
34547
+ };
34548
+ }
34455
34549
  const user = message.role === "user" || message.role === "developer";
34456
34550
  if (!user && message.role !== "toolResult")
34457
34551
  return;
@@ -34462,7 +34556,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
34462
34556
  const images = [];
34463
34557
  const ordered = [];
34464
34558
  for (const value of content) {
34465
- const block = object(value);
34559
+ const block = object2(value);
34466
34560
  if (block?.type === "text" && typeof block.text === "string") {
34467
34561
  texts.push(block.text);
34468
34562
  if (!user || block.text.trim())
@@ -34490,7 +34584,7 @@ function piEncodeChainTail(messages, assistant, responseItems, model) {
34490
34584
  if (typeof message.toolCallId !== "string" || message.providerMetadata !== undefined)
34491
34585
  return;
34492
34586
  const id = piToolCallWireId(message.toolCallId, model, assistant);
34493
- const call = responseItems.map(object).find((item) => item?.call_id === id);
34587
+ const call = responseItems.map(object2).find((item) => item?.call_id === id);
34494
34588
  if (!id || call?.type !== "function_call" && call?.type !== "custom_tool_call")
34495
34589
  return;
34496
34590
  const joined = texts.join(`
@@ -34507,7 +34601,7 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
34507
34601
  }
34508
34602
 
34509
34603
  // src/pi-dispatch-chain.ts
34510
- function object2(value) {
34604
+ function object3(value) {
34511
34605
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
34512
34606
  }
34513
34607
  function piChainCapableApi(api) {
@@ -34521,14 +34615,14 @@ function piPreparedHistory(messages, model) {
34521
34615
  if (!fields)
34522
34616
  return;
34523
34617
  snapshots.push({ id: "", fields });
34524
- const source = object2(message);
34618
+ const source = object3(message);
34525
34619
  responseIds.push(source?.role === "assistant" && typeof source.responseId === "string" && source.responseId.length > 0 ? source.responseId : undefined);
34526
34620
  }
34527
34621
  const prepared = { snapshots, responseIds };
34528
34622
  let index = responseIds.length - 1;
34529
34623
  while (index >= 0 && responseIds[index] === undefined)
34530
34624
  index--;
34531
- const assistant = object2(messages[index]);
34625
+ const assistant = object3(messages[index]);
34532
34626
  const response = piChainResponse(assistant);
34533
34627
  if (model && assistant && response) {
34534
34628
  const delta = piEncodeChainTail(messages.slice(index + 1), assistant, response.responseItems, model);
@@ -34538,7 +34632,7 @@ function piPreparedHistory(messages, model) {
34538
34632
  return prepared;
34539
34633
  }
34540
34634
  function piChainedRequest(payload) {
34541
- const body = object2(payload);
34635
+ const body = object3(payload);
34542
34636
  if (!body || body.previous_response_id === undefined)
34543
34637
  return;
34544
34638
  const id = body.previous_response_id;
@@ -34547,14 +34641,14 @@ function piChainedRequest(payload) {
34547
34641
  return { previousResponseId: id, delta: body.input };
34548
34642
  }
34549
34643
  function piChainResponse(message) {
34550
- const source = object2(message);
34644
+ const source = object3(message);
34551
34645
  if (source?.role !== "assistant")
34552
34646
  return;
34553
34647
  if (source.stopReason !== "stop" && source.stopReason !== "toolUse")
34554
34648
  return;
34555
34649
  if (typeof source.responseId !== "string" || !source.responseId)
34556
34650
  return;
34557
- const payload = object2(source.providerPayload);
34651
+ const payload = object3(source.providerPayload);
34558
34652
  if (payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
34559
34653
  return;
34560
34654
  return {
@@ -34744,74 +34838,6 @@ function piHasManagedSignature(payload, signature) {
34744
34838
  return false;
34745
34839
  }
34746
34840
 
34747
- // src/pi-dispatch-agent-history.ts
34748
- function object3(value) {
34749
- return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
34750
- }
34751
- function piAgentHistory(messages, api) {
34752
- return messages.flatMap((value) => {
34753
- const message = object3(value);
34754
- if (!message)
34755
- return [value];
34756
- if (message.role === "compactionSummary") {
34757
- return [
34758
- {
34759
- ...message,
34760
- role: "user",
34761
- content: message.blocks !== undefined ? [
34762
- { type: "text", text: message.summary },
34763
- ...Array.isArray(message.blocks) ? message.blocks : []
34764
- ] : [
34765
- { type: "text", text: "Compaction context envelope" },
34766
- ...Array.isArray(message.images) ? message.images : []
34767
- ]
34768
- }
34769
- ];
34770
- }
34771
- if (message.role !== "custom" && message.role !== "hookMessage")
34772
- return [value];
34773
- if (typeof message.content !== "string" && !Array.isArray(message.content))
34774
- return [];
34775
- const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
34776
- const userInvoked = message.role === "custom" && message.attribution === "user";
34777
- if (userInvoked && message.customType === "collab-prompt") {
34778
- const text = content.filter((part) => object3(part)?.type === "text").map((part) => object3(part)?.text).join(`
34779
- `);
34780
- return [
34781
- {
34782
- ...message,
34783
- role: "user",
34784
- content: [
34785
- {
34786
- type: "text",
34787
- text: text.length ? "User interjection envelope" : ""
34788
- },
34789
- ...content.filter((part) => object3(part)?.type === "image")
34790
- ]
34791
- }
34792
- ];
34793
- }
34794
- if (userInvoked && message.customType === "skill-prompt")
34795
- return [{ ...message, role: "user", content }];
34796
- const images = content.filter((part) => object3(part)?.type === "image");
34797
- const developerRole = api === "ollama-chat" && message.attribution !== "user" ? "developer" : "user";
34798
- if (!images.length)
34799
- return [{ ...message, role: developerRole, content }];
34800
- const texts = content.filter((part) => object3(part)?.type === "text");
34801
- return [
34802
- ...texts.length ? [{ ...message, role: developerRole, content: texts }] : [],
34803
- {
34804
- ...message,
34805
- role: "user",
34806
- content: [
34807
- { type: "text", text: `Images attached to ${message.customType}.` },
34808
- ...images
34809
- ]
34810
- }
34811
- ];
34812
- });
34813
- }
34814
-
34815
34841
  // src/pi-dispatch-chat-history.ts
34816
34842
  var MAX_EXACT_UNITS = 32 * 1024 * 1024;
34817
34843
  var IMAGE_CAPTION = "Attached image(s) from tool result:";
@@ -35282,7 +35308,7 @@ function messageStructure(value) {
35282
35308
  "bashExecution",
35283
35309
  "pythonExecution"
35284
35310
  ].includes(String(message.role)) ? "user" : message.role;
35285
- if (role !== "user" && role !== "assistant" && role !== "toolResult")
35311
+ if (role !== "user" && role !== "assistant" && role !== "toolResult" && role !== "system")
35286
35312
  return;
35287
35313
  const row = { role, calls: [], results: [] };
35288
35314
  if (ORPHAN_NOTE in message && typeof message.content === "string") {
@@ -35511,6 +35537,28 @@ function buildPiPreparedStructure(messages, model, prepareUser) {
35511
35537
  }
35512
35538
  if (!valid)
35513
35539
  return;
35540
+ const positionedRows = [...byIndex];
35541
+ for (let position = positionedRows.length - 1;position >= 0; position--) {
35542
+ const [index, row] = positionedRows[position];
35543
+ const source = object7(projectedMessages[index]);
35544
+ if (!source)
35545
+ return;
35546
+ const content = source.content;
35547
+ const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
35548
+ const textOnly = Array.isArray(parts) && parts.every((part) => object7(part)?.type === "text" && typeof object7(part)?.text === "string");
35549
+ if (piIsDeveloperHistory(source) && source.attribution !== "user") {
35550
+ const previous = rows[position - 1];
35551
+ const next = rows[position + 1];
35552
+ if (model?.api === "ollama-chat" || model?.api === "anthropic-messages" && object7(model.compat)?.supportsMidConversationSystem === true && textOnly && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
35553
+ row.role = "system";
35554
+ }
35555
+ if (row.role === "system") {
35556
+ if (!textOnly)
35557
+ return;
35558
+ const texts = parts.map((part) => part.text);
35559
+ row.systemText = model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
35560
+ }
35561
+ }
35514
35562
  const responsesApi = responsesLane(model?.api);
35515
35563
  let responsesMessages = responsesApi ? [] : undefined;
35516
35564
  if (responsesMessages) {
@@ -35684,7 +35732,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
35684
35732
  continue;
35685
35733
  }
35686
35734
  }
35687
- const row = messageStructure(ollama && message.role === "system" ? { ...message, role: "user" } : message);
35735
+ const row = messageStructure(message);
35688
35736
  if (!row)
35689
35737
  return;
35690
35738
  row.wireContent = message.content;
@@ -35823,7 +35871,7 @@ function safeRole(row, readable) {
35823
35871
  return "unreadable";
35824
35872
  if (!row)
35825
35873
  return "missing";
35826
- return ["user", "assistant", "toolResult"].includes(row.role) ? row.role : "unknown";
35874
+ return ["user", "assistant", "toolResult", "system"].includes(row.role) ? row.role : "unknown";
35827
35875
  }
35828
35876
  function safeCount(value) {
35829
35877
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : "unreadable";
@@ -35903,6 +35951,14 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
35903
35951
  const actual = rows[i];
35904
35952
  if (actual.role !== expected.role)
35905
35953
  return structureDetail(i, expectedRows, rows, "role");
35954
+ if (expected.systemText !== undefined) {
35955
+ const texts = expected.systemText;
35956
+ const content = actual.wireContent;
35957
+ const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object7(part)?.type === "text" && typeof object7(part)?.text === "string") ? content.map((part) => part.text) : undefined;
35958
+ if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
35959
+ `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
35960
+ return structureDetail(i, expectedRows, rows, "content");
35961
+ }
35906
35962
  if (imageProjection && !piMatchesImages(actual.images ?? [], expected.images ?? []))
35907
35963
  return structureDetail(i, expectedRows, rows, "content");
35908
35964
  if (expected.responseTexts !== undefined && (expected.responseTexts.length !== actual.responseTexts?.length || expected.responseTexts.some((text, index) => text !== actual.responseTexts?.[index])))
@@ -43731,10 +43787,7 @@ function registerPiContextHandler(pi, baseOptions) {
43731
43787
  messages: inputForThinkingFit,
43732
43788
  forceSignedRebuildForFit: true,
43733
43789
  forceMaterialization: true,
43734
- contextUsage: {
43735
- ...pipelineArgs.contextUsage,
43736
- percentage: Math.max(95, pipelineArgs.contextUsage.percentage)
43737
- }
43790
+ contextUsage: pipelineArgs.contextUsage
43738
43791
  }));
43739
43792
  observePipelineResultForTests(sessionId, result);
43740
43793
  fitReclaimedThisPass = true;
@@ -43845,7 +43898,7 @@ function registerPiContextHandler(pi, baseOptions) {
43845
43898
  sessionMeta: freshMeta
43846
43899
  }) : undefined,
43847
43900
  contextUsage: {
43848
- percentage: fitCase === "over-window-proof" ? Math.max(95, usagePercentage) : usagePercentage,
43901
+ percentage: usagePercentage,
43849
43902
  inputTokens: usageInputTokens
43850
43903
  }
43851
43904
  }));