@cortexkit/pi-magic-context 0.49.17 → 0.49.18

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.
package/dist/index.js CHANGED
@@ -249,7 +249,7 @@ import {
249
249
  registerTodoStateLifecycle,
250
250
  syncCtxMemoryToolEnabled,
251
251
  registerMagicContextTools
252
- } from "./index-es03azap.js";
252
+ } from "./index-xxn1tpnv.js";
253
253
  import"./index-4knyh1kt.js";
254
254
  import {
255
255
  canonicalModelIdentity,
@@ -290,7 +290,7 @@ import {
290
290
  openCurrentDatabase,
291
291
  openDatabaseAsync,
292
292
  closeDatabase
293
- } from "./index-469ttgzv.js";
293
+ } from "./index-gp928w10.js";
294
294
  import {
295
295
  pruneMissingProjectIdentities,
296
296
  setHomeProjectPermission,
@@ -415,6 +415,7 @@ import {
415
415
  computeRawRangeFingerprint,
416
416
  invalidateTrueRawTokenCache,
417
417
  stripSystemInjection,
418
+ isFilePart,
418
419
  hasUserAnswerMetadata,
419
420
  DreamTokenBudgetExceeded,
420
421
  TOKEN_BUDGET_FINALIZE_MESSAGE,
@@ -461,7 +462,7 @@ import {
461
462
  getRawSessionTagKeysThrough2,
462
463
  getLegacyProtectedTailStartOrdinal2,
463
464
  readSessionChunk2
464
- } from "./index-5k2mshvq.js";
465
+ } from "./index-r9f4f6s1.js";
465
466
  import {
466
467
  UNKNOWN_FIT_RATIO,
467
468
  hasMeasuredDecisionCalibration,
@@ -548,7 +549,7 @@ import {
548
549
  getToolTagNumberByOwner2,
549
550
  getNullOwnerToolTag2,
550
551
  adoptNullOwnerToolTag2
551
- } from "./index-ej4eak9d.js";
552
+ } from "./index-rhprywn6.js";
552
553
  import {
553
554
  textMentionsRecentCommit,
554
555
  hasMeaningfulUserText2,
@@ -610,7 +611,7 @@ import {
610
611
  indexSingleMessage2,
611
612
  indexMessagesAfterOrdinal2,
612
613
  sweepOrphanedOpenCodeMessageIndexesCooperatively2
613
- } from "./index-8r2t8fv2.js";
614
+ } from "./index-fvjthct0.js";
614
615
  import {
615
616
  resolveOpenCodeDbPath,
616
617
  assertOpenCodeStoreGeneration,
@@ -737,7 +738,7 @@ import {
737
738
  normalizeVerificationFiles,
738
739
  indexCommitsForProject,
739
740
  embedUnembeddedCommits
740
- } from "./index-9j809q6f.js";
741
+ } from "./index-d43hmn31.js";
741
742
  import {
742
743
  setEmbeddingSessionBusy2,
743
744
  isEmbeddingHostBusy2
@@ -794,10 +795,10 @@ import {
794
795
  drainPiTagSnapshotSession,
795
796
  assertPiTagSnapshotReady,
796
797
  ensurePiTagSnapshotReady
797
- } from "./index-dvbjsh98.js";
798
+ } from "./index-4bv5bttd.js";
798
799
  import"./index-f18ec69t.js";
799
800
  import"./index-1cvyaw9a.js";
800
- import"./index-z7kbck29.js";
801
+ import"./index-d21pdr8v.js";
801
802
  import {
802
803
  __toESM
803
804
  } from "./index-22jkk6wg.js";
@@ -3519,7 +3520,7 @@ function startHostStallProfilerSwitch() {
3519
3520
  // package.json
3520
3521
  var package_default = {
3521
3522
  name: "@cortexkit/pi-magic-context",
3522
- version: "0.49.17",
3523
+ version: "0.49.18",
3523
3524
  type: "module",
3524
3525
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3525
3526
  main: "dist/index.js",
@@ -3584,8 +3585,13 @@ var package_default = {
3584
3585
  "@types/bun": "^1.3.10",
3585
3586
  "@types/node": "^22.20.0",
3586
3587
  "omp-coding-agent-1812": "npm:@oh-my-pi/pi-coding-agent@18.12.3",
3588
+ "omp-pi-ai-1889": "npm:@oh-my-pi/pi-ai@18.8.9",
3589
+ "omp-pi-ai-1811": "npm:@oh-my-pi/pi-ai@18.11.3",
3590
+ "omp-pi-ai-1812": "npm:@oh-my-pi/pi-ai@18.12.3",
3587
3591
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3588
3592
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3593
+ "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
3594
+ "pi-ai-130": "npm:@earendil-works/pi-ai@1.3.0",
3589
3595
  "pi-coding-agent-086": "npm:@earendil-works/pi-coding-agent@0.86.0",
3590
3596
  "pi-coding-agent-087": "npm:@earendil-works/pi-coding-agent@0.87.1",
3591
3597
  "pi-coding-agent-130": "npm:@earendil-works/pi-coding-agent@1.3.0",
@@ -24620,6 +24626,12 @@ function applyFlushedStatuses(sessionId, db, targets, preloadedTags) {
24620
24626
  function hasReclaimRide(signals) {
24621
24627
  return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory || signals.subagentExecute === true;
24622
24628
  }
24629
+ function prefixMutationPermitted(gate) {
24630
+ return !gate.signedThinkingHold || gate.firstRender || gate.idleExpiry || gate.emergency;
24631
+ }
24632
+ function reclaimRidePermitted(signals, gate) {
24633
+ return prefixMutationPermitted(gate) && hasReclaimRide(signals);
24634
+ }
24623
24635
  var RECLAIM_RIDE_NAMES = [
24624
24636
  "hardFold",
24625
24637
  "force",
@@ -24858,6 +24870,31 @@ function rearmChannel2AfterMeasuredCollapse(input) {
24858
24870
  return casChannel2NudgeState(input.db, input.sessionId, "delivered", "");
24859
24871
  }
24860
24872
 
24873
+ // ../plugin/src/hooks/magic-context/file-token-coverage.ts
24874
+ function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
24875
+ const filesByMessage = new Map;
24876
+ for (const message of messages) {
24877
+ const count = message.parts.filter(isFilePart).length;
24878
+ if (count > 0 && totals.has(message.id))
24879
+ filesByMessage.set(message.id, count);
24880
+ }
24881
+ if (filesByMessage.size === 0)
24882
+ return totals;
24883
+ const rows = db.prepare(`
24884
+ SELECT o.value AS owner, COUNT(t.id) AS count
24885
+ FROM json_each(?) o LEFT JOIN tags t
24886
+ ON t.session_id = ? AND t.type = 'file'
24887
+ AND t.message_id >= o.value || ':file'
24888
+ AND t.message_id < o.value || ':file;'
24889
+ GROUP BY o.value
24890
+ `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
24891
+ for (const row of rows) {
24892
+ if (row.count < (filesByMessage.get(row.owner) ?? 0))
24893
+ totals.delete(row.owner);
24894
+ }
24895
+ return totals;
24896
+ }
24897
+
24861
24898
  // ../plugin/src/hooks/magic-context/protected-tail-boundary.ts
24862
24899
  function describeBoundaryDiagnostics(snapshot) {
24863
24900
  return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
@@ -25082,7 +25119,7 @@ function resolveProtectedTailBoundary(ctx) {
25082
25119
  const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
25083
25120
  const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
25084
25121
  const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
25085
- const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
25122
+ const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
25086
25123
  const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
25087
25124
  providerShapeVersion: ctx.providerShapeVersion,
25088
25125
  cacheNamespace: ctx.cacheNamespace,
@@ -25325,9 +25362,10 @@ function resolveBoundaryContext(args) {
25325
25362
  migrationFloorActive = seedResult.seeded;
25326
25363
  }
25327
25364
  const calibration = sessionDecisionCalibration(args.db, args.sessionId);
25328
- const storedTokenTotalsForMessages = (messageIds) => {
25365
+ const storedTokenTotalsForMessages = (messageIds, messages = []) => {
25329
25366
  try {
25330
- return getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds).totals;
25367
+ const totals = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds).totals;
25368
+ return omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, totals);
25331
25369
  } catch (error) {
25332
25370
  sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
25333
25371
  return;
@@ -25362,7 +25400,7 @@ function resolveWrapupProtectedTailBoundary(args) {
25362
25400
  const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
25363
25401
  const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
25364
25402
  const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
25365
- const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id)) ?? ctx.storedTokenTotals;
25403
+ const storedTotals = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages) ?? ctx.storedTokenTotals;
25366
25404
  const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
25367
25405
  providerShapeVersion: ctx.providerShapeVersion,
25368
25406
  cacheNamespace: ctx.cacheNamespace,
@@ -25860,8 +25898,9 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
25860
25898
  const canClearReasoning = reasoningProjection?.canClearReasoning ?? modelAcceptsEmptyContent(reasoningProjection?.providerID);
25861
25899
  const projectedPostDropPercentage = estimateProjectedPostDropPercentage(db, sessionId, usage, preloadedActiveTags ?? getActiveTagsBySession2(db, sessionId), keepReasoningTokens, sessionMeta.clearedReasoningThroughTag, canClearReasoning, reasoningProjection?.budgetCutoff, eligiblePendingDropTagIds);
25862
25900
  const relativePostDropTarget = executeThresholdPercentage * POST_DROP_TARGET_RATIO;
25901
+ const ridePermitted = reclaimRide !== undefined && (reclaimRide.permission ? reclaimRidePermitted(reclaimRide, reclaimRide.permission) : hasReclaimRide(reclaimRide));
25863
25902
  const rideLabel = reclaimRide ? reclaimRideLabel(reclaimRide) : "ride=none";
25864
- const dropsCanLand = reclaimRide !== undefined && hasReclaimRide(reclaimRide);
25903
+ const dropsCanLand = ridePermitted;
25865
25904
  const forceMaterializationPercentage = escalationBands(executeThresholdPercentage).forceMaterializationPercentage;
25866
25905
  if (usage.percentage >= forceMaterializationPercentage) {
25867
25906
  if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
@@ -26355,6 +26394,101 @@ function opencodeReasoningBudgetStatus(messages, budget, prefixBound, proseRatio
26355
26394
  };
26356
26395
  }
26357
26396
 
26397
+ // ../plugin/src/hooks/magic-context/signed-thinking-hold.ts
26398
+ var HEAVY_REASONING_TOKENS = 1500;
26399
+ var HEAVY_REASONING_WINDOW_STEPS = 15;
26400
+ var HOLD_CAP_POINTS = 10;
26401
+ var REASONING_TYPES = new Set(["reasoning", "thinking"]);
26402
+ function role2(message) {
26403
+ if (!isRecord(message))
26404
+ return;
26405
+ return isRecord(message.info) ? message.info.role : message.role;
26406
+ }
26407
+ function parts(message) {
26408
+ if (!isRecord(message))
26409
+ return [];
26410
+ if (Array.isArray(message.parts))
26411
+ return message.parts;
26412
+ return Array.isArray(message.content) ? message.content : [];
26413
+ }
26414
+ function recordedReasoningTokens(message) {
26415
+ if (!isRecord(message))
26416
+ return;
26417
+ const info = isRecord(message.info) ? message.info : undefined;
26418
+ const candidates = [];
26419
+ if (info && isRecord(info.tokens))
26420
+ candidates.push(info.tokens.reasoning);
26421
+ if (isRecord(message.usage)) {
26422
+ candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
26423
+ }
26424
+ for (const value of candidates) {
26425
+ if (typeof value === "number" && Number.isFinite(value) && value > 0)
26426
+ return value;
26427
+ }
26428
+ return;
26429
+ }
26430
+ function stepReasoningTokens(message, estimateTextTokens) {
26431
+ let text = "";
26432
+ let opaque = false;
26433
+ for (const part of parts(message)) {
26434
+ if (!isRecord(part))
26435
+ continue;
26436
+ const type = String(part.type ?? part.kind);
26437
+ if (type === "redacted_thinking" || part.redacted === true) {
26438
+ opaque = true;
26439
+ continue;
26440
+ }
26441
+ if (!REASONING_TYPES.has(type))
26442
+ continue;
26443
+ const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
26444
+ if (body.length > 0)
26445
+ text += body;
26446
+ else
26447
+ opaque = true;
26448
+ }
26449
+ if (!text && !opaque)
26450
+ return 0;
26451
+ return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
26452
+ }
26453
+ function decideSignedThinkingHold(args) {
26454
+ const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
26455
+ let heavyStepsBack = null;
26456
+ let heavyStepTokens = 0;
26457
+ const start = latestAssistantTurnStart(args.messages);
26458
+ let stepsBack = 0;
26459
+ for (let index = args.messages.length - 1;index >= start; index--) {
26460
+ const message = args.messages[index];
26461
+ if (role2(message) !== "assistant" || parts(message).length === 0)
26462
+ continue;
26463
+ stepsBack++;
26464
+ if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
26465
+ break;
26466
+ const tokens = stepReasoningTokens(message, args.estimateTextTokens);
26467
+ if (tokens > HEAVY_REASONING_TOKENS) {
26468
+ heavyStepsBack = stepsBack;
26469
+ heavyStepTokens = tokens;
26470
+ break;
26471
+ }
26472
+ }
26473
+ if (heavyStepsBack === null)
26474
+ return {
26475
+ held: false,
26476
+ reason: "no_recent_heavy_reasoning",
26477
+ heavyStepsBack,
26478
+ heavyStepTokens,
26479
+ capPercentage
26480
+ };
26481
+ if (!(args.usagePercentage < capPercentage))
26482
+ return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
26483
+ return {
26484
+ held: true,
26485
+ reason: "heavy_reasoning",
26486
+ heavyStepsBack,
26487
+ heavyStepTokens,
26488
+ capPercentage
26489
+ };
26490
+ }
26491
+
26358
26492
  // ../plugin/src/hooks/magic-context/strict-thinking-prefix.ts
26359
26493
  function servedPrefixMatches(args) {
26360
26494
  const heads = args.messages?.slice(0, 2);
@@ -35135,10 +35269,50 @@ function piHasManagedSignature(payload, signature) {
35135
35269
  return false;
35136
35270
  }
35137
35271
 
35272
+ // src/pi-dispatch-tool-pairing.ts
35273
+ var RESPONSES_APIS = new Set([
35274
+ "openai-responses",
35275
+ "openai-codex-responses",
35276
+ "azure-openai-responses"
35277
+ ]);
35278
+ function object4(value) {
35279
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35280
+ }
35281
+ function piResponsesCallComponent(id) {
35282
+ const pipe = id.indexOf("|");
35283
+ return pipe <= 0 ? id : id.slice(0, pipe);
35284
+ }
35285
+ function piToolCallPairing(messages) {
35286
+ const responsesComponents = new Set;
35287
+ const opaqueCompositeIds = new Set;
35288
+ for (const value of messages) {
35289
+ const message = object4(value);
35290
+ if (message?.role !== "assistant" || !Array.isArray(message.content))
35291
+ continue;
35292
+ const responses = RESPONSES_APIS.has(String(message.api));
35293
+ for (const part of message.content) {
35294
+ const block = object4(part);
35295
+ if (block?.type !== "toolCall" || typeof block.id !== "string")
35296
+ continue;
35297
+ if (responses)
35298
+ responsesComponents.add(piResponsesCallComponent(block.id));
35299
+ else if (block.id.includes("|"))
35300
+ opaqueCompositeIds.add(block.id);
35301
+ }
35302
+ }
35303
+ return (id) => {
35304
+ const pipe = id.indexOf("|");
35305
+ if (pipe <= 0 || opaqueCompositeIds.has(id))
35306
+ return id;
35307
+ const prefix = id.slice(0, pipe);
35308
+ return responsesComponents.has(prefix) ? prefix : id;
35309
+ };
35310
+ }
35311
+
35138
35312
  // src/pi-dispatch-chat-history.ts
35139
35313
  var MAX_EXACT_UNITS = 32 * 1024 * 1024;
35140
35314
  var IMAGE_CAPTION = "Attached image(s) from tool result:";
35141
- function object4(value) {
35315
+ function object5(value) {
35142
35316
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35143
35317
  }
35144
35318
  function omitsAssistant(message, model, compat) {
@@ -35147,7 +35321,7 @@ function omitsAssistant(message, model, compat) {
35147
35321
  let thinking = false;
35148
35322
  let hasTextBlock = false;
35149
35323
  for (const value of message.content) {
35150
- const block = object4(value);
35324
+ const block = object5(value);
35151
35325
  if (!block)
35152
35326
  return false;
35153
35327
  if (block.type === "text") {
@@ -35172,23 +35346,24 @@ function omitsAssistant(message, model, compat) {
35172
35346
  function piChatHistoryPlan(messages, model) {
35173
35347
  if (model?.api !== "openai-completions")
35174
35348
  return;
35175
- const compat = object4(model.compat) ?? {};
35349
+ const compat = object5(model.compat) ?? {};
35350
+ const pairingId = piToolCallPairing(messages);
35176
35351
  const calls = new Set;
35177
35352
  for (const value of messages) {
35178
- const message = object4(value);
35353
+ const message = object5(value);
35179
35354
  if (message?.role !== "assistant" || !Array.isArray(message.content))
35180
35355
  continue;
35181
35356
  for (const value of message.content) {
35182
- const block = object4(value);
35357
+ const block = object5(value);
35183
35358
  if (block?.type === "toolCall" && typeof block.id === "string")
35184
- calls.add(block.id);
35359
+ calls.add(pairingId(block.id));
35185
35360
  }
35186
35361
  }
35187
35362
  const transformed = [];
35188
35363
  let pending = new Set;
35189
35364
  let exactUnits = 0;
35190
35365
  for (let index = 0;index < messages.length; index++) {
35191
- const message = object4(messages[index]);
35366
+ const message = object5(messages[index]);
35192
35367
  if (!message)
35193
35368
  return;
35194
35369
  if ((message.role === "bashExecution" || message.role === "pythonExecution") && message.excludeFromContext === true)
@@ -35200,19 +35375,19 @@ function piChatHistoryPlan(messages, model) {
35200
35375
  continue;
35201
35376
  if (Array.isArray(message.content))
35202
35377
  for (const value of message.content) {
35203
- const block = object4(value);
35378
+ const block = object5(value);
35204
35379
  if (block?.type === "toolCall" && typeof block.id === "string")
35205
- pending.add(block.id);
35380
+ pending.add(pairingId(block.id));
35206
35381
  }
35207
35382
  }
35208
35383
  if (message.role === "toolResult" && typeof message.toolCallId === "string") {
35209
- pending.delete(message.toolCallId);
35210
- if (!calls.has(message.toolCallId)) {
35384
+ pending.delete(pairingId(message.toolCallId));
35385
+ if (!calls.has(pairingId(message.toolCallId))) {
35211
35386
  if (pending.size || typeof message.toolName !== "string" || !Array.isArray(message.content))
35212
35387
  return;
35213
35388
  const parts = [];
35214
35389
  for (const value of message.content) {
35215
- const part = object4(value);
35390
+ const part = object5(value);
35216
35391
  if (part?.type === "text" && typeof part.text === "string" && part.text.trim())
35217
35392
  parts.push(part.text);
35218
35393
  }
@@ -35245,14 +35420,14 @@ ${parts.join(`
35245
35420
  };
35246
35421
  const vision = model.input?.includes("image") === true && compat.stripImageInput !== true;
35247
35422
  for (const step of transformed) {
35248
- const message = step.kind === "source" ? object4(messages[step.index]) : undefined;
35423
+ const message = step.kind === "source" ? object5(messages[step.index]) : undefined;
35249
35424
  if (message?.role !== "toolResult")
35250
35425
  flushImages();
35251
35426
  steps.push(step);
35252
35427
  if (message?.role !== "toolResult" || !vision || !Array.isArray(message.content))
35253
35428
  continue;
35254
35429
  for (const value of message.content) {
35255
- const block = object4(value);
35430
+ const block = object5(value);
35256
35431
  if (block?.type !== "image")
35257
35432
  continue;
35258
35433
  if (compat.requiresAssistantAfterToolResult === true)
@@ -35276,12 +35451,12 @@ ${parts.join(`
35276
35451
  function piMatchesChatImages(content, urls) {
35277
35452
  if (!Array.isArray(content) || content.length !== urls.length + 1)
35278
35453
  return false;
35279
- const caption = object4(content[0]);
35454
+ const caption = object5(content[0]);
35280
35455
  if (caption?.type !== "text" || caption.text !== IMAGE_CAPTION || Object.keys(caption).length !== 2)
35281
35456
  return false;
35282
35457
  for (let i = 0;i < urls.length; i++) {
35283
- const block = object4(content[i + 1]);
35284
- const image = object4(block?.image_url);
35458
+ const block = object5(content[i + 1]);
35459
+ const image = object5(block?.image_url);
35285
35460
  if (block?.type !== "image_url" || Object.keys(block).length !== 2 || !image || Object.keys(image).length !== 1 || image.url !== urls[i])
35286
35461
  return false;
35287
35462
  }
@@ -35289,22 +35464,22 @@ function piMatchesChatImages(content, urls) {
35289
35464
  }
35290
35465
 
35291
35466
  // src/pi-dispatch-image-budget.ts
35292
- function object5(value) {
35467
+ function object6(value) {
35293
35468
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35294
35469
  }
35295
35470
  function piImageBudgetPlan(model) {
35296
- if (!model?.input?.includes("image") || object5(model.compat)?.stripImageInput === true)
35471
+ if (!model?.input?.includes("image") || object6(model.compat)?.stripImageInput === true)
35297
35472
  return;
35298
35473
  return {
35299
35474
  count: 0,
35300
35475
  api: model.api,
35301
35476
  rows: new Map,
35302
- hoistToolImages: model.api?.startsWith("google-") === true && object5(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
35477
+ hoistToolImages: model.api?.startsWith("google-") === true && object6(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
35303
35478
  hoistErrorImages: model.api === "anthropic-messages" || model.api === "bedrock-converse-stream"
35304
35479
  };
35305
35480
  }
35306
35481
  function inputImage(block, api) {
35307
- const file = object5(block.providerFile);
35482
+ const file = object6(block.providerFile);
35308
35483
  if (api === "ollama-chat")
35309
35484
  return { kind: "bytes", value: String(block.data ?? "") };
35310
35485
  if ((api?.endsWith("responses") && file?.provider === "openai" || api === "anthropic-messages" && file?.provider === "anthropic") && typeof file?.id === "string")
@@ -35324,7 +35499,7 @@ function piRecordImages(plan, row, source) {
35324
35499
  return;
35325
35500
  const images = [];
35326
35501
  for (const value of source.content) {
35327
- const block = object5(value);
35502
+ const block = object6(value);
35328
35503
  if (block?.type === "image")
35329
35504
  images.push(inputImage(block, plan.api));
35330
35505
  }
@@ -35350,20 +35525,20 @@ function piWireImages(content, ollamaImages) {
35350
35525
  return [];
35351
35526
  const images = [];
35352
35527
  for (const value of content) {
35353
- const block = object5(value);
35528
+ const block = object6(value);
35354
35529
  if (!block)
35355
35530
  continue;
35356
- const source = object5(block.source);
35357
- const inline = object5(block.inlineData);
35358
- const file = object5(block.fileData);
35359
- const bedrock = object5(block.image);
35531
+ const source = object6(block.source);
35532
+ const inline = object6(block.inlineData);
35533
+ const file = object6(block.fileData);
35534
+ const bedrock = object6(block.image);
35360
35535
  if (block.type === "image_url" || block.type === "input_image") {
35361
35536
  if (typeof block.file_id === "string")
35362
35537
  images.push({ kind: "file", value: block.file_id });
35363
35538
  else
35364
35539
  images.push({
35365
35540
  kind: "url",
35366
- value: String(typeof block.image_url === "string" ? block.image_url : object5(block.image_url)?.url)
35541
+ value: String(typeof block.image_url === "string" ? block.image_url : object6(block.image_url)?.url)
35367
35542
  });
35368
35543
  } else if (block.type === "image") {
35369
35544
  if (source?.type === "file")
@@ -35387,7 +35562,7 @@ function piWireImages(content, ollamaImages) {
35387
35562
  else if (bedrock)
35388
35563
  images.push({
35389
35564
  kind: "data",
35390
- value: String(object5(bedrock.source)?.bytes),
35565
+ value: String(object6(bedrock.source)?.bytes),
35391
35566
  mime: `image/${bedrock.format}`
35392
35567
  });
35393
35568
  }
@@ -35409,11 +35584,11 @@ function piMatchesImages(actual, expected) {
35409
35584
  return true;
35410
35585
  }
35411
35586
  function piWireImageCount(payload) {
35412
- const body = object5(payload);
35587
+ const body = object6(payload);
35413
35588
  const visit = (value) => {
35414
35589
  if (Array.isArray(value))
35415
35590
  return value.reduce((n, item) => n + visit(item), 0);
35416
- const block = object5(value);
35591
+ const block = object6(value);
35417
35592
  if (!block)
35418
35593
  return 0;
35419
35594
  if (["image", "image_url", "input_image"].includes(String(block.type)) || block.inlineData || block.fileData || block.image)
@@ -35427,12 +35602,12 @@ function piWireImageCount(payload) {
35427
35602
  block.response
35428
35603
  ].reduce((n, item) => n + visit(item), Array.isArray(block.images) ? block.images.length : 0);
35429
35604
  };
35430
- return visit(body?.messages ?? body?.input ?? body?.contents ?? object5(body?.request)?.contents);
35605
+ return visit(body?.messages ?? body?.input ?? body?.contents ?? object6(body?.request)?.contents);
35431
35606
  }
35432
35607
 
35433
35608
  // src/pi-dispatch-responses-history.ts
35434
35609
  var MAX_TEXT_UNITS = 32 * 1024 * 1024;
35435
- function object6(value) {
35610
+ function object7(value) {
35436
35611
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35437
35612
  }
35438
35613
  function wellFormed(text) {
@@ -35447,7 +35622,7 @@ function textIdentity2(text, phase) {
35447
35622
  function signaturePhase(block) {
35448
35623
  try {
35449
35624
  if (typeof block.textSignature === "string") {
35450
- const signature = object6(JSON.parse(block.textSignature));
35625
+ const signature = object7(JSON.parse(block.textSignature));
35451
35626
  if (signature?.v === 1 && typeof signature.id === "string")
35452
35627
  return signature.phase;
35453
35628
  }
@@ -35467,17 +35642,17 @@ ${wellFormed(text)}
35467
35642
  return;
35468
35643
  }
35469
35644
  function piResponsesAssistantTexts(value, model) {
35470
- const message = object6(value);
35645
+ const message = object7(value);
35471
35646
  if (!message || !Array.isArray(message.content))
35472
35647
  return;
35473
- if (["length", "error", "aborted"].includes(String(message.stopReason)) && !message.content.some((value) => ["text", "toolCall"].includes(String(object6(value)?.type))))
35648
+ if (["length", "error", "aborted"].includes(String(message.stopReason)) && !message.content.some((value) => ["text", "toolCall"].includes(String(object7(value)?.type))))
35474
35649
  return [];
35475
35650
  const texts = [];
35476
35651
  const blocks = [];
35477
35652
  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;
35478
35653
  let units = 0;
35479
35654
  for (const value of message.content) {
35480
- const block = object6(value);
35655
+ const block = object7(value);
35481
35656
  if (block?.type === "toolCall")
35482
35657
  continue;
35483
35658
  if (block?.type === "thinking") {
@@ -35487,7 +35662,7 @@ function piResponsesAssistantTexts(value, model) {
35487
35662
  return;
35488
35663
  if (!block.thinking.trim())
35489
35664
  continue;
35490
- const compat = object6(model.compat);
35665
+ const compat = object7(model.compat);
35491
35666
  if (block.summary === false && (compat?.requiresReasoningContentForToolCalls === true || compat?.requiresReasoningContentForAllAssistantTurns === true))
35492
35667
  return;
35493
35668
  const text = demotedThinking(block.thinking, model);
@@ -35507,14 +35682,14 @@ function piResponsesAssistantTexts(value, model) {
35507
35682
  texts.push(textIdentity2(wellFormed(block.text), sameModel ? signaturePhase(block) : undefined));
35508
35683
  blocks.push(block);
35509
35684
  }
35510
- const payload = object6(message.providerPayload);
35685
+ const payload = object7(message.providerPayload);
35511
35686
  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))
35512
35687
  return texts;
35513
35688
  const replay = [];
35514
35689
  let bound = 0;
35515
35690
  let output = false;
35516
35691
  for (const value of payload.items) {
35517
- const item = object6(value);
35692
+ const item = object7(value);
35518
35693
  if (item?.type === "reasoning")
35519
35694
  continue;
35520
35695
  if (item?.type === "function_call" || item?.type === "custom_tool_call") {
@@ -35525,14 +35700,14 @@ function piResponsesAssistantTexts(value, model) {
35525
35700
  return texts;
35526
35701
  const itemTexts = [];
35527
35702
  for (const value of item.content) {
35528
- const part = object6(value);
35703
+ const part = object7(value);
35529
35704
  const block = blocks[bound];
35530
35705
  if (!block || part?.type !== "output_text" || typeof part.text !== "string")
35531
35706
  return texts;
35532
35707
  let signature;
35533
35708
  try {
35534
35709
  if (typeof block.textSignature === "string")
35535
- signature = object6(JSON.parse(block.textSignature));
35710
+ signature = object7(JSON.parse(block.textSignature));
35536
35711
  } catch {
35537
35712
  return texts;
35538
35713
  }
@@ -35559,7 +35734,7 @@ function piResponsesWireTexts(value, phase) {
35559
35734
  const texts = [];
35560
35735
  let units = 0;
35561
35736
  for (const partValue of value) {
35562
- const part = object6(partValue);
35737
+ const part = object7(partValue);
35563
35738
  if (part?.type !== "output_text" || typeof part.text !== "string")
35564
35739
  return;
35565
35740
  units += part.text.length;
@@ -35589,11 +35764,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
35589
35764
  "devin-agent",
35590
35765
  "apple-foundation-models"
35591
35766
  ]);
35592
- function object7(value) {
35767
+ function object8(value) {
35593
35768
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
35594
35769
  }
35595
35770
  function messageStructure(value) {
35596
- const message = object7(value);
35771
+ const message = object8(value);
35597
35772
  if (!message)
35598
35773
  return;
35599
35774
  const role = [
@@ -35622,7 +35797,7 @@ function messageStructure(value) {
35622
35797
  }
35623
35798
  if (role === "assistant" && Array.isArray(message.content)) {
35624
35799
  for (const value of message.content) {
35625
- const block = object7(value);
35800
+ const block = object8(value);
35626
35801
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
35627
35802
  continue;
35628
35803
  if (typeof block.id !== "string")
@@ -35634,41 +35809,249 @@ function messageStructure(value) {
35634
35809
  }
35635
35810
  return row;
35636
35811
  }
35637
- function projectMissingToolResults(messages, api) {
35638
- const projectOrphans = TRANSFORM_MESSAGES_APIS.has(api ?? "");
35812
+ function windowCalls(message) {
35813
+ if (!Array.isArray(message.content))
35814
+ return [];
35815
+ return message.content.flatMap((value) => {
35816
+ const block = object8(value);
35817
+ return block?.type === "toolCall" && typeof block.id === "string" ? [
35818
+ {
35819
+ id: block.id,
35820
+ name: typeof block.name === "string" ? block.name : ""
35821
+ }
35822
+ ] : [];
35823
+ });
35824
+ }
35825
+ function duplicateSuffix(model) {
35826
+ const compat = object8(model?.compat);
35827
+ if (model?.api === "openai-completions") {
35828
+ if (compat?.requiresMistralToolIds === true)
35829
+ return { prefix: "dup", max: 9 };
35830
+ if (compat?.usesOpenAIToolCallIdLimit === true)
35831
+ return { prefix: "_dup", max: 40 };
35832
+ }
35833
+ if (model?.api === "devin-agent")
35834
+ return { prefix: "_dup", max: 40 };
35835
+ return { prefix: "_dup", max: 64 };
35836
+ }
35837
+ function appendDuplicateSuffix(id, suffix, max) {
35838
+ const segment = (part) => part.length + suffix.length <= max ? `${part}${suffix}` : `${part.slice(0, Math.max(0, max - suffix.length))}${suffix}`;
35839
+ return id.includes("|") ? id.split("|").map(segment).join("|") : segment(id);
35840
+ }
35841
+ function projectMissingToolResults(messages, model, host = "omp") {
35842
+ const input = messages.filter((value) => {
35843
+ const message = object8(value);
35844
+ return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
35845
+ });
35846
+ if (host === "pi")
35847
+ return projectPiToolResults(input);
35848
+ const api = model?.api;
35849
+ if (!TRANSFORM_MESSAGES_APIS.has(api ?? ""))
35850
+ return projectUnmodeledToolResults(messages);
35851
+ const pairingId = piToolCallPairing(input);
35852
+ const { prefix, max } = duplicateSuffix(model);
35853
+ const seen = new Map;
35854
+ const renames = new Map;
35855
+ const realResults = new Map;
35856
+ const validToolUseIds = new Set;
35857
+ const deduplicated = input.map((value, index) => {
35858
+ const message = object8(value);
35859
+ if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
35860
+ let key = pairingId(message.toolCallId);
35861
+ let output = value;
35862
+ const queue = renames.get(key);
35863
+ if (queue?.length) {
35864
+ const replacement = queue.shift();
35865
+ if (!queue.length)
35866
+ renames.delete(key);
35867
+ if (replacement !== undefined) {
35868
+ output = { ...message, toolCallId: replacement };
35869
+ key = pairingId(replacement);
35870
+ }
35871
+ }
35872
+ const entry = { index, message: output, consumed: false };
35873
+ const entries = realResults.get(key);
35874
+ if (entries)
35875
+ entries.push(entry);
35876
+ else
35877
+ realResults.set(key, [entry]);
35878
+ return output;
35879
+ }
35880
+ if (message?.role !== "assistant" || !Array.isArray(message.content))
35881
+ return value;
35882
+ const touched = new Set;
35883
+ let changed = false;
35884
+ const content = message.content.map((part) => {
35885
+ const block = object8(part);
35886
+ if (block?.type !== "toolCall" || typeof block.id !== "string")
35887
+ return part;
35888
+ const key = pairingId(block.id);
35889
+ if (!touched.has(key)) {
35890
+ touched.add(key);
35891
+ renames.delete(key);
35892
+ }
35893
+ const count = seen.get(key) ?? 0;
35894
+ const queue = renames.get(key) ?? [];
35895
+ renames.set(key, queue);
35896
+ if (count === 0) {
35897
+ seen.set(key, 1);
35898
+ queue.push(undefined);
35899
+ return part;
35900
+ }
35901
+ let suffix = count;
35902
+ let replacement = appendDuplicateSuffix(block.id, `${prefix}${suffix}`, max);
35903
+ while (seen.has(pairingId(replacement))) {
35904
+ suffix++;
35905
+ replacement = appendDuplicateSuffix(block.id, `${prefix}${suffix}`, max);
35906
+ }
35907
+ seen.set(key, suffix + 1);
35908
+ seen.set(pairingId(replacement), 1);
35909
+ queue.push(replacement);
35910
+ changed = true;
35911
+ return { ...block, id: replacement };
35912
+ });
35913
+ for (const call of windowCalls({ content }))
35914
+ validToolUseIds.add(pairingId(call.id));
35915
+ return changed ? { ...message, content } : value;
35916
+ });
35917
+ const takeRealResult = (id, afterIndex) => {
35918
+ for (const entry of realResults.get(pairingId(id)) ?? []) {
35919
+ if (entry.consumed || entry.index <= afterIndex)
35920
+ continue;
35921
+ entry.consumed = true;
35922
+ return entry.message;
35923
+ }
35924
+ return;
35925
+ };
35926
+ const projected = [];
35927
+ const answered = new Set;
35928
+ let pending = [];
35929
+ let pendingStart = -1;
35930
+ let aborted = new Map;
35931
+ let abortedTimestamp;
35932
+ let abortedStart = -1;
35933
+ const stub = (call, text, timestamp) => ({
35934
+ role: "toolResult",
35935
+ toolCallId: call.id,
35936
+ toolName: call.name,
35937
+ content: [{ type: "text", text }],
35938
+ isError: true,
35939
+ timestamp
35940
+ });
35941
+ const flush = (boundaryTimestamp) => {
35942
+ for (const call of pending) {
35943
+ const key = pairingId(call.id);
35944
+ if (answered.has(key))
35945
+ continue;
35946
+ projected.push(takeRealResult(call.id, pendingStart) ?? stub(call, "No result provided", boundaryTimestamp));
35947
+ answered.add(key);
35948
+ }
35949
+ pending = [];
35950
+ if (abortedTimestamp === undefined)
35951
+ return;
35952
+ for (const call of aborted.values()) {
35953
+ const key = pairingId(call.id);
35954
+ if (answered.has(key))
35955
+ continue;
35956
+ projected.push(takeRealResult(call.id, abortedStart) ?? stub(call, "aborted", abortedTimestamp));
35957
+ answered.add(key);
35958
+ }
35959
+ aborted = new Map;
35960
+ abortedTimestamp = undefined;
35961
+ };
35962
+ for (let index = 0;index < deduplicated.length; index++) {
35963
+ const value = deduplicated[index];
35964
+ const message = object8(value);
35965
+ if (message?.role === "assistant") {
35966
+ flush(message.timestamp);
35967
+ projected.push(value);
35968
+ const calls = windowCalls(message);
35969
+ const truncated = ["length", "error", "aborted"].includes(String(message.stopReason));
35970
+ if (truncated && Array.isArray(message.content) && !message.content.some((part) => ["toolCall", "text"].includes(String(object8(part)?.type))))
35971
+ continue;
35972
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
35973
+ aborted = new Map(calls.map((call) => [pairingId(call.id), call]));
35974
+ abortedTimestamp = message.timestamp;
35975
+ abortedStart = index;
35976
+ } else if (calls.length) {
35977
+ pending = calls;
35978
+ pendingStart = index;
35979
+ }
35980
+ continue;
35981
+ }
35982
+ if (message?.role !== "toolResult" || typeof message.toolCallId !== "string") {
35983
+ if (message?.role !== "toolResult")
35984
+ flush(message?.timestamp);
35985
+ projected.push(value);
35986
+ continue;
35987
+ }
35988
+ const key = pairingId(message.toolCallId);
35989
+ if (answered.has(key))
35990
+ continue;
35991
+ if (aborted.has(key) || pending.some((call) => pairingId(call.id) === key)) {
35992
+ aborted.delete(key);
35993
+ answered.add(key);
35994
+ projected.push(value);
35995
+ continue;
35996
+ }
35997
+ if (validToolUseIds.has(key))
35998
+ continue;
35999
+ if (typeof message.toolName !== "string" || !Array.isArray(message.content)) {
36000
+ projected.push(value);
36001
+ continue;
36002
+ }
36003
+ if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
36004
+ continue;
36005
+ const parts = message.content.flatMap((value) => {
36006
+ const part = object8(value);
36007
+ return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
36008
+ });
36009
+ if (!parts.length)
36010
+ continue;
36011
+ const error = message.isError ? ' is-error="true"' : "";
36012
+ const note = `<stale-tool-result tool="${message.toolName}" id="${message.toolCallId}"${error}>
36013
+ ${parts.join(`
36014
+ `)}
36015
+ </stale-tool-result>`;
36016
+ projected.push({
36017
+ role: "user",
36018
+ content: api === "ollama-chat" ? note : new TextDecoder().decode(new TextEncoder().encode(note)),
36019
+ timestamp: message.timestamp,
36020
+ [ORPHAN_NOTE]: true
36021
+ });
36022
+ }
36023
+ flush();
36024
+ return projected;
36025
+ }
36026
+ function projectUnmodeledToolResults(messages) {
35639
36027
  const responsesComponents = new Set;
35640
36028
  const opaqueIds = new Set;
35641
- const validToolUseIds = projectOrphans ? new Set : undefined;
35642
36029
  const component = (id) => {
35643
36030
  const pipe = id.indexOf("|");
35644
36031
  return pipe > 0 ? id.slice(0, pipe) : id;
35645
36032
  };
35646
36033
  for (const value of messages) {
35647
- const message = object7(value);
36034
+ const message = object8(value);
35648
36035
  if (message?.role !== "assistant" || !Array.isArray(message.content))
35649
36036
  continue;
35650
36037
  for (const value of message.content) {
35651
- const block = object7(value);
36038
+ const block = object8(value);
35652
36039
  if (block?.type !== "toolCall" || typeof block.id !== "string")
35653
36040
  continue;
35654
36041
  if ([
35655
36042
  "openai-responses",
35656
36043
  "azure-openai-responses",
35657
36044
  "openai-codex-responses"
35658
- ].includes(String(message.api))) {
36045
+ ].includes(String(message.api)))
35659
36046
  responsesComponents.add(component(block.id));
35660
- validToolUseIds?.add(component(block.id));
35661
- } else {
35662
- if (block.id.includes("|"))
35663
- opaqueIds.add(block.id);
35664
- validToolUseIds?.add(block.id);
35665
- }
36047
+ else if (block.id.includes("|"))
36048
+ opaqueIds.add(block.id);
35666
36049
  }
35667
36050
  }
35668
36051
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
35669
36052
  const lastResult = new Map;
35670
36053
  messages.forEach((value, index) => {
35671
- const message = object7(value);
36054
+ const message = object8(value);
35672
36055
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
35673
36056
  lastResult.set(pairingId(message.toolCallId), index);
35674
36057
  });
@@ -35699,35 +36082,13 @@ function projectMissingToolResults(messages, api) {
35699
36082
  };
35700
36083
  for (let index = 0;index < messages.length; index++) {
35701
36084
  const value = messages[index];
35702
- const message = object7(value);
36085
+ const message = object8(value);
35703
36086
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
35704
36087
  continue;
35705
36088
  if (message?.role !== "toolResult")
35706
36089
  flush(message?.timestamp);
35707
36090
  else if (typeof message.toolCallId === "string" && pending.some((call) => pairingId(call.id) === pairingId(String(message.toolCallId))))
35708
36091
  resolved.add(pairingId(message.toolCallId));
35709
- else if (validToolUseIds && message?.role === "toolResult" && typeof message.toolCallId === "string" && typeof message.toolName === "string" && !validToolUseIds.has(pairingId(message.toolCallId)) && Array.isArray(message.content)) {
35710
- if (pending.some((call) => !resolved.has(pairingId(call.id))))
35711
- continue;
35712
- const parts = message.content.flatMap((value) => {
35713
- const part = object7(value);
35714
- return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
35715
- });
35716
- if (parts.length) {
35717
- const error = message.isError ? ' is-error="true"' : "";
35718
- const note = `<stale-tool-result tool="${message.toolName}" id="${message.toolCallId}"${error}>
35719
- ${parts.join(`
35720
- `)}
35721
- </stale-tool-result>`;
35722
- projected.push({
35723
- role: "user",
35724
- content: api === "ollama-chat" ? note : new TextDecoder().decode(new TextEncoder().encode(note)),
35725
- timestamp: message.timestamp,
35726
- [ORPHAN_NOTE]: true
35727
- });
35728
- }
35729
- continue;
35730
- }
35731
36092
  projected.push(value);
35732
36093
  if (message?.role !== "assistant" || !Array.isArray(message.content))
35733
36094
  continue;
@@ -35736,39 +36097,82 @@ ${parts.join(`
35736
36097
  timestamp = message.timestamp;
35737
36098
  if (aborted && typeof timestamp !== "number")
35738
36099
  continue;
35739
- for (const value of message.content) {
35740
- const block = object7(value);
35741
- if (block?.type === "toolCall" && typeof block.id === "string")
35742
- pending.push({
35743
- id: block.id,
35744
- name: typeof block.name === "string" ? block.name : ""
35745
- });
35746
- }
36100
+ pending.push(...windowCalls(message));
35747
36101
  }
35748
36102
  flush();
35749
36103
  return projected;
35750
36104
  }
36105
+ function projectPiToolResults(messages) {
36106
+ const projected = [];
36107
+ let pending = [];
36108
+ let answered = new Set;
36109
+ const held = [];
36110
+ const close = (timestamp) => {
36111
+ for (const call of pending)
36112
+ if (!answered.has(call.id))
36113
+ projected.push({
36114
+ role: "toolResult",
36115
+ toolCallId: call.id,
36116
+ toolName: call.name,
36117
+ content: [{ type: "text", text: "No result provided" }],
36118
+ isError: true,
36119
+ timestamp
36120
+ });
36121
+ pending = [];
36122
+ answered = new Set;
36123
+ projected.push(...held);
36124
+ held.length = 0;
36125
+ };
36126
+ for (const value of messages) {
36127
+ const message = object8(value);
36128
+ const role = message?.role;
36129
+ if (role === "assistant") {
36130
+ close(message?.timestamp);
36131
+ if (message?.stopReason === "error" || message?.stopReason === "aborted")
36132
+ continue;
36133
+ const calls = message ? windowCalls(message) : [];
36134
+ if (calls.length)
36135
+ pending = calls;
36136
+ } else if (role === "toolResult") {
36137
+ if (typeof message?.toolCallId === "string")
36138
+ answered.add(message.toolCallId);
36139
+ } else if (role === "system" && pending.length) {
36140
+ held.push(value);
36141
+ continue;
36142
+ } else if ([
36143
+ "user",
36144
+ "custom",
36145
+ "bashExecution",
36146
+ "branchSummary",
36147
+ "compactionSummary"
36148
+ ].includes(String(role)))
36149
+ close(message?.timestamp);
36150
+ projected.push(value);
36151
+ }
36152
+ close();
36153
+ return projected;
36154
+ }
35751
36155
  function preparePiDispatch(messages, model, omp) {
35752
36156
  let output = messages;
35753
36157
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
35754
- if (object7(source.providerPayload)?.type !== "openaiResponsesHistory")
36158
+ if (object8(source.providerPayload)?.type !== "openaiResponsesHistory")
35755
36159
  return;
35756
36160
  if (output === messages)
35757
36161
  output = messages.slice();
35758
36162
  const { providerPayload: _payload, ...copy } = source;
35759
36163
  output[index] = copy;
35760
- } : undefined);
36164
+ } : undefined, omp ? "omp" : "pi");
35761
36165
  return { messages: output, structure };
35762
36166
  }
35763
- function buildPiPreparedStructure(messages, model, prepareUser) {
36167
+ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
35764
36168
  if (!messages.length || messages.length > MAX_MESSAGES)
35765
36169
  return;
35766
36170
  for (let index = 0;index < messages.length; index++) {
35767
- const source = object7(messages[index]);
36171
+ const source = object8(messages[index]);
35768
36172
  if (source?.role === "user" || source?.role === "compactionSummary")
35769
36173
  prepareUser?.(index, source);
35770
36174
  }
35771
- const projectedMessages = projectMissingToolResults(model?.api ? piAgentHistory(messages, model.api) : messages, model?.api);
36175
+ const projectedMessages = projectMissingToolResults(model?.api && host === "omp" ? piAgentHistory(messages, model.api) : messages, model, host);
35772
36176
  if (projectedMessages.length > MAX_MESSAGES)
35773
36177
  return;
35774
36178
  const rows = [];
@@ -35780,7 +36184,7 @@ function buildPiPreparedStructure(messages, model, prepareUser) {
35780
36184
  let valid = true;
35781
36185
  for (let index = 0;index < projectedMessages.length; index++) {
35782
36186
  const message = projectedMessages[index];
35783
- const source = object7(message);
36187
+ const source = object8(message);
35784
36188
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
35785
36189
  continue;
35786
36190
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -35804,7 +36208,7 @@ function buildPiPreparedStructure(messages, model, prepareUser) {
35804
36208
  "azure-openai-responses",
35805
36209
  "openai-codex-responses"
35806
36210
  ].includes(model?.api ?? "") && (source?.role === "user" || source?.role === "developer") && (typeof source.content === "string" ? !source.content.trim() : Array.isArray(source.content) && !source.content.some((value) => {
35807
- const block = object7(value);
36211
+ const block = object8(value);
35808
36212
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
35809
36213
  })))
35810
36214
  continue;
@@ -35837,16 +36241,16 @@ function buildPiPreparedStructure(messages, model, prepareUser) {
35837
36241
  const positionedRows = [...byIndex];
35838
36242
  for (let position = positionedRows.length - 1;position >= 0; position--) {
35839
36243
  const [index, row] = positionedRows[position];
35840
- const source = object7(projectedMessages[index]);
36244
+ const source = object8(projectedMessages[index]);
35841
36245
  if (!source)
35842
36246
  return;
35843
36247
  const content = source.content;
35844
36248
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
35845
- const textOnly = Array.isArray(parts) && parts.every((part) => object7(part)?.type === "text" && typeof object7(part)?.text === "string");
36249
+ const textOnly = Array.isArray(parts) && parts.every((part) => object8(part)?.type === "text" && typeof object8(part)?.text === "string");
35846
36250
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
35847
36251
  const previous = rows[position - 1];
35848
36252
  const next = rows[position + 1];
35849
- 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"))
36253
+ 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"))
35850
36254
  row.role = "system";
35851
36255
  }
35852
36256
  if (row.role === "system") {
@@ -35919,7 +36323,7 @@ function buildPiPreparedStructure(messages, model, prepareUser) {
35919
36323
  ...responsesMessages ? { responsesMessages } : {},
35920
36324
  ...model?.api ? { api: model.api } : {},
35921
36325
  ...model?.api?.startsWith("google-") ? {
35922
- googleFunctionIds: object7(model.compat)?.supportsFunctionPartId === true
36326
+ googleFunctionIds: object8(model.compat)?.supportsFunctionPartId === true
35923
36327
  } : {}
35924
36328
  };
35925
36329
  }
@@ -35931,7 +36335,7 @@ function responsesLane(api) {
35931
36335
  ].includes(api ?? "");
35932
36336
  }
35933
36337
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false) {
35934
- const body = object7(payload);
36338
+ const body = object8(payload);
35935
36339
  if (!body)
35936
36340
  return;
35937
36341
  const google = piGoogleConversation(payload);
@@ -35946,7 +36350,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
35946
36350
  return;
35947
36351
  const rows = [];
35948
36352
  for (const value of messages) {
35949
- const message = object7(value);
36353
+ const message = object8(value);
35950
36354
  if (!message)
35951
36355
  return;
35952
36356
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
@@ -36006,7 +36410,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
36006
36410
  continue;
36007
36411
  }
36008
36412
  if (message.role === "user" && Array.isArray(message.content)) {
36009
- const results = message.content.filter((block) => object7(block)?.type === "tool_result" || bedrock && object7(block)?.toolResult);
36413
+ const results = message.content.filter((block) => object8(block)?.type === "tool_result" || bedrock && object8(block)?.toolResult);
36010
36414
  if (results.length) {
36011
36415
  for (const block of results) {
36012
36416
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -36053,11 +36457,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
36053
36457
  }
36054
36458
  if (Array.isArray(message.tool_calls)) {
36055
36459
  for (const call of message.tool_calls) {
36056
- const source = object7(call);
36460
+ const source = object8(call);
36057
36461
  if (!source)
36058
36462
  return;
36059
36463
  if (source.id === undefined && ollama) {
36060
- const fn = object7(source.function);
36464
+ const fn = object8(source.function);
36061
36465
  if (typeof fn?.name !== "string")
36062
36466
  return;
36063
36467
  row.calls.push("");
@@ -36093,7 +36497,7 @@ function googleStructure(contents, imageProjection = false) {
36093
36497
  return;
36094
36498
  const rows = [];
36095
36499
  for (const value of contents) {
36096
- const message = object7(value);
36500
+ const message = object8(value);
36097
36501
  if (!message || !Array.isArray(message.parts))
36098
36502
  return;
36099
36503
  if (message.role !== "user" && message.role !== "model")
@@ -36108,11 +36512,11 @@ function googleStructure(contents, imageProjection = false) {
36108
36512
  };
36109
36513
  const results = [];
36110
36514
  for (const value of message.parts) {
36111
- const part = object7(value);
36515
+ const part = object8(value);
36112
36516
  if (!part)
36113
36517
  return;
36114
36518
  if (part.functionCall) {
36115
- const call = object7(part.functionCall);
36519
+ const call = object8(part.functionCall);
36116
36520
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
36117
36521
  return;
36118
36522
  row.calls.push(call.id ?? "");
@@ -36120,7 +36524,7 @@ function googleStructure(contents, imageProjection = false) {
36120
36524
  row.callNames.push(call.name);
36121
36525
  }
36122
36526
  if (part.functionResponse) {
36123
- const result = object7(part.functionResponse);
36527
+ const result = object8(part.functionResponse);
36124
36528
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
36125
36529
  return;
36126
36530
  results.push({
@@ -36154,11 +36558,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
36154
36558
  if (responses || googleOrBedrock) {
36155
36559
  if (!Array.isArray(content) || content.length !== 1)
36156
36560
  return false;
36157
- const block = object7(content[0]);
36561
+ const block = object8(content[0]);
36158
36562
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
36159
36563
  }
36160
36564
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
36161
- const block = content.length === 1 ? object7(content[0]) : undefined;
36565
+ const block = content.length === 1 ? object8(content[0]) : undefined;
36162
36566
  return block?.type === "text" && block.text === text;
36163
36567
  }
36164
36568
  return content === text;
@@ -36226,7 +36630,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
36226
36630
  return "comparison=image count";
36227
36631
  const imageProjection = trimmed > 0;
36228
36632
  stage = "wire rows";
36229
- const body = object7(payload);
36633
+ const body = object8(payload);
36230
36634
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
36231
36635
  const responses = body?.messages === undefined && Array.isArray(body?.input);
36232
36636
  rows = payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection);
@@ -36251,7 +36655,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
36251
36655
  if (expected.systemText !== undefined) {
36252
36656
  const texts = expected.systemText;
36253
36657
  const content = actual.wireContent;
36254
- 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;
36658
+ 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;
36255
36659
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
36256
36660
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
36257
36661
  return structureDetail(i, expectedRows, rows, "content");
@@ -43658,6 +44062,14 @@ function registerPiContextHandler(pi, baseOptions) {
43658
44062
  schedulerDeferReason,
43659
44063
  forceMaterialization: forceMaterialization || isEmergency,
43660
44064
  forceMaterializationPercentage,
44065
+ signedThinkingHold: resolvePiSignedThinkingHold({
44066
+ sessionId,
44067
+ db: options.db,
44068
+ messages: event.messages,
44069
+ prefixBound: isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id),
44070
+ usagePercentage,
44071
+ executeThresholdPercentage: effectiveExecuteThresholdPercentage
44072
+ }),
43661
44073
  contextUsage: {
43662
44074
  percentage: usagePercentage,
43663
44075
  inputTokens: usageInputTokens
@@ -43774,7 +44186,8 @@ function registerPiContextHandler(pi, baseOptions) {
43774
44186
  minimumPercentage: usagePercentage,
43775
44187
  liveIsRawBranchEstimate: piLiveUsageIsRawBranchEstimate,
43776
44188
  historianStateSnapshot: historianStateForPass,
43777
- publishedHistoryRide: isCacheBusting
44189
+ publishedHistoryRide: isCacheBusting,
44190
+ signedThinkingHeld: result.strictThinkingKept
43778
44191
  });
43779
44192
  } catch (error) {
43780
44193
  budget.assertOutcome();
@@ -44167,6 +44580,7 @@ function registerPiContextHandler(pi, baseOptions) {
44167
44580
  },
44168
44581
  minimumPercentage: 95,
44169
44582
  publishedHistoryRide: false,
44583
+ signedThinkingHeld: result.strictThinkingKept,
44170
44584
  historianStateSnapshot: loadPiHistorianStateSnapshot(options.db, sessionId)
44171
44585
  });
44172
44586
  const pending = inFlightHistorian.get(sessionId);
@@ -44928,8 +45342,14 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
44928
45342
  const trigger = checkCompartmentTrigger(db, sessionId, sessionMeta, usage, 0, triggerInputs.executeThresholdPercentage, triggerInputs.triggerBudget, triggerInputs.keepReasoningTokens, triggerInputs.commitClusterTrigger, args.activeTags, boundaryContextLimit, () => readPiHistorianTail(db, sessionId, provider), args.taggerFloor, { canClearReasoning: true }, {
44929
45343
  hardFold: false,
44930
45344
  force: usage.percentage >= historianForceMaterializationPercentage && (usage.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
44931
- explicitFlush: hasPendingMaterialization(sessionId),
44932
- publishedHistory: args.publishedHistoryRide
45345
+ explicitFlush: hasPendingMaterializationOrigin(pendingMaterializationSessions, sessionId, "user_flush"),
45346
+ publishedHistory: args.publishedHistoryRide,
45347
+ permission: {
45348
+ signedThinkingHold: args.signedThinkingHeld === true,
45349
+ firstRender: false,
45350
+ idleExpiry: false,
45351
+ emergency: usage.percentage >= historianForceMaterializationPercentage
45352
+ }
44933
45353
  }, args.eligiblePendingDropTagIds);
44934
45354
  if (!trigger.shouldFire) {
44935
45355
  sessionLog2(sessionId, `historian trigger eval: shouldFire=false (no trigger condition met)`);
@@ -45030,7 +45450,7 @@ function captureReasoningMutationRollback(messages) {
45030
45450
  async function runCompactionOffPipeline(args) {
45031
45451
  let injectionResult = null;
45032
45452
  if (args.injection) {
45033
- injectionResult = injectM0M1Pi({
45453
+ const state = {
45034
45454
  sessionId: args.sessionId,
45035
45455
  projectIdentity: args.projectIdentity,
45036
45456
  projectDirectory: args.projectDirectory,
@@ -45041,7 +45461,10 @@ async function runCompactionOffPipeline(args) {
45041
45461
  historyBudgetPolicyIdentity: args.injection.historyBudgetPolicyIdentity,
45042
45462
  muralEnabled: args.injection.muralEnabled === true,
45043
45463
  compactionOff: true
45044
- }, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
45464
+ };
45465
+ if (args.reasoningClearing?.prefixBound === true && hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID))
45466
+ state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
45467
+ injectionResult = injectM0M1Pi(state, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
45045
45468
  }
45046
45469
  return {
45047
45470
  messages: args.messages,
@@ -45077,6 +45500,27 @@ async function runCompactionOffPipeline(args) {
45077
45500
  lkgEntryIdByRef: new Map
45078
45501
  };
45079
45502
  }
45503
+ var signedThinkingHoldLogKeys = new Map;
45504
+ function resolvePiSignedThinkingHold(args) {
45505
+ if (!args.prefixBound)
45506
+ return false;
45507
+ let proseRatio;
45508
+ const decision = decideSignedThinkingHold({
45509
+ messages: args.messages,
45510
+ usagePercentage: args.usagePercentage,
45511
+ executeThresholdPercentage: args.executeThresholdPercentage,
45512
+ estimateTextTokens: (text) => {
45513
+ proseRatio ??= sessionDecisionCalibration(args.db, args.sessionId).proseRatio;
45514
+ return estimateTokens(text) * proseRatio;
45515
+ }
45516
+ });
45517
+ const key = `${decision.reason}:${decision.heavyStepsBack ?? "none"}`;
45518
+ if (signedThinkingHoldLogKeys.get(args.sessionId) !== key) {
45519
+ signedThinkingHoldLogKeys.set(args.sessionId, key);
45520
+ sessionLog2(args.sessionId, `signed thinking hold: held=${decision.held} reason=${decision.reason} heavyStepsBack=${decision.heavyStepsBack ?? "none"} heavyStepTokens=${decision.heavyStepTokens} usage=${args.usagePercentage.toFixed(1)}% cap=${decision.capPercentage}%`);
45521
+ }
45522
+ return decision.held;
45523
+ }
45080
45524
  async function runPipeline(args) {
45081
45525
  args.assertCurrentPass?.();
45082
45526
  if (args.compactionOff)
@@ -45092,7 +45536,8 @@ async function runPipeline(args) {
45092
45536
  signalPiPendingMaterialization(args.sessionId, "thinking_hold");
45093
45537
  let restoreOriginals;
45094
45538
  let activeThinkingTurn = hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID);
45095
- let protectedSignedPrefix = activeThinkingTurn && args.reasoningClearing?.prefixBound === true;
45539
+ const signedTurnOnPrefixBoundModel = args.reasoningClearing?.prefixBound === true && (activeThinkingTurn || activeAnthropicTurnStart(args.messages, true) === undefined && args.messages.some((message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some((part) => part?.type === "thinking" || part?.type === "redacted_thinking")));
45540
+ let protectedSignedPrefix = signedTurnOnPrefixBoundModel && args.signedThinkingHold === true;
45096
45541
  let rewritingSignedPrefix = false;
45097
45542
  let isCacheBustingPass = args.recoveryRebuildReason === "lkg_recovery_input_rebuild" || (!!args.recoveryRebuildReason || args.forceSignedRebuildForFit === true) && hasUnfrozenPiThinking({
45098
45543
  messages: args.messages,
@@ -45123,8 +45568,12 @@ async function runPipeline(args) {
45123
45568
  activeThinkingTurn = false;
45124
45569
  protectedSignedPrefix = false;
45125
45570
  };
45126
- if (args.recoveryRebuildReason || args.forceSignedRebuildForFit && protectedSignedPrefix)
45571
+ if (args.recoveryRebuildReason || args.forceSignedRebuildForFit && signedTurnOnPrefixBoundModel)
45127
45572
  stripForPrefixRewrite(isCacheBustingPass);
45573
+ const stripUnheldSignedTurnOnBust = () => {
45574
+ if (isCacheBustingPass && signedTurnOnPrefixBoundModel && !protectedSignedPrefix && !rewritingSignedPrefix)
45575
+ stripForPrefixRewrite();
45576
+ };
45128
45577
  const realStableId = (msg, index) => resolvePiRealStableId(msg, index, args.entryIds, args.entryIdByRef ?? undefined);
45129
45578
  const passFallbackIds = settlePiFallbackOccurrences(args.db, args.sessionId, piContentFallbackIds(args.messages, realStableId));
45130
45579
  const stableIdResolver = (msg, index) => realStableId(msg, index) ?? passFallbackIds[index] ?? resolvePiStableId(msg, index);
@@ -45367,9 +45816,16 @@ async function runPipeline(args) {
45367
45816
  explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_flush")),
45368
45817
  publishedHistory: !prefixPreflightContended && publishedM1RefreshedThisPass
45369
45818
  };
45370
- let prefixMutationAllowed = !protectedSignedPrefix || firstRenderBust || heldIdleExpiryRebuild || emergencyDropEligible;
45371
- isCacheBustingPass = prefixMutationAllowed && hasReclaimRide(rideSignals);
45819
+ const ridePermissionGate = {
45820
+ signedThinkingHold: protectedSignedPrefix,
45821
+ firstRender: firstRenderBust,
45822
+ idleExpiry: heldIdleExpiryRebuild,
45823
+ emergency: emergencyDropEligible
45824
+ };
45825
+ let prefixMutationAllowed = prefixMutationPermitted(ridePermissionGate);
45826
+ isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
45372
45827
  let publishedWorkDrainAllowed = isCacheBustingPass;
45828
+ stripUnheldSignedTurnOnBust();
45373
45829
  const usesTokenProtection = args.protectedTokenTierOverrides !== undefined || args.protectedTokens !== undefined;
45374
45830
  const resolveProtectionFloor = () => resolveEpochFloorForPass(args.db, args.sessionId, {
45375
45831
  configuredOverride: args.protectedTokens,
@@ -45444,6 +45900,7 @@ async function runPipeline(args) {
45444
45900
  deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId);
45445
45901
  isCacheBustingPass = prefixMutationAllowed;
45446
45902
  publishedWorkDrainAllowed = isCacheBustingPass;
45903
+ stripUnheldSignedTurnOnBust();
45447
45904
  shouldRunHeuristics = args.heuristics !== undefined;
45448
45905
  if (piM0State && prefixMutationAllowed) {
45449
45906
  try {
@@ -46652,6 +47109,7 @@ function clearContextHandlerSession(sessionId) {
46652
47109
  clearPiChannel1State(sessionId);
46653
47110
  lastHeuristicsTurnIdBySession.delete(sessionId);
46654
47111
  routinePressureAppliedBySession.delete(sessionId);
47112
+ signedThinkingHoldLogKeys.delete(sessionId);
46655
47113
  lastSeenProjectIdentityBySession.delete(sessionId);
46656
47114
  persistedProjectIdentityBySession.delete(sessionId);
46657
47115
  sessionProjectBindingFailureLogAtBySession.delete(sessionId);