@cortexkit/pi-magic-context 0.49.62 → 0.49.64
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/auto-search-worker.js +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{index-w4sqw9mf.js → index-67q9cz3f.js} +1 -1
- package/dist/{index-418za765.js → index-691zz6f4.js} +7 -7
- package/dist/{index-zgsemyph.js → index-6vmpw4z3.js} +3 -3
- package/dist/{index-8gvbskcm.js → index-7vhbmjgv.js} +87 -44
- package/dist/{index-5hhhxck7.js → index-8328rak2.js} +1 -1
- package/dist/{index-xan5mt5f.js → index-98e27fdt.js} +1 -1
- package/dist/{index-f4n7tnsf.js → index-hja11zte.js} +1 -1
- package/dist/{index-m6kszx0e.js → index-renfmk50.js} +1 -1
- package/dist/{index-9cqfbdgb.js → index-vkcb1cg1.js} +3 -3
- package/dist/{index-fz4gexgk.js → index-ye6b3dr4.js} +1 -1
- package/dist/index.js +520 -302
- package/dist/{message-index-bounded-behq385r.js → message-index-bounded-b5vft8jk.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-ksh32zfv.js → read-session-chunk-nfkemn80.js} +2 -2
- package/dist/{render-2qed2svq.js → render-173bqp1y.js} +5 -5
- package/dist/{search-archive-qqj7j1w1.js → search-archive-7snt7cyv.js} +4 -4
- package/dist/{search-vmw1xbqx.js → search-ea9x8vxk.js} +4 -4
- package/dist/{storage-tags-s0m7e39a.js → storage-tags-n8q8jk1b.js} +3 -1
- package/dist/subagent-entry.js +9 -9
- package/dist/tag-snapshot-worker-pi.js +3 -3
- package/dist/{v2-archive-reader-cc7sx6dk.js → v2-archive-reader-5vmwk9y5.js} +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -154,7 +154,7 @@ import {
|
|
|
154
154
|
registerTodoStateLifecycle,
|
|
155
155
|
syncCtxMemoryToolEnabled,
|
|
156
156
|
registerMagicContextTools
|
|
157
|
-
} from "./index-
|
|
157
|
+
} from "./index-691zz6f4.js";
|
|
158
158
|
import"./index-4knyh1kt.js";
|
|
159
159
|
import {
|
|
160
160
|
canonicalModelIdentity,
|
|
@@ -282,6 +282,7 @@ import {
|
|
|
282
282
|
getTriggerTagTokenUpperBound2,
|
|
283
283
|
updateTagInputByteSize2,
|
|
284
284
|
updateTagTokenCount2,
|
|
285
|
+
setTagTokenCount2,
|
|
285
286
|
getPersistedToolTagAccounting2,
|
|
286
287
|
getAllStatusTagTokenTotalsFlat2,
|
|
287
288
|
tryGetReasoningTokenEstimatesByMessage2,
|
|
@@ -403,7 +404,7 @@ import {
|
|
|
403
404
|
setSessionWorkMetrics,
|
|
404
405
|
getSessionWorkMetrics,
|
|
405
406
|
resolveEpochFloorForPass
|
|
406
|
-
} from "./index-
|
|
407
|
+
} from "./index-7vhbmjgv.js";
|
|
407
408
|
import {
|
|
408
409
|
textMentionsRecentCommit,
|
|
409
410
|
hasMeaningfulUserText2,
|
|
@@ -454,7 +455,7 @@ import {
|
|
|
454
455
|
openCurrentDatabase,
|
|
455
456
|
openDatabaseAsync,
|
|
456
457
|
closeDatabase
|
|
457
|
-
} from "./index-
|
|
458
|
+
} from "./index-67q9cz3f.js";
|
|
458
459
|
import {
|
|
459
460
|
LkgRecoveryFenceError,
|
|
460
461
|
clearLkgFenceProcessState,
|
|
@@ -581,7 +582,7 @@ import {
|
|
|
581
582
|
getSourceContents,
|
|
582
583
|
recordSubagentInvocation,
|
|
583
584
|
getLatestHistorianInvocationId
|
|
584
|
-
} from "./index-
|
|
585
|
+
} from "./index-6vmpw4z3.js";
|
|
585
586
|
import {
|
|
586
587
|
resolveOpenCodeDbPath,
|
|
587
588
|
assertOpenCodeStoreGeneration,
|
|
@@ -647,7 +648,7 @@ import {
|
|
|
647
648
|
getRawSessionTagKeysThrough2,
|
|
648
649
|
getLegacyProtectedTailStartOrdinal2,
|
|
649
650
|
readSessionChunk2
|
|
650
|
-
} from "./index-
|
|
651
|
+
} from "./index-98e27fdt.js";
|
|
651
652
|
import"./index-nvh6d3bz.js";
|
|
652
653
|
import {
|
|
653
654
|
formatSynapseLaneDescriptor
|
|
@@ -687,7 +688,7 @@ import {
|
|
|
687
688
|
clearCompressionDepthRange,
|
|
688
689
|
cleanSearchText,
|
|
689
690
|
matchedSearchSnippet
|
|
690
|
-
} from "./index-
|
|
691
|
+
} from "./index-renfmk50.js";
|
|
691
692
|
import {
|
|
692
693
|
rememberV1HiddenRun
|
|
693
694
|
} from "./index-6x556c2q.js";
|
|
@@ -816,7 +817,7 @@ import {
|
|
|
816
817
|
scheduleClearAndReindex,
|
|
817
818
|
clearSessionTracking,
|
|
818
819
|
createAutoSearchDiagnostics
|
|
819
|
-
} from "./index-
|
|
820
|
+
} from "./index-8328rak2.js";
|
|
820
821
|
import"./index-3s39a1md.js";
|
|
821
822
|
import {
|
|
822
823
|
DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
|
|
@@ -845,11 +846,11 @@ import {
|
|
|
845
846
|
drainPiTagSnapshotSession,
|
|
846
847
|
assertPiTagSnapshotReady,
|
|
847
848
|
ensurePiTagSnapshotReady
|
|
848
|
-
} from "./index-
|
|
849
|
+
} from "./index-ye6b3dr4.js";
|
|
849
850
|
import"./index-71rg8j43.js";
|
|
850
851
|
import"./index-8d2z6503.js";
|
|
851
|
-
import"./index-
|
|
852
|
-
import"./index-
|
|
852
|
+
import"./index-vkcb1cg1.js";
|
|
853
|
+
import"./index-hja11zte.js";
|
|
853
854
|
import {
|
|
854
855
|
__toESM
|
|
855
856
|
} from "./index-22jkk6wg.js";
|
|
@@ -3601,7 +3602,7 @@ function startHostStallProfilerSwitch() {
|
|
|
3601
3602
|
// package.json
|
|
3602
3603
|
var package_default = {
|
|
3603
3604
|
name: "@cortexkit/pi-magic-context",
|
|
3604
|
-
version: "0.49.
|
|
3605
|
+
version: "0.49.64",
|
|
3605
3606
|
type: "module",
|
|
3606
3607
|
description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
|
|
3607
3608
|
main: "dist/index.js",
|
|
@@ -24799,26 +24800,24 @@ function schedulePiTransformDecisionResolve(args) {
|
|
|
24799
24800
|
return false;
|
|
24800
24801
|
pendingPiDecisionBySession.delete(args.sessionId);
|
|
24801
24802
|
const token = addScheduledWriteToken(args.sessionId);
|
|
24803
|
+
const assertQueuedWrite = args.assertQueuedWrite ?? args.assertCurrentPass;
|
|
24802
24804
|
inRootAsyncContext2(() => setTimeout(() => {
|
|
24805
|
+
if (!hasScheduledWriteToken(args.sessionId, token))
|
|
24806
|
+
return;
|
|
24803
24807
|
try {
|
|
24804
|
-
|
|
24805
|
-
|
|
24806
|
-
|
|
24807
|
-
pending.publicationGuard?.();
|
|
24808
|
-
args.assertCurrentPass?.();
|
|
24809
|
-
} catch {
|
|
24810
|
-
sessionLog2(args.sessionId, "DISCARDED CONTEXT RESULT: queued Pi transform decision");
|
|
24811
|
-
return;
|
|
24812
|
-
}
|
|
24813
|
-
writeTransformDecisionBestEffort(dbPath, {
|
|
24814
|
-
...pending,
|
|
24815
|
-
sessionId: args.sessionId,
|
|
24816
|
-
harness: "pi",
|
|
24817
|
-
messageId: targetMessageId
|
|
24818
|
-
});
|
|
24819
|
-
} finally {
|
|
24808
|
+
pending.publicationGuard?.();
|
|
24809
|
+
assertQueuedWrite?.();
|
|
24810
|
+
} catch {
|
|
24820
24811
|
deleteScheduledWriteToken(args.sessionId, token);
|
|
24812
|
+
sessionLog2(args.sessionId, "DISCARDED CONTEXT RESULT: queued Pi transform decision");
|
|
24813
|
+
return;
|
|
24821
24814
|
}
|
|
24815
|
+
writeQueuedTransformDecision(dbPath, token, {
|
|
24816
|
+
...pending,
|
|
24817
|
+
sessionId: args.sessionId,
|
|
24818
|
+
harness: "pi",
|
|
24819
|
+
messageId: targetMessageId
|
|
24820
|
+
});
|
|
24822
24821
|
}, 0));
|
|
24823
24822
|
return true;
|
|
24824
24823
|
}
|
|
@@ -24879,11 +24878,25 @@ function findNewestPiAssistantEntryIdAfter(entries, snapshotNewestAssistantEntry
|
|
|
24879
24878
|
}
|
|
24880
24879
|
return null;
|
|
24881
24880
|
}
|
|
24882
|
-
|
|
24881
|
+
var DECISION_WRITE_RETRY_DELAYS_MS = [10, 25, 50, 100, 250, 500, 1000];
|
|
24882
|
+
function writeQueuedTransformDecision(dbPath, token, row, attempt = 0) {
|
|
24883
|
+
let retryInMs;
|
|
24883
24884
|
try {
|
|
24884
|
-
|
|
24885
|
-
|
|
24886
|
-
|
|
24885
|
+
if (!hasScheduledWriteToken(row.sessionId, token))
|
|
24886
|
+
return;
|
|
24887
|
+
try {
|
|
24888
|
+
(writerOverrideForTests ?? writeTransformDecisionRow)(dbPath, row);
|
|
24889
|
+
} catch (error) {
|
|
24890
|
+
if (isTransientSqliteError2(error))
|
|
24891
|
+
retryInMs = DECISION_WRITE_RETRY_DELAYS_MS[attempt];
|
|
24892
|
+
}
|
|
24893
|
+
} finally {
|
|
24894
|
+
if (retryInMs === undefined)
|
|
24895
|
+
deleteScheduledWriteToken(row.sessionId, token);
|
|
24896
|
+
}
|
|
24897
|
+
if (retryInMs === undefined)
|
|
24898
|
+
return;
|
|
24899
|
+
inRootAsyncContext2(() => setTimeout(() => writeQueuedTransformDecision(dbPath, token, row, attempt + 1), retryInMs));
|
|
24887
24900
|
}
|
|
24888
24901
|
function writeTransformDecisionRow(dbPath, row) {
|
|
24889
24902
|
const db = new Database2(dbPath);
|
|
@@ -28845,6 +28858,9 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
|
|
|
28845
28858
|
timing.identity += performance.now() - identityStart;
|
|
28846
28859
|
}
|
|
28847
28860
|
existing.identityReusable &&= reuseIdentity;
|
|
28861
|
+
if (part.kind === "tool_result") {
|
|
28862
|
+
noteResultBlock(existing, part, text, tokenCacheKey);
|
|
28863
|
+
}
|
|
28848
28864
|
applyToolPrefixAndTarget({
|
|
28849
28865
|
skipPrefixInjection,
|
|
28850
28866
|
part,
|
|
@@ -28873,6 +28889,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
|
|
|
28873
28889
|
occurrences: [{ message, part, kind: part.kind }],
|
|
28874
28890
|
maxByteSize: reusableAccounting.byteSize,
|
|
28875
28891
|
maxTokenCount: reusableAccounting.tokenCount ?? 0,
|
|
28892
|
+
resultImageTokens: 0,
|
|
28893
|
+
resultTexts: [],
|
|
28876
28894
|
toolName: null,
|
|
28877
28895
|
inputByteSize: reusableAccounting.inputByteSize,
|
|
28878
28896
|
inputTokenCount: reusableAccounting.inputTokenCount,
|
|
@@ -28914,6 +28932,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
|
|
|
28914
28932
|
occurrences: [{ message, part, kind: part.kind }],
|
|
28915
28933
|
maxByteSize: persistedAccounting?.byteSize ?? outputByteSize,
|
|
28916
28934
|
maxTokenCount: persistedAccounting?.tokenCount ?? outputTokenCount,
|
|
28935
|
+
resultImageTokens: 0,
|
|
28936
|
+
resultTexts: [],
|
|
28917
28937
|
toolName: accounting.toolName,
|
|
28918
28938
|
inputByteSize: persistedAccounting?.inputByteSize ?? (part.kind === "tool_use" ? accounting.inputByteSize : 0),
|
|
28919
28939
|
inputTokenCount: persistedAccounting?.inputTokenCount ?? (part.kind === "tool_use" ? firstInputTokenCount : null),
|
|
@@ -28939,6 +28959,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
|
|
|
28939
28959
|
toolAggregates.set(aggregateKey, aggregate);
|
|
28940
28960
|
if (part.kind === "tool_use") {
|
|
28941
28961
|
openToolAggregateKeysByCallId.set(callId, [...pendingKeys, aggregateKey]);
|
|
28962
|
+
} else {
|
|
28963
|
+
noteResultBlock(aggregate, part, text, tokenCacheKey);
|
|
28942
28964
|
}
|
|
28943
28965
|
applyToolPrefixAndTarget({
|
|
28944
28966
|
skipPrefixInjection,
|
|
@@ -28957,6 +28979,16 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
|
|
|
28957
28979
|
}
|
|
28958
28980
|
}
|
|
28959
28981
|
}
|
|
28982
|
+
for (const aggregate of toolAggregates.values()) {
|
|
28983
|
+
applyImageResultAccounting({
|
|
28984
|
+
db,
|
|
28985
|
+
sessionId,
|
|
28986
|
+
tagger,
|
|
28987
|
+
aggregate,
|
|
28988
|
+
timing,
|
|
28989
|
+
tokenCache: options.toolTokenCache
|
|
28990
|
+
});
|
|
28991
|
+
}
|
|
28960
28992
|
if (timing && options.onTiming) {
|
|
28961
28993
|
options.onTiming("identity", timing.identity);
|
|
28962
28994
|
options.onTiming("prefix", timing.prefix);
|
|
@@ -28988,10 +29020,36 @@ function applyGrownToolResultAccounting(args) {
|
|
|
28988
29020
|
}
|
|
28989
29021
|
args.aggregate.maxByteSize = args.byteSize;
|
|
28990
29022
|
args.aggregate.maxTokenCount = tokenCount;
|
|
29023
|
+
args.aggregate.tokenCountGrewThisPass = true;
|
|
28991
29024
|
updateTagByteSize2(args.db, args.sessionId, args.aggregate.tagId, args.byteSize);
|
|
28992
29025
|
updateTagTokenCount2(args.db, args.sessionId, args.aggregate.tagId, tokenCount);
|
|
28993
29026
|
syncToolAggregateAccounting(args.tagger, args.sessionId, args.aggregate);
|
|
28994
29027
|
}
|
|
29028
|
+
function noteResultBlock(aggregate, part, text, tokenCacheKey) {
|
|
29029
|
+
const imageTokens = part.imageTokens?.() ?? 0;
|
|
29030
|
+
if (imageTokens > 0)
|
|
29031
|
+
aggregate.resultImageTokens += imageTokens;
|
|
29032
|
+
else if (text.length > 0)
|
|
29033
|
+
aggregate.resultTexts.push({ part, text, tokenCacheKey });
|
|
29034
|
+
}
|
|
29035
|
+
function applyImageResultAccounting(args) {
|
|
29036
|
+
const { aggregate } = args;
|
|
29037
|
+
if (aggregate.resultImageTokens === 0)
|
|
29038
|
+
return;
|
|
29039
|
+
const tokenStart = args.timing ? performance.now() : 0;
|
|
29040
|
+
let textTokens = 0;
|
|
29041
|
+
for (const block of aggregate.resultTexts) {
|
|
29042
|
+
textTokens = Math.max(textTokens, getCachedToolPartTokenCount(block.part, block.text, args.tokenCache, block.tokenCacheKey));
|
|
29043
|
+
}
|
|
29044
|
+
if (args.timing)
|
|
29045
|
+
args.timing.tokenCounting += performance.now() - tokenStart;
|
|
29046
|
+
const tokenCount = textTokens + aggregate.resultImageTokens;
|
|
29047
|
+
if (tokenCount === aggregate.maxTokenCount && !aggregate.tokenCountGrewThisPass)
|
|
29048
|
+
return;
|
|
29049
|
+
aggregate.maxTokenCount = tokenCount;
|
|
29050
|
+
setTagTokenCount2(args.db, args.sessionId, aggregate.tagId, tokenCount);
|
|
29051
|
+
syncToolAggregateAccounting(args.tagger, args.sessionId, aggregate);
|
|
29052
|
+
}
|
|
28995
29053
|
function readAggregateToolAccounting(part, timing, tokenCache, tokenCacheKey, persisted) {
|
|
28996
29054
|
const text = part.getText() ?? "";
|
|
28997
29055
|
const byteSize = getToolPartByteSize(part, text);
|
|
@@ -29097,6 +29155,9 @@ function getToolPartByteSize(part, text) {
|
|
|
29097
29155
|
function getToolPartTokenCount(part, text) {
|
|
29098
29156
|
if (text.length > 0 || part.kind !== "tool_result")
|
|
29099
29157
|
return estimateTokens(text);
|
|
29158
|
+
const imageTokens = part.imageTokens?.() ?? 0;
|
|
29159
|
+
if (imageTokens > 0)
|
|
29160
|
+
return imageTokens;
|
|
29100
29161
|
const raw = part.rawByteSize?.();
|
|
29101
29162
|
if (typeof raw === "number" && raw > 0) {
|
|
29102
29163
|
const record = isRecord2(part) ? part : undefined;
|
|
@@ -30573,37 +30634,6 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
30573
30634
|
return saved;
|
|
30574
30635
|
}
|
|
30575
30636
|
|
|
30576
|
-
// src/pi-history-retirement.ts
|
|
30577
|
-
var KEY2 = "piHistorianRetirement";
|
|
30578
|
-
function readState2(db, sessionId) {
|
|
30579
|
-
const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
30580
|
-
const state = row?.state ? JSON.parse(row.state) : {};
|
|
30581
|
-
if (!state || typeof state !== "object" || Array.isArray(state))
|
|
30582
|
-
throw new Error("Invalid session metadata JSON");
|
|
30583
|
-
return state;
|
|
30584
|
-
}
|
|
30585
|
-
function readPiHistoryRetirement(db, sessionId) {
|
|
30586
|
-
const target = readState2(db, sessionId)[KEY2];
|
|
30587
|
-
return typeof target === "string" && target.length > 0 ? target : null;
|
|
30588
|
-
}
|
|
30589
|
-
function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
|
|
30590
|
-
ensureSessionMetaRow(db, sessionId);
|
|
30591
|
-
const state = readState2(db, sessionId);
|
|
30592
|
-
state[KEY2] = throughMessageId;
|
|
30593
|
-
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30594
|
-
}
|
|
30595
|
-
function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
|
|
30596
|
-
const state = readState2(db, sessionId);
|
|
30597
|
-
const target = state[KEY2];
|
|
30598
|
-
if (typeof target !== "string")
|
|
30599
|
-
return;
|
|
30600
|
-
const ordinal = ordinalOf(target);
|
|
30601
|
-
if (ordinal === undefined || ordinal > publishedEnd)
|
|
30602
|
-
return;
|
|
30603
|
-
delete state[KEY2];
|
|
30604
|
-
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30605
|
-
}
|
|
30606
|
-
|
|
30607
30637
|
// src/system-entry-pi.ts
|
|
30608
30638
|
function isPiSystemEntry(message) {
|
|
30609
30639
|
return message !== null && typeof message === "object" && "role" in message && message.role === "system";
|
|
@@ -30752,6 +30782,198 @@ function adoptPiCompactionSystemSnapshot(messages, entries, compactionId, foldin
|
|
|
30752
30782
|
}
|
|
30753
30783
|
}
|
|
30754
30784
|
|
|
30785
|
+
// src/pi-history-cut.ts
|
|
30786
|
+
function isPiContextEmitEligible(entry) {
|
|
30787
|
+
if (!entry || typeof entry !== "object")
|
|
30788
|
+
return false;
|
|
30789
|
+
const row = entry;
|
|
30790
|
+
if (typeof row.id !== "string")
|
|
30791
|
+
return false;
|
|
30792
|
+
return row.type === "message" || row.type === "custom_message" || row.type === "branch_summary" && typeof row.summary === "string" && row.summary.length > 0;
|
|
30793
|
+
}
|
|
30794
|
+
function piCutMessageForEntry(entry) {
|
|
30795
|
+
if (!isPiContextEmitEligible(entry))
|
|
30796
|
+
return;
|
|
30797
|
+
const row = entry;
|
|
30798
|
+
if (row.type === "custom_message")
|
|
30799
|
+
return { role: "custom" };
|
|
30800
|
+
if (row.type === "branch_summary")
|
|
30801
|
+
return { role: "branchSummary" };
|
|
30802
|
+
return row.message && typeof row.message === "object" ? row.message : undefined;
|
|
30803
|
+
}
|
|
30804
|
+
function planPiHistoryCut(messages, cutoffIndex, promptReachesBoundary) {
|
|
30805
|
+
const remove = new Set;
|
|
30806
|
+
for (let i = 0;i <= cutoffIndex; i++) {
|
|
30807
|
+
if (!isPiSystemEntry(messages[i]))
|
|
30808
|
+
remove.add(i);
|
|
30809
|
+
}
|
|
30810
|
+
let changed = true;
|
|
30811
|
+
while (changed) {
|
|
30812
|
+
changed = false;
|
|
30813
|
+
const removedCallKeys = new Set;
|
|
30814
|
+
const removedResultKeys = new Set;
|
|
30815
|
+
for (const index of remove) {
|
|
30816
|
+
const msg = messages[index];
|
|
30817
|
+
if (!msg)
|
|
30818
|
+
continue;
|
|
30819
|
+
if (msg.role === "assistant") {
|
|
30820
|
+
for (const callId of getPiToolCallIds(msg)) {
|
|
30821
|
+
removedCallKeys.add(toolPairKey(callId, index));
|
|
30822
|
+
}
|
|
30823
|
+
} else if (msg.role === "toolResult") {
|
|
30824
|
+
const callId = getPiToolResultCallId(msg);
|
|
30825
|
+
const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, index, callId) : null;
|
|
30826
|
+
if (callId && ownerIndex !== null) {
|
|
30827
|
+
removedResultKeys.add(toolPairKey(callId, ownerIndex));
|
|
30828
|
+
}
|
|
30829
|
+
}
|
|
30830
|
+
}
|
|
30831
|
+
for (let i = 0;i < messages.length; i++) {
|
|
30832
|
+
if (remove.has(i))
|
|
30833
|
+
continue;
|
|
30834
|
+
const msg = messages[i];
|
|
30835
|
+
if (!msg)
|
|
30836
|
+
continue;
|
|
30837
|
+
if (msg.role === "toolResult") {
|
|
30838
|
+
const callId = getPiToolResultCallId(msg);
|
|
30839
|
+
const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, i, callId) : null;
|
|
30840
|
+
if (callId && ownerIndex !== null && removedCallKeys.has(toolPairKey(callId, ownerIndex))) {
|
|
30841
|
+
remove.add(i);
|
|
30842
|
+
changed = true;
|
|
30843
|
+
}
|
|
30844
|
+
continue;
|
|
30845
|
+
}
|
|
30846
|
+
if (msg.role === "assistant") {
|
|
30847
|
+
const callIds = getPiToolCallIds(msg);
|
|
30848
|
+
if (callIds.some((callId) => removedResultKeys.has(toolPairKey(callId, i)))) {
|
|
30849
|
+
remove.add(i);
|
|
30850
|
+
changed = true;
|
|
30851
|
+
}
|
|
30852
|
+
}
|
|
30853
|
+
}
|
|
30854
|
+
}
|
|
30855
|
+
const keptPrompt = keptPromptIndex(messages, cutoffIndex, remove, promptReachesBoundary);
|
|
30856
|
+
if (keptPrompt >= 0)
|
|
30857
|
+
remove.delete(keptPrompt);
|
|
30858
|
+
return remove;
|
|
30859
|
+
}
|
|
30860
|
+
function firstMessageKeptByPiHistoryCut(messages, remove) {
|
|
30861
|
+
for (let i = 0;i < messages.length; i++) {
|
|
30862
|
+
if (!remove.has(i) && !isPiSystemEntry(messages[i]))
|
|
30863
|
+
return i;
|
|
30864
|
+
}
|
|
30865
|
+
return -1;
|
|
30866
|
+
}
|
|
30867
|
+
function resolvePiMarkerKeptEntry(branchEntries, endMessageId) {
|
|
30868
|
+
const boundaryId = endMessageId.startsWith(SYNTH_USER_ID_PREFIX) ? endMessageId.slice(SYNTH_USER_ID_PREFIX.length) : endMessageId;
|
|
30869
|
+
if (boundaryId.length === 0)
|
|
30870
|
+
return { kind: "missing" };
|
|
30871
|
+
const messages = [];
|
|
30872
|
+
const ids = [];
|
|
30873
|
+
for (const entry of branchEntries) {
|
|
30874
|
+
const message = piCutMessageForEntry(entry);
|
|
30875
|
+
const id = entry.id;
|
|
30876
|
+
if (!message || id.length === 0)
|
|
30877
|
+
continue;
|
|
30878
|
+
messages.push(message);
|
|
30879
|
+
ids.push(id);
|
|
30880
|
+
}
|
|
30881
|
+
const cutoffIndex = ids.indexOf(boundaryId);
|
|
30882
|
+
if (cutoffIndex < 0)
|
|
30883
|
+
return { kind: "missing" };
|
|
30884
|
+
if (!messages.slice(cutoffIndex + 1).some((m) => !isPiSystemEntry(m)))
|
|
30885
|
+
return { kind: "waiting" };
|
|
30886
|
+
const kept = firstMessageKeptByPiHistoryCut(messages, planPiHistoryCut(messages, cutoffIndex));
|
|
30887
|
+
return kept < 0 ? { kind: "waiting" } : { kind: "resolved", entryId: ids[kept] };
|
|
30888
|
+
}
|
|
30889
|
+
function keptPromptIndex(messages, cutoffIndex, removed, promptReachesBoundary) {
|
|
30890
|
+
let promptIndex = -1;
|
|
30891
|
+
for (let i = cutoffIndex;i >= 0; i--) {
|
|
30892
|
+
if (messages[i]?.role === "user") {
|
|
30893
|
+
promptIndex = i;
|
|
30894
|
+
break;
|
|
30895
|
+
}
|
|
30896
|
+
}
|
|
30897
|
+
if (promptIndex < 0)
|
|
30898
|
+
return -1;
|
|
30899
|
+
for (let i = cutoffIndex + 1;i < messages.length; i++) {
|
|
30900
|
+
if (removed.has(i))
|
|
30901
|
+
continue;
|
|
30902
|
+
const message = messages[i];
|
|
30903
|
+
if (message?.role === "user")
|
|
30904
|
+
return -1;
|
|
30905
|
+
if (message?.role === "assistant" && message.stopReason !== "error")
|
|
30906
|
+
break;
|
|
30907
|
+
}
|
|
30908
|
+
if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
|
|
30909
|
+
return -1;
|
|
30910
|
+
return promptIndex;
|
|
30911
|
+
}
|
|
30912
|
+
function toolPairKey(callId, assistantIndex) {
|
|
30913
|
+
return `${callId}\x00${assistantIndex}`;
|
|
30914
|
+
}
|
|
30915
|
+
function findToolResultOwnerAssistantIndex(messages, resultIndex, callId) {
|
|
30916
|
+
for (let i = resultIndex - 1;i >= 0; i--) {
|
|
30917
|
+
const msg = messages[i];
|
|
30918
|
+
if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
|
|
30919
|
+
return i;
|
|
30920
|
+
}
|
|
30921
|
+
}
|
|
30922
|
+
for (let i = resultIndex + 1;i < messages.length; i++) {
|
|
30923
|
+
const msg = messages[i];
|
|
30924
|
+
if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
|
|
30925
|
+
return i;
|
|
30926
|
+
}
|
|
30927
|
+
}
|
|
30928
|
+
return null;
|
|
30929
|
+
}
|
|
30930
|
+
function getPiToolCallIds(message) {
|
|
30931
|
+
if (!Array.isArray(message.content))
|
|
30932
|
+
return [];
|
|
30933
|
+
const ids = [];
|
|
30934
|
+
for (const part of message.content) {
|
|
30935
|
+
if (part && typeof part === "object" && part.type === "toolCall" && typeof part.id === "string") {
|
|
30936
|
+
ids.push(part.id);
|
|
30937
|
+
}
|
|
30938
|
+
}
|
|
30939
|
+
return ids;
|
|
30940
|
+
}
|
|
30941
|
+
function getPiToolResultCallId(message) {
|
|
30942
|
+
const callId = message.toolCallId;
|
|
30943
|
+
return typeof callId === "string" && callId.length > 0 ? callId : null;
|
|
30944
|
+
}
|
|
30945
|
+
|
|
30946
|
+
// src/pi-history-retirement.ts
|
|
30947
|
+
var KEY2 = "piHistorianRetirement";
|
|
30948
|
+
function readState2(db, sessionId) {
|
|
30949
|
+
const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
30950
|
+
const state = row?.state ? JSON.parse(row.state) : {};
|
|
30951
|
+
if (!state || typeof state !== "object" || Array.isArray(state))
|
|
30952
|
+
throw new Error("Invalid session metadata JSON");
|
|
30953
|
+
return state;
|
|
30954
|
+
}
|
|
30955
|
+
function readPiHistoryRetirement(db, sessionId) {
|
|
30956
|
+
const target = readState2(db, sessionId)[KEY2];
|
|
30957
|
+
return typeof target === "string" && target.length > 0 ? target : null;
|
|
30958
|
+
}
|
|
30959
|
+
function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
|
|
30960
|
+
ensureSessionMetaRow(db, sessionId);
|
|
30961
|
+
const state = readState2(db, sessionId);
|
|
30962
|
+
state[KEY2] = throughMessageId;
|
|
30963
|
+
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30964
|
+
}
|
|
30965
|
+
function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
|
|
30966
|
+
const state = readState2(db, sessionId);
|
|
30967
|
+
const target = state[KEY2];
|
|
30968
|
+
if (typeof target !== "string")
|
|
30969
|
+
return;
|
|
30970
|
+
const ordinal = ordinalOf(target);
|
|
30971
|
+
if (ordinal === undefined || ordinal > publishedEnd)
|
|
30972
|
+
return;
|
|
30973
|
+
delete state[KEY2];
|
|
30974
|
+
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30975
|
+
}
|
|
30976
|
+
|
|
30755
30977
|
// src/pi-historian-runner.ts
|
|
30756
30978
|
var HISTORIAN_AGENT_NAME = "magic-context-historian";
|
|
30757
30979
|
var DEFAULT_HISTORIAN_TIMEOUT_MS2 = 600000;
|
|
@@ -31475,9 +31697,7 @@ ${chunkText}`,
|
|
|
31475
31697
|
let firstKeptEntryId = null;
|
|
31476
31698
|
if (readBranchEntries) {
|
|
31477
31699
|
try {
|
|
31478
|
-
|
|
31479
|
-
const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
|
|
31480
|
-
firstKeptEntryId = isPiOrdinalAlignmentUnanchored(alignment) ? null : findFirstKeptEntryId(branchEntries, lastNewEnd, alignment.offset);
|
|
31700
|
+
firstKeptEntryId = lastNewEndMessageId ? placePiMarkerKeptEntry(db, sessionId, readBranchEntries(), lastNewEndMessageId, lastNewEnd) : null;
|
|
31481
31701
|
if (!firstKeptEntryId) {
|
|
31482
31702
|
sessionLog2(sessionId, `historian: native compaction marker waiting; no resolvable firstKeptEntryId at or after ordinal ${lastNewEnd + 1}`);
|
|
31483
31703
|
}
|
|
@@ -31789,6 +32009,17 @@ function buildPiCompactionSummary(compartments) {
|
|
|
31789
32009
|
const shown = titles.slice(0, MAX_SUMMARY_TITLES).join("; ");
|
|
31790
32010
|
return `Magic Context compacted ${titles.length} segments: ${shown}; …and ${titles.length - MAX_SUMMARY_TITLES} more`;
|
|
31791
32011
|
}
|
|
32012
|
+
function placePiMarkerKeptEntry(db, sessionId, branchEntries, endMessageId, endOrdinal) {
|
|
32013
|
+
const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
|
|
32014
|
+
if (isPiOrdinalAlignmentUnanchored(alignment))
|
|
32015
|
+
return null;
|
|
32016
|
+
const kept = resolvePiMarkerKeptEntry(branchEntries, endMessageId);
|
|
32017
|
+
if (kept.kind === "resolved")
|
|
32018
|
+
return kept.entryId;
|
|
32019
|
+
if (kept.kind === "waiting")
|
|
32020
|
+
return null;
|
|
32021
|
+
return findFirstKeptEntryId(branchEntries, endOrdinal, alignment.offset);
|
|
32022
|
+
}
|
|
31792
32023
|
function findFirstKeptEntryId(entries, lastCompactedOrdinal, ordinalOffset = 0) {
|
|
31793
32024
|
const boundary = resolvePiFirstKeptEntry(entries, lastCompactedOrdinal, ordinalOffset);
|
|
31794
32025
|
return boundary.kind === "resolved" ? boundary.entryId : null;
|
|
@@ -31901,7 +32132,13 @@ function applyDeferredPiCompactionMarker(deps, sessionId, pending) {
|
|
|
31901
32132
|
}
|
|
31902
32133
|
const branchEntries = deps.readBranchEntries();
|
|
31903
32134
|
let firstKeptEntryId = pending.firstKeptEntryId;
|
|
31904
|
-
|
|
32135
|
+
let placedByCut = false;
|
|
32136
|
+
const kept = resolvePiMarkerKeptEntry(branchEntries, pending.endMessageId);
|
|
32137
|
+
if (kept.kind !== "missing" && !isPiOrdinalAlignmentUnanchored(resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries))) {
|
|
32138
|
+
placedByCut = true;
|
|
32139
|
+
firstKeptEntryId = kept.kind === "resolved" ? kept.entryId : null;
|
|
32140
|
+
}
|
|
32141
|
+
if (!placedByCut && !firstKeptEntryId) {
|
|
31905
32142
|
const alignment = resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries);
|
|
31906
32143
|
if (isPiOrdinalAlignmentUnanchored(alignment)) {
|
|
31907
32144
|
if (alignment.kind === "unanchored" && alignment.reason === "anchor-missing" && hasMergedSyntheticBoundary(branchEntries, pending.endMessageId)) {
|
|
@@ -34933,64 +35170,10 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
|
|
|
34933
35170
|
}
|
|
34934
35171
|
if (cutoffIndex < 0)
|
|
34935
35172
|
return 0;
|
|
34936
|
-
const
|
|
34937
|
-
let preserved = 0;
|
|
34938
|
-
for (let i = 0;i <= cutoffIndex; i++) {
|
|
34939
|
-
if (isPiSystemEntry(piMessages[i]))
|
|
34940
|
-
preserved++;
|
|
34941
|
-
else
|
|
34942
|
-
remove.add(i);
|
|
34943
|
-
}
|
|
35173
|
+
const preserved = piMessages.slice(0, cutoffIndex + 1).filter((message) => isPiSystemEntry(message)).length;
|
|
34944
35174
|
if (preserved > 0)
|
|
34945
35175
|
sessionLog2(sessionId ?? "unknown", `pi system entries preserved across fold: ${preserved}`);
|
|
34946
|
-
|
|
34947
|
-
while (changed) {
|
|
34948
|
-
changed = false;
|
|
34949
|
-
const removedCallKeys = new Set;
|
|
34950
|
-
const removedResultKeys = new Set;
|
|
34951
|
-
for (const index of remove) {
|
|
34952
|
-
const msg = piMessages[index];
|
|
34953
|
-
if (!msg)
|
|
34954
|
-
continue;
|
|
34955
|
-
if (msg.role === "assistant") {
|
|
34956
|
-
for (const callId of getPiToolCallIds(msg)) {
|
|
34957
|
-
removedCallKeys.add(toolPairKey(callId, index));
|
|
34958
|
-
}
|
|
34959
|
-
} else if (msg.role === "toolResult") {
|
|
34960
|
-
const callId = getPiToolResultCallId(msg);
|
|
34961
|
-
const ownerIndex = callId ? findToolResultOwnerAssistantIndex(piMessages, index, callId) : null;
|
|
34962
|
-
if (callId && ownerIndex !== null) {
|
|
34963
|
-
removedResultKeys.add(toolPairKey(callId, ownerIndex));
|
|
34964
|
-
}
|
|
34965
|
-
}
|
|
34966
|
-
}
|
|
34967
|
-
for (let i = 0;i < piMessages.length; i++) {
|
|
34968
|
-
if (remove.has(i))
|
|
34969
|
-
continue;
|
|
34970
|
-
const msg = piMessages[i];
|
|
34971
|
-
if (!msg)
|
|
34972
|
-
continue;
|
|
34973
|
-
if (msg.role === "toolResult") {
|
|
34974
|
-
const callId = getPiToolResultCallId(msg);
|
|
34975
|
-
const ownerIndex = callId ? findToolResultOwnerAssistantIndex(piMessages, i, callId) : null;
|
|
34976
|
-
if (callId && ownerIndex !== null && removedCallKeys.has(toolPairKey(callId, ownerIndex))) {
|
|
34977
|
-
remove.add(i);
|
|
34978
|
-
changed = true;
|
|
34979
|
-
}
|
|
34980
|
-
continue;
|
|
34981
|
-
}
|
|
34982
|
-
if (msg.role === "assistant") {
|
|
34983
|
-
const callIds = getPiToolCallIds(msg);
|
|
34984
|
-
if (callIds.some((callId) => removedResultKeys.has(toolPairKey(callId, i)))) {
|
|
34985
|
-
remove.add(i);
|
|
34986
|
-
changed = true;
|
|
34987
|
-
}
|
|
34988
|
-
}
|
|
34989
|
-
}
|
|
34990
|
-
}
|
|
34991
|
-
const keptPrompt = keptPromptIndex(piMessages, cutoffIndex, remove, promptReachesBoundary);
|
|
34992
|
-
if (keptPrompt >= 0)
|
|
34993
|
-
remove.delete(keptPrompt);
|
|
35176
|
+
const remove = planPiHistoryCut(piMessages, cutoffIndex, promptReachesBoundary);
|
|
34994
35177
|
const retiredIds = new Set;
|
|
34995
35178
|
if (retireDecisions) {
|
|
34996
35179
|
for (const index of remove) {
|
|
@@ -35071,29 +35254,6 @@ function placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, session
|
|
|
35071
35254
|
}
|
|
35072
35255
|
};
|
|
35073
35256
|
}
|
|
35074
|
-
function keptPromptIndex(piMessages, cutoffIndex, removed, promptReachesBoundary) {
|
|
35075
|
-
let promptIndex = -1;
|
|
35076
|
-
for (let i = cutoffIndex;i >= 0; i--) {
|
|
35077
|
-
if (piMessages[i]?.role === "user") {
|
|
35078
|
-
promptIndex = i;
|
|
35079
|
-
break;
|
|
35080
|
-
}
|
|
35081
|
-
}
|
|
35082
|
-
if (promptIndex < 0)
|
|
35083
|
-
return -1;
|
|
35084
|
-
for (let i = cutoffIndex + 1;i < piMessages.length; i++) {
|
|
35085
|
-
if (removed.has(i))
|
|
35086
|
-
continue;
|
|
35087
|
-
const message = piMessages[i];
|
|
35088
|
-
if (message?.role === "user")
|
|
35089
|
-
return -1;
|
|
35090
|
-
if (message?.role === "assistant" && message.stopReason !== "error")
|
|
35091
|
-
break;
|
|
35092
|
-
}
|
|
35093
|
-
if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
|
|
35094
|
-
return -1;
|
|
35095
|
-
return promptIndex;
|
|
35096
|
-
}
|
|
35097
35257
|
var idCutBoundaryByMessages = new WeakMap;
|
|
35098
35258
|
var unplacedCutLoggedSessions = new Set;
|
|
35099
35259
|
function resetPiUnplacedCutLog(sessionId) {
|
|
@@ -35105,39 +35265,6 @@ function logUnplacedCut(sessionId, boundaryMessageId, eventLength, reason, first
|
|
|
35105
35265
|
unplacedCutLoggedSessions.add(sessionId);
|
|
35106
35266
|
sessionLog2(sessionId, `pi history cut not placed: boundary ${boundaryMessageId} is not among the ${eventLength} context messages and ${reason}; first message without a branch position: ${firstUnplacedRole}; nothing was cut at this boundary`);
|
|
35107
35267
|
}
|
|
35108
|
-
function toolPairKey(callId, assistantIndex) {
|
|
35109
|
-
return `${callId}\x00${assistantIndex}`;
|
|
35110
|
-
}
|
|
35111
|
-
function findToolResultOwnerAssistantIndex(messages, resultIndex, callId) {
|
|
35112
|
-
for (let i = resultIndex - 1;i >= 0; i--) {
|
|
35113
|
-
const msg = messages[i];
|
|
35114
|
-
if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
|
|
35115
|
-
return i;
|
|
35116
|
-
}
|
|
35117
|
-
}
|
|
35118
|
-
for (let i = resultIndex + 1;i < messages.length; i++) {
|
|
35119
|
-
const msg = messages[i];
|
|
35120
|
-
if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
|
|
35121
|
-
return i;
|
|
35122
|
-
}
|
|
35123
|
-
}
|
|
35124
|
-
return null;
|
|
35125
|
-
}
|
|
35126
|
-
function getPiToolCallIds(message) {
|
|
35127
|
-
if (!Array.isArray(message.content))
|
|
35128
|
-
return [];
|
|
35129
|
-
const ids = [];
|
|
35130
|
-
for (const part of message.content) {
|
|
35131
|
-
if (part && typeof part === "object" && part.type === "toolCall" && typeof part.id === "string") {
|
|
35132
|
-
ids.push(part.id);
|
|
35133
|
-
}
|
|
35134
|
-
}
|
|
35135
|
-
return ids;
|
|
35136
|
-
}
|
|
35137
|
-
function getPiToolResultCallId(message) {
|
|
35138
|
-
const callId = message.toolCallId;
|
|
35139
|
-
return typeof callId === "string" && callId.length > 0 ? callId : null;
|
|
35140
|
-
}
|
|
35141
35268
|
var PI_M1_PLACEHOLDER = "<session-history-since>(no new content since last materialization)</session-history-since>";
|
|
35142
35269
|
var MAX_FORCED_MEMORIES_PER_DELTA = 10;
|
|
35143
35270
|
var PI_M0_UPGRADE_STATE = "pi-m0m1-v2";
|
|
@@ -43538,6 +43665,160 @@ function safeJsonStringify2(value) {
|
|
|
43538
43665
|
}
|
|
43539
43666
|
}
|
|
43540
43667
|
|
|
43668
|
+
// src/strip-processed-images-pi.ts
|
|
43669
|
+
var STRIPPED_IMAGE_MARKER = "[image stripped]";
|
|
43670
|
+
function isLargeImagePart(value) {
|
|
43671
|
+
if (!value || typeof value !== "object")
|
|
43672
|
+
return false;
|
|
43673
|
+
const part = value;
|
|
43674
|
+
return part.type === "image" && typeof part.mimeType === "string" && part.mimeType.startsWith("image/") && typeof part.data === "string" && part.data.length > 200;
|
|
43675
|
+
}
|
|
43676
|
+
var PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
|
|
43677
|
+
var PI_NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
|
|
43678
|
+
function piModelAcceptsImages(model) {
|
|
43679
|
+
const input = model?.input;
|
|
43680
|
+
return !Array.isArray(input) || input.includes("image");
|
|
43681
|
+
}
|
|
43682
|
+
function piImageWirePlaceholder(args) {
|
|
43683
|
+
if (args.block?.type !== "image")
|
|
43684
|
+
return;
|
|
43685
|
+
if (args.stripped && isLargeImagePart(args.block))
|
|
43686
|
+
return STRIPPED_IMAGE_MARKER;
|
|
43687
|
+
if (!args.modelAcceptsImages)
|
|
43688
|
+
return args.role === "toolResult" ? PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER : PI_NON_VISION_USER_IMAGE_PLACEHOLDER;
|
|
43689
|
+
return;
|
|
43690
|
+
}
|
|
43691
|
+
function piToolImageWireTokens(args) {
|
|
43692
|
+
const placeholder = piImageWirePlaceholder({ ...args, role: "toolResult" });
|
|
43693
|
+
return placeholder === undefined ? PI_IMAGE_TOKENS : estimateTokens(placeholder);
|
|
43694
|
+
}
|
|
43695
|
+
function piMessagesWithWireImages(messages, args) {
|
|
43696
|
+
if (args.modelAcceptsImages && !args.strippedMessage)
|
|
43697
|
+
return messages;
|
|
43698
|
+
let changed = false;
|
|
43699
|
+
const sent = messages.map((raw, index) => {
|
|
43700
|
+
const message = raw;
|
|
43701
|
+
if (!message || typeof message !== "object")
|
|
43702
|
+
return raw;
|
|
43703
|
+
const content = message.content;
|
|
43704
|
+
if (!Array.isArray(content))
|
|
43705
|
+
return raw;
|
|
43706
|
+
let stripped;
|
|
43707
|
+
let replaced;
|
|
43708
|
+
for (let partIndex = 0;partIndex < content.length; partIndex++) {
|
|
43709
|
+
const block = content[partIndex];
|
|
43710
|
+
if (block?.type !== "image")
|
|
43711
|
+
continue;
|
|
43712
|
+
stripped ??= args.strippedMessage?.(raw, index) ?? false;
|
|
43713
|
+
const placeholder = piImageWirePlaceholder({
|
|
43714
|
+
block,
|
|
43715
|
+
role: message.role,
|
|
43716
|
+
stripped,
|
|
43717
|
+
modelAcceptsImages: args.modelAcceptsImages
|
|
43718
|
+
});
|
|
43719
|
+
if (placeholder === undefined)
|
|
43720
|
+
continue;
|
|
43721
|
+
replaced ??= content.slice();
|
|
43722
|
+
replaced[partIndex] = { type: "text", text: placeholder };
|
|
43723
|
+
}
|
|
43724
|
+
if (!replaced)
|
|
43725
|
+
return raw;
|
|
43726
|
+
changed = true;
|
|
43727
|
+
return { ...message, content: replaced };
|
|
43728
|
+
});
|
|
43729
|
+
return changed ? sent : messages;
|
|
43730
|
+
}
|
|
43731
|
+
function planPiProcessedImageIds(args, frozenIds) {
|
|
43732
|
+
if (!args.detect || args.watermark <= 0)
|
|
43733
|
+
return [];
|
|
43734
|
+
const ids = args.messages.map(args.stableId);
|
|
43735
|
+
const ownTags = ids.map((id) => id ? args.messageIdToMaxTag.get(id) ?? 0 : 0);
|
|
43736
|
+
const completeToolResults = new Set;
|
|
43737
|
+
const openCalls = new Map;
|
|
43738
|
+
for (let i = 0;i < args.messages.length; i++) {
|
|
43739
|
+
const message = args.messages[i];
|
|
43740
|
+
if (!message || typeof message !== "object")
|
|
43741
|
+
continue;
|
|
43742
|
+
if (message.role === "assistant" && Array.isArray(message.content)) {
|
|
43743
|
+
for (const part of message.content) {
|
|
43744
|
+
if (part?.type === "toolCall" && typeof part.id === "string") {
|
|
43745
|
+
openCalls.set(part.id, `${ids[i] ?? ""}\x00${part.id}`);
|
|
43746
|
+
}
|
|
43747
|
+
}
|
|
43748
|
+
} else if (message.role === "toolResult" && message.toolCallId) {
|
|
43749
|
+
const key = openCalls.get(message.toolCallId);
|
|
43750
|
+
if (key !== undefined && !args.protectedToolKeys?.has(key) && !args.protectedToolKeys?.has(message.toolCallId)) {
|
|
43751
|
+
completeToolResults.add(i);
|
|
43752
|
+
}
|
|
43753
|
+
openCalls.delete(message.toolCallId);
|
|
43754
|
+
}
|
|
43755
|
+
}
|
|
43756
|
+
const selected = [];
|
|
43757
|
+
let hasAssistantResponse = false;
|
|
43758
|
+
let nextTag;
|
|
43759
|
+
for (let i = args.messages.length - 1;i >= 0; i--) {
|
|
43760
|
+
const ownTag = ownTags[i];
|
|
43761
|
+
const positionTag = ownTag > 0 ? ownTag : nextTag;
|
|
43762
|
+
if (ownTag > 0)
|
|
43763
|
+
nextTag = ownTag;
|
|
43764
|
+
const raw = args.messages[i];
|
|
43765
|
+
if (!raw || typeof raw !== "object")
|
|
43766
|
+
continue;
|
|
43767
|
+
const message = raw;
|
|
43768
|
+
if (message.role === "assistant") {
|
|
43769
|
+
hasAssistantResponse = true;
|
|
43770
|
+
continue;
|
|
43771
|
+
}
|
|
43772
|
+
if (message.role !== "user" && message.role !== "toolResult" || message.role === "toolResult" && !completeToolResults.has(i) || !hasAssistantResponse || !Array.isArray(message.content) || !message.content.some(isLargeImagePart))
|
|
43773
|
+
continue;
|
|
43774
|
+
const id = ids[i];
|
|
43775
|
+
if (!id || frozenIds.has(id) || positionTag === undefined || positionTag > args.watermark)
|
|
43776
|
+
continue;
|
|
43777
|
+
if ((args.usagePercentage ?? 0) < 95 && positionTag >= (args.protectedCutoff ?? Infinity))
|
|
43778
|
+
continue;
|
|
43779
|
+
selected.push(id);
|
|
43780
|
+
}
|
|
43781
|
+
return selected;
|
|
43782
|
+
}
|
|
43783
|
+
function stripPiProcessedImages(args) {
|
|
43784
|
+
const frozenIds = getProcessedImageStrippedIds(args.db, args.sessionId);
|
|
43785
|
+
const newlyStrippedIds = planPiProcessedImageIds(args, frozenIds);
|
|
43786
|
+
if (newlyStrippedIds.length > 0) {
|
|
43787
|
+
const persisted = (args.addIds ?? addProcessedImageStrippedIds)(args.db, args.sessionId, newlyStrippedIds);
|
|
43788
|
+
if (persisted) {
|
|
43789
|
+
for (const id of newlyStrippedIds)
|
|
43790
|
+
frozenIds.add(id);
|
|
43791
|
+
} else {
|
|
43792
|
+
newlyStrippedIds.length = 0;
|
|
43793
|
+
sessionLog2(args.sessionId, "processed-image strip: persistence failed; leaving newly detected images intact");
|
|
43794
|
+
}
|
|
43795
|
+
}
|
|
43796
|
+
let stripped = 0;
|
|
43797
|
+
for (let i = 0;i < args.messages.length; i++) {
|
|
43798
|
+
const raw = args.messages[i];
|
|
43799
|
+
if (!raw || typeof raw !== "object")
|
|
43800
|
+
continue;
|
|
43801
|
+
const id = args.stableId(raw, i);
|
|
43802
|
+
if (!id || !frozenIds.has(id))
|
|
43803
|
+
continue;
|
|
43804
|
+
const message = raw;
|
|
43805
|
+
if (!Array.isArray(message.content))
|
|
43806
|
+
continue;
|
|
43807
|
+
for (let partIndex = 0;partIndex < message.content.length; partIndex++) {
|
|
43808
|
+
if (!isLargeImagePart(message.content[partIndex]))
|
|
43809
|
+
continue;
|
|
43810
|
+
if (newlyStrippedIds.includes(id))
|
|
43811
|
+
args.onFirstApplication?.(raw, i, partIndex);
|
|
43812
|
+
message.content[partIndex] = {
|
|
43813
|
+
type: "text",
|
|
43814
|
+
text: STRIPPED_IMAGE_MARKER
|
|
43815
|
+
};
|
|
43816
|
+
stripped++;
|
|
43817
|
+
}
|
|
43818
|
+
}
|
|
43819
|
+
return { stripped, newlyStrippedIds };
|
|
43820
|
+
}
|
|
43821
|
+
|
|
43541
43822
|
// src/pi-raw-fallback.ts
|
|
43542
43823
|
class PiStorageBusyError extends Error {
|
|
43543
43824
|
code = "PI_STORAGE_BUSY";
|
|
@@ -43569,9 +43850,24 @@ function piFallbackRefusal(site, cause) {
|
|
|
43569
43850
|
}
|
|
43570
43851
|
return cause instanceof PiDegradedPassError ? cause : new PiDegradedPassError(site, { cause });
|
|
43571
43852
|
}
|
|
43572
|
-
function
|
|
43853
|
+
function piSentMessages(messages, observed) {
|
|
43854
|
+
return piMessagesWithWireImages(messages, {
|
|
43855
|
+
modelAcceptsImages: observed?.modelAcceptsImages !== false
|
|
43856
|
+
});
|
|
43857
|
+
}
|
|
43858
|
+
function piSentMeasuredPrefix(measuredPrefix, observed) {
|
|
43859
|
+
if (!measuredPrefix || observed?.modelAcceptsImages !== false)
|
|
43860
|
+
return measuredPrefix;
|
|
43861
|
+
return {
|
|
43862
|
+
...measuredPrefix,
|
|
43863
|
+
appendedMessages: piSentMessages(measuredPrefix.appendedMessages, observed)
|
|
43864
|
+
};
|
|
43865
|
+
}
|
|
43866
|
+
function estimatePiOutgoingInputTokens(servedMessages, observed, servedMeasuredPrefix, contextLimit, tokenCounts) {
|
|
43573
43867
|
if (!observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || !hasTokenizerForFit())
|
|
43574
43868
|
return { tokens: 0, trusted: false };
|
|
43869
|
+
const messages = piSentMessages(servedMessages, observed);
|
|
43870
|
+
const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
|
|
43575
43871
|
const knownRole = (message) => {
|
|
43576
43872
|
if (!message || typeof message !== "object")
|
|
43577
43873
|
return false;
|
|
@@ -43708,7 +44004,9 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
|
|
|
43708
44004
|
refusalBasis: refusalGrade ? measured ? "provider-prefix" : "calibrated" : undefined
|
|
43709
44005
|
};
|
|
43710
44006
|
}
|
|
43711
|
-
function assertPiRawFallbackFits(
|
|
44007
|
+
function assertPiRawFallbackFits(servedMessages, contextLimit, log, cause, observed, servedMeasuredPrefix) {
|
|
44008
|
+
const messages = piSentMessages(servedMessages, observed);
|
|
44009
|
+
const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
|
|
43712
44010
|
if (!contextLimit || !Number.isFinite(contextLimit) || !observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || observed.envelopeBytes !== undefined && (!Number.isFinite(observed.envelopeBytes) || observed.envelopeBytes < 0)) {
|
|
43713
44011
|
log("raw_fallback_refused completeness=partial");
|
|
43714
44012
|
throw piFallbackRefusal("fallback-metadata-incomplete", cause);
|
|
@@ -44648,7 +44946,8 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
|
44648
44946
|
toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
|
|
44649
44947
|
envelopeBytes: Buffer.byteLength(envelopeJson),
|
|
44650
44948
|
envelopeSignature: activeNames ? createHash18("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
|
|
44651
|
-
calibration
|
|
44949
|
+
calibration,
|
|
44950
|
+
...piModelAcceptsImages(ctx.model) ? {} : { modelAcceptsImages: false }
|
|
44652
44951
|
};
|
|
44653
44952
|
} catch {
|
|
44654
44953
|
return;
|
|
@@ -45391,9 +45690,12 @@ function piToolResultImageTokens(messages, priceImage) {
|
|
|
45391
45690
|
}
|
|
45392
45691
|
return counts;
|
|
45393
45692
|
}
|
|
45394
|
-
function estimatePiOverflowRecoveryInputTokens(
|
|
45693
|
+
function estimatePiOverflowRecoveryInputTokens(servedMessages, envelope, options = {}) {
|
|
45395
45694
|
if (!envelope || !estimatePiOutgoingInputTokens([], envelope).trusted)
|
|
45396
45695
|
return;
|
|
45696
|
+
const messages = piMessagesWithWireImages(servedMessages, {
|
|
45697
|
+
modelAcceptsImages: envelope.modelAcceptsImages !== false
|
|
45698
|
+
});
|
|
45397
45699
|
const raw = tokenizePiMessages([...messages]);
|
|
45398
45700
|
for (const value of messages) {
|
|
45399
45701
|
if (!value || typeof value !== "object")
|
|
@@ -47094,105 +47396,6 @@ function stripPiDroppedPlaceholderMessages(args) {
|
|
|
47094
47396
|
return { removed, discovered };
|
|
47095
47397
|
}
|
|
47096
47398
|
|
|
47097
|
-
// src/strip-processed-images-pi.ts
|
|
47098
|
-
var STRIPPED_IMAGE_MARKER = "[image stripped]";
|
|
47099
|
-
function isLargeImagePart(value) {
|
|
47100
|
-
if (!value || typeof value !== "object")
|
|
47101
|
-
return false;
|
|
47102
|
-
const part = value;
|
|
47103
|
-
return part.type === "image" && typeof part.mimeType === "string" && part.mimeType.startsWith("image/") && typeof part.data === "string" && part.data.length > 200;
|
|
47104
|
-
}
|
|
47105
|
-
function planPiProcessedImageIds(args, frozenIds) {
|
|
47106
|
-
if (!args.detect || args.watermark <= 0)
|
|
47107
|
-
return [];
|
|
47108
|
-
const ids = args.messages.map(args.stableId);
|
|
47109
|
-
const ownTags = ids.map((id) => id ? args.messageIdToMaxTag.get(id) ?? 0 : 0);
|
|
47110
|
-
const completeToolResults = new Set;
|
|
47111
|
-
const openCalls = new Map;
|
|
47112
|
-
for (let i = 0;i < args.messages.length; i++) {
|
|
47113
|
-
const message = args.messages[i];
|
|
47114
|
-
if (!message || typeof message !== "object")
|
|
47115
|
-
continue;
|
|
47116
|
-
if (message.role === "assistant" && Array.isArray(message.content)) {
|
|
47117
|
-
for (const part of message.content) {
|
|
47118
|
-
if (part?.type === "toolCall" && typeof part.id === "string") {
|
|
47119
|
-
openCalls.set(part.id, `${ids[i] ?? ""}\x00${part.id}`);
|
|
47120
|
-
}
|
|
47121
|
-
}
|
|
47122
|
-
} else if (message.role === "toolResult" && message.toolCallId) {
|
|
47123
|
-
const key = openCalls.get(message.toolCallId);
|
|
47124
|
-
if (key !== undefined && !args.protectedToolKeys?.has(key) && !args.protectedToolKeys?.has(message.toolCallId)) {
|
|
47125
|
-
completeToolResults.add(i);
|
|
47126
|
-
}
|
|
47127
|
-
openCalls.delete(message.toolCallId);
|
|
47128
|
-
}
|
|
47129
|
-
}
|
|
47130
|
-
const selected = [];
|
|
47131
|
-
let hasAssistantResponse = false;
|
|
47132
|
-
let nextTag;
|
|
47133
|
-
for (let i = args.messages.length - 1;i >= 0; i--) {
|
|
47134
|
-
const ownTag = ownTags[i];
|
|
47135
|
-
const positionTag = ownTag > 0 ? ownTag : nextTag;
|
|
47136
|
-
if (ownTag > 0)
|
|
47137
|
-
nextTag = ownTag;
|
|
47138
|
-
const raw = args.messages[i];
|
|
47139
|
-
if (!raw || typeof raw !== "object")
|
|
47140
|
-
continue;
|
|
47141
|
-
const message = raw;
|
|
47142
|
-
if (message.role === "assistant") {
|
|
47143
|
-
hasAssistantResponse = true;
|
|
47144
|
-
continue;
|
|
47145
|
-
}
|
|
47146
|
-
if (message.role !== "user" && message.role !== "toolResult" || message.role === "toolResult" && !completeToolResults.has(i) || !hasAssistantResponse || !Array.isArray(message.content) || !message.content.some(isLargeImagePart))
|
|
47147
|
-
continue;
|
|
47148
|
-
const id = ids[i];
|
|
47149
|
-
if (!id || frozenIds.has(id) || positionTag === undefined || positionTag > args.watermark)
|
|
47150
|
-
continue;
|
|
47151
|
-
if ((args.usagePercentage ?? 0) < 95 && positionTag >= (args.protectedCutoff ?? Infinity))
|
|
47152
|
-
continue;
|
|
47153
|
-
selected.push(id);
|
|
47154
|
-
}
|
|
47155
|
-
return selected;
|
|
47156
|
-
}
|
|
47157
|
-
function stripPiProcessedImages(args) {
|
|
47158
|
-
const frozenIds = getProcessedImageStrippedIds(args.db, args.sessionId);
|
|
47159
|
-
const newlyStrippedIds = planPiProcessedImageIds(args, frozenIds);
|
|
47160
|
-
if (newlyStrippedIds.length > 0) {
|
|
47161
|
-
const persisted = (args.addIds ?? addProcessedImageStrippedIds)(args.db, args.sessionId, newlyStrippedIds);
|
|
47162
|
-
if (persisted) {
|
|
47163
|
-
for (const id of newlyStrippedIds)
|
|
47164
|
-
frozenIds.add(id);
|
|
47165
|
-
} else {
|
|
47166
|
-
newlyStrippedIds.length = 0;
|
|
47167
|
-
sessionLog2(args.sessionId, "processed-image strip: persistence failed; leaving newly detected images intact");
|
|
47168
|
-
}
|
|
47169
|
-
}
|
|
47170
|
-
let stripped = 0;
|
|
47171
|
-
for (let i = 0;i < args.messages.length; i++) {
|
|
47172
|
-
const raw = args.messages[i];
|
|
47173
|
-
if (!raw || typeof raw !== "object")
|
|
47174
|
-
continue;
|
|
47175
|
-
const id = args.stableId(raw, i);
|
|
47176
|
-
if (!id || !frozenIds.has(id))
|
|
47177
|
-
continue;
|
|
47178
|
-
const message = raw;
|
|
47179
|
-
if (!Array.isArray(message.content))
|
|
47180
|
-
continue;
|
|
47181
|
-
for (let partIndex = 0;partIndex < message.content.length; partIndex++) {
|
|
47182
|
-
if (!isLargeImagePart(message.content[partIndex]))
|
|
47183
|
-
continue;
|
|
47184
|
-
if (newlyStrippedIds.includes(id))
|
|
47185
|
-
args.onFirstApplication?.(raw, i, partIndex);
|
|
47186
|
-
message.content[partIndex] = {
|
|
47187
|
-
type: "text",
|
|
47188
|
-
text: STRIPPED_IMAGE_MARKER
|
|
47189
|
-
};
|
|
47190
|
-
stripped++;
|
|
47191
|
-
}
|
|
47192
|
-
}
|
|
47193
|
-
return { stripped, newlyStrippedIds };
|
|
47194
|
-
}
|
|
47195
|
-
|
|
47196
47399
|
// ../plugin/src/hooks/magic-context/system-prompt-dates.ts
|
|
47197
47400
|
function replaceHostDates(prompt, replace) {
|
|
47198
47401
|
const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
|
|
@@ -47364,6 +47567,8 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
|
|
|
47364
47567
|
toolRemovals.set(working, removals);
|
|
47365
47568
|
if (options.authorizeToolRemoval)
|
|
47366
47569
|
toolRemovalAuthorization.set(working, options.authorizeToolRemoval);
|
|
47570
|
+
if (options.toolImageTokens)
|
|
47571
|
+
toolImageTokenCost.set(working, options.toolImageTokens);
|
|
47367
47572
|
const emptyRemovedMessages = new Set;
|
|
47368
47573
|
const toolInputChanges = new Map;
|
|
47369
47574
|
const transcriptMessages = buildTranscriptView(working, sessionId, (messageIndex, toolCallId) => {
|
|
@@ -47835,7 +48040,10 @@ function createPiToolResultPart(working, messageIndex, partIndex, markDirty) {
|
|
|
47835
48040
|
kind,
|
|
47836
48041
|
id: msg.toolCallId,
|
|
47837
48042
|
imageTokens() {
|
|
47838
|
-
|
|
48043
|
+
if (working[messageIndex].content[partIndex]?.type !== "image")
|
|
48044
|
+
return 0;
|
|
48045
|
+
const cost = toolImageTokenCost.get(working);
|
|
48046
|
+
return cost ? cost(messageIndex, partIndex) : PI_IMAGE_TOKENS;
|
|
47839
48047
|
},
|
|
47840
48048
|
remove() {
|
|
47841
48049
|
return markToolRemoval(working, messageIndex, partIndex);
|
|
@@ -47934,6 +48142,7 @@ function extractStableId(msg, index, entryIds) {
|
|
|
47934
48142
|
}
|
|
47935
48143
|
var toolRemovals = new WeakMap;
|
|
47936
48144
|
var toolRemovalAuthorization = new WeakMap;
|
|
48145
|
+
var toolImageTokenCost = new WeakMap;
|
|
47937
48146
|
function markToolRemoval(working, messageIndex, partIndex) {
|
|
47938
48147
|
const removals = toolRemovals.get(working);
|
|
47939
48148
|
if (!removals)
|
|
@@ -48725,14 +48934,6 @@ function addPiBranchEntryToLookup(lookup, entry) {
|
|
|
48725
48934
|
else
|
|
48726
48935
|
lookup.entryIdsByFingerprint.set(fingerprint, [row.id]);
|
|
48727
48936
|
}
|
|
48728
|
-
function isPiContextEmitEligible(entry) {
|
|
48729
|
-
if (!entry || typeof entry !== "object")
|
|
48730
|
-
return false;
|
|
48731
|
-
const row = entry;
|
|
48732
|
-
if (typeof row.id !== "string")
|
|
48733
|
-
return false;
|
|
48734
|
-
return row.type === "message" || row.type === "custom_message" || row.type === "branch_summary" && typeof row.summary === "string" && row.summary.length > 0;
|
|
48735
|
-
}
|
|
48736
48937
|
function buildPiAlignedEntryIds(entries) {
|
|
48737
48938
|
const all = buildPiAlignedEntryIdsIncludingSystem(entries);
|
|
48738
48939
|
return { all, visible: buildPiAlignedVisibleEntryIds(entries) };
|
|
@@ -49956,7 +50157,8 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49956
50157
|
db: options.db,
|
|
49957
50158
|
sessionId,
|
|
49958
50159
|
branchEntries,
|
|
49959
|
-
assertCurrentPass
|
|
50160
|
+
assertCurrentPass,
|
|
50161
|
+
assertQueuedWrite: budget.assertDecisionPublication
|
|
49960
50162
|
});
|
|
49961
50163
|
let rawOrdinalCount;
|
|
49962
50164
|
let passOrdinalAlignment;
|
|
@@ -50534,6 +50736,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
50534
50736
|
resolvedProviderID: ctx.model?.provider,
|
|
50535
50737
|
resolvedModelID: ctx.model?.id,
|
|
50536
50738
|
providerApi: ctx.model?.api,
|
|
50739
|
+
modelAcceptsImages: piModelAcceptsImages(ctx.model),
|
|
50537
50740
|
canUseEmptySentinels,
|
|
50538
50741
|
temporalAwareness: options.injection?.temporalAwareness === true,
|
|
50539
50742
|
appendCompaction: guardedPiAppendCompaction(ctx, assertCurrentPass),
|
|
@@ -52493,6 +52696,12 @@ async function runPipeline(args) {
|
|
|
52493
52696
|
}
|
|
52494
52697
|
};
|
|
52495
52698
|
const tTranscriptBuild = performance.now();
|
|
52699
|
+
let frozenImageMessageIds;
|
|
52700
|
+
const imageStrippedMessage = (message, index) => {
|
|
52701
|
+
const id = stableIdResolver(message, index);
|
|
52702
|
+
frozenImageMessageIds ??= getProcessedImageStrippedIds(args.db, args.sessionId);
|
|
52703
|
+
return id !== undefined && frozenImageMessageIds.has(id);
|
|
52704
|
+
};
|
|
52496
52705
|
const transcript = createPiTranscript(args.messages, args.sessionId, args.messages.map(stableIdResolver), {
|
|
52497
52706
|
preserveReasoningToolArcs: args.reasoningClearing?.preserveReasoningToolArcs,
|
|
52498
52707
|
authorizeToolRemoval: (callId) => authorizePiToolRemoval({
|
|
@@ -52508,7 +52717,15 @@ async function runPipeline(args) {
|
|
|
52508
52717
|
callIds,
|
|
52509
52718
|
saved: nativeRemovalInputs,
|
|
52510
52719
|
canApply: isCacheBustingPass
|
|
52511
|
-
})
|
|
52720
|
+
}),
|
|
52721
|
+
toolImageTokens: (messageIndex, partIndex) => {
|
|
52722
|
+
const message = args.messages[messageIndex];
|
|
52723
|
+
return piToolImageWireTokens({
|
|
52724
|
+
block: Array.isArray(message?.content) ? message.content[partIndex] : undefined,
|
|
52725
|
+
stripped: imageStrippedMessage(message, messageIndex),
|
|
52726
|
+
modelAcceptsImages: args.modelAcceptsImages !== false
|
|
52727
|
+
});
|
|
52728
|
+
}
|
|
52512
52729
|
});
|
|
52513
52730
|
logTransformTiming(args.sessionId, "transcriptBuild", tTranscriptBuild);
|
|
52514
52731
|
const workingMessages = transcript.getWorkingMessages();
|
|
@@ -52943,7 +53160,13 @@ async function runPipeline(args) {
|
|
|
52943
53160
|
const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
|
|
52944
53161
|
const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
|
|
52945
53162
|
const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
|
|
52946
|
-
const emergencyToolImageTokens = () =>
|
|
53163
|
+
const emergencyToolImageTokens = () => {
|
|
53164
|
+
const sent = piMessagesWithWireImages(workingMessages, {
|
|
53165
|
+
modelAcceptsImages: args.modelAcceptsImages !== false,
|
|
53166
|
+
strippedMessage: imageStrippedMessage
|
|
53167
|
+
});
|
|
53168
|
+
return args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(sent) : piToolImageCostTokens(sent);
|
|
53169
|
+
};
|
|
52947
53170
|
const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, emergencyToolImageTokens()) : undefined;
|
|
52948
53171
|
mutationGateObserverForTests?.({
|
|
52949
53172
|
foldDue: foldDueDecision.value,
|
|
@@ -54217,25 +54440,20 @@ function makeMessage2(role, text) {
|
|
|
54217
54440
|
}
|
|
54218
54441
|
|
|
54219
54442
|
// src/pi-recomp-marker.ts
|
|
54220
|
-
function placeFirstKeptEntryId(db, sessionId, branchEntries,
|
|
54221
|
-
|
|
54222
|
-
if (isPiOrdinalAlignmentUnanchored(alignment))
|
|
54223
|
-
return null;
|
|
54224
|
-
return findFirstKeptEntryId(branchEntries, lastCompactedOrdinal, alignment.offset);
|
|
54443
|
+
function placeFirstKeptEntryId(db, sessionId, branchEntries, last) {
|
|
54444
|
+
return placePiMarkerKeptEntry(db, sessionId, branchEntries, last.endMessageId, last.endMessage);
|
|
54225
54445
|
}
|
|
54226
54446
|
function stagePiRecompMarker(args) {
|
|
54227
54447
|
const compartments = getCompartments(args.db, args.sessionId);
|
|
54228
54448
|
const last = compartments[compartments.length - 1];
|
|
54229
|
-
if (!last)
|
|
54449
|
+
if (!last || last.endMessageId.length === 0)
|
|
54230
54450
|
return;
|
|
54231
54451
|
let firstKeptEntryId = null;
|
|
54232
54452
|
try {
|
|
54233
|
-
firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last
|
|
54453
|
+
firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last);
|
|
54234
54454
|
} catch {
|
|
54235
54455
|
firstKeptEntryId = null;
|
|
54236
54456
|
}
|
|
54237
|
-
if (!firstKeptEntryId || last.endMessageId.length === 0)
|
|
54238
|
-
return;
|
|
54239
54457
|
setPendingPiCompactionMarkerState(args.db, args.sessionId, {
|
|
54240
54458
|
firstKeptEntryId,
|
|
54241
54459
|
endMessageId: last.endMessageId,
|