@cortexkit/opencode-magic-context 0.49.78 → 0.49.80
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 +2 -2
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-6pxdmpay.js → context-7rkrv5q8.js} +162 -68
- package/dist/{derive-budgets-def8genf.js → derive-budgets-2z6xxm7e.js} +1 -1
- package/dist/{embedding-backfill-rrmzvg7n.js → embedding-backfill-0tvprmrn.js} +1 -1
- package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts +1 -1
- package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts +5 -1
- package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-executor.d.ts +2 -0
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-backfill.d.ts +4 -0
- package/dist/features/magic-context/memory/embedding-backfill.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
- package/dist/{index-16h5fhem.js → index-177yv84k.js} +4 -6
- package/dist/{index-8mt6vvwx.js → index-2q0t43fy.js} +1 -1
- package/dist/{index-jfs6k0xk.js → index-9554nr2q.js} +6 -6
- package/dist/{index-kn23xzst.js → index-aawwdt26.js} +1 -1
- package/dist/{index-dcdk1thy.js → index-exvsw656.js} +7 -7
- package/dist/{index-7jj5jk78.js → index-ezgeq2z7.js} +5 -5
- package/dist/{index-xkn7vq89.js → index-hpmx99e9.js} +4 -4
- package/dist/{index-c3a833vk.js → index-jhhkb4jv.js} +2 -2
- package/dist/{index-cssarkg7.js → index-m4q6ptgz.js} +4 -4
- package/dist/{index-r865s8hf.js → index-m6rkq3t4.js} +1 -1
- package/dist/{index-1pfjvk89.js → index-mgvj4vkb.js} +7 -7
- package/dist/{index-ngwmx6nt.js → index-tky3j43e.js} +47 -5
- package/dist/{index-k6b1av2m.js → index-twmeey4h.js} +2 -2
- package/dist/{index-enpatj5k.js → index-v0epndb8.js} +7 -7
- package/dist/{index-c7xvvhdd.js → index-xjpemea9.js} +115 -68
- package/dist/{index-rjm4hjyb.js → index-xsdaz3mq.js} +1 -1
- package/dist/{index-bdnak4d0.js → index-y208s7zx.js} +5 -3
- package/dist/{index-72qk8fs8.js → index-zpd4pxnp.js} +13 -8
- package/dist/{index-vr6t0y4w.js → index-zzvd4a9z.js} +1 -1
- package/dist/index.js +21 -21
- package/dist/{message-index-bounded-s0bckzqz.js → message-index-bounded-cfkeyf72.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-kqyb1y8c.js → read-session-chunk-s3qac56g.js} +2 -2
- package/dist/{recomp-orchestrator-38ed4yhj.js → recomp-orchestrator-n7h0a0tn.js} +10 -10
- package/dist/{render-8s531gd5.js → render-bjxgkrk6.js} +6 -6
- package/dist/{search-archive-2f1j2dh8.js → search-archive-p3jhx9wc.js} +4 -4
- package/dist/{search-m4r4v4aw.js → search-z56487n8.js} +7 -7
- package/dist/shared/models-dev-cache.d.ts +2 -0
- package/dist/shared/models-dev-cache.d.ts.map +1 -1
- package/dist/shared/subagent-runner.d.ts +9 -0
- package/dist/shared/subagent-runner.d.ts.map +1 -1
- package/dist/{storage-tags-d3nqrva7.js → storage-tags-6e83pvff.js} +1 -1
- package/dist/{store-j5rvve3v.js → store-8trkpmtx.js} +3 -1
- package/dist/{transform-postprocess-phase-ch5fsw7h.js → transform-postprocess-phase-f0wssyce.js} +11 -11
- package/dist/v2/auto-search-worker.js +2 -2
- package/dist/v2/chunk-embedding-write-worker.js +2 -2
- package/dist/v2/{context-h3r9gxrd.js → context-r1swhysg.js} +256 -119
- package/dist/v2/{derive-budgets-z93fdnp7.js → derive-budgets-2eam671q.js} +2 -2
- package/dist/v2/{embedding-backfill-g9scycm5.js → embedding-backfill-qnaswpmb.js} +1 -1
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/fold/owner.d.ts +2 -4
- package/dist/v2/fold/owner.d.ts.map +1 -1
- package/dist/v2/fold/partial-boundary.d.ts +25 -0
- package/dist/v2/fold/partial-boundary.d.ts.map +1 -0
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-vfx2zx9y.js → message-index-bounded-0xy4dn04.js} +3 -3
- package/dist/v2/migration-worker.js +2 -2
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-bh402br0.js → read-session-chunk-6mt2t6dy.js} +2 -2
- package/dist/v2/{recomp-orchestrator-43grkr1k.js → recomp-orchestrator-4w2w4kd4.js} +12 -12
- package/dist/v2/{render-90pve6jf.js → render-hwqk0d8t.js} +7 -7
- package/dist/v2/{search-archive-ha08g13n.js → search-archive-mdxzvgpm.js} +4 -4
- package/dist/v2/{search-xr5wb3a3.js → search-eftsvbg7.js} +6 -6
- package/dist/v2/{server-86vydsx9.js → server-0dmzr7f9.js} +2 -2
- package/dist/v2/{server-kmaxv4g3.js → server-25qtxt4d.js} +6 -6
- package/dist/v2/{server-6jxvkyrr.js → server-2gcfmd47.js} +1 -1
- package/dist/v2/{server-wc0bb04b.js → server-34pvhvxt.js} +8 -8
- package/dist/v2/{server-468mya5v.js → server-39bcszk4.js} +47 -1
- package/dist/v2/{server-b8qp1ark.js → server-76v5y7zm.js} +2 -2
- package/dist/v2/{server-9sf3qp02.js → server-bj779zmp.js} +1 -1
- package/dist/v2/{server-gsz7h1zr.js → server-dhdn8mwq.js} +1 -1
- package/dist/v2/{server-92fhew3p.js → server-fqnty3nk.js} +10 -10
- package/dist/v2/{server-qcbxjpkv.js → server-ma9jwnas.js} +4 -4
- package/dist/v2/{server-2adwe0be.js → server-nqdzv8b7.js} +47 -5
- package/dist/v2/{server-65r7p1z4.js → server-pxdpwycq.js} +12 -7
- package/dist/v2/{server-fw2sjpkx.js → server-r00xyx66.js} +1 -1
- package/dist/v2/{server-aewxmvnf.js → server-rp52f40v.js} +1 -1
- package/dist/v2/{server-10af6m7d.js → server-x8ksqcw7.js} +4 -6
- package/dist/v2/{server-cxkb9725.js → server-xdh4r20h.js} +5 -3
- package/dist/v2/{server-fjd90bk0.js → server-zw1e3wq5.js} +2 -2
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-j4he6hwe.js → storage-tags-z8j8wq34.js} +1 -1
- package/dist/v2/{store-1fax2zhj.js → store-m3zny7q2.js} +4 -2
- package/dist/v2/{v2-archive-reader-xs0d7yyr.js → v2-archive-reader-p89x05hj.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-ghbsa00k.js → wrapup-orchestrator-0f4nwpbv.js} +12 -12
- package/dist/{v2-archive-reader-maj9xst8.js → v2-archive-reader-vzmzb245.js} +1 -1
- package/dist/{wrapup-orchestrator-q12ejyw9.js → wrapup-orchestrator-5k9hgb3t.js} +11 -11
- package/package.json +1 -1
- package/src/shared/models-dev-cache.test.ts +67 -1
- package/src/shared/models-dev-cache.ts +71 -4
- package/src/shared/subagent-runner.ts +10 -0
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveLegacyConfigSources,
|
|
8
8
|
getProtectedTokensTierOverrides,
|
|
9
9
|
loadPluginConfigDetailed
|
|
10
|
-
} from "./server-
|
|
10
|
+
} from "./server-bj779zmp.js";
|
|
11
11
|
import {
|
|
12
12
|
getHarness2,
|
|
13
13
|
harnessOwnsOpenCodeStore2
|
|
@@ -33,11 +33,12 @@ import {
|
|
|
33
33
|
setOutputReserveConfig,
|
|
34
34
|
resolveLimit,
|
|
35
35
|
refreshModelLimitsFromApi,
|
|
36
|
+
useV2DraftModelLimits,
|
|
36
37
|
getSdkWindowGeometry,
|
|
37
38
|
getSdkContextLimit,
|
|
38
39
|
getSdkOutputLimit,
|
|
39
40
|
getModelsDevCacheState
|
|
40
|
-
} from "./server-
|
|
41
|
+
} from "./server-nqdzv8b7.js";
|
|
41
42
|
import {
|
|
42
43
|
string,
|
|
43
44
|
number,
|
|
@@ -220,7 +221,7 @@ import {
|
|
|
220
221
|
startCompartmentAgent,
|
|
221
222
|
setRecompStarting2,
|
|
222
223
|
setRecompTerminal2
|
|
223
|
-
} from "./server-
|
|
224
|
+
} from "./server-fqnty3nk.js";
|
|
224
225
|
import {
|
|
225
226
|
resolveHistorianModel2
|
|
226
227
|
} from "./server-5kym00ag.js";
|
|
@@ -230,8 +231,9 @@ import {
|
|
|
230
231
|
createFailClosedBlockingError,
|
|
231
232
|
isFailClosedBlockingError,
|
|
232
233
|
shouldBypassFailClosedBlock,
|
|
233
|
-
resolveAgentNameFromMessages
|
|
234
|
-
|
|
234
|
+
resolveAgentNameFromMessages,
|
|
235
|
+
createFailClosedController
|
|
236
|
+
} from "./server-39bcszk4.js";
|
|
235
237
|
import {
|
|
236
238
|
pruneMissingProjectIdentities,
|
|
237
239
|
setHomeProjectPermission,
|
|
@@ -534,7 +536,7 @@ import {
|
|
|
534
536
|
adoptNullOwnerToolTag2,
|
|
535
537
|
getCandidateToolOwners2,
|
|
536
538
|
pickNearestPriorOwner2
|
|
537
|
-
} from "./server-
|
|
539
|
+
} from "./server-xdh4r20h.js";
|
|
538
540
|
import {
|
|
539
541
|
textMentionsRecentCommit,
|
|
540
542
|
hasMeaningfulUserText2,
|
|
@@ -616,12 +618,12 @@ import {
|
|
|
616
618
|
readRawSessionMessageOrdinalById2,
|
|
617
619
|
readSessionChunk2,
|
|
618
620
|
readRawSessionSeedTail2
|
|
619
|
-
} from "./server-
|
|
621
|
+
} from "./server-2gcfmd47.js";
|
|
620
622
|
import {
|
|
621
623
|
cleanSearchText,
|
|
622
624
|
matchedSearchSnippet,
|
|
623
625
|
getLastIndexedOrdinal
|
|
624
|
-
} from "./server-
|
|
626
|
+
} from "./server-r00xyx66.js";
|
|
625
627
|
import"./server-ds8vpfkr.js";
|
|
626
628
|
import {
|
|
627
629
|
getMessageIndexEpoch,
|
|
@@ -648,7 +650,7 @@ import {
|
|
|
648
650
|
resolveMemoriesByIdsForSearch2,
|
|
649
651
|
unifiedSearch2,
|
|
650
652
|
formatSearchResults2
|
|
651
|
-
} from "./server-
|
|
653
|
+
} from "./server-pxdpwycq.js";
|
|
652
654
|
import {
|
|
653
655
|
embedPauseBySession,
|
|
654
656
|
embedRunStateBySession,
|
|
@@ -796,7 +798,7 @@ import {
|
|
|
796
798
|
saveSourceContent,
|
|
797
799
|
replaceSourceContent,
|
|
798
800
|
getSourceContents
|
|
799
|
-
} from "./server-
|
|
801
|
+
} from "./server-dhdn8mwq.js";
|
|
800
802
|
import {
|
|
801
803
|
startBootDeadline,
|
|
802
804
|
getUnconfirmedMigrationHolders,
|
|
@@ -812,7 +814,7 @@ import {
|
|
|
812
814
|
openDatabaseAsync,
|
|
813
815
|
isDatabasePersisted,
|
|
814
816
|
getDatabasePersistenceError
|
|
815
|
-
} from "./server-
|
|
817
|
+
} from "./server-76v5y7zm.js";
|
|
816
818
|
import {
|
|
817
819
|
V2_MEMORY_CATEGORIES,
|
|
818
820
|
CATEGORY_PRIORITY
|
|
@@ -867,7 +869,7 @@ import {
|
|
|
867
869
|
resolveKnownHistorianContextLimit2,
|
|
868
870
|
resolveHistorianProducerLimits2,
|
|
869
871
|
resolveHistorianContextLimit2
|
|
870
|
-
} from "./server-
|
|
872
|
+
} from "./server-rp52f40v.js";
|
|
871
873
|
import"./server-at0v0z4t.js";
|
|
872
874
|
import {
|
|
873
875
|
isEmbeddingHostBusy2
|
|
@@ -933,8 +935,8 @@ import {
|
|
|
933
935
|
readGitFileChangeTimesSince,
|
|
934
936
|
verificationFileExists,
|
|
935
937
|
normalizeVerificationFiles
|
|
936
|
-
} from "./server-
|
|
937
|
-
import"./server-
|
|
938
|
+
} from "./server-25qtxt4d.js";
|
|
939
|
+
import"./server-x8ksqcw7.js";
|
|
938
940
|
import {
|
|
939
941
|
computeCueContentHash,
|
|
940
942
|
hasMuralCueColumns,
|
|
@@ -987,13 +989,14 @@ import {
|
|
|
987
989
|
dropStorageNotices,
|
|
988
990
|
HOST_RESTORE_MEDIA,
|
|
989
991
|
restoreRow,
|
|
992
|
+
rawMessagePage2,
|
|
990
993
|
servedBoundaryRow2,
|
|
991
994
|
resolveV2BoundaryUserMessage2,
|
|
992
995
|
readAllV2RawMessagesForConversion2,
|
|
993
996
|
readV2RawMessagePagesForConversion2,
|
|
994
997
|
createV2RawMessageReader2,
|
|
995
998
|
createV2RawMessageProvider2
|
|
996
|
-
} from "./server-
|
|
999
|
+
} from "./server-34pvhvxt.js";
|
|
997
1000
|
import {
|
|
998
1001
|
resolvePromptContext2
|
|
999
1002
|
} from "./server-fmsr7v69.js";
|
|
@@ -1001,14 +1004,14 @@ import {
|
|
|
1001
1004
|
renderMessageByOrdinal2,
|
|
1002
1005
|
renderVerboseRangeForTool2,
|
|
1003
1006
|
renderItemByTag2
|
|
1004
|
-
} from "./server-
|
|
1007
|
+
} from "./server-0dmzr7f9.js";
|
|
1005
1008
|
import"./server-52x68mj4.js";
|
|
1006
1009
|
import {
|
|
1007
1010
|
readV2ArchiveOffThread2
|
|
1008
|
-
} from "./server-
|
|
1011
|
+
} from "./server-ma9jwnas.js";
|
|
1009
1012
|
import {
|
|
1010
1013
|
renderSearchArchiveOffThread2
|
|
1011
|
-
} from "./server-
|
|
1014
|
+
} from "./server-zw1e3wq5.js";
|
|
1012
1015
|
import {
|
|
1013
1016
|
markHostInstructionRow,
|
|
1014
1017
|
hostInstructionRow,
|
|
@@ -1761,6 +1764,7 @@ __export(exports_coerce, {
|
|
|
1761
1764
|
});
|
|
1762
1765
|
|
|
1763
1766
|
// src/v2/hooks/context.ts
|
|
1767
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
1764
1768
|
import { setTimeout as delay } from "node:timers/promises";
|
|
1765
1769
|
|
|
1766
1770
|
// src/config/dependency-notes.ts
|
|
@@ -5496,7 +5500,7 @@ function beginCurateCategoryRun(db, projectIdentity, memories) {
|
|
|
5496
5500
|
}));
|
|
5497
5501
|
return scope;
|
|
5498
5502
|
}
|
|
5499
|
-
function
|
|
5503
|
+
function curateTaskStateAfterCategoryTurn(db, projectIdentity, category) {
|
|
5500
5504
|
const state = readState(db, projectIdentity);
|
|
5501
5505
|
return JSON.stringify({
|
|
5502
5506
|
...state,
|
|
@@ -26141,7 +26145,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26141
26145
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
26142
26146
|
});
|
|
26143
26147
|
const buildManagedCtx = async (db) => {
|
|
26144
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
26148
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-2eam671q.js"));
|
|
26145
26149
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
26146
26150
|
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-7md27rx8.js"));
|
|
26147
26151
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -26193,7 +26197,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26193
26197
|
const db = readDatabase();
|
|
26194
26198
|
if (!db)
|
|
26195
26199
|
return { ok: false, error: "db unavailable" };
|
|
26196
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
26200
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4w2w4kd4.js"));
|
|
26197
26201
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-8g4r97bp.js"));
|
|
26198
26202
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
26199
26203
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -26278,7 +26282,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26278
26282
|
const db = readDatabase();
|
|
26279
26283
|
if (!db)
|
|
26280
26284
|
return { ok: false, error: "db unavailable" };
|
|
26281
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
26285
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-0f4nwpbv.js"));
|
|
26282
26286
|
const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
|
|
26283
26287
|
const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
|
|
26284
26288
|
if (!window)
|
|
@@ -27666,11 +27670,15 @@ class FoldOwner {
|
|
|
27666
27670
|
const same = previous && (args.runningCut !== undefined ? previous.cutSeq === args.runningCut : previous.cutSeq === undefined && previous.watermark === args.watermark);
|
|
27667
27671
|
if (same) {
|
|
27668
27672
|
const id = args.checkpointID;
|
|
27669
|
-
if (id !== undefined &&
|
|
27670
|
-
|
|
27671
|
-
|
|
27672
|
-
|
|
27673
|
-
|
|
27673
|
+
if (args.runningCut === undefined || id !== undefined && ownsCheckpoint(previous, id))
|
|
27674
|
+
return previous;
|
|
27675
|
+
if (args.checkpointText !== undefined && isCheckpointNote(args.checkpointText))
|
|
27676
|
+
return {
|
|
27677
|
+
watermark: args.watermark,
|
|
27678
|
+
cutSeq: args.runningCut,
|
|
27679
|
+
submitted: args.checkpointText,
|
|
27680
|
+
submittedSha: foldDigest(args.checkpointText)
|
|
27681
|
+
};
|
|
27674
27682
|
}
|
|
27675
27683
|
const head = args.materialize();
|
|
27676
27684
|
const submitted = args.checkpointText ?? head;
|
|
@@ -27689,12 +27697,8 @@ class FoldOwner {
|
|
|
27689
27697
|
async observe(args) {
|
|
27690
27698
|
return this.serial(args.sessionID, async () => {
|
|
27691
27699
|
let state = await this.read(args.sessionID);
|
|
27692
|
-
|
|
27693
|
-
if (state && (state.rendered ? state.rendered.id !== args.rendered.id : state.answered !== undefined && !state.answered.includes(args.rendered.id ?? ""))) {
|
|
27694
|
-
if (isCheckpointNote(args.summary) && state.answered?.includes(args.rendered.id ?? ""))
|
|
27695
|
-
carriedHead = state.head;
|
|
27700
|
+
if (state && (state.rendered || state.answered !== undefined || state.head !== undefined && state.cutSeq !== undefined) && !ownsCheckpoint(state, args.rendered.id ?? ""))
|
|
27696
27701
|
state = undefined;
|
|
27697
|
-
}
|
|
27698
27702
|
let changed = !state;
|
|
27699
27703
|
const observedSha = foldDigest(JSON.stringify(args.rendered));
|
|
27700
27704
|
const rendered = structuredClone(args.rendered);
|
|
@@ -27707,7 +27711,6 @@ class FoldOwner {
|
|
|
27707
27711
|
watermark: args.cutSeq,
|
|
27708
27712
|
submitted: args.summary,
|
|
27709
27713
|
submittedSha: foldDigest(args.summary),
|
|
27710
|
-
...carriedHead === undefined ? {} : { head: carriedHead },
|
|
27711
27714
|
reason: "boot_recovery"
|
|
27712
27715
|
};
|
|
27713
27716
|
}
|
|
@@ -27749,6 +27752,11 @@ class FoldOwner {
|
|
|
27749
27752
|
});
|
|
27750
27753
|
}
|
|
27751
27754
|
}
|
|
27755
|
+
function ownsCheckpoint(state, id) {
|
|
27756
|
+
if (state.reason === "boot_recovery" && state.head !== undefined || (state.answered?.length ?? 0) > 1)
|
|
27757
|
+
return false;
|
|
27758
|
+
return state.rendered ? state.rendered.id === id : state.answered?.length === 1 && state.answered[0] === id;
|
|
27759
|
+
}
|
|
27752
27760
|
function stripCheckpointRecentContext(message, summary) {
|
|
27753
27761
|
let changed = false;
|
|
27754
27762
|
for (const part of message.content) {
|
|
@@ -28701,6 +28709,21 @@ function controlsThrough(controls, reader, sessionID, through) {
|
|
|
28701
28709
|
return controls.filter((control) => !control.after || (reader.sequenceForId(sessionID, control.after) ?? Infinity) <= through);
|
|
28702
28710
|
}
|
|
28703
28711
|
|
|
28712
|
+
// src/v2/fold/partial-boundary.ts
|
|
28713
|
+
function hasUnsummarizedBlocks(db, reader, sessionID, rowID) {
|
|
28714
|
+
const ends = db.prepare("SELECT end_block_index AS block FROM compartments WHERE session_id=? AND end_message_id=? AND end_block_index IS NOT NULL").all(sessionID, rowID);
|
|
28715
|
+
if (ends.length === 0)
|
|
28716
|
+
return false;
|
|
28717
|
+
const row = reader.messageById(sessionID, rowID);
|
|
28718
|
+
if (!row)
|
|
28719
|
+
return false;
|
|
28720
|
+
const last = moduleRawBlockMappings(rawMessagePage2([row], 0)[0] ?? null).at(-1)?.blockIndex;
|
|
28721
|
+
return last !== undefined && ends.some((end) => end.block < last);
|
|
28722
|
+
}
|
|
28723
|
+
function restoreAfter(db, reader, sessionID, floor) {
|
|
28724
|
+
return floor.kind === "summary" && hasUnsummarizedBlocks(db, reader, sessionID, floor.id) ? floor.after - 1 : floor.after;
|
|
28725
|
+
}
|
|
28726
|
+
|
|
28704
28727
|
// src/v2/fold/native-replay.ts
|
|
28705
28728
|
var coordinates = new WeakMap;
|
|
28706
28729
|
var sequences = new WeakMap;
|
|
@@ -29327,7 +29350,7 @@ ${cached}
|
|
|
29327
29350
|
const replay = replayOverride ?? this.tail(sessionID)?.replay;
|
|
29328
29351
|
if (!replay || !validFloor(reader, sessionID, replay.floor))
|
|
29329
29352
|
return;
|
|
29330
|
-
after = replay.floor
|
|
29353
|
+
after = restoreAfter(this.storage.db, reader, sessionID, replay.floor);
|
|
29331
29354
|
} else if (args.bounded && !this.changed.has(sessionID)) {
|
|
29332
29355
|
const state = readSessionMeta(this.storage.db, sessionID);
|
|
29333
29356
|
const max = this.storage.db.prepare("SELECT COALESCE(MAX(id),0) AS id FROM m0_mutation_log WHERE session_id=?").get(sessionID);
|
|
@@ -29368,7 +29391,7 @@ ${cached}
|
|
|
29368
29391
|
return { id: row.id, type: row.type, seq: row.seq, data, digest: foldDigest(data) };
|
|
29369
29392
|
}
|
|
29370
29393
|
records(sessionID, native, reader, selection) {
|
|
29371
|
-
const after = selection
|
|
29394
|
+
const after = selection ? restoreAfter(this.storage.db, reader, sessionID, selection.floor) : undefined;
|
|
29372
29395
|
const candidates = native.flatMap((message) => {
|
|
29373
29396
|
if (!selection)
|
|
29374
29397
|
return [{ message, covered: false }];
|
|
@@ -29376,7 +29399,7 @@ ${cached}
|
|
|
29376
29399
|
if (effortPart(message) || HEAD_IDS.some((head) => head === id) || !id && selection.baseline && message.role === "user" && message.content.some((part) => part.type === "text" && part.text === selection.baseline))
|
|
29377
29400
|
return [];
|
|
29378
29401
|
const seq = id && selection.floor.kind !== "start" ? reader.sequenceForId(sessionID, id) : undefined;
|
|
29379
|
-
return [{ message, covered: seq !== undefined && seq <=
|
|
29402
|
+
return [{ message, covered: seq !== undefined && after !== undefined && seq <= after }];
|
|
29380
29403
|
});
|
|
29381
29404
|
native = candidates.filter(({ covered }) => !covered).map(({ message }) => message);
|
|
29382
29405
|
const through = reader.latestSequence(sessionID);
|
|
@@ -29725,12 +29748,15 @@ ${cached}
|
|
|
29725
29748
|
async restore(sessionID, cut, model, options = {}) {
|
|
29726
29749
|
let replay;
|
|
29727
29750
|
let controls = [];
|
|
29751
|
+
let after;
|
|
29728
29752
|
if (this.options.protocol === 3) {
|
|
29729
29753
|
const reader = this.openReader(sessionID);
|
|
29730
29754
|
try {
|
|
29731
29755
|
replay = await this.floorState(sessionID, reader);
|
|
29732
|
-
if (replay)
|
|
29756
|
+
if (replay) {
|
|
29733
29757
|
controls = controlsThrough(replay.controls, reader, sessionID, cut.seq - 1);
|
|
29758
|
+
after = restoreAfter(this.storage.db, reader, sessionID, replay.floor);
|
|
29759
|
+
}
|
|
29734
29760
|
} finally {
|
|
29735
29761
|
reader.close();
|
|
29736
29762
|
}
|
|
@@ -29741,7 +29767,7 @@ ${cached}
|
|
|
29741
29767
|
options = {
|
|
29742
29768
|
...options,
|
|
29743
29769
|
bounded: false,
|
|
29744
|
-
after
|
|
29770
|
+
after,
|
|
29745
29771
|
retiredInstructionThrough: replay.retiredInstructionThrough,
|
|
29746
29772
|
retiredInstructionIDs: replay.retiredInstructionIDs
|
|
29747
29773
|
};
|
|
@@ -29830,7 +29856,8 @@ ${cached}
|
|
|
29830
29856
|
throw new NativeReplayUnavailable("Host checkpoint replay boundary is unavailable");
|
|
29831
29857
|
}
|
|
29832
29858
|
const retired = instructionRetirement(replay);
|
|
29833
|
-
const
|
|
29859
|
+
const after = replay ? restoreAfter(this.storage.db, reader, sessionID, replay.floor) : -1;
|
|
29860
|
+
const messages = reader.range(sessionID, after, cut.seq - 1).filter(conversational).filter((row) => !retired(row)).flatMap((row) => {
|
|
29834
29861
|
const messages = this.rendered(row, model);
|
|
29835
29862
|
for (const message of messages)
|
|
29836
29863
|
bindNativeRowID(message, row.id, row.seq);
|
|
@@ -33785,6 +33812,22 @@ function isDirectiveShapedProjectRule(category, content) {
|
|
|
33785
33812
|
// src/features/magic-context/dreamer/curate-memory-safety.ts
|
|
33786
33813
|
var PROJECT_SCOPED_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
|
|
33787
33814
|
var USER_PROFILE_REFERENCE = /\buser(?:[\s_-]+)(?:profile|preferences?)\b|\bU\d+\b/i;
|
|
33815
|
+
var CURATE_SAFETY_REFUSAL_REASONS = [
|
|
33816
|
+
"missing-active-same-category-successor",
|
|
33817
|
+
"user-profile-is-not-project-memory",
|
|
33818
|
+
"directive-shaped-project-rule",
|
|
33819
|
+
"content-loss"
|
|
33820
|
+
];
|
|
33821
|
+
var refusalReasons = new Set(CURATE_SAFETY_REFUSAL_REASONS);
|
|
33822
|
+
function parseCurateSafetyRefusal(action, output) {
|
|
33823
|
+
if (action !== "archive" && action !== "update")
|
|
33824
|
+
return null;
|
|
33825
|
+
const refusal = /^Skipped (archive|update) for memory \[ID: -?\d+(?:, -?\d+)*\]: curate safety refusal \(([a-z,-]+)\); refused=[1-9]\d*\.$/.exec(output);
|
|
33826
|
+
if (refusal?.[1] !== action || !refusal[2])
|
|
33827
|
+
return null;
|
|
33828
|
+
const reasons = [...new Set(refusal[2].split(","))];
|
|
33829
|
+
return reasons.every((reason) => refusalReasons.has(reason)) ? reasons : null;
|
|
33830
|
+
}
|
|
33788
33831
|
var refusalCountsBySession = new Map;
|
|
33789
33832
|
function isSurvivingConsolidationTarget(memory, successor, projectIdentity) {
|
|
33790
33833
|
return successor !== null && successor.id !== memory.id && successor.status === "active" && successor.supersededByMemoryId === null && (successor.expiresAt === null || successor.expiresAt > Date.now()) && projectIdentity(successor) === projectIdentity(memory) && successor.category === memory.category;
|
|
@@ -38782,8 +38825,11 @@ function validateCurateAssistantText(text) {
|
|
|
38782
38825
|
}
|
|
38783
38826
|
return text;
|
|
38784
38827
|
}
|
|
38828
|
+
function emptyCurateMemoryOperations() {
|
|
38829
|
+
return { totalCalls: 0, completedActions: [], refusals: [] };
|
|
38830
|
+
}
|
|
38785
38831
|
function inspectCurateMemoryOperations(messages) {
|
|
38786
|
-
const summary =
|
|
38832
|
+
const summary = emptyCurateMemoryOperations();
|
|
38787
38833
|
if (!Array.isArray(messages))
|
|
38788
38834
|
return summary;
|
|
38789
38835
|
for (const message of messages) {
|
|
@@ -38798,28 +38844,69 @@ function inspectCurateMemoryOperations(messages) {
|
|
|
38798
38844
|
const toolName = part.tool ?? part.name;
|
|
38799
38845
|
if (toolName !== "ctx_memory")
|
|
38800
38846
|
continue;
|
|
38847
|
+
const state = isRecord(part.state) ? part.state : null;
|
|
38848
|
+
const input = isRecord(state?.input) ? state.input : null;
|
|
38849
|
+
const action = input?.action;
|
|
38850
|
+
const output = state?.status === "completed" && typeof state.output === "string" ? state.output : null;
|
|
38851
|
+
if (output && (action === "get" || action === "list") && /^(?:Found \d+ (?:active )?memor(?:y|ies):|No active memories found\.$|id -?\d+: not found or not visible from this project)/.test(output))
|
|
38852
|
+
continue;
|
|
38801
38853
|
summary.totalCalls += 1;
|
|
38802
|
-
if (!
|
|
38854
|
+
if (!output)
|
|
38803
38855
|
continue;
|
|
38804
|
-
|
|
38805
|
-
const action = input?.action;
|
|
38806
|
-
const output = typeof part.state.output === "string" ? part.state.output : "";
|
|
38807
|
-
if (output === "completed" && (action === "merge" || action === "archive" || action === "update") || action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory"))
|
|
38856
|
+
if (action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory")) {
|
|
38808
38857
|
summary.completedActions.push(action);
|
|
38858
|
+
} else {
|
|
38859
|
+
const reasons = parseCurateSafetyRefusal(action, output);
|
|
38860
|
+
if (reasons)
|
|
38861
|
+
summary.refusals.push(reasons);
|
|
38862
|
+
}
|
|
38809
38863
|
}
|
|
38810
38864
|
}
|
|
38811
38865
|
return summary;
|
|
38812
38866
|
}
|
|
38867
|
+
function unrecognisedCurateOperations(operations) {
|
|
38868
|
+
return operations.totalCalls - operations.completedActions.length - operations.refusals.length;
|
|
38869
|
+
}
|
|
38870
|
+
function validateCurateOutput(messages, text, transport) {
|
|
38871
|
+
const operations = inspectCurateMemoryOperations(messages);
|
|
38872
|
+
if (text)
|
|
38873
|
+
validateCurateAssistantText(text);
|
|
38874
|
+
if (operations.completedActions.length || operations.refusals.length && !unrecognisedCurateOperations(operations))
|
|
38875
|
+
return operations;
|
|
38876
|
+
if (!text && transport === "child")
|
|
38877
|
+
throw new Error("Dreamer returned no assistant output.");
|
|
38878
|
+
if (operations.totalCalls > 0)
|
|
38879
|
+
throw new Error("Curate returned no completed ctx_memory tool result.");
|
|
38880
|
+
if (!text)
|
|
38881
|
+
throw new Error("Dreamer returned no assistant output.");
|
|
38882
|
+
return operations;
|
|
38883
|
+
}
|
|
38813
38884
|
function formatExpiredArchiveProgress(count) {
|
|
38814
38885
|
return `curate: archived ${count} expired ${count === 1 ? "memory" : "memories"}`;
|
|
38815
38886
|
}
|
|
38816
|
-
function formatCurateMemoryOperations(
|
|
38887
|
+
function formatCurateMemoryOperations(operations) {
|
|
38888
|
+
const { completedActions: actions, refusals } = operations;
|
|
38889
|
+
if (!actions.length && !refusals.length)
|
|
38890
|
+
return null;
|
|
38817
38891
|
const actionCounts = new Map;
|
|
38818
38892
|
for (const action of actions)
|
|
38819
38893
|
actionCounts.set(action, (actionCounts.get(action) ?? 0) + 1);
|
|
38820
38894
|
const actionDetail = [...actionCounts].map(([action, count]) => count === 1 ? action : `${action} ×${count}`).join(", ");
|
|
38821
|
-
const
|
|
38822
|
-
|
|
38895
|
+
const applied = actions.length ? `${actions.length} memory ${actions.length === 1 ? "operation" : "operations"} applied (${actionDetail})` : "no changes";
|
|
38896
|
+
const detail = [`curate: ${applied}`];
|
|
38897
|
+
if (refusals.length) {
|
|
38898
|
+
const reasonCounts = new Map;
|
|
38899
|
+
for (const reasons of refusals) {
|
|
38900
|
+
for (const reason of reasons)
|
|
38901
|
+
reasonCounts.set(reason, (reasonCounts.get(reason) ?? 0) + 1);
|
|
38902
|
+
}
|
|
38903
|
+
const countedReasons = [...reasonCounts].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason} ×${count}`).join(", ");
|
|
38904
|
+
detail.push(`${refusals.length} ${refusals.length === 1 ? "operation" : "operations"} refused (${countedReasons})`);
|
|
38905
|
+
}
|
|
38906
|
+
const unrecognised = unrecognisedCurateOperations(operations);
|
|
38907
|
+
if (unrecognised)
|
|
38908
|
+
detail.push(`${unrecognised} with an unrecognised result`);
|
|
38909
|
+
return detail.join("; ");
|
|
38823
38910
|
}
|
|
38824
38911
|
function requireDreamClient(client) {
|
|
38825
38912
|
if (!client)
|
|
@@ -39027,6 +39114,7 @@ function createDreamTaskExecutor(deps) {
|
|
|
39027
39114
|
};
|
|
39028
39115
|
return writtenIds.length || deletedIds.length || archivedIds.length || mergedIds.length ? changes : null;
|
|
39029
39116
|
}
|
|
39117
|
+
let curateCategory;
|
|
39030
39118
|
try {
|
|
39031
39119
|
const skip = (reason) => {
|
|
39032
39120
|
log2(`[dreamer] ${config.task}: skipped (${reason})`);
|
|
@@ -39338,7 +39426,10 @@ function createDreamTaskExecutor(deps) {
|
|
|
39338
39426
|
computeMemoryDelta,
|
|
39339
39427
|
reportProgress,
|
|
39340
39428
|
leaseAcquisition,
|
|
39341
|
-
moduleRoute
|
|
39429
|
+
moduleRoute,
|
|
39430
|
+
onCurateCategory: (category) => {
|
|
39431
|
+
curateCategory = category;
|
|
39432
|
+
}
|
|
39342
39433
|
});
|
|
39343
39434
|
} catch (error) {
|
|
39344
39435
|
if (error instanceof DreamTokenBudgetExceeded) {
|
|
@@ -39356,7 +39447,11 @@ function createDreamTaskExecutor(deps) {
|
|
|
39356
39447
|
transient,
|
|
39357
39448
|
error: brief,
|
|
39358
39449
|
failureDetail: formatDreamRunFailure(failure),
|
|
39359
|
-
...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : {
|
|
39450
|
+
...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : curateCategory && !transient ? {
|
|
39451
|
+
schedulePatch: {
|
|
39452
|
+
taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
|
|
39453
|
+
}
|
|
39454
|
+
} : {}
|
|
39360
39455
|
};
|
|
39361
39456
|
} finally {
|
|
39362
39457
|
deps.onProgress?.(null, config.task);
|
|
@@ -39863,6 +39958,8 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
39863
39958
|
const scope = beginCurateCategoryRun(db, projectIdentity, loadActiveMemoryPromptMemories(db, projectIdentity));
|
|
39864
39959
|
curateMemories = scope?.memories ?? [];
|
|
39865
39960
|
curateCategory = scope?.category;
|
|
39961
|
+
if (curateCategory)
|
|
39962
|
+
helpers.onCurateCategory(curateCategory);
|
|
39866
39963
|
log2(`[dreamer] curate pool: category=${curateCategory ?? "none"} in_scope=${curateMemories.length} expired_archived=${expiredArchived}`);
|
|
39867
39964
|
if (curateMemories.length === 0) {
|
|
39868
39965
|
const progress = expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : "curate: no populated project-memory category";
|
|
@@ -39890,15 +39987,11 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
39890
39987
|
if (task === "maintain-docs" && hasCurrentDocsProposal(docsDir)) {
|
|
39891
39988
|
const reason = "pending proposal matches current docs";
|
|
39892
39989
|
helpers.recordRun("completed", null, { progress: reason });
|
|
39893
|
-
return {
|
|
39894
|
-
status: "completed",
|
|
39895
|
-
detail: reason,
|
|
39896
|
-
...changes ? { schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) } } : {}
|
|
39897
|
-
};
|
|
39990
|
+
return { status: "completed", detail: reason };
|
|
39898
39991
|
}
|
|
39899
39992
|
const curateChunks = curateMemories ? chunkCurateMemories(curateMemories, Math.max(4000, Math.floor(resolveRetrospectiveUsableInputTokens(config, deps) * 2))) : [];
|
|
39900
39993
|
const batches = task === "curate" ? curateChunks : [{ memories: [], crossChunkCandidates: [] }];
|
|
39901
|
-
const
|
|
39994
|
+
const curateOperations = emptyCurateMemoryOperations();
|
|
39902
39995
|
let curateRefused = 0;
|
|
39903
39996
|
let run = {
|
|
39904
39997
|
output: [],
|
|
@@ -39947,14 +40040,7 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
39947
40040
|
parseDocsProposalOutput(text);
|
|
39948
40041
|
if (task !== "curate")
|
|
39949
40042
|
return text;
|
|
39950
|
-
|
|
39951
|
-
if (text)
|
|
39952
|
-
validateCurateAssistantText(text);
|
|
39953
|
-
if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
|
|
39954
|
-
throw new Error("Curate returned no completed ctx_memory tool result.");
|
|
39955
|
-
if (!text && memoryOperations.completedActions.length === 0)
|
|
39956
|
-
throw new Error("Dreamer returned no assistant output.");
|
|
39957
|
-
return { text: text || null, memoryOperations };
|
|
40043
|
+
return validateCurateOutput(completion.messages, text, "hidden");
|
|
39958
40044
|
}
|
|
39959
40045
|
});
|
|
39960
40046
|
childSessionId = hidden.childSessionId;
|
|
@@ -40013,24 +40099,15 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
40013
40099
|
parseDocsProposalOutput(text);
|
|
40014
40100
|
return text;
|
|
40015
40101
|
}
|
|
40016
|
-
|
|
40017
|
-
if (text)
|
|
40018
|
-
validateCurateAssistantText(text);
|
|
40019
|
-
if (memoryOperations.completedActions.length > 0) {
|
|
40020
|
-
return { text, memoryOperations };
|
|
40021
|
-
}
|
|
40022
|
-
if (!text)
|
|
40023
|
-
throw new Error("Dreamer returned no assistant output.");
|
|
40024
|
-
if (memoryOperations.totalCalls > 0) {
|
|
40025
|
-
throw new Error("Curate returned no completed ctx_memory tool result.");
|
|
40026
|
-
}
|
|
40027
|
-
return { text, memoryOperations };
|
|
40102
|
+
return validateCurateOutput(messages, text, "child");
|
|
40028
40103
|
}
|
|
40029
40104
|
});
|
|
40030
40105
|
promptSettled = true;
|
|
40031
40106
|
}
|
|
40032
|
-
if (
|
|
40033
|
-
|
|
40107
|
+
if (typeof run.validated !== "string") {
|
|
40108
|
+
curateOperations.totalCalls += run.validated.totalCalls;
|
|
40109
|
+
curateOperations.completedActions.push(...run.validated.completedActions);
|
|
40110
|
+
curateOperations.refusals.push(...run.validated.refusals);
|
|
40034
40111
|
curateRefused += takeCurateSafetyRefusalCount(childSessionId ?? "");
|
|
40035
40112
|
}
|
|
40036
40113
|
if (childSessionId && !deps.hiddenCompletionExecutor) {
|
|
@@ -40046,17 +40123,15 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
40046
40123
|
childSessionId = null;
|
|
40047
40124
|
}
|
|
40048
40125
|
}
|
|
40049
|
-
if (task === "curate")
|
|
40050
|
-
run.validated = {
|
|
40051
|
-
text: null,
|
|
40052
|
-
memoryOperations: { totalCalls: completedActions.length, completedActions }
|
|
40053
|
-
};
|
|
40054
40126
|
if (leaseLost)
|
|
40055
40127
|
throw new Error("Dream lease lost during task");
|
|
40056
40128
|
if (curateRefused > 0) {
|
|
40057
40129
|
helpers.reportProgress(curateRefused, curateRefused);
|
|
40058
40130
|
log2(`[dreamer] curate safety summary: refused=${curateRefused}`);
|
|
40059
40131
|
}
|
|
40132
|
+
const unrecognised = unrecognisedCurateOperations(curateOperations);
|
|
40133
|
+
if (unrecognised > 0)
|
|
40134
|
+
log2(`[dreamer] curate result summary: unrecognised=${unrecognised}`);
|
|
40060
40135
|
recordInvocation("completed", run.output);
|
|
40061
40136
|
if (task === "maintain-docs" && docsHashes && changes) {
|
|
40062
40137
|
try {
|
|
@@ -40076,13 +40151,12 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
40076
40151
|
return { status: "failed", error: reason };
|
|
40077
40152
|
}
|
|
40078
40153
|
}
|
|
40079
|
-
const curateOutput = task === "curate" ? run.validated : undefined;
|
|
40080
40154
|
const curateScopeProgress = task === "curate" && curateCategory && curateMemories ? `curate: ${curateCategory} (${curateMemories.length})` : null;
|
|
40081
40155
|
const progress = [
|
|
40082
40156
|
curateScopeProgress,
|
|
40083
40157
|
expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : null,
|
|
40084
|
-
|
|
40085
|
-
curateRefused > 0 ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
|
|
40158
|
+
formatCurateMemoryOperations(curateOperations),
|
|
40159
|
+
curateRefused > 0 && !curateOperations.refusals.length ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
|
|
40086
40160
|
].filter((value) => Boolean(value)).join("; ");
|
|
40087
40161
|
const curateCount = task === "curate" && curateCategory ? loadActiveMemoryPromptMemories(db, projectIdentity).filter((memory) => curateCategoryForMemoryCategory(memory.category) === curateCategory).length : undefined;
|
|
40088
40162
|
const curateBacklog = curateCount !== undefined && curateCategory ? {
|
|
@@ -40101,7 +40175,7 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
40101
40175
|
...curateBacklog ? { backlog: curateBacklog } : {},
|
|
40102
40176
|
...curateCategory ? {
|
|
40103
40177
|
schedulePatch: {
|
|
40104
|
-
taskStateJson:
|
|
40178
|
+
taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
|
|
40105
40179
|
}
|
|
40106
40180
|
} : {}
|
|
40107
40181
|
};
|
|
@@ -56839,7 +56913,15 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
|
|
|
56839
56913
|
sessionLog2(sessionID, "v2 session directory lookup failed; using the launch directory:", error);
|
|
56840
56914
|
}
|
|
56841
56915
|
}
|
|
56916
|
+
var contextPass = new AsyncLocalStorage2;
|
|
56917
|
+
function withV2ContextPass(sessionID, run) {
|
|
56918
|
+
const pass = { sessionID, refused: false };
|
|
56919
|
+
return withSqliteTransformPass2(() => contextPass.run(pass, () => run(pass)));
|
|
56920
|
+
}
|
|
56842
56921
|
function refuseBeforeProvider(session, sessionID, arm, cause) {
|
|
56922
|
+
const pass = contextPass.getStore();
|
|
56923
|
+
if (pass?.sessionID === sessionID)
|
|
56924
|
+
pass.refused = true;
|
|
56843
56925
|
const detail = cause instanceof Error ? `${cause.name}: ${cause.message}` : cause === undefined ? "" : String(cause);
|
|
56844
56926
|
sessionLog2(sessionID, `v2 refusal: interrupting the turn before the provider request arm=${arm}${detail ? ` cause=${JSON.stringify(detail.slice(0, 500))}` : ""}`);
|
|
56845
56927
|
noteServedRefusal(sessionID);
|
|
@@ -57073,6 +57155,13 @@ async function registerContext(context) {
|
|
|
57073
57155
|
log2(`[magic-context] v2 storage unavailable: ${message}`);
|
|
57074
57156
|
}
|
|
57075
57157
|
});
|
|
57158
|
+
const failClosed = createFailClosedController();
|
|
57159
|
+
const failClosedBlockingEnabled = !compactionOff && config.fail_closed_blocking !== false;
|
|
57160
|
+
const tryReopenStorage = async () => {
|
|
57161
|
+
const reopened = await openDatabaseAsync({ busyTimeoutMs: 0 });
|
|
57162
|
+
return reopened !== null && reopened === storage.current();
|
|
57163
|
+
};
|
|
57164
|
+
const wrapperStorageGuard = { failClosed, failClosedBlockingEnabled };
|
|
57076
57165
|
let db = await probeV2StorageAtBoot(storage);
|
|
57077
57166
|
const storageOpenedAtBoot = db !== undefined;
|
|
57078
57167
|
let legacyCleanupStarted = false;
|
|
@@ -57109,6 +57198,10 @@ async function registerContext(context) {
|
|
|
57109
57198
|
storageNoticeBySession.set(sessionID, message);
|
|
57110
57199
|
storeStorageNotice(sessionID, message, "refusal");
|
|
57111
57200
|
};
|
|
57201
|
+
const refuseUnavailableStorage = async (sessionID, reason) => {
|
|
57202
|
+
noticeStorageRefusal(sessionID, reason);
|
|
57203
|
+
await refuseBeforeProvider(context.session, sessionID, "storage-unavailable", formatFailClosedBlockingMessage(reason));
|
|
57204
|
+
};
|
|
57112
57205
|
const rustModeModuleClient = resolveV2RustModeModuleClient(config, directory);
|
|
57113
57206
|
const rustMemorySyncRequestedSessions = new Set;
|
|
57114
57207
|
const moduleToolBackends = db && isDatabasePersisted(db) ? createModuleToolBackends({
|
|
@@ -57436,25 +57529,35 @@ async function registerContext(context) {
|
|
|
57436
57529
|
});
|
|
57437
57530
|
const draftModelKey = `${draft.model.providerID}/${draft.model.id}`;
|
|
57438
57531
|
if (!queriedModels.has(draftModelKey)) {
|
|
57439
|
-
|
|
57440
|
-
|
|
57441
|
-
|
|
57442
|
-
|
|
57443
|
-
|
|
57444
|
-
|
|
57445
|
-
|
|
57446
|
-
|
|
57447
|
-
provider.models[model.id] = { limit: model.limit };
|
|
57448
|
-
providers.set(model.providerID, provider);
|
|
57532
|
+
let catalog;
|
|
57533
|
+
let catalogFailed = false;
|
|
57534
|
+
try {
|
|
57535
|
+
catalog = await Promise.resolve(context.model.list());
|
|
57536
|
+
} catch (error) {
|
|
57537
|
+
if (!useV2DraftModelLimits(draft.model.providerID, draft.model.id, draft.model.limit))
|
|
57538
|
+
throw error;
|
|
57539
|
+
catalogFailed = true;
|
|
57449
57540
|
}
|
|
57450
|
-
|
|
57451
|
-
|
|
57452
|
-
|
|
57453
|
-
|
|
57454
|
-
|
|
57541
|
+
if (!catalogFailed) {
|
|
57542
|
+
const providers = new Map;
|
|
57543
|
+
for (const model of catalogModels(catalog, draft.model)) {
|
|
57544
|
+
rawLimits.set(`${model.providerID}/${model.id}`, model.limit);
|
|
57545
|
+
const provider = providers.get(model.providerID) ?? {
|
|
57546
|
+
id: model.providerID,
|
|
57547
|
+
models: {}
|
|
57548
|
+
};
|
|
57549
|
+
provider.models[model.id] = { limit: model.limit };
|
|
57550
|
+
providers.set(model.providerID, provider);
|
|
57455
57551
|
}
|
|
57456
|
-
|
|
57457
|
-
|
|
57552
|
+
await refreshModelLimitsFromApi({
|
|
57553
|
+
config: {
|
|
57554
|
+
providers: async () => ({
|
|
57555
|
+
data: { providers: [...providers.values()] }
|
|
57556
|
+
})
|
|
57557
|
+
}
|
|
57558
|
+
});
|
|
57559
|
+
queriedModels.add(draftModelKey);
|
|
57560
|
+
}
|
|
57458
57561
|
}
|
|
57459
57562
|
const usageDb = db;
|
|
57460
57563
|
const limitFor = (providerID, modelID) => {
|
|
@@ -57489,7 +57592,8 @@ async function registerContext(context) {
|
|
|
57489
57592
|
reader.close();
|
|
57490
57593
|
}
|
|
57491
57594
|
} catch (error) {
|
|
57492
|
-
|
|
57595
|
+
if (storage.current() || !storage.reason() || failClosedBlockingEnabled && !shouldBypassFailClosedBlock({ agent: draft.agent }))
|
|
57596
|
+
reportPreProviderRefusal(draft.sessionID, error);
|
|
57493
57597
|
unsafe = true;
|
|
57494
57598
|
}
|
|
57495
57599
|
return unsafe;
|
|
@@ -57860,7 +57964,9 @@ async function registerContext(context) {
|
|
|
57860
57964
|
const servedBoundary = boundaryID ? servedBoundaryRow2(reader, draft.sessionID, boundaryID) : null;
|
|
57861
57965
|
const nativeFloor = await nativeFoldReplay?.restorationFloor(draft.sessionID, cut, reader);
|
|
57862
57966
|
const retiredInstructions = await nativeFoldReplay?.instructionRetirement(draft.sessionID, reader) ?? (() => false);
|
|
57863
|
-
const
|
|
57967
|
+
const floor = Math.max(nativeFloor ?? -Infinity, (nativeFoldReplay?.sourceChanged(draft.sessionID) && !rustModeModuleClient ? (reader.earliestSequence(draft.sessionID) ?? 0) - 1 : undefined) ?? (moduleBoundarySeq !== undefined ? moduleBoundarySeq - 1 : undefined) ?? servedBoundary?.seq ?? reader.sequenceForId(draft.sessionID, boundaryID) ?? (reader.earliestSequence(draft.sessionID) ?? 0) - 1);
|
|
57968
|
+
const floorRow = !rustModeModuleClient && Number.isFinite(floor) ? reader.range(draft.sessionID, floor - 1, floor).find((row) => row.seq === floor) : undefined;
|
|
57969
|
+
const boundary = floorRow && hasUnsummarizedBlocks(db, reader, draft.sessionID, floorRow.id) ? floor - 1 : floor;
|
|
57864
57970
|
if (moduleBoundarySeq !== undefined)
|
|
57865
57971
|
sessionLog2(draft.sessionID, `v2 restore: from the module boundary ${moduleBoundaryID} to the host checkpoint`);
|
|
57866
57972
|
const present = new Set(args.messages.map((message) => message.id));
|
|
@@ -57969,12 +58075,12 @@ async function registerContext(context) {
|
|
|
57969
58075
|
const runManagedContext = async (draft) => {
|
|
57970
58076
|
rememberHostMedia(draft.messages);
|
|
57971
58077
|
if (hiddenChildHook.apply(draft))
|
|
57972
|
-
return;
|
|
58078
|
+
return "skipped";
|
|
57973
58079
|
if (dreamTrigger === undefined && hiddenCompletionExecutor !== undefined)
|
|
57974
58080
|
dreamTrigger = startDreamer(hiddenCompletionExecutor);
|
|
57975
58081
|
removeDreamerOnlyTools(draft);
|
|
57976
58082
|
if (deletedSessions.has(draft.sessionID))
|
|
57977
|
-
return;
|
|
58083
|
+
return "skipped";
|
|
57978
58084
|
const systemAtEntry = structuredClone(draft.system);
|
|
57979
58085
|
const slotAtEntry = getSlot(draft.sessionID);
|
|
57980
58086
|
let checkpointAtEntry;
|
|
@@ -58003,7 +58109,7 @@ async function registerContext(context) {
|
|
|
58003
58109
|
const newest = draft.messages.at(-1);
|
|
58004
58110
|
if (newest && hasStorageNoticeShape(newest) && await isMagicContextSynthetic(newest.id)) {
|
|
58005
58111
|
await refuseBeforeProvider(context.session, draft.sessionID, "storage-notice-turn");
|
|
58006
|
-
return;
|
|
58112
|
+
return "skipped";
|
|
58007
58113
|
}
|
|
58008
58114
|
await dropStorageNotices(draft.messages, isMagicContextSynthetic);
|
|
58009
58115
|
const hostMessagesAtEntry = [...draft.messages];
|
|
@@ -58133,6 +58239,13 @@ async function registerContext(context) {
|
|
|
58133
58239
|
applyCheckpointHead(draft, replayHead);
|
|
58134
58240
|
};
|
|
58135
58241
|
try {
|
|
58242
|
+
const storageExempt = () => shouldBypassFailClosedBlock({ agent: draft.agent });
|
|
58243
|
+
if (failClosed.isArmed())
|
|
58244
|
+
await failClosed.enforce({
|
|
58245
|
+
blockingEnabled: failClosedBlockingEnabled,
|
|
58246
|
+
exempt: storageExempt(),
|
|
58247
|
+
tryReopen: tryReopenStorage
|
|
58248
|
+
});
|
|
58136
58249
|
if (!compactionOff && admissionDb)
|
|
58137
58250
|
await withAsyncPrivilegedWriter2(admissionDb, () => {
|
|
58138
58251
|
return;
|
|
@@ -58141,6 +58254,13 @@ async function registerContext(context) {
|
|
|
58141
58254
|
const input = await buildReplayInput();
|
|
58142
58255
|
if (!input)
|
|
58143
58256
|
return;
|
|
58257
|
+
if (failClosedBlockingEnabled && !storageExempt() && !openDatabase()) {
|
|
58258
|
+
const fence = getSchemaFenceRejection();
|
|
58259
|
+
if (fence) {
|
|
58260
|
+
failClosed.arm({ kind: "schema_fence", ...fence });
|
|
58261
|
+
await failClosed.enforce({ blockingEnabled: true, exempt: false });
|
|
58262
|
+
}
|
|
58263
|
+
}
|
|
58144
58264
|
const { mapped } = input;
|
|
58145
58265
|
if (tryMessagesTransformLkgReplay({
|
|
58146
58266
|
output: mapped,
|
|
@@ -58168,15 +58288,15 @@ async function registerContext(context) {
|
|
|
58168
58288
|
if (await recordUsage(draft, true) && !compactionOff) {
|
|
58169
58289
|
const storageReason = storage.current() ? null : storage.reason();
|
|
58170
58290
|
if (storageReason) {
|
|
58171
|
-
|
|
58172
|
-
|
|
58173
|
-
return;
|
|
58291
|
+
if (failClosedBlockingEnabled && !storageExempt())
|
|
58292
|
+
await refuseUnavailableStorage(draft.sessionID, storageReason);
|
|
58293
|
+
return "skipped";
|
|
58174
58294
|
}
|
|
58175
58295
|
await refuseBeforeProvider(context.session, draft.sessionID, "usage-unavailable");
|
|
58176
|
-
return;
|
|
58296
|
+
return "skipped";
|
|
58177
58297
|
}
|
|
58178
58298
|
if (!db)
|
|
58179
|
-
return;
|
|
58299
|
+
return "skipped";
|
|
58180
58300
|
if (!storageOpenedAtBoot && !storageRecoveryAnnounced) {
|
|
58181
58301
|
storageRecoveryAnnounced = true;
|
|
58182
58302
|
const recovered = await recoverHiddenWork(db);
|
|
@@ -58390,6 +58510,7 @@ async function registerContext(context) {
|
|
|
58390
58510
|
}
|
|
58391
58511
|
}
|
|
58392
58512
|
await createMessagesTransformHandler({
|
|
58513
|
+
...wrapperStorageGuard,
|
|
58393
58514
|
magicContext: { "experimental.chat.messages.transform": transform },
|
|
58394
58515
|
compactionOff,
|
|
58395
58516
|
recordServed: false,
|
|
@@ -58455,11 +58576,16 @@ async function registerContext(context) {
|
|
|
58455
58576
|
if (capturedSlot && (!slotAtEntry || capturedSlot.capturedAt !== slotAtEntry.capturedAt || capturedSlot.captureSequence !== slotAtEntry.captureSequence || capturedSlot.jsonPrefix !== slotAtEntry.jsonPrefix)) {
|
|
58456
58577
|
lkgSystems.capture(draft.sessionID, capturedSlot, { system: systemAtEntry, checkpoint: checkpointAtEntry ?? null }, draft.system, headApplied ? servedHead : null);
|
|
58457
58578
|
}
|
|
58579
|
+
return "managed";
|
|
58458
58580
|
} catch (error) {
|
|
58459
58581
|
if (error instanceof V2LkgAdmissionReplay)
|
|
58460
|
-
return;
|
|
58582
|
+
return "managed";
|
|
58461
58583
|
if (error instanceof V2ContextRefusal)
|
|
58462
58584
|
throw error;
|
|
58585
|
+
if (!compactionOff && isFailClosedBlockingError(error)) {
|
|
58586
|
+
await refuseUnavailableStorage(draft.sessionID, error.reason);
|
|
58587
|
+
return "skipped";
|
|
58588
|
+
}
|
|
58463
58589
|
if (!compactionOff && (isTransientSqliteError2(error) || error instanceof StorageBusyRefusalError)) {
|
|
58464
58590
|
if (isTransientSqliteError2(error)) {
|
|
58465
58591
|
const input = await buildReplayInput();
|
|
@@ -58468,6 +58594,7 @@ async function registerContext(context) {
|
|
|
58468
58594
|
throw new StorageBusyRefusalError(error, "v2-context");
|
|
58469
58595
|
const { mapped } = input;
|
|
58470
58596
|
await createMessagesTransformHandler({
|
|
58597
|
+
...wrapperStorageGuard,
|
|
58471
58598
|
recordServed: false,
|
|
58472
58599
|
replayFits,
|
|
58473
58600
|
onLkgReplay: restoreLkgSystem,
|
|
@@ -58480,8 +58607,12 @@ async function registerContext(context) {
|
|
|
58480
58607
|
})({}, mapped);
|
|
58481
58608
|
mapped.commit();
|
|
58482
58609
|
adoptReplay(input.draft);
|
|
58483
|
-
return;
|
|
58610
|
+
return "managed";
|
|
58484
58611
|
} catch (replayError) {
|
|
58612
|
+
if (isFailClosedBlockingError(replayError)) {
|
|
58613
|
+
await refuseUnavailableStorage(draft.sessionID, replayError.reason);
|
|
58614
|
+
return "skipped";
|
|
58615
|
+
}
|
|
58485
58616
|
if (!(replayError instanceof StorageBusyRefusalError))
|
|
58486
58617
|
throw replayError;
|
|
58487
58618
|
}
|
|
@@ -58507,6 +58638,7 @@ async function registerContext(context) {
|
|
|
58507
58638
|
} else {
|
|
58508
58639
|
log2("[magic-context] v2 context unavailable", error);
|
|
58509
58640
|
}
|
|
58641
|
+
return "skipped";
|
|
58510
58642
|
}
|
|
58511
58643
|
};
|
|
58512
58644
|
const finishServedRequest = (draft, returned) => {
|
|
@@ -58550,14 +58682,19 @@ async function registerContext(context) {
|
|
|
58550
58682
|
await refuseBeforeProvider(context.session, draft.sessionID, "checkpoint-over-window");
|
|
58551
58683
|
throw new V2ContextRefusal("Magic Context refused an oversized host checkpoint.");
|
|
58552
58684
|
};
|
|
58553
|
-
await context.session.hook("context", (draft) =>
|
|
58685
|
+
await context.session.hook("context", (draft) => withV2ContextPass(draft.sessionID, async (pass) => {
|
|
58554
58686
|
hostFoldIdle?.active(draft.sessionID);
|
|
58555
58687
|
const hiddenChild = hiddenChildHook.owns(draft.sessionID);
|
|
58556
58688
|
const anchor = compactionOff || hiddenChild ? undefined : generateReplayAnchor(draft.messages);
|
|
58557
58689
|
beginServedRequest(draft.sessionID);
|
|
58558
58690
|
let returned = false;
|
|
58691
|
+
let outcome;
|
|
58559
58692
|
try {
|
|
58560
|
-
await runManagedContext(draft);
|
|
58693
|
+
outcome = await runManagedContext(draft);
|
|
58694
|
+
if (pass.refused) {
|
|
58695
|
+
returned = true;
|
|
58696
|
+
return;
|
|
58697
|
+
}
|
|
58561
58698
|
if (!compactionOff)
|
|
58562
58699
|
await refuseOversizedCheckpoint(draft);
|
|
58563
58700
|
if (!deletedSessions.has(draft.sessionID) && admissionRebuildPasses.has(draft.sessionID)) {
|
|
@@ -58581,7 +58718,7 @@ async function registerContext(context) {
|
|
|
58581
58718
|
}
|
|
58582
58719
|
if (compactionOff)
|
|
58583
58720
|
sessionLog2(draft.sessionID, "generate replay capture skipped: compaction-disabled");
|
|
58584
|
-
else if (!hiddenChild && !deletedSessions.has(draft.sessionID))
|
|
58721
|
+
else if (!pass.refused && outcome === "managed" && !hiddenChild && !deletedSessions.has(draft.sessionID))
|
|
58585
58722
|
generateReplay.capture(draft, anchor);
|
|
58586
58723
|
}));
|
|
58587
58724
|
await context.session.hook("generate", async (draft) => {
|